1 //===- CompilerInvocation.cpp ---------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/Frontend/CompilerInvocation.h" 10 #include "TestModuleFileExtension.h" 11 #include "clang/Basic/Builtins.h" 12 #include "clang/Basic/CharInfo.h" 13 #include "clang/Basic/CodeGenOptions.h" 14 #include "clang/Basic/CommentOptions.h" 15 #include "clang/Basic/DebugInfoOptions.h" 16 #include "clang/Basic/Diagnostic.h" 17 #include "clang/Basic/DiagnosticDriver.h" 18 #include "clang/Basic/DiagnosticOptions.h" 19 #include "clang/Basic/FileSystemOptions.h" 20 #include "clang/Basic/LLVM.h" 21 #include "clang/Basic/LangOptions.h" 22 #include "clang/Basic/LangStandard.h" 23 #include "clang/Basic/ObjCRuntime.h" 24 #include "clang/Basic/Sanitizers.h" 25 #include "clang/Basic/SourceLocation.h" 26 #include "clang/Basic/TargetOptions.h" 27 #include "clang/Basic/Version.h" 28 #include "clang/Basic/Visibility.h" 29 #include "clang/Basic/XRayInstr.h" 30 #include "clang/Config/config.h" 31 #include "clang/Driver/Driver.h" 32 #include "clang/Driver/DriverDiagnostic.h" 33 #include "clang/Driver/Options.h" 34 #include "clang/Frontend/CommandLineSourceLoc.h" 35 #include "clang/Frontend/DependencyOutputOptions.h" 36 #include "clang/Frontend/FrontendDiagnostic.h" 37 #include "clang/Frontend/FrontendOptions.h" 38 #include "clang/Frontend/FrontendPluginRegistry.h" 39 #include "clang/Frontend/MigratorOptions.h" 40 #include "clang/Frontend/PreprocessorOutputOptions.h" 41 #include "clang/Frontend/Utils.h" 42 #include "clang/Lex/HeaderSearchOptions.h" 43 #include "clang/Lex/PreprocessorOptions.h" 44 #include "clang/Sema/CodeCompleteOptions.h" 45 #include "clang/Serialization/ASTBitCodes.h" 46 #include "clang/Serialization/ModuleFileExtension.h" 47 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" 48 #include "llvm/ADT/APInt.h" 49 #include "llvm/ADT/ArrayRef.h" 50 #include "llvm/ADT/CachedHashString.h" 51 #include "llvm/ADT/FloatingPointMode.h" 52 #include "llvm/ADT/Hashing.h" 53 #include "llvm/ADT/None.h" 54 #include "llvm/ADT/Optional.h" 55 #include "llvm/ADT/SmallString.h" 56 #include "llvm/ADT/SmallVector.h" 57 #include "llvm/ADT/StringRef.h" 58 #include "llvm/ADT/StringSwitch.h" 59 #include "llvm/ADT/Triple.h" 60 #include "llvm/ADT/Twine.h" 61 #include "llvm/Config/llvm-config.h" 62 #include "llvm/IR/DebugInfoMetadata.h" 63 #include "llvm/Linker/Linker.h" 64 #include "llvm/MC/MCTargetOptions.h" 65 #include "llvm/Option/Arg.h" 66 #include "llvm/Option/ArgList.h" 67 #include "llvm/Option/OptSpecifier.h" 68 #include "llvm/Option/OptTable.h" 69 #include "llvm/Option/Option.h" 70 #include "llvm/ProfileData/InstrProfReader.h" 71 #include "llvm/Remarks/HotnessThresholdParser.h" 72 #include "llvm/Support/CodeGen.h" 73 #include "llvm/Support/Compiler.h" 74 #include "llvm/Support/Error.h" 75 #include "llvm/Support/ErrorHandling.h" 76 #include "llvm/Support/ErrorOr.h" 77 #include "llvm/Support/FileSystem.h" 78 #include "llvm/Support/Host.h" 79 #include "llvm/Support/MathExtras.h" 80 #include "llvm/Support/MemoryBuffer.h" 81 #include "llvm/Support/Path.h" 82 #include "llvm/Support/Process.h" 83 #include "llvm/Support/Regex.h" 84 #include "llvm/Support/VersionTuple.h" 85 #include "llvm/Support/VirtualFileSystem.h" 86 #include "llvm/Support/raw_ostream.h" 87 #include "llvm/Target/TargetOptions.h" 88 #include <algorithm> 89 #include <atomic> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstring> 93 #include <memory> 94 #include <string> 95 #include <tuple> 96 #include <type_traits> 97 #include <utility> 98 #include <vector> 99 100 using namespace clang; 101 using namespace driver; 102 using namespace options; 103 using namespace llvm::opt; 104 105 //===----------------------------------------------------------------------===// 106 // Initialization. 107 //===----------------------------------------------------------------------===// 108 109 CompilerInvocationBase::CompilerInvocationBase() 110 : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()), 111 DiagnosticOpts(new DiagnosticOptions()), 112 HeaderSearchOpts(new HeaderSearchOptions()), 113 PreprocessorOpts(new PreprocessorOptions()) {} 114 115 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X) 116 : LangOpts(new LangOptions(*X.getLangOpts())), 117 TargetOpts(new TargetOptions(X.getTargetOpts())), 118 DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())), 119 HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())), 120 PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {} 121 122 CompilerInvocationBase::~CompilerInvocationBase() = default; 123 124 //===----------------------------------------------------------------------===// 125 // Normalizers 126 //===----------------------------------------------------------------------===// 127 128 #define SIMPLE_ENUM_VALUE_TABLE 129 #include "clang/Driver/Options.inc" 130 #undef SIMPLE_ENUM_VALUE_TABLE 131 132 static llvm::Optional<bool> normalizeSimpleFlag(OptSpecifier Opt, 133 unsigned TableIndex, 134 const ArgList &Args, 135 DiagnosticsEngine &Diags) { 136 if (Args.hasArg(Opt)) 137 return true; 138 return None; 139 } 140 141 static Optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned, 142 const ArgList &Args, 143 DiagnosticsEngine &) { 144 if (Args.hasArg(Opt)) 145 return false; 146 return None; 147 } 148 149 /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but 150 /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with 151 /// unnecessary template instantiations and just ignore it with a variadic 152 /// argument. 153 static void denormalizeSimpleFlag(SmallVectorImpl<const char *> &Args, 154 const char *Spelling, 155 CompilerInvocation::StringAllocator, 156 Option::OptionClass, unsigned, /*T*/...) { 157 Args.push_back(Spelling); 158 } 159 160 namespace { 161 template <typename T> struct FlagToValueNormalizer { 162 T Value; 163 164 Optional<T> operator()(OptSpecifier Opt, unsigned, const ArgList &Args, 165 DiagnosticsEngine &) { 166 if (Args.hasArg(Opt)) 167 return Value; 168 return None; 169 } 170 }; 171 } // namespace 172 173 template <typename T> static constexpr bool is_int_convertible() { 174 return sizeof(T) <= sizeof(uint64_t) && 175 std::is_trivially_constructible<T, uint64_t>::value && 176 std::is_trivially_constructible<uint64_t, T>::value; 177 } 178 179 template <typename T, std::enable_if_t<is_int_convertible<T>(), bool> = false> 180 static FlagToValueNormalizer<uint64_t> makeFlagToValueNormalizer(T Value) { 181 return FlagToValueNormalizer<uint64_t>{Value}; 182 } 183 184 template <typename T, std::enable_if_t<!is_int_convertible<T>(), bool> = false> 185 static FlagToValueNormalizer<T> makeFlagToValueNormalizer(T Value) { 186 return FlagToValueNormalizer<T>{std::move(Value)}; 187 } 188 189 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue, 190 OptSpecifier OtherOpt) { 191 return [Value, OtherValue, OtherOpt](OptSpecifier Opt, unsigned, 192 const ArgList &Args, 193 DiagnosticsEngine &) -> Optional<bool> { 194 if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) { 195 return A->getOption().matches(Opt) ? Value : OtherValue; 196 } 197 return None; 198 }; 199 } 200 201 static auto makeBooleanOptionDenormalizer(bool Value) { 202 return [Value](SmallVectorImpl<const char *> &Args, const char *Spelling, 203 CompilerInvocation::StringAllocator, Option::OptionClass, 204 unsigned, bool KeyPath) { 205 if (KeyPath == Value) 206 Args.push_back(Spelling); 207 }; 208 } 209 210 static void denormalizeStringImpl(SmallVectorImpl<const char *> &Args, 211 const char *Spelling, 212 CompilerInvocation::StringAllocator SA, 213 Option::OptionClass OptClass, unsigned, 214 Twine Value) { 215 switch (OptClass) { 216 case Option::SeparateClass: 217 case Option::JoinedOrSeparateClass: 218 Args.push_back(Spelling); 219 Args.push_back(SA(Value)); 220 break; 221 case Option::JoinedClass: 222 Args.push_back(SA(Twine(Spelling) + Value)); 223 break; 224 default: 225 llvm_unreachable("Cannot denormalize an option with option class " 226 "incompatible with string denormalization."); 227 } 228 } 229 230 template <typename T> 231 static void 232 denormalizeString(SmallVectorImpl<const char *> &Args, const char *Spelling, 233 CompilerInvocation::StringAllocator SA, 234 Option::OptionClass OptClass, unsigned TableIndex, T Value) { 235 denormalizeStringImpl(Args, Spelling, SA, OptClass, TableIndex, Twine(Value)); 236 } 237 238 static Optional<SimpleEnumValue> 239 findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) { 240 for (int I = 0, E = Table.Size; I != E; ++I) 241 if (Name == Table.Table[I].Name) 242 return Table.Table[I]; 243 244 return None; 245 } 246 247 static Optional<SimpleEnumValue> 248 findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) { 249 for (int I = 0, E = Table.Size; I != E; ++I) 250 if (Value == Table.Table[I].Value) 251 return Table.Table[I]; 252 253 return None; 254 } 255 256 static llvm::Optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt, 257 unsigned TableIndex, 258 const ArgList &Args, 259 DiagnosticsEngine &Diags) { 260 assert(TableIndex < SimpleEnumValueTablesSize); 261 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex]; 262 263 auto *Arg = Args.getLastArg(Opt); 264 if (!Arg) 265 return None; 266 267 StringRef ArgValue = Arg->getValue(); 268 if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue)) 269 return MaybeEnumVal->Value; 270 271 Diags.Report(diag::err_drv_invalid_value) 272 << Arg->getAsString(Args) << ArgValue; 273 return None; 274 } 275 276 static void denormalizeSimpleEnumImpl(SmallVectorImpl<const char *> &Args, 277 const char *Spelling, 278 CompilerInvocation::StringAllocator SA, 279 Option::OptionClass OptClass, 280 unsigned TableIndex, unsigned Value) { 281 assert(TableIndex < SimpleEnumValueTablesSize); 282 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex]; 283 if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) { 284 denormalizeString(Args, Spelling, SA, OptClass, TableIndex, 285 MaybeEnumVal->Name); 286 } else { 287 llvm_unreachable("The simple enum value was not correctly defined in " 288 "the tablegen option description"); 289 } 290 } 291 292 template <typename T> 293 static void denormalizeSimpleEnum(SmallVectorImpl<const char *> &Args, 294 const char *Spelling, 295 CompilerInvocation::StringAllocator SA, 296 Option::OptionClass OptClass, 297 unsigned TableIndex, T Value) { 298 return denormalizeSimpleEnumImpl(Args, Spelling, SA, OptClass, TableIndex, 299 static_cast<unsigned>(Value)); 300 } 301 302 static Optional<std::string> normalizeString(OptSpecifier Opt, int TableIndex, 303 const ArgList &Args, 304 DiagnosticsEngine &Diags) { 305 auto *Arg = Args.getLastArg(Opt); 306 if (!Arg) 307 return None; 308 return std::string(Arg->getValue()); 309 } 310 311 template <typename IntTy> 312 static Optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int, 313 const ArgList &Args, 314 DiagnosticsEngine &Diags) { 315 auto *Arg = Args.getLastArg(Opt); 316 if (!Arg) 317 return None; 318 IntTy Res; 319 if (StringRef(Arg->getValue()).getAsInteger(0, Res)) { 320 Diags.Report(diag::err_drv_invalid_int_value) 321 << Arg->getAsString(Args) << Arg->getValue(); 322 } 323 return Res; 324 } 325 326 static Optional<std::string> normalizeTriple(OptSpecifier Opt, int TableIndex, 327 const ArgList &Args, 328 DiagnosticsEngine &Diags) { 329 auto *Arg = Args.getLastArg(Opt); 330 if (!Arg) 331 return None; 332 return llvm::Triple::normalize(Arg->getValue()); 333 } 334 335 template <typename T, typename U> 336 static T mergeForwardValue(T KeyPath, U Value) { 337 return static_cast<T>(Value); 338 } 339 340 template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) { 341 return KeyPath | Value; 342 } 343 344 template <typename T> static T extractForwardValue(T KeyPath) { 345 return KeyPath; 346 } 347 348 template <typename T, typename U, U Value> 349 static T extractMaskValue(T KeyPath) { 350 return KeyPath & Value; 351 } 352 353 static void FixupInvocation(CompilerInvocation &Invocation, 354 DiagnosticsEngine &Diags, 355 const InputArgList &Args) { 356 LangOptions &LangOpts = *Invocation.getLangOpts(); 357 DiagnosticOptions &DiagOpts = Invocation.getDiagnosticOpts(); 358 CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts(); 359 TargetOptions &TargetOpts = Invocation.getTargetOpts(); 360 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts(); 361 CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument; 362 CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents; 363 CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents; 364 CodeGenOpts.DisableFree = FrontendOpts.DisableFree; 365 FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex; 366 367 LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables; 368 LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening; 369 LangOpts.CurrentModule = LangOpts.ModuleName; 370 371 llvm::sys::Process::UseANSIEscapeCodes(DiagOpts.UseANSIEscapeCodes); 372 373 llvm::Triple T(TargetOpts.Triple); 374 llvm::Triple::ArchType Arch = T.getArch(); 375 376 if (LangOpts.getExceptionHandling() != llvm::ExceptionHandling::None && 377 T.isWindowsMSVCEnvironment()) 378 Diags.Report(diag::err_fe_invalid_exception_model) 379 << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str(); 380 381 if (LangOpts.AppleKext && !LangOpts.CPlusPlus) 382 Diags.Report(diag::warn_c_kext); 383 384 if (LangOpts.NewAlignOverride && 385 !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) { 386 Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ); 387 Diags.Report(diag::err_fe_invalid_alignment) 388 << A->getAsString(Args) << A->getValue(); 389 LangOpts.NewAlignOverride = 0; 390 } 391 392 if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) { 393 auto DefaultCC = LangOpts.getDefaultCallingConv(); 394 395 bool emitError = (DefaultCC == LangOptions::DCC_FastCall || 396 DefaultCC == LangOptions::DCC_StdCall) && 397 Arch != llvm::Triple::x86; 398 emitError |= (DefaultCC == LangOptions::DCC_VectorCall || 399 DefaultCC == LangOptions::DCC_RegCall) && 400 !T.isX86(); 401 if (emitError) 402 Diags.Report(diag::err_drv_argument_not_allowed_with) 403 << A->getSpelling() << T.getTriple(); 404 } 405 406 if (!CodeGenOpts.ProfileRemappingFile.empty() && CodeGenOpts.LegacyPassManager) 407 Diags.Report(diag::err_drv_argument_only_allowed_with) 408 << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args) 409 << "-fno-legacy-pass-manager"; 410 } 411 412 //===----------------------------------------------------------------------===// 413 // Deserialization (from args) 414 //===----------------------------------------------------------------------===// 415 416 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK, 417 DiagnosticsEngine &Diags) { 418 unsigned DefaultOpt = llvm::CodeGenOpt::None; 419 if (IK.getLanguage() == Language::OpenCL && !Args.hasArg(OPT_cl_opt_disable)) 420 DefaultOpt = llvm::CodeGenOpt::Default; 421 422 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 423 if (A->getOption().matches(options::OPT_O0)) 424 return llvm::CodeGenOpt::None; 425 426 if (A->getOption().matches(options::OPT_Ofast)) 427 return llvm::CodeGenOpt::Aggressive; 428 429 assert(A->getOption().matches(options::OPT_O)); 430 431 StringRef S(A->getValue()); 432 if (S == "s" || S == "z") 433 return llvm::CodeGenOpt::Default; 434 435 if (S == "g") 436 return llvm::CodeGenOpt::Less; 437 438 return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags); 439 } 440 441 return DefaultOpt; 442 } 443 444 static unsigned getOptimizationLevelSize(ArgList &Args) { 445 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 446 if (A->getOption().matches(options::OPT_O)) { 447 switch (A->getValue()[0]) { 448 default: 449 return 0; 450 case 's': 451 return 1; 452 case 'z': 453 return 2; 454 } 455 } 456 } 457 return 0; 458 } 459 460 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, 461 OptSpecifier GroupWithValue, 462 std::vector<std::string> &Diagnostics) { 463 for (auto *A : Args.filtered(Group)) { 464 if (A->getOption().getKind() == Option::FlagClass) { 465 // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add 466 // its name (minus the "W" or "R" at the beginning) to the warning list. 467 Diagnostics.push_back( 468 std::string(A->getOption().getName().drop_front(1))); 469 } else if (A->getOption().matches(GroupWithValue)) { 470 // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group. 471 Diagnostics.push_back( 472 std::string(A->getOption().getName().drop_front(1).rtrim("=-"))); 473 } else { 474 // Otherwise, add its value (for OPT_W_Joined and similar). 475 for (const auto *Arg : A->getValues()) 476 Diagnostics.emplace_back(Arg); 477 } 478 } 479 } 480 481 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr, 482 // it won't verify the input. 483 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, 484 DiagnosticsEngine *Diags); 485 486 static void getAllNoBuiltinFuncValues(ArgList &Args, 487 std::vector<std::string> &Funcs) { 488 SmallVector<const char *, 8> Values; 489 for (const auto &Arg : Args) { 490 const Option &O = Arg->getOption(); 491 if (O.matches(options::OPT_fno_builtin_)) { 492 const char *FuncName = Arg->getValue(); 493 if (Builtin::Context::isBuiltinFunc(FuncName)) 494 Values.push_back(FuncName); 495 } 496 } 497 Funcs.insert(Funcs.end(), Values.begin(), Values.end()); 498 } 499 500 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, 501 DiagnosticsEngine &Diags) { 502 bool Success = true; 503 if (Arg *A = Args.getLastArg(OPT_analyzer_store)) { 504 StringRef Name = A->getValue(); 505 AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name) 506 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \ 507 .Case(CMDFLAG, NAME##Model) 508 #include "clang/StaticAnalyzer/Core/Analyses.def" 509 .Default(NumStores); 510 if (Value == NumStores) { 511 Diags.Report(diag::err_drv_invalid_value) 512 << A->getAsString(Args) << Name; 513 Success = false; 514 } else { 515 Opts.AnalysisStoreOpt = Value; 516 } 517 } 518 519 if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) { 520 StringRef Name = A->getValue(); 521 AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name) 522 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \ 523 .Case(CMDFLAG, NAME##Model) 524 #include "clang/StaticAnalyzer/Core/Analyses.def" 525 .Default(NumConstraints); 526 if (Value == NumConstraints) { 527 Diags.Report(diag::err_drv_invalid_value) 528 << A->getAsString(Args) << Name; 529 Success = false; 530 } else { 531 Opts.AnalysisConstraintsOpt = Value; 532 } 533 } 534 535 if (Arg *A = Args.getLastArg(OPT_analyzer_output)) { 536 StringRef Name = A->getValue(); 537 AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name) 538 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \ 539 .Case(CMDFLAG, PD_##NAME) 540 #include "clang/StaticAnalyzer/Core/Analyses.def" 541 .Default(NUM_ANALYSIS_DIAG_CLIENTS); 542 if (Value == NUM_ANALYSIS_DIAG_CLIENTS) { 543 Diags.Report(diag::err_drv_invalid_value) 544 << A->getAsString(Args) << Name; 545 Success = false; 546 } else { 547 Opts.AnalysisDiagOpt = Value; 548 } 549 } 550 551 if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) { 552 StringRef Name = A->getValue(); 553 AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name) 554 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \ 555 .Case(CMDFLAG, NAME) 556 #include "clang/StaticAnalyzer/Core/Analyses.def" 557 .Default(NumPurgeModes); 558 if (Value == NumPurgeModes) { 559 Diags.Report(diag::err_drv_invalid_value) 560 << A->getAsString(Args) << Name; 561 Success = false; 562 } else { 563 Opts.AnalysisPurgeOpt = Value; 564 } 565 } 566 567 if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) { 568 StringRef Name = A->getValue(); 569 AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name) 570 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \ 571 .Case(CMDFLAG, NAME) 572 #include "clang/StaticAnalyzer/Core/Analyses.def" 573 .Default(NumInliningModes); 574 if (Value == NumInliningModes) { 575 Diags.Report(diag::err_drv_invalid_value) 576 << A->getAsString(Args) << Name; 577 Success = false; 578 } else { 579 Opts.InliningMode = Value; 580 } 581 } 582 583 Opts.ShouldEmitErrorsOnInvalidConfigValue = 584 /* negated */!llvm::StringSwitch<bool>( 585 Args.getLastArgValue(OPT_analyzer_config_compatibility_mode)) 586 .Case("true", true) 587 .Case("false", false) 588 .Default(false); 589 590 Opts.CheckersAndPackages.clear(); 591 for (const Arg *A : 592 Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) { 593 A->claim(); 594 bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker; 595 // We can have a list of comma separated checker names, e.g: 596 // '-analyzer-checker=cocoa,unix' 597 StringRef CheckerAndPackageList = A->getValue(); 598 SmallVector<StringRef, 16> CheckersAndPackages; 599 CheckerAndPackageList.split(CheckersAndPackages, ","); 600 for (const StringRef &CheckerOrPackage : CheckersAndPackages) 601 Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage), 602 IsEnabled); 603 } 604 605 // Go through the analyzer configuration options. 606 for (const auto *A : Args.filtered(OPT_analyzer_config)) { 607 608 // We can have a list of comma separated config names, e.g: 609 // '-analyzer-config key1=val1,key2=val2' 610 StringRef configList = A->getValue(); 611 SmallVector<StringRef, 4> configVals; 612 configList.split(configVals, ","); 613 for (const auto &configVal : configVals) { 614 StringRef key, val; 615 std::tie(key, val) = configVal.split("="); 616 if (val.empty()) { 617 Diags.Report(SourceLocation(), 618 diag::err_analyzer_config_no_value) << configVal; 619 Success = false; 620 break; 621 } 622 if (val.find('=') != StringRef::npos) { 623 Diags.Report(SourceLocation(), 624 diag::err_analyzer_config_multiple_values) 625 << configVal; 626 Success = false; 627 break; 628 } 629 630 // TODO: Check checker options too, possibly in CheckerRegistry. 631 // Leave unknown non-checker configs unclaimed. 632 if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) { 633 if (Opts.ShouldEmitErrorsOnInvalidConfigValue) 634 Diags.Report(diag::err_analyzer_config_unknown) << key; 635 continue; 636 } 637 638 A->claim(); 639 Opts.Config[key] = std::string(val); 640 } 641 } 642 643 if (Opts.ShouldEmitErrorsOnInvalidConfigValue) 644 parseAnalyzerConfigs(Opts, &Diags); 645 else 646 parseAnalyzerConfigs(Opts, nullptr); 647 648 llvm::raw_string_ostream os(Opts.FullCompilerInvocation); 649 for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) { 650 if (i != 0) 651 os << " "; 652 os << Args.getArgString(i); 653 } 654 os.flush(); 655 656 return Success; 657 } 658 659 static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config, 660 StringRef OptionName, StringRef DefaultVal) { 661 return Config.insert({OptionName, std::string(DefaultVal)}).first->second; 662 } 663 664 static void initOption(AnalyzerOptions::ConfigTable &Config, 665 DiagnosticsEngine *Diags, 666 StringRef &OptionField, StringRef Name, 667 StringRef DefaultVal) { 668 // String options may be known to invalid (e.g. if the expected string is a 669 // file name, but the file does not exist), those will have to be checked in 670 // parseConfigs. 671 OptionField = getStringOption(Config, Name, DefaultVal); 672 } 673 674 static void initOption(AnalyzerOptions::ConfigTable &Config, 675 DiagnosticsEngine *Diags, 676 bool &OptionField, StringRef Name, bool DefaultVal) { 677 auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>( 678 getStringOption(Config, Name, (DefaultVal ? "true" : "false"))) 679 .Case("true", true) 680 .Case("false", false) 681 .Default(None); 682 683 if (!PossiblyInvalidVal) { 684 if (Diags) 685 Diags->Report(diag::err_analyzer_config_invalid_input) 686 << Name << "a boolean"; 687 else 688 OptionField = DefaultVal; 689 } else 690 OptionField = PossiblyInvalidVal.getValue(); 691 } 692 693 static void initOption(AnalyzerOptions::ConfigTable &Config, 694 DiagnosticsEngine *Diags, 695 unsigned &OptionField, StringRef Name, 696 unsigned DefaultVal) { 697 698 OptionField = DefaultVal; 699 bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal)) 700 .getAsInteger(0, OptionField); 701 if (Diags && HasFailed) 702 Diags->Report(diag::err_analyzer_config_invalid_input) 703 << Name << "an unsigned"; 704 } 705 706 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, 707 DiagnosticsEngine *Diags) { 708 // TODO: There's no need to store the entire configtable, it'd be plenty 709 // enough tostore checker options. 710 711 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \ 712 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL); 713 714 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \ 715 SHALLOW_VAL, DEEP_VAL) \ 716 switch (AnOpts.getUserMode()) { \ 717 case UMK_Shallow: \ 718 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL); \ 719 break; \ 720 case UMK_Deep: \ 721 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL); \ 722 break; \ 723 } \ 724 725 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def" 726 #undef ANALYZER_OPTION 727 #undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE 728 729 // At this point, AnalyzerOptions is configured. Let's validate some options. 730 731 // FIXME: Here we try to validate the silenced checkers or packages are valid. 732 // The current approach only validates the registered checkers which does not 733 // contain the runtime enabled checkers and optimally we would validate both. 734 if (!AnOpts.RawSilencedCheckersAndPackages.empty()) { 735 std::vector<StringRef> Checkers = 736 AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true); 737 std::vector<StringRef> Packages = 738 AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true); 739 740 SmallVector<StringRef, 16> CheckersAndPackages; 741 AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";"); 742 743 for (const StringRef &CheckerOrPackage : CheckersAndPackages) { 744 if (Diags) { 745 bool IsChecker = CheckerOrPackage.contains('.'); 746 bool IsValidName = 747 IsChecker 748 ? llvm::find(Checkers, CheckerOrPackage) != Checkers.end() 749 : llvm::find(Packages, CheckerOrPackage) != Packages.end(); 750 751 if (!IsValidName) 752 Diags->Report(diag::err_unknown_analyzer_checker_or_package) 753 << CheckerOrPackage; 754 } 755 756 AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage); 757 } 758 } 759 760 if (!Diags) 761 return; 762 763 if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions) 764 Diags->Report(diag::err_analyzer_config_invalid_input) 765 << "track-conditions-debug" << "'track-conditions' to also be enabled"; 766 767 if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir)) 768 Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir" 769 << "a filename"; 770 771 if (!AnOpts.ModelPath.empty() && 772 !llvm::sys::fs::is_directory(AnOpts.ModelPath)) 773 Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path" 774 << "a filename"; 775 } 776 777 static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) { 778 Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands); 779 Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments); 780 } 781 782 /// Create a new Regex instance out of the string value in \p RpassArg. 783 /// It returns a pointer to the newly generated Regex instance. 784 static std::shared_ptr<llvm::Regex> 785 GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args, 786 Arg *RpassArg) { 787 StringRef Val = RpassArg->getValue(); 788 std::string RegexError; 789 std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val); 790 if (!Pattern->isValid(RegexError)) { 791 Diags.Report(diag::err_drv_optimization_remark_pattern) 792 << RegexError << RpassArg->getAsString(Args); 793 Pattern.reset(); 794 } 795 return Pattern; 796 } 797 798 static bool parseDiagnosticLevelMask(StringRef FlagName, 799 const std::vector<std::string> &Levels, 800 DiagnosticsEngine *Diags, 801 DiagnosticLevelMask &M) { 802 bool Success = true; 803 for (const auto &Level : Levels) { 804 DiagnosticLevelMask const PM = 805 llvm::StringSwitch<DiagnosticLevelMask>(Level) 806 .Case("note", DiagnosticLevelMask::Note) 807 .Case("remark", DiagnosticLevelMask::Remark) 808 .Case("warning", DiagnosticLevelMask::Warning) 809 .Case("error", DiagnosticLevelMask::Error) 810 .Default(DiagnosticLevelMask::None); 811 if (PM == DiagnosticLevelMask::None) { 812 Success = false; 813 if (Diags) 814 Diags->Report(diag::err_drv_invalid_value) << FlagName << Level; 815 } 816 M = M | PM; 817 } 818 return Success; 819 } 820 821 static void parseSanitizerKinds(StringRef FlagName, 822 const std::vector<std::string> &Sanitizers, 823 DiagnosticsEngine &Diags, SanitizerSet &S) { 824 for (const auto &Sanitizer : Sanitizers) { 825 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false); 826 if (K == SanitizerMask()) 827 Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer; 828 else 829 S.set(K, true); 830 } 831 } 832 833 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle, 834 ArgList &Args, DiagnosticsEngine &D, 835 XRayInstrSet &S) { 836 llvm::SmallVector<StringRef, 2> BundleParts; 837 llvm::SplitString(Bundle, BundleParts, ","); 838 for (const auto &B : BundleParts) { 839 auto Mask = parseXRayInstrValue(B); 840 if (Mask == XRayInstrKind::None) 841 if (B != "none") 842 D.Report(diag::err_drv_invalid_value) << FlagName << Bundle; 843 else 844 S.Mask = Mask; 845 else if (Mask == XRayInstrKind::All) 846 S.Mask = Mask; 847 else 848 S.set(Mask, true); 849 } 850 } 851 852 // Set the profile kind using fprofile-instrument-use-path. 853 static void setPGOUseInstrumentor(CodeGenOptions &Opts, 854 const Twine &ProfileName) { 855 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName); 856 // In error, return silently and let Clang PGOUse report the error message. 857 if (auto E = ReaderOrErr.takeError()) { 858 llvm::consumeError(std::move(E)); 859 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr); 860 return; 861 } 862 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader = 863 std::move(ReaderOrErr.get()); 864 if (PGOReader->isIRLevelProfile()) { 865 if (PGOReader->hasCSIRLevelProfile()) 866 Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr); 867 else 868 Opts.setProfileUse(CodeGenOptions::ProfileIRInstr); 869 } else 870 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr); 871 } 872 873 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, 874 DiagnosticsEngine &Diags, 875 const TargetOptions &TargetOpts, 876 const FrontendOptions &FrontendOpts) { 877 bool Success = true; 878 llvm::Triple Triple = llvm::Triple(TargetOpts.Triple); 879 880 unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags); 881 // TODO: This could be done in Driver 882 unsigned MaxOptLevel = 3; 883 if (OptimizationLevel > MaxOptLevel) { 884 // If the optimization level is not supported, fall back on the default 885 // optimization 886 Diags.Report(diag::warn_drv_optimization_value) 887 << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel; 888 OptimizationLevel = MaxOptLevel; 889 } 890 Opts.OptimizationLevel = OptimizationLevel; 891 892 // At O0 we want to fully disable inlining outside of cases marked with 893 // 'alwaysinline' that are required for correctness. 894 Opts.setInlining((Opts.OptimizationLevel == 0) 895 ? CodeGenOptions::OnlyAlwaysInlining 896 : CodeGenOptions::NormalInlining); 897 // Explicit inlining flags can disable some or all inlining even at 898 // optimization levels above zero. 899 if (Arg *InlineArg = Args.getLastArg( 900 options::OPT_finline_functions, options::OPT_finline_hint_functions, 901 options::OPT_fno_inline_functions, options::OPT_fno_inline)) { 902 if (Opts.OptimizationLevel > 0) { 903 const Option &InlineOpt = InlineArg->getOption(); 904 if (InlineOpt.matches(options::OPT_finline_functions)) 905 Opts.setInlining(CodeGenOptions::NormalInlining); 906 else if (InlineOpt.matches(options::OPT_finline_hint_functions)) 907 Opts.setInlining(CodeGenOptions::OnlyHintInlining); 908 else 909 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining); 910 } 911 } 912 913 // If -fuse-ctor-homing is set and limited debug info is already on, then use 914 // constructor homing. 915 if (Args.getLastArg(OPT_fuse_ctor_homing)) 916 if (Opts.getDebugInfo() == codegenoptions::LimitedDebugInfo) 917 Opts.setDebugInfo(codegenoptions::DebugInfoConstructor); 918 919 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) { 920 auto Split = StringRef(Arg).split('='); 921 Opts.DebugPrefixMap.insert( 922 {std::string(Split.first), std::string(Split.second)}); 923 } 924 925 const llvm::Triple::ArchType DebugEntryValueArchs[] = { 926 llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64, 927 llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips, 928 llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el}; 929 930 llvm::Triple T(TargetOpts.Triple); 931 if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() && 932 llvm::is_contained(DebugEntryValueArchs, T.getArch())) 933 Opts.EmitCallSiteInfo = true; 934 935 Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) && 936 Args.hasArg(OPT_new_struct_path_tbaa); 937 Opts.OptimizeSize = getOptimizationLevelSize(Args); 938 Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) || 939 Args.hasArg(OPT_ffreestanding)); 940 if (Opts.SimplifyLibCalls) 941 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs); 942 Opts.UnrollLoops = 943 Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops, 944 (Opts.OptimizationLevel > 1)); 945 946 Opts.DebugNameTable = static_cast<unsigned>( 947 Args.hasArg(OPT_ggnu_pubnames) 948 ? llvm::DICompileUnit::DebugNameTableKind::GNU 949 : Args.hasArg(OPT_gpubnames) 950 ? llvm::DICompileUnit::DebugNameTableKind::Default 951 : llvm::DICompileUnit::DebugNameTableKind::None); 952 953 if (!Opts.ProfileInstrumentUsePath.empty()) 954 setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath); 955 956 Opts.CodeModel = TargetOpts.CodeModel; 957 958 if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) { 959 Opts.TimePasses = true; 960 961 // -ftime-report= is only for new pass manager. 962 if (A->getOption().getID() == OPT_ftime_report_EQ) { 963 if (Opts.LegacyPassManager) 964 Diags.Report(diag::err_drv_argument_only_allowed_with) 965 << A->getAsString(Args) << "-fno-legacy-pass-manager"; 966 967 StringRef Val = A->getValue(); 968 if (Val == "per-pass") 969 Opts.TimePassesPerRun = false; 970 else if (Val == "per-pass-run") 971 Opts.TimePassesPerRun = true; 972 else 973 Diags.Report(diag::err_drv_invalid_value) 974 << A->getAsString(Args) << A->getValue(); 975 } 976 } 977 978 Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ); 979 980 // Basic Block Sections implies Function Sections. 981 Opts.FunctionSections = 982 Args.hasArg(OPT_ffunction_sections) || 983 (Opts.BBSections != "none" && Opts.BBSections != "labels"); 984 985 Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ); 986 Opts.PrepareForThinLTO = false; 987 if (Arg *A = Args.getLastArg(OPT_flto_EQ)) { 988 StringRef S = A->getValue(); 989 if (S == "thin") 990 Opts.PrepareForThinLTO = true; 991 else if (S != "full") 992 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S; 993 } 994 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) { 995 if (IK.getLanguage() != Language::LLVM_IR) 996 Diags.Report(diag::err_drv_argument_only_allowed_with) 997 << A->getAsString(Args) << "-x ir"; 998 Opts.ThinLTOIndexFile = 999 std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ)); 1000 } 1001 if (Arg *A = Args.getLastArg(OPT_save_temps_EQ)) 1002 Opts.SaveTempsFilePrefix = 1003 llvm::StringSwitch<std::string>(A->getValue()) 1004 .Case("obj", FrontendOpts.OutputFile) 1005 .Default(llvm::sys::path::filename(FrontendOpts.OutputFile).str()); 1006 1007 // The memory profile runtime appends the pid to make this name more unique. 1008 const char *MemProfileBasename = "memprof.profraw"; 1009 if (Args.hasArg(OPT_fmemory_profile_EQ)) { 1010 SmallString<128> Path( 1011 std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ))); 1012 llvm::sys::path::append(Path, MemProfileBasename); 1013 Opts.MemoryProfileOutput = std::string(Path); 1014 } else if (Args.hasArg(OPT_fmemory_profile)) 1015 Opts.MemoryProfileOutput = MemProfileBasename; 1016 1017 if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) { 1018 Opts.CoverageDataFile = 1019 std::string(Args.getLastArgValue(OPT_coverage_data_file)); 1020 Opts.CoverageNotesFile = 1021 std::string(Args.getLastArgValue(OPT_coverage_notes_file)); 1022 Opts.ProfileFilterFiles = 1023 std::string(Args.getLastArgValue(OPT_fprofile_filter_files_EQ)); 1024 Opts.ProfileExcludeFiles = 1025 std::string(Args.getLastArgValue(OPT_fprofile_exclude_files_EQ)); 1026 if (Args.hasArg(OPT_coverage_version_EQ)) { 1027 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ); 1028 if (CoverageVersion.size() != 4) { 1029 Diags.Report(diag::err_drv_invalid_value) 1030 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args) 1031 << CoverageVersion; 1032 } else { 1033 memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4); 1034 } 1035 } 1036 } 1037 // FIXME: For backend options that are not yet recorded as function 1038 // attributes in the IR, keep track of them so we can embed them in a 1039 // separate data section and use them when building the bitcode. 1040 for (const auto &A : Args) { 1041 // Do not encode output and input. 1042 if (A->getOption().getID() == options::OPT_o || 1043 A->getOption().getID() == options::OPT_INPUT || 1044 A->getOption().getID() == options::OPT_x || 1045 A->getOption().getID() == options::OPT_fembed_bitcode || 1046 A->getOption().matches(options::OPT_W_Group)) 1047 continue; 1048 ArgStringList ASL; 1049 A->render(Args, ASL); 1050 for (const auto &arg : ASL) { 1051 StringRef ArgStr(arg); 1052 Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end()); 1053 // using \00 to separate each commandline options. 1054 Opts.CmdArgs.push_back('\0'); 1055 } 1056 } 1057 1058 Opts.XRayTotalFunctionGroups = 1059 getLastArgIntValue(Args, OPT_fxray_function_groups, 1, Diags); 1060 Opts.XRaySelectedFunctionGroup = 1061 getLastArgIntValue(Args, OPT_fxray_selected_function_group, 0, Diags); 1062 1063 auto XRayInstrBundles = 1064 Args.getAllArgValues(OPT_fxray_instrumentation_bundle); 1065 if (XRayInstrBundles.empty()) 1066 Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All; 1067 else 1068 for (const auto &A : XRayInstrBundles) 1069 parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args, 1070 Diags, Opts.XRayInstrumentationBundle); 1071 1072 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 1073 StringRef Name = A->getValue(); 1074 if (Name == "full") { 1075 Opts.CFProtectionReturn = 1; 1076 Opts.CFProtectionBranch = 1; 1077 } else if (Name == "return") 1078 Opts.CFProtectionReturn = 1; 1079 else if (Name == "branch") 1080 Opts.CFProtectionBranch = 1; 1081 else if (Name != "none") { 1082 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 1083 Success = false; 1084 } 1085 } 1086 1087 if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections_EQ)) { 1088 auto DCT = llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue()) 1089 .Case("none", llvm::DebugCompressionType::None) 1090 .Case("zlib", llvm::DebugCompressionType::Z) 1091 .Case("zlib-gnu", llvm::DebugCompressionType::GNU) 1092 .Default(llvm::DebugCompressionType::None); 1093 Opts.setCompressDebugSections(DCT); 1094 } 1095 1096 for (auto *A : 1097 Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) { 1098 CodeGenOptions::BitcodeFileToLink F; 1099 F.Filename = A->getValue(); 1100 if (A->getOption().matches(OPT_mlink_builtin_bitcode)) { 1101 F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded; 1102 // When linking CUDA bitcode, propagate function attributes so that 1103 // e.g. libdevice gets fast-math attrs if we're building with fast-math. 1104 F.PropagateAttrs = true; 1105 F.Internalize = true; 1106 } 1107 Opts.LinkBitcodeFiles.push_back(F); 1108 } 1109 Opts.SanitizeCoverageAllowlistFiles = 1110 Args.getAllArgValues(OPT_fsanitize_coverage_allowlist); 1111 Opts.SanitizeCoverageBlocklistFiles = 1112 Args.getAllArgValues(OPT_fsanitize_coverage_blocklist); 1113 Opts.SSPBufferSize = 1114 getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags); 1115 1116 Opts.StackProtectorGuard = 1117 std::string(Args.getLastArgValue(OPT_mstack_protector_guard_EQ)); 1118 1119 if (Arg *A = Args.getLastArg(OPT_mstack_protector_guard_offset_EQ)) { 1120 StringRef Val = A->getValue(); 1121 unsigned Offset = Opts.StackProtectorGuardOffset; 1122 Val.getAsInteger(10, Offset); 1123 Opts.StackProtectorGuardOffset = Offset; 1124 } 1125 1126 Opts.StackProtectorGuardReg = 1127 std::string(Args.getLastArgValue(OPT_mstack_protector_guard_reg_EQ, 1128 "none")); 1129 1130 1131 if (Args.getLastArg(OPT_femulated_tls) || 1132 Args.getLastArg(OPT_fno_emulated_tls)) { 1133 Opts.ExplicitEmulatedTLS = true; 1134 Opts.EmulatedTLS = 1135 Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false); 1136 } 1137 1138 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) { 1139 StringRef Val = A->getValue(); 1140 Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val); 1141 if (!Opts.FPDenormalMode.isValid()) 1142 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 1143 } 1144 1145 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) { 1146 StringRef Val = A->getValue(); 1147 Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val); 1148 if (!Opts.FP32DenormalMode.isValid()) 1149 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 1150 } 1151 1152 // X86_32 has -fppc-struct-return and -freg-struct-return. 1153 // PPC32 has -maix-struct-return and -msvr4-struct-return. 1154 if (Arg *A = 1155 Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return, 1156 OPT_maix_struct_return, OPT_msvr4_struct_return)) { 1157 // TODO: We might want to consider enabling these options on AIX in the 1158 // future. 1159 if (T.isOSAIX()) 1160 Diags.Report(diag::err_drv_unsupported_opt_for_target) 1161 << A->getSpelling() << T.str(); 1162 1163 const Option &O = A->getOption(); 1164 if (O.matches(OPT_fpcc_struct_return) || 1165 O.matches(OPT_maix_struct_return)) { 1166 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack); 1167 } else { 1168 assert(O.matches(OPT_freg_struct_return) || 1169 O.matches(OPT_msvr4_struct_return)); 1170 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs); 1171 } 1172 } 1173 1174 if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility) || 1175 !Args.hasArg(OPT_fvisibility))) 1176 Opts.IgnoreXCOFFVisibility = 1; 1177 1178 if (Arg *A = 1179 Args.getLastArg(OPT_mabi_EQ_vec_default, OPT_mabi_EQ_vec_extabi)) { 1180 if (!T.isOSAIX()) 1181 Diags.Report(diag::err_drv_unsupported_opt_for_target) 1182 << A->getSpelling() << T.str(); 1183 1184 const Option &O = A->getOption(); 1185 if (O.matches(OPT_mabi_EQ_vec_default)) 1186 Diags.Report(diag::err_aix_default_altivec_abi) 1187 << A->getSpelling() << T.str(); 1188 else { 1189 assert(O.matches(OPT_mabi_EQ_vec_extabi)); 1190 Opts.EnableAIXExtendedAltivecABI = 1; 1191 } 1192 } 1193 1194 Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib); 1195 Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option); 1196 bool NeedLocTracking = false; 1197 1198 if (!Opts.OptRecordFile.empty()) 1199 NeedLocTracking = true; 1200 1201 if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) { 1202 Opts.OptRecordPasses = A->getValue(); 1203 NeedLocTracking = true; 1204 } 1205 1206 if (Arg *A = Args.getLastArg(OPT_opt_record_format)) { 1207 Opts.OptRecordFormat = A->getValue(); 1208 NeedLocTracking = true; 1209 } 1210 1211 if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) { 1212 Opts.OptimizationRemarkPattern = 1213 GenerateOptimizationRemarkRegex(Diags, Args, A); 1214 NeedLocTracking = true; 1215 } 1216 1217 if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) { 1218 Opts.OptimizationRemarkMissedPattern = 1219 GenerateOptimizationRemarkRegex(Diags, Args, A); 1220 NeedLocTracking = true; 1221 } 1222 1223 if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) { 1224 Opts.OptimizationRemarkAnalysisPattern = 1225 GenerateOptimizationRemarkRegex(Diags, Args, A); 1226 NeedLocTracking = true; 1227 } 1228 1229 bool UsingSampleProfile = !Opts.SampleProfileFile.empty(); 1230 bool UsingProfile = UsingSampleProfile || 1231 (Opts.getProfileUse() != CodeGenOptions::ProfileNone); 1232 1233 if (Opts.DiagnosticsWithHotness && !UsingProfile && 1234 // An IR file will contain PGO as metadata 1235 IK.getLanguage() != Language::LLVM_IR) 1236 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) 1237 << "-fdiagnostics-show-hotness"; 1238 1239 // Parse remarks hotness threshold. Valid value is either integer or 'auto'. 1240 if (auto *arg = 1241 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) { 1242 auto ResultOrErr = 1243 llvm::remarks::parseHotnessThresholdOption(arg->getValue()); 1244 1245 if (!ResultOrErr) { 1246 Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold) 1247 << "-fdiagnostics-hotness-threshold="; 1248 } else { 1249 Opts.DiagnosticsHotnessThreshold = *ResultOrErr; 1250 if ((!Opts.DiagnosticsHotnessThreshold.hasValue() || 1251 Opts.DiagnosticsHotnessThreshold.getValue() > 0) && 1252 !UsingProfile) 1253 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) 1254 << "-fdiagnostics-hotness-threshold="; 1255 } 1256 } 1257 1258 // If the user requested to use a sample profile for PGO, then the 1259 // backend will need to track source location information so the profile 1260 // can be incorporated into the IR. 1261 if (UsingSampleProfile) 1262 NeedLocTracking = true; 1263 1264 // If the user requested a flag that requires source locations available in 1265 // the backend, make sure that the backend tracks source location information. 1266 if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo) 1267 Opts.setDebugInfo(codegenoptions::LocTrackingOnly); 1268 1269 Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file); 1270 1271 // Parse -fsanitize-recover= arguments. 1272 // FIXME: Report unrecoverable sanitizers incorrectly specified here. 1273 parseSanitizerKinds("-fsanitize-recover=", 1274 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags, 1275 Opts.SanitizeRecover); 1276 parseSanitizerKinds("-fsanitize-trap=", 1277 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags, 1278 Opts.SanitizeTrap); 1279 1280 Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true); 1281 1282 Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr); 1283 1284 Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ); 1285 1286 return Success; 1287 } 1288 1289 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts, 1290 ArgList &Args) { 1291 Opts.Targets = Args.getAllArgValues(OPT_MT); 1292 if (Args.hasArg(OPT_show_includes)) { 1293 // Writing both /showIncludes and preprocessor output to stdout 1294 // would produce interleaved output, so use stderr for /showIncludes. 1295 // This behaves the same as cl.exe, when /E, /EP or /P are passed. 1296 if (Args.hasArg(options::OPT_E) || Args.hasArg(options::OPT_P)) 1297 Opts.ShowIncludesDest = ShowIncludesDestination::Stderr; 1298 else 1299 Opts.ShowIncludesDest = ShowIncludesDestination::Stdout; 1300 } else { 1301 Opts.ShowIncludesDest = ShowIncludesDestination::None; 1302 } 1303 // Add sanitizer blacklists as extra dependencies. 1304 // They won't be discovered by the regular preprocessor, so 1305 // we let make / ninja to know about this implicit dependency. 1306 if (!Args.hasArg(OPT_fno_sanitize_blacklist)) { 1307 for (const auto *A : Args.filtered(OPT_fsanitize_blacklist)) { 1308 StringRef Val = A->getValue(); 1309 if (Val.find('=') == StringRef::npos) 1310 Opts.ExtraDeps.push_back(std::string(Val)); 1311 } 1312 if (Opts.IncludeSystemHeaders) { 1313 for (const auto *A : Args.filtered(OPT_fsanitize_system_blacklist)) { 1314 StringRef Val = A->getValue(); 1315 if (Val.find('=') == StringRef::npos) 1316 Opts.ExtraDeps.push_back(std::string(Val)); 1317 } 1318 } 1319 } 1320 1321 // Propagate the extra dependencies. 1322 for (const auto *A : Args.filtered(OPT_fdepfile_entry)) { 1323 Opts.ExtraDeps.push_back(A->getValue()); 1324 } 1325 1326 // Only the -fmodule-file=<file> form. 1327 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 1328 StringRef Val = A->getValue(); 1329 if (Val.find('=') == StringRef::npos) 1330 Opts.ExtraDeps.push_back(std::string(Val)); 1331 } 1332 } 1333 1334 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) { 1335 // Color diagnostics default to auto ("on" if terminal supports) in the driver 1336 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color. 1337 // Support both clang's -f[no-]color-diagnostics and gcc's 1338 // -f[no-]diagnostics-colors[=never|always|auto]. 1339 enum { 1340 Colors_On, 1341 Colors_Off, 1342 Colors_Auto 1343 } ShowColors = DefaultColor ? Colors_Auto : Colors_Off; 1344 for (auto *A : Args) { 1345 const Option &O = A->getOption(); 1346 if (O.matches(options::OPT_fcolor_diagnostics) || 1347 O.matches(options::OPT_fdiagnostics_color)) { 1348 ShowColors = Colors_On; 1349 } else if (O.matches(options::OPT_fno_color_diagnostics) || 1350 O.matches(options::OPT_fno_diagnostics_color)) { 1351 ShowColors = Colors_Off; 1352 } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) { 1353 StringRef Value(A->getValue()); 1354 if (Value == "always") 1355 ShowColors = Colors_On; 1356 else if (Value == "never") 1357 ShowColors = Colors_Off; 1358 else if (Value == "auto") 1359 ShowColors = Colors_Auto; 1360 } 1361 } 1362 return ShowColors == Colors_On || 1363 (ShowColors == Colors_Auto && 1364 llvm::sys::Process::StandardErrHasColors()); 1365 } 1366 1367 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes, 1368 DiagnosticsEngine *Diags) { 1369 bool Success = true; 1370 for (const auto &Prefix : VerifyPrefixes) { 1371 // Every prefix must start with a letter and contain only alphanumeric 1372 // characters, hyphens, and underscores. 1373 auto BadChar = llvm::find_if(Prefix, [](char C) { 1374 return !isAlphanumeric(C) && C != '-' && C != '_'; 1375 }); 1376 if (BadChar != Prefix.end() || !isLetter(Prefix[0])) { 1377 Success = false; 1378 if (Diags) { 1379 Diags->Report(diag::err_drv_invalid_value) << "-verify=" << Prefix; 1380 Diags->Report(diag::note_drv_verify_prefix_spelling); 1381 } 1382 } 1383 } 1384 return Success; 1385 } 1386 1387 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args, 1388 DiagnosticsEngine *Diags, 1389 bool DefaultDiagColor) { 1390 bool Success = true; 1391 1392 Opts.DiagnosticLogFile = 1393 std::string(Args.getLastArgValue(OPT_diagnostic_log_file)); 1394 if (Arg *A = 1395 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags)) 1396 Opts.DiagnosticSerializationFile = A->getValue(); 1397 Opts.IgnoreWarnings = Args.hasArg(OPT_w); 1398 Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros); 1399 Opts.Pedantic = Args.hasArg(OPT_pedantic); 1400 Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors); 1401 Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics); 1402 Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor); 1403 Opts.ShowColumn = !Args.hasArg(OPT_fno_show_column); 1404 Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info); 1405 Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location); 1406 Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths); 1407 Opts.ShowOptionNames = !Args.hasArg(OPT_fno_diagnostics_show_option); 1408 1409 // Default behavior is to not to show note include stacks. 1410 Opts.ShowNoteIncludeStack = false; 1411 if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack, 1412 OPT_fno_diagnostics_show_note_include_stack)) 1413 if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack)) 1414 Opts.ShowNoteIncludeStack = true; 1415 1416 StringRef ShowOverloads = 1417 Args.getLastArgValue(OPT_fshow_overloads_EQ, "all"); 1418 if (ShowOverloads == "best") 1419 Opts.setShowOverloads(Ovl_Best); 1420 else if (ShowOverloads == "all") 1421 Opts.setShowOverloads(Ovl_All); 1422 else { 1423 Success = false; 1424 if (Diags) 1425 Diags->Report(diag::err_drv_invalid_value) 1426 << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args) 1427 << ShowOverloads; 1428 } 1429 1430 StringRef ShowCategory = 1431 Args.getLastArgValue(OPT_fdiagnostics_show_category, "none"); 1432 if (ShowCategory == "none") 1433 Opts.ShowCategories = 0; 1434 else if (ShowCategory == "id") 1435 Opts.ShowCategories = 1; 1436 else if (ShowCategory == "name") 1437 Opts.ShowCategories = 2; 1438 else { 1439 Success = false; 1440 if (Diags) 1441 Diags->Report(diag::err_drv_invalid_value) 1442 << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args) 1443 << ShowCategory; 1444 } 1445 1446 StringRef Format = 1447 Args.getLastArgValue(OPT_fdiagnostics_format, "clang"); 1448 if (Format == "clang") 1449 Opts.setFormat(DiagnosticOptions::Clang); 1450 else if (Format == "msvc") 1451 Opts.setFormat(DiagnosticOptions::MSVC); 1452 else if (Format == "msvc-fallback") { 1453 Opts.setFormat(DiagnosticOptions::MSVC); 1454 Opts.CLFallbackMode = true; 1455 } else if (Format == "vi") 1456 Opts.setFormat(DiagnosticOptions::Vi); 1457 else { 1458 Success = false; 1459 if (Diags) 1460 Diags->Report(diag::err_drv_invalid_value) 1461 << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args) 1462 << Format; 1463 } 1464 1465 Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info); 1466 Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits); 1467 Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location); 1468 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ); 1469 Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ); 1470 if (Args.hasArg(OPT_verify)) 1471 Opts.VerifyPrefixes.push_back("expected"); 1472 // Keep VerifyPrefixes in its original order for the sake of diagnostics, and 1473 // then sort it to prepare for fast lookup using std::binary_search. 1474 if (!checkVerifyPrefixes(Opts.VerifyPrefixes, Diags)) { 1475 Opts.VerifyDiagnostics = false; 1476 Success = false; 1477 } 1478 else 1479 llvm::sort(Opts.VerifyPrefixes); 1480 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None; 1481 Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=", 1482 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), 1483 Diags, DiagMask); 1484 if (Args.hasArg(OPT_verify_ignore_unexpected)) 1485 DiagMask = DiagnosticLevelMask::All; 1486 Opts.setVerifyIgnoreUnexpected(DiagMask); 1487 Opts.ElideType = !Args.hasArg(OPT_fno_elide_type); 1488 Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree); 1489 Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags); 1490 Opts.MacroBacktraceLimit = 1491 getLastArgIntValue(Args, OPT_fmacro_backtrace_limit, 1492 DiagnosticOptions::DefaultMacroBacktraceLimit, Diags); 1493 Opts.TemplateBacktraceLimit = getLastArgIntValue( 1494 Args, OPT_ftemplate_backtrace_limit, 1495 DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags); 1496 Opts.ConstexprBacktraceLimit = getLastArgIntValue( 1497 Args, OPT_fconstexpr_backtrace_limit, 1498 DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags); 1499 Opts.SpellCheckingLimit = getLastArgIntValue( 1500 Args, OPT_fspell_checking_limit, 1501 DiagnosticOptions::DefaultSpellCheckingLimit, Diags); 1502 Opts.SnippetLineLimit = getLastArgIntValue( 1503 Args, OPT_fcaret_diagnostics_max_lines, 1504 DiagnosticOptions::DefaultSnippetLineLimit, Diags); 1505 Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop, 1506 DiagnosticOptions::DefaultTabStop, Diags); 1507 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) { 1508 Opts.TabStop = DiagnosticOptions::DefaultTabStop; 1509 if (Diags) 1510 Diags->Report(diag::warn_ignoring_ftabstop_value) 1511 << Opts.TabStop << DiagnosticOptions::DefaultTabStop; 1512 } 1513 Opts.MessageLength = 1514 getLastArgIntValue(Args, OPT_fmessage_length_EQ, 0, Diags); 1515 1516 Opts.UndefPrefixes = Args.getAllArgValues(OPT_Wundef_prefix_EQ); 1517 1518 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings); 1519 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks); 1520 1521 return Success; 1522 } 1523 1524 /// Parse the argument to the -ftest-module-file-extension 1525 /// command-line argument. 1526 /// 1527 /// \returns true on error, false on success. 1528 static bool parseTestModuleFileExtensionArg(StringRef Arg, 1529 std::string &BlockName, 1530 unsigned &MajorVersion, 1531 unsigned &MinorVersion, 1532 bool &Hashed, 1533 std::string &UserInfo) { 1534 SmallVector<StringRef, 5> Args; 1535 Arg.split(Args, ':', 5); 1536 if (Args.size() < 5) 1537 return true; 1538 1539 BlockName = std::string(Args[0]); 1540 if (Args[1].getAsInteger(10, MajorVersion)) return true; 1541 if (Args[2].getAsInteger(10, MinorVersion)) return true; 1542 if (Args[3].getAsInteger(2, Hashed)) return true; 1543 if (Args.size() > 4) 1544 UserInfo = std::string(Args[4]); 1545 return false; 1546 } 1547 1548 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, 1549 DiagnosticsEngine &Diags, 1550 bool &IsHeaderFile) { 1551 Opts.ProgramAction = frontend::ParseSyntaxOnly; 1552 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) { 1553 switch (A->getOption().getID()) { 1554 default: 1555 llvm_unreachable("Invalid option in group!"); 1556 case OPT_ast_list: 1557 Opts.ProgramAction = frontend::ASTDeclList; break; 1558 case OPT_ast_dump_all_EQ: 1559 case OPT_ast_dump_EQ: { 1560 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue()) 1561 .CaseLower("default", ADOF_Default) 1562 .CaseLower("json", ADOF_JSON) 1563 .Default(std::numeric_limits<unsigned>::max()); 1564 1565 if (Val != std::numeric_limits<unsigned>::max()) 1566 Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val); 1567 else { 1568 Diags.Report(diag::err_drv_invalid_value) 1569 << A->getAsString(Args) << A->getValue(); 1570 Opts.ASTDumpFormat = ADOF_Default; 1571 } 1572 LLVM_FALLTHROUGH; 1573 } 1574 case OPT_ast_dump: 1575 case OPT_ast_dump_all: 1576 case OPT_ast_dump_lookups: 1577 case OPT_ast_dump_decl_types: 1578 Opts.ProgramAction = frontend::ASTDump; break; 1579 case OPT_ast_print: 1580 Opts.ProgramAction = frontend::ASTPrint; break; 1581 case OPT_ast_view: 1582 Opts.ProgramAction = frontend::ASTView; break; 1583 case OPT_compiler_options_dump: 1584 Opts.ProgramAction = frontend::DumpCompilerOptions; break; 1585 case OPT_dump_raw_tokens: 1586 Opts.ProgramAction = frontend::DumpRawTokens; break; 1587 case OPT_dump_tokens: 1588 Opts.ProgramAction = frontend::DumpTokens; break; 1589 case OPT_S: 1590 Opts.ProgramAction = frontend::EmitAssembly; break; 1591 case OPT_emit_llvm_bc: 1592 Opts.ProgramAction = frontend::EmitBC; break; 1593 case OPT_emit_html: 1594 Opts.ProgramAction = frontend::EmitHTML; break; 1595 case OPT_emit_llvm: 1596 Opts.ProgramAction = frontend::EmitLLVM; break; 1597 case OPT_emit_llvm_only: 1598 Opts.ProgramAction = frontend::EmitLLVMOnly; break; 1599 case OPT_emit_codegen_only: 1600 Opts.ProgramAction = frontend::EmitCodeGenOnly; break; 1601 case OPT_emit_obj: 1602 Opts.ProgramAction = frontend::EmitObj; break; 1603 case OPT_fixit_EQ: 1604 Opts.FixItSuffix = A->getValue(); 1605 LLVM_FALLTHROUGH; 1606 case OPT_fixit: 1607 Opts.ProgramAction = frontend::FixIt; break; 1608 case OPT_emit_module: 1609 Opts.ProgramAction = frontend::GenerateModule; break; 1610 case OPT_emit_module_interface: 1611 Opts.ProgramAction = frontend::GenerateModuleInterface; break; 1612 case OPT_emit_header_module: 1613 Opts.ProgramAction = frontend::GenerateHeaderModule; break; 1614 case OPT_emit_pch: 1615 Opts.ProgramAction = frontend::GeneratePCH; break; 1616 case OPT_emit_interface_stubs: { 1617 StringRef ArgStr = 1618 Args.hasArg(OPT_interface_stub_version_EQ) 1619 ? Args.getLastArgValue(OPT_interface_stub_version_EQ) 1620 : "experimental-ifs-v2"; 1621 if (ArgStr == "experimental-yaml-elf-v1" || 1622 ArgStr == "experimental-ifs-v1" || 1623 ArgStr == "experimental-tapi-elf-v1") { 1624 std::string ErrorMessage = 1625 "Invalid interface stub format: " + ArgStr.str() + 1626 " is deprecated."; 1627 Diags.Report(diag::err_drv_invalid_value) 1628 << "Must specify a valid interface stub format type, ie: " 1629 "-interface-stub-version=experimental-ifs-v2" 1630 << ErrorMessage; 1631 } else if (!ArgStr.startswith("experimental-ifs-")) { 1632 std::string ErrorMessage = 1633 "Invalid interface stub format: " + ArgStr.str() + "."; 1634 Diags.Report(diag::err_drv_invalid_value) 1635 << "Must specify a valid interface stub format type, ie: " 1636 "-interface-stub-version=experimental-ifs-v2" 1637 << ErrorMessage; 1638 } else { 1639 Opts.ProgramAction = frontend::GenerateInterfaceStubs; 1640 } 1641 break; 1642 } 1643 case OPT_init_only: 1644 Opts.ProgramAction = frontend::InitOnly; break; 1645 case OPT_fsyntax_only: 1646 Opts.ProgramAction = frontend::ParseSyntaxOnly; break; 1647 case OPT_module_file_info: 1648 Opts.ProgramAction = frontend::ModuleFileInfo; break; 1649 case OPT_verify_pch: 1650 Opts.ProgramAction = frontend::VerifyPCH; break; 1651 case OPT_print_preamble: 1652 Opts.ProgramAction = frontend::PrintPreamble; break; 1653 case OPT_E: 1654 Opts.ProgramAction = frontend::PrintPreprocessedInput; break; 1655 case OPT_templight_dump: 1656 Opts.ProgramAction = frontend::TemplightDump; break; 1657 case OPT_rewrite_macros: 1658 Opts.ProgramAction = frontend::RewriteMacros; break; 1659 case OPT_rewrite_objc: 1660 Opts.ProgramAction = frontend::RewriteObjC; break; 1661 case OPT_rewrite_test: 1662 Opts.ProgramAction = frontend::RewriteTest; break; 1663 case OPT_analyze: 1664 Opts.ProgramAction = frontend::RunAnalysis; break; 1665 case OPT_migrate: 1666 Opts.ProgramAction = frontend::MigrateSource; break; 1667 case OPT_Eonly: 1668 Opts.ProgramAction = frontend::RunPreprocessorOnly; break; 1669 case OPT_print_dependency_directives_minimized_source: 1670 Opts.ProgramAction = 1671 frontend::PrintDependencyDirectivesSourceMinimizerOutput; 1672 break; 1673 } 1674 } 1675 1676 if (const Arg* A = Args.getLastArg(OPT_plugin)) { 1677 Opts.Plugins.emplace_back(A->getValue(0)); 1678 Opts.ProgramAction = frontend::PluginAction; 1679 Opts.ActionName = A->getValue(); 1680 } 1681 Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin); 1682 for (const auto *AA : Args.filtered(OPT_plugin_arg)) 1683 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1)); 1684 1685 for (const std::string &Arg : 1686 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) { 1687 std::string BlockName; 1688 unsigned MajorVersion; 1689 unsigned MinorVersion; 1690 bool Hashed; 1691 std::string UserInfo; 1692 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion, 1693 MinorVersion, Hashed, UserInfo)) { 1694 Diags.Report(diag::err_test_module_file_extension_format) << Arg; 1695 1696 continue; 1697 } 1698 1699 // Add the testing module file extension. 1700 Opts.ModuleFileExtensions.push_back( 1701 std::make_shared<TestModuleFileExtension>( 1702 BlockName, MajorVersion, MinorVersion, Hashed, UserInfo)); 1703 } 1704 1705 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) { 1706 Opts.CodeCompletionAt = 1707 ParsedSourceLocation::FromString(A->getValue()); 1708 if (Opts.CodeCompletionAt.FileName.empty()) 1709 Diags.Report(diag::err_drv_invalid_value) 1710 << A->getAsString(Args) << A->getValue(); 1711 } 1712 1713 Opts.Plugins = Args.getAllArgValues(OPT_load); 1714 Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge); 1715 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm); 1716 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ); 1717 Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ); 1718 Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file); 1719 // Only the -fmodule-file=<file> form. 1720 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 1721 StringRef Val = A->getValue(); 1722 if (Val.find('=') == StringRef::npos) 1723 Opts.ModuleFiles.push_back(std::string(Val)); 1724 } 1725 Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ); 1726 Opts.AllowPCMWithCompilerErrors = Args.hasArg(OPT_fallow_pcm_with_errors); 1727 1728 if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule) 1729 Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module" 1730 << "-emit-module"; 1731 1732 if (Args.hasArg(OPT_aux_target_cpu)) 1733 Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu)); 1734 if (Args.hasArg(OPT_aux_target_feature)) 1735 Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature); 1736 1737 if (Opts.ARCMTAction != FrontendOptions::ARCMT_None && 1738 Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) { 1739 Diags.Report(diag::err_drv_argument_not_allowed_with) 1740 << "ARC migration" << "ObjC migration"; 1741 } 1742 1743 InputKind DashX(Language::Unknown); 1744 if (const Arg *A = Args.getLastArg(OPT_x)) { 1745 StringRef XValue = A->getValue(); 1746 1747 // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'. 1748 // FIXME: Supporting '<lang>-header-cpp-output' would be useful. 1749 bool Preprocessed = XValue.consume_back("-cpp-output"); 1750 bool ModuleMap = XValue.consume_back("-module-map"); 1751 IsHeaderFile = !Preprocessed && !ModuleMap && 1752 XValue != "precompiled-header" && 1753 XValue.consume_back("-header"); 1754 1755 // Principal languages. 1756 DashX = llvm::StringSwitch<InputKind>(XValue) 1757 .Case("c", Language::C) 1758 .Case("cl", Language::OpenCL) 1759 .Case("cuda", Language::CUDA) 1760 .Case("hip", Language::HIP) 1761 .Case("c++", Language::CXX) 1762 .Case("objective-c", Language::ObjC) 1763 .Case("objective-c++", Language::ObjCXX) 1764 .Case("renderscript", Language::RenderScript) 1765 .Default(Language::Unknown); 1766 1767 // "objc[++]-cpp-output" is an acceptable synonym for 1768 // "objective-c[++]-cpp-output". 1769 if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap) 1770 DashX = llvm::StringSwitch<InputKind>(XValue) 1771 .Case("objc", Language::ObjC) 1772 .Case("objc++", Language::ObjCXX) 1773 .Default(Language::Unknown); 1774 1775 // Some special cases cannot be combined with suffixes. 1776 if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile) 1777 DashX = llvm::StringSwitch<InputKind>(XValue) 1778 .Case("cpp-output", InputKind(Language::C).getPreprocessed()) 1779 .Case("assembler-with-cpp", Language::Asm) 1780 .Cases("ast", "pcm", "precompiled-header", 1781 InputKind(Language::Unknown, InputKind::Precompiled)) 1782 .Case("ir", Language::LLVM_IR) 1783 .Default(Language::Unknown); 1784 1785 if (DashX.isUnknown()) 1786 Diags.Report(diag::err_drv_invalid_value) 1787 << A->getAsString(Args) << A->getValue(); 1788 1789 if (Preprocessed) 1790 DashX = DashX.getPreprocessed(); 1791 if (ModuleMap) 1792 DashX = DashX.withFormat(InputKind::ModuleMap); 1793 } 1794 1795 // '-' is the default input if none is given. 1796 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT); 1797 Opts.Inputs.clear(); 1798 if (Inputs.empty()) 1799 Inputs.push_back("-"); 1800 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { 1801 InputKind IK = DashX; 1802 if (IK.isUnknown()) { 1803 IK = FrontendOptions::getInputKindForExtension( 1804 StringRef(Inputs[i]).rsplit('.').second); 1805 // FIXME: Warn on this? 1806 if (IK.isUnknown()) 1807 IK = Language::C; 1808 // FIXME: Remove this hack. 1809 if (i == 0) 1810 DashX = IK; 1811 } 1812 1813 bool IsSystem = false; 1814 1815 // The -emit-module action implicitly takes a module map. 1816 if (Opts.ProgramAction == frontend::GenerateModule && 1817 IK.getFormat() == InputKind::Source) { 1818 IK = IK.withFormat(InputKind::ModuleMap); 1819 IsSystem = Opts.IsSystemModule; 1820 } 1821 1822 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem); 1823 } 1824 1825 return DashX; 1826 } 1827 1828 std::string CompilerInvocation::GetResourcesPath(const char *Argv0, 1829 void *MainAddr) { 1830 std::string ClangExecutable = 1831 llvm::sys::fs::getMainExecutable(Argv0, MainAddr); 1832 return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR); 1833 } 1834 1835 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, 1836 const std::string &WorkingDir) { 1837 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ)) 1838 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0); 1839 1840 // Canonicalize -fmodules-cache-path before storing it. 1841 SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path)); 1842 if (!(P.empty() || llvm::sys::path::is_absolute(P))) { 1843 if (WorkingDir.empty()) 1844 llvm::sys::fs::make_absolute(P); 1845 else 1846 llvm::sys::fs::make_absolute(WorkingDir, P); 1847 } 1848 llvm::sys::path::remove_dots(P); 1849 Opts.ModuleCachePath = std::string(P.str()); 1850 1851 // Only the -fmodule-file=<name>=<file> form. 1852 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 1853 StringRef Val = A->getValue(); 1854 if (Val.find('=') != StringRef::npos){ 1855 auto Split = Val.split('='); 1856 Opts.PrebuiltModuleFiles.insert( 1857 {std::string(Split.first), std::string(Split.second)}); 1858 } 1859 } 1860 for (const auto *A : Args.filtered(OPT_fprebuilt_module_path)) 1861 Opts.AddPrebuiltModulePath(A->getValue()); 1862 1863 for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) { 1864 StringRef MacroDef = A->getValue(); 1865 Opts.ModulesIgnoreMacros.insert( 1866 llvm::CachedHashString(MacroDef.split('=').first)); 1867 } 1868 1869 // Add -I..., -F..., and -index-header-map options in order. 1870 bool IsIndexHeaderMap = false; 1871 bool IsSysrootSpecified = 1872 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot); 1873 for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) { 1874 if (A->getOption().matches(OPT_index_header_map)) { 1875 // -index-header-map applies to the next -I or -F. 1876 IsIndexHeaderMap = true; 1877 continue; 1878 } 1879 1880 frontend::IncludeDirGroup Group = 1881 IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled; 1882 1883 bool IsFramework = A->getOption().matches(OPT_F); 1884 std::string Path = A->getValue(); 1885 1886 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') { 1887 SmallString<32> Buffer; 1888 llvm::sys::path::append(Buffer, Opts.Sysroot, 1889 llvm::StringRef(A->getValue()).substr(1)); 1890 Path = std::string(Buffer.str()); 1891 } 1892 1893 Opts.AddPath(Path, Group, IsFramework, 1894 /*IgnoreSysroot*/ true); 1895 IsIndexHeaderMap = false; 1896 } 1897 1898 // Add -iprefix/-iwithprefix/-iwithprefixbefore options. 1899 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix. 1900 for (const auto *A : 1901 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) { 1902 if (A->getOption().matches(OPT_iprefix)) 1903 Prefix = A->getValue(); 1904 else if (A->getOption().matches(OPT_iwithprefix)) 1905 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true); 1906 else 1907 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true); 1908 } 1909 1910 for (const auto *A : Args.filtered(OPT_idirafter)) 1911 Opts.AddPath(A->getValue(), frontend::After, false, true); 1912 for (const auto *A : Args.filtered(OPT_iquote)) 1913 Opts.AddPath(A->getValue(), frontend::Quoted, false, true); 1914 for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot)) 1915 Opts.AddPath(A->getValue(), frontend::System, false, 1916 !A->getOption().matches(OPT_iwithsysroot)); 1917 for (const auto *A : Args.filtered(OPT_iframework)) 1918 Opts.AddPath(A->getValue(), frontend::System, true, true); 1919 for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot)) 1920 Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true, 1921 /*IgnoreSysRoot=*/false); 1922 1923 // Add the paths for the various language specific isystem flags. 1924 for (const auto *A : Args.filtered(OPT_c_isystem)) 1925 Opts.AddPath(A->getValue(), frontend::CSystem, false, true); 1926 for (const auto *A : Args.filtered(OPT_cxx_isystem)) 1927 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true); 1928 for (const auto *A : Args.filtered(OPT_objc_isystem)) 1929 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true); 1930 for (const auto *A : Args.filtered(OPT_objcxx_isystem)) 1931 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true); 1932 1933 // Add the internal paths from a driver that detects standard include paths. 1934 for (const auto *A : 1935 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) { 1936 frontend::IncludeDirGroup Group = frontend::System; 1937 if (A->getOption().matches(OPT_internal_externc_isystem)) 1938 Group = frontend::ExternCSystem; 1939 Opts.AddPath(A->getValue(), Group, false, true); 1940 } 1941 1942 // Add the path prefixes which are implicitly treated as being system headers. 1943 for (const auto *A : 1944 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix)) 1945 Opts.AddSystemHeaderPrefix( 1946 A->getValue(), A->getOption().matches(OPT_system_header_prefix)); 1947 1948 for (const auto *A : Args.filtered(OPT_ivfsoverlay)) 1949 Opts.AddVFSOverlayFile(A->getValue()); 1950 } 1951 1952 void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK, 1953 const llvm::Triple &T, 1954 PreprocessorOptions &PPOpts, 1955 LangStandard::Kind LangStd) { 1956 // Set some properties which depend solely on the input kind; it would be nice 1957 // to move these to the language standard, and have the driver resolve the 1958 // input kind + language standard. 1959 // 1960 // FIXME: Perhaps a better model would be for a single source file to have 1961 // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std) 1962 // simultaneously active? 1963 if (IK.getLanguage() == Language::Asm) { 1964 Opts.AsmPreprocessor = 1; 1965 } else if (IK.isObjectiveC()) { 1966 Opts.ObjC = 1; 1967 } 1968 1969 if (LangStd == LangStandard::lang_unspecified) { 1970 // Based on the base language, pick one. 1971 switch (IK.getLanguage()) { 1972 case Language::Unknown: 1973 case Language::LLVM_IR: 1974 llvm_unreachable("Invalid input kind!"); 1975 case Language::OpenCL: 1976 LangStd = LangStandard::lang_opencl10; 1977 break; 1978 case Language::CUDA: 1979 LangStd = LangStandard::lang_cuda; 1980 break; 1981 case Language::Asm: 1982 case Language::C: 1983 #if defined(CLANG_DEFAULT_STD_C) 1984 LangStd = CLANG_DEFAULT_STD_C; 1985 #else 1986 // The PS4 uses C99 as the default C standard. 1987 if (T.isPS4()) 1988 LangStd = LangStandard::lang_gnu99; 1989 else 1990 LangStd = LangStandard::lang_gnu17; 1991 #endif 1992 break; 1993 case Language::ObjC: 1994 #if defined(CLANG_DEFAULT_STD_C) 1995 LangStd = CLANG_DEFAULT_STD_C; 1996 #else 1997 LangStd = LangStandard::lang_gnu11; 1998 #endif 1999 break; 2000 case Language::CXX: 2001 case Language::ObjCXX: 2002 #if defined(CLANG_DEFAULT_STD_CXX) 2003 LangStd = CLANG_DEFAULT_STD_CXX; 2004 #else 2005 LangStd = LangStandard::lang_gnucxx14; 2006 #endif 2007 break; 2008 case Language::RenderScript: 2009 LangStd = LangStandard::lang_c99; 2010 break; 2011 case Language::HIP: 2012 LangStd = LangStandard::lang_hip; 2013 break; 2014 } 2015 } 2016 2017 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); 2018 Opts.LineComment = Std.hasLineComments(); 2019 Opts.C99 = Std.isC99(); 2020 Opts.C11 = Std.isC11(); 2021 Opts.C17 = Std.isC17(); 2022 Opts.C2x = Std.isC2x(); 2023 Opts.CPlusPlus = Std.isCPlusPlus(); 2024 Opts.CPlusPlus11 = Std.isCPlusPlus11(); 2025 Opts.CPlusPlus14 = Std.isCPlusPlus14(); 2026 Opts.CPlusPlus17 = Std.isCPlusPlus17(); 2027 Opts.CPlusPlus20 = Std.isCPlusPlus20(); 2028 Opts.CPlusPlus2b = Std.isCPlusPlus2b(); 2029 Opts.Digraphs = Std.hasDigraphs(); 2030 Opts.GNUMode = Std.isGNUMode(); 2031 Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus; 2032 Opts.GNUCVersion = 0; 2033 Opts.HexFloats = Std.hasHexFloats(); 2034 Opts.ImplicitInt = Std.hasImplicitInt(); 2035 2036 // Set OpenCL Version. 2037 Opts.OpenCL = Std.isOpenCL(); 2038 if (LangStd == LangStandard::lang_opencl10) 2039 Opts.OpenCLVersion = 100; 2040 else if (LangStd == LangStandard::lang_opencl11) 2041 Opts.OpenCLVersion = 110; 2042 else if (LangStd == LangStandard::lang_opencl12) 2043 Opts.OpenCLVersion = 120; 2044 else if (LangStd == LangStandard::lang_opencl20) 2045 Opts.OpenCLVersion = 200; 2046 else if (LangStd == LangStandard::lang_opencl30) 2047 Opts.OpenCLVersion = 300; 2048 else if (LangStd == LangStandard::lang_openclcpp) 2049 Opts.OpenCLCPlusPlusVersion = 100; 2050 2051 // OpenCL has some additional defaults. 2052 if (Opts.OpenCL) { 2053 Opts.AltiVec = 0; 2054 Opts.ZVector = 0; 2055 Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::None); 2056 Opts.setDefaultFPContractMode(LangOptions::FPM_On); 2057 Opts.NativeHalfType = 1; 2058 Opts.NativeHalfArgsAndReturns = 1; 2059 Opts.OpenCLCPlusPlus = Opts.CPlusPlus; 2060 2061 // Include default header file for OpenCL. 2062 if (Opts.IncludeDefaultHeader) { 2063 if (Opts.DeclareOpenCLBuiltins) { 2064 // Only include base header file for builtin types and constants. 2065 PPOpts.Includes.push_back("opencl-c-base.h"); 2066 } else { 2067 PPOpts.Includes.push_back("opencl-c.h"); 2068 } 2069 } 2070 } 2071 2072 Opts.HIP = IK.getLanguage() == Language::HIP; 2073 Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP; 2074 if (Opts.HIP) { 2075 // HIP toolchain does not support 'Fast' FPOpFusion in backends since it 2076 // fuses multiplication/addition instructions without contract flag from 2077 // device library functions in LLVM bitcode, which causes accuracy loss in 2078 // certain math functions, e.g. tan(-1e20) becomes -0.933 instead of 0.8446. 2079 // For device library functions in bitcode to work, 'Strict' or 'Standard' 2080 // FPOpFusion options in backends is needed. Therefore 'fast-honor-pragmas' 2081 // FP contract option is used to allow fuse across statements in frontend 2082 // whereas respecting contract flag in backend. 2083 Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas); 2084 } else if (Opts.CUDA) { 2085 // Allow fuse across statements disregarding pragmas. 2086 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast); 2087 } 2088 2089 Opts.RenderScript = IK.getLanguage() == Language::RenderScript; 2090 if (Opts.RenderScript) { 2091 Opts.NativeHalfType = 1; 2092 Opts.NativeHalfArgsAndReturns = 1; 2093 } 2094 2095 // OpenCL and C++ both have bool, true, false keywords. 2096 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus; 2097 2098 // OpenCL has half keyword 2099 Opts.Half = Opts.OpenCL; 2100 2101 // C++ has wchar_t keyword. 2102 Opts.WChar = Opts.CPlusPlus; 2103 2104 Opts.GNUKeywords = Opts.GNUMode; 2105 Opts.CXXOperatorNames = Opts.CPlusPlus; 2106 2107 Opts.AlignedAllocation = Opts.CPlusPlus17; 2108 2109 Opts.DollarIdents = !Opts.AsmPreprocessor; 2110 2111 // Enable [[]] attributes in C++11 and C2x by default. 2112 Opts.DoubleSquareBracketAttributes = Opts.CPlusPlus11 || Opts.C2x; 2113 } 2114 2115 /// Attempt to parse a visibility value out of the given argument. 2116 static Visibility parseVisibility(Arg *arg, ArgList &args, 2117 DiagnosticsEngine &diags) { 2118 StringRef value = arg->getValue(); 2119 if (value == "default") { 2120 return DefaultVisibility; 2121 } else if (value == "hidden" || value == "internal") { 2122 return HiddenVisibility; 2123 } else if (value == "protected") { 2124 // FIXME: diagnose if target does not support protected visibility 2125 return ProtectedVisibility; 2126 } 2127 2128 diags.Report(diag::err_drv_invalid_value) 2129 << arg->getAsString(args) << value; 2130 return DefaultVisibility; 2131 } 2132 2133 /// Check if input file kind and language standard are compatible. 2134 static bool IsInputCompatibleWithStandard(InputKind IK, 2135 const LangStandard &S) { 2136 switch (IK.getLanguage()) { 2137 case Language::Unknown: 2138 case Language::LLVM_IR: 2139 llvm_unreachable("should not parse language flags for this input"); 2140 2141 case Language::C: 2142 case Language::ObjC: 2143 case Language::RenderScript: 2144 return S.getLanguage() == Language::C; 2145 2146 case Language::OpenCL: 2147 return S.getLanguage() == Language::OpenCL; 2148 2149 case Language::CXX: 2150 case Language::ObjCXX: 2151 return S.getLanguage() == Language::CXX; 2152 2153 case Language::CUDA: 2154 // FIXME: What -std= values should be permitted for CUDA compilations? 2155 return S.getLanguage() == Language::CUDA || 2156 S.getLanguage() == Language::CXX; 2157 2158 case Language::HIP: 2159 return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP; 2160 2161 case Language::Asm: 2162 // Accept (and ignore) all -std= values. 2163 // FIXME: The -std= value is not ignored; it affects the tokenization 2164 // and preprocessing rules if we're preprocessing this asm input. 2165 return true; 2166 } 2167 2168 llvm_unreachable("unexpected input language"); 2169 } 2170 2171 /// Get language name for given input kind. 2172 static const StringRef GetInputKindName(InputKind IK) { 2173 switch (IK.getLanguage()) { 2174 case Language::C: 2175 return "C"; 2176 case Language::ObjC: 2177 return "Objective-C"; 2178 case Language::CXX: 2179 return "C++"; 2180 case Language::ObjCXX: 2181 return "Objective-C++"; 2182 case Language::OpenCL: 2183 return "OpenCL"; 2184 case Language::CUDA: 2185 return "CUDA"; 2186 case Language::RenderScript: 2187 return "RenderScript"; 2188 case Language::HIP: 2189 return "HIP"; 2190 2191 case Language::Asm: 2192 return "Asm"; 2193 case Language::LLVM_IR: 2194 return "LLVM IR"; 2195 2196 case Language::Unknown: 2197 break; 2198 } 2199 llvm_unreachable("unknown input language"); 2200 } 2201 2202 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, 2203 const TargetOptions &TargetOpts, 2204 PreprocessorOptions &PPOpts, 2205 DiagnosticsEngine &Diags) { 2206 // FIXME: Cleanup per-file based stuff. 2207 LangStandard::Kind LangStd = LangStandard::lang_unspecified; 2208 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) { 2209 LangStd = LangStandard::getLangKind(A->getValue()); 2210 if (LangStd == LangStandard::lang_unspecified) { 2211 Diags.Report(diag::err_drv_invalid_value) 2212 << A->getAsString(Args) << A->getValue(); 2213 // Report supported standards with short description. 2214 for (unsigned KindValue = 0; 2215 KindValue != LangStandard::lang_unspecified; 2216 ++KindValue) { 2217 const LangStandard &Std = LangStandard::getLangStandardForKind( 2218 static_cast<LangStandard::Kind>(KindValue)); 2219 if (IsInputCompatibleWithStandard(IK, Std)) { 2220 auto Diag = Diags.Report(diag::note_drv_use_standard); 2221 Diag << Std.getName() << Std.getDescription(); 2222 unsigned NumAliases = 0; 2223 #define LANGSTANDARD(id, name, lang, desc, features) 2224 #define LANGSTANDARD_ALIAS(id, alias) \ 2225 if (KindValue == LangStandard::lang_##id) ++NumAliases; 2226 #define LANGSTANDARD_ALIAS_DEPR(id, alias) 2227 #include "clang/Basic/LangStandards.def" 2228 Diag << NumAliases; 2229 #define LANGSTANDARD(id, name, lang, desc, features) 2230 #define LANGSTANDARD_ALIAS(id, alias) \ 2231 if (KindValue == LangStandard::lang_##id) Diag << alias; 2232 #define LANGSTANDARD_ALIAS_DEPR(id, alias) 2233 #include "clang/Basic/LangStandards.def" 2234 } 2235 } 2236 } else { 2237 // Valid standard, check to make sure language and standard are 2238 // compatible. 2239 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); 2240 if (!IsInputCompatibleWithStandard(IK, Std)) { 2241 Diags.Report(diag::err_drv_argument_not_allowed_with) 2242 << A->getAsString(Args) << GetInputKindName(IK); 2243 } 2244 } 2245 } 2246 2247 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 2248 StringRef Name = A->getValue(); 2249 if (Name == "full" || Name == "branch") { 2250 Opts.CFProtectionBranch = 1; 2251 } 2252 } 2253 // -cl-std only applies for OpenCL language standards. 2254 // Override the -std option in this case. 2255 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) { 2256 LangStandard::Kind OpenCLLangStd 2257 = llvm::StringSwitch<LangStandard::Kind>(A->getValue()) 2258 .Cases("cl", "CL", LangStandard::lang_opencl10) 2259 .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10) 2260 .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11) 2261 .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12) 2262 .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20) 2263 .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30) 2264 .Cases("clc++", "CLC++", LangStandard::lang_openclcpp) 2265 .Default(LangStandard::lang_unspecified); 2266 2267 if (OpenCLLangStd == LangStandard::lang_unspecified) { 2268 Diags.Report(diag::err_drv_invalid_value) 2269 << A->getAsString(Args) << A->getValue(); 2270 } 2271 else 2272 LangStd = OpenCLLangStd; 2273 } 2274 2275 Opts.SYCLIsDevice = Opts.SYCL && Args.hasArg(options::OPT_fsycl_is_device); 2276 if (Opts.SYCL) { 2277 // -sycl-std applies to any SYCL source, not only those containing kernels, 2278 // but also those using the SYCL API 2279 if (const Arg *A = Args.getLastArg(OPT_sycl_std_EQ)) { 2280 Opts.setSYCLVersion( 2281 llvm::StringSwitch<LangOptions::SYCLMajorVersion>(A->getValue()) 2282 .Cases("2017", "1.2.1", "121", "sycl-1.2.1", 2283 LangOptions::SYCL_2017) 2284 .Default(LangOptions::SYCL_None)); 2285 2286 if (Opts.getSYCLVersion() == LangOptions::SYCL_None) { 2287 // User has passed an invalid value to the flag, this is an error 2288 Diags.Report(diag::err_drv_invalid_value) 2289 << A->getAsString(Args) << A->getValue(); 2290 } 2291 } 2292 } 2293 2294 llvm::Triple T(TargetOpts.Triple); 2295 CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd); 2296 2297 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0. 2298 // This option should be deprecated for CL > 1.0 because 2299 // this option was added for compatibility with OpenCL 1.0. 2300 if (Args.getLastArg(OPT_cl_strict_aliasing) 2301 && Opts.OpenCLVersion > 100) { 2302 Diags.Report(diag::warn_option_invalid_ocl_version) 2303 << Opts.getOpenCLVersionTuple().getAsString() 2304 << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args); 2305 } 2306 2307 // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension 2308 // keywords. This behavior is provided by GCC's poorly named '-fasm' flag, 2309 // while a subset (the non-C++ GNU keywords) is provided by GCC's 2310 // '-fgnu-keywords'. Clang conflates the two for simplicity under the single 2311 // name, as it doesn't seem a useful distinction. 2312 Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords, 2313 Opts.GNUKeywords); 2314 2315 Opts.Digraphs = Args.hasFlag(OPT_fdigraphs, OPT_fno_digraphs, Opts.Digraphs); 2316 2317 if (Args.hasArg(OPT_fno_operator_names)) 2318 Opts.CXXOperatorNames = 0; 2319 2320 if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals)) 2321 Opts.CUDADeviceApproxTranscendentals = 1; 2322 2323 if (Args.hasArg(OPT_fgpu_allow_device_init)) { 2324 if (Opts.HIP) 2325 Opts.GPUAllowDeviceInit = 1; 2326 else 2327 Diags.Report(diag::warn_ignored_hip_only_option) 2328 << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args); 2329 } 2330 if (Opts.HIP) 2331 Opts.GPUMaxThreadsPerBlock = getLastArgIntValue( 2332 Args, OPT_gpu_max_threads_per_block_EQ, Opts.GPUMaxThreadsPerBlock); 2333 else if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ)) 2334 Diags.Report(diag::warn_ignored_hip_only_option) 2335 << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args); 2336 2337 if (Opts.ObjC) { 2338 if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) { 2339 StringRef value = arg->getValue(); 2340 if (Opts.ObjCRuntime.tryParse(value)) 2341 Diags.Report(diag::err_drv_unknown_objc_runtime) << value; 2342 } 2343 2344 if (Args.hasArg(OPT_fobjc_gc_only)) 2345 Opts.setGC(LangOptions::GCOnly); 2346 else if (Args.hasArg(OPT_fobjc_gc)) 2347 Opts.setGC(LangOptions::HybridGC); 2348 else if (Args.hasArg(OPT_fobjc_arc)) { 2349 Opts.ObjCAutoRefCount = 1; 2350 if (!Opts.ObjCRuntime.allowsARC()) 2351 Diags.Report(diag::err_arc_unsupported_on_runtime); 2352 } 2353 2354 // ObjCWeakRuntime tracks whether the runtime supports __weak, not 2355 // whether the feature is actually enabled. This is predominantly 2356 // determined by -fobjc-runtime, but we allow it to be overridden 2357 // from the command line for testing purposes. 2358 if (Args.hasArg(OPT_fobjc_runtime_has_weak)) 2359 Opts.ObjCWeakRuntime = 1; 2360 else 2361 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak(); 2362 2363 // ObjCWeak determines whether __weak is actually enabled. 2364 // Note that we allow -fno-objc-weak to disable this even in ARC mode. 2365 if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) { 2366 if (!weakArg->getOption().matches(OPT_fobjc_weak)) { 2367 assert(!Opts.ObjCWeak); 2368 } else if (Opts.getGC() != LangOptions::NonGC) { 2369 Diags.Report(diag::err_objc_weak_with_gc); 2370 } else if (!Opts.ObjCWeakRuntime) { 2371 Diags.Report(diag::err_objc_weak_unsupported); 2372 } else { 2373 Opts.ObjCWeak = 1; 2374 } 2375 } else if (Opts.ObjCAutoRefCount) { 2376 Opts.ObjCWeak = Opts.ObjCWeakRuntime; 2377 } 2378 2379 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime)) 2380 Opts.ObjCSubscriptingLegacyRuntime = 2381 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX); 2382 } 2383 2384 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) { 2385 // Check that the version has 1 to 3 components and the minor and patch 2386 // versions fit in two decimal digits. 2387 VersionTuple GNUCVer; 2388 bool Invalid = GNUCVer.tryParse(A->getValue()); 2389 unsigned Major = GNUCVer.getMajor(); 2390 unsigned Minor = GNUCVer.getMinor().getValueOr(0); 2391 unsigned Patch = GNUCVer.getSubminor().getValueOr(0); 2392 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) { 2393 Diags.Report(diag::err_drv_invalid_value) 2394 << A->getAsString(Args) << A->getValue(); 2395 } 2396 Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch; 2397 } 2398 2399 if (Args.hasArg(OPT_fgnu89_inline)) { 2400 if (Opts.CPlusPlus) 2401 Diags.Report(diag::err_drv_argument_not_allowed_with) 2402 << "-fgnu89-inline" << GetInputKindName(IK); 2403 else 2404 Opts.GNUInline = 1; 2405 } 2406 2407 // The type-visibility mode defaults to the value-visibility mode. 2408 if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) { 2409 Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags)); 2410 } else { 2411 Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode()); 2412 } 2413 2414 if (Args.hasArg(OPT_fvisibility_from_dllstorageclass)) { 2415 Opts.VisibilityFromDLLStorageClass = 1; 2416 2417 // Translate dllexport defintions to default visibility, by default. 2418 if (Arg *O = Args.getLastArg(OPT_fvisibility_dllexport_EQ)) 2419 Opts.setDLLExportVisibility(parseVisibility(O, Args, Diags)); 2420 else 2421 Opts.setDLLExportVisibility(DefaultVisibility); 2422 2423 // Translate defintions without an explict DLL storage class to hidden 2424 // visibility, by default. 2425 if (Arg *O = Args.getLastArg(OPT_fvisibility_nodllstorageclass_EQ)) 2426 Opts.setNoDLLStorageClassVisibility(parseVisibility(O, Args, Diags)); 2427 else 2428 Opts.setNoDLLStorageClassVisibility(HiddenVisibility); 2429 2430 // Translate dllimport external declarations to default visibility, by 2431 // default. 2432 if (Arg *O = Args.getLastArg(OPT_fvisibility_externs_dllimport_EQ)) 2433 Opts.setExternDeclDLLImportVisibility(parseVisibility(O, Args, Diags)); 2434 else 2435 Opts.setExternDeclDLLImportVisibility(DefaultVisibility); 2436 2437 // Translate external declarations without an explicit DLL storage class 2438 // to hidden visibility, by default. 2439 if (Arg *O = Args.getLastArg(OPT_fvisibility_externs_nodllstorageclass_EQ)) 2440 Opts.setExternDeclNoDLLStorageClassVisibility( 2441 parseVisibility(O, Args, Diags)); 2442 else 2443 Opts.setExternDeclNoDLLStorageClassVisibility(HiddenVisibility); 2444 } 2445 2446 if (Args.hasArg(OPT_ftrapv)) { 2447 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping); 2448 // Set the handler, if one is specified. 2449 Opts.OverflowHandler = 2450 std::string(Args.getLastArgValue(OPT_ftrapv_handler)); 2451 } 2452 else if (Args.hasArg(OPT_fwrapv)) 2453 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined); 2454 2455 Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions); 2456 Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt; 2457 Opts.MSCompatibilityVersion = 0; 2458 if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) { 2459 VersionTuple VT; 2460 if (VT.tryParse(A->getValue())) 2461 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 2462 << A->getValue(); 2463 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 + 2464 VT.getMinor().getValueOr(0) * 100000 + 2465 VT.getSubminor().getValueOr(0); 2466 } 2467 2468 // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs 2469 // is specified, or -std is set to a conforming mode. 2470 // Trigraphs are disabled by default in c++1z onwards. 2471 // For z/OS, trigraphs are enabled by default (without regard to the above). 2472 Opts.Trigraphs = 2473 (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS(); 2474 Opts.Trigraphs = 2475 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs); 2476 2477 Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers, 2478 OPT_fno_dollars_in_identifiers, 2479 Opts.DollarIdents); 2480 2481 // -ffixed-point 2482 Opts.FixedPoint = 2483 Args.hasFlag(OPT_ffixed_point, OPT_fno_fixed_point, /*Default=*/false) && 2484 !Opts.CPlusPlus; 2485 Opts.PaddingOnUnsignedFixedPoint = 2486 Args.hasFlag(OPT_fpadding_on_unsigned_fixed_point, 2487 OPT_fno_padding_on_unsigned_fixed_point, 2488 /*Default=*/false) && 2489 Opts.FixedPoint; 2490 2491 Opts.RTTI = Opts.CPlusPlus && !Args.hasArg(OPT_fno_rtti); 2492 Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data); 2493 Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL 2494 && Opts.OpenCLVersion == 200); 2495 Opts.Coroutines = Opts.CPlusPlus20 || Args.hasArg(OPT_fcoroutines_ts); 2496 2497 Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || 2498 Opts.SYCLIsDevice || 2499 Args.hasArg(OPT_fconvergent_functions); 2500 2501 Opts.DoubleSquareBracketAttributes = 2502 Args.hasFlag(OPT_fdouble_square_bracket_attributes, 2503 OPT_fno_double_square_bracket_attributes, 2504 Opts.DoubleSquareBracketAttributes); 2505 2506 Opts.CPlusPlusModules = Opts.CPlusPlus20; 2507 Opts.Modules = 2508 Args.hasArg(OPT_fmodules) || Opts.ModulesTS || Opts.CPlusPlusModules; 2509 Opts.ModulesDeclUse = 2510 Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse; 2511 // FIXME: We only need this in C++ modules / Modules TS if we might textually 2512 // enter a different module (eg, when building a header unit). 2513 Opts.ModulesLocalVisibility = 2514 Args.hasArg(OPT_fmodules_local_submodule_visibility) || Opts.ModulesTS || 2515 Opts.CPlusPlusModules; 2516 Opts.ModulesSearchAll = Opts.Modules && 2517 !Args.hasArg(OPT_fno_modules_search_all) && 2518 Args.hasArg(OPT_fmodules_search_all); 2519 Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char); 2520 Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar); 2521 Opts.Char8 = Args.hasFlag(OPT_fchar8__t, OPT_fno_char8__t, Opts.CPlusPlus20); 2522 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding; 2523 if (!Opts.NoBuiltin) 2524 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs); 2525 Opts.AlignedAllocation = 2526 Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation, 2527 Opts.AlignedAllocation); 2528 Opts.AlignedAllocationUnavailable = 2529 Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable); 2530 if (Args.hasArg(OPT_fconcepts_ts)) 2531 Diags.Report(diag::warn_fe_concepts_ts_flag); 2532 Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno); 2533 Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128) 2534 ? 128 2535 : Args.hasArg(OPT_mlong_double_64) ? 64 : 0; 2536 Opts.EnableAIXExtendedAltivecABI = Args.hasArg(OPT_mabi_EQ_vec_extabi); 2537 Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags); 2538 Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple 2539 || Args.hasArg(OPT_fdump_record_layouts); 2540 if (Opts.FastRelaxedMath) 2541 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast); 2542 Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature); 2543 llvm::sort(Opts.ModuleFeatures); 2544 Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type); 2545 Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns); 2546 // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns 2547 // is enabled. 2548 Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns) 2549 | Opts.NativeHalfArgsAndReturns; 2550 2551 Opts.ArmSveVectorBits = 2552 getLastArgIntValue(Args, options::OPT_msve_vector_bits_EQ, 0, Diags); 2553 2554 // __declspec is enabled by default for the PS4 by the driver, and also 2555 // enabled for Microsoft Extensions or Borland Extensions, here. 2556 // 2557 // FIXME: __declspec is also currently enabled for CUDA, but isn't really a 2558 // CUDA extension. However, it is required for supporting 2559 // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has 2560 // been rewritten in terms of something more generic, remove the Opts.CUDA 2561 // term here. 2562 Opts.DeclSpecKeyword = 2563 Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec, 2564 (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA)); 2565 2566 // -mrtd option 2567 if (Arg *A = Args.getLastArg(OPT_mrtd)) { 2568 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None) 2569 Diags.Report(diag::err_drv_argument_not_allowed_with) 2570 << A->getSpelling() << "-fdefault-calling-conv"; 2571 else { 2572 llvm::Triple T(TargetOpts.Triple); 2573 if (T.getArch() != llvm::Triple::x86) 2574 Diags.Report(diag::err_drv_argument_not_allowed_with) 2575 << A->getSpelling() << T.getTriple(); 2576 else 2577 Opts.setDefaultCallingConv(LangOptions::DCC_StdCall); 2578 } 2579 } 2580 2581 // Check if -fopenmp-simd is specified. 2582 bool IsSimdSpecified = 2583 Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd, 2584 /*Default=*/false); 2585 Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified; 2586 Opts.OpenMPUseTLS = 2587 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls); 2588 Opts.OpenMPIsDevice = 2589 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device); 2590 Opts.OpenMPIRBuilder = 2591 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder); 2592 bool IsTargetSpecified = 2593 Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ); 2594 2595 if (Opts.OpenMP || Opts.OpenMPSimd) { 2596 if (int Version = getLastArgIntValue( 2597 Args, OPT_fopenmp_version_EQ, 2598 (IsSimdSpecified || IsTargetSpecified) ? 50 : Opts.OpenMP, Diags)) 2599 Opts.OpenMP = Version; 2600 // Provide diagnostic when a given target is not expected to be an OpenMP 2601 // device or host. 2602 if (!Opts.OpenMPIsDevice) { 2603 switch (T.getArch()) { 2604 default: 2605 break; 2606 // Add unsupported host targets here: 2607 case llvm::Triple::nvptx: 2608 case llvm::Triple::nvptx64: 2609 Diags.Report(diag::err_drv_omp_host_target_not_supported) 2610 << TargetOpts.Triple; 2611 break; 2612 } 2613 } 2614 } 2615 2616 // Set the flag to prevent the implementation from emitting device exception 2617 // handling code for those requiring so. 2618 if ((Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN())) || 2619 Opts.OpenCLCPlusPlus) { 2620 Opts.Exceptions = 0; 2621 Opts.CXXExceptions = 0; 2622 } 2623 if (Opts.OpenMPIsDevice && T.isNVPTX()) { 2624 Opts.OpenMPCUDANumSMs = 2625 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ, 2626 Opts.OpenMPCUDANumSMs, Diags); 2627 Opts.OpenMPCUDABlocksPerSM = 2628 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ, 2629 Opts.OpenMPCUDABlocksPerSM, Diags); 2630 Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue( 2631 Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ, 2632 Opts.OpenMPCUDAReductionBufNum, Diags); 2633 } 2634 2635 // Get the OpenMP target triples if any. 2636 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) { 2637 enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit }; 2638 auto getArchPtrSize = [](const llvm::Triple &T) { 2639 if (T.isArch16Bit()) 2640 return Arch16Bit; 2641 if (T.isArch32Bit()) 2642 return Arch32Bit; 2643 assert(T.isArch64Bit() && "Expected 64-bit architecture"); 2644 return Arch64Bit; 2645 }; 2646 2647 for (unsigned i = 0; i < A->getNumValues(); ++i) { 2648 llvm::Triple TT(A->getValue(i)); 2649 2650 if (TT.getArch() == llvm::Triple::UnknownArch || 2651 !(TT.getArch() == llvm::Triple::aarch64 || 2652 TT.getArch() == llvm::Triple::ppc || 2653 TT.getArch() == llvm::Triple::ppc64 || 2654 TT.getArch() == llvm::Triple::ppc64le || 2655 TT.getArch() == llvm::Triple::nvptx || 2656 TT.getArch() == llvm::Triple::nvptx64 || 2657 TT.getArch() == llvm::Triple::amdgcn || 2658 TT.getArch() == llvm::Triple::x86 || 2659 TT.getArch() == llvm::Triple::x86_64)) 2660 Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i); 2661 else if (getArchPtrSize(T) != getArchPtrSize(TT)) 2662 Diags.Report(diag::err_drv_incompatible_omp_arch) 2663 << A->getValue(i) << T.str(); 2664 else 2665 Opts.OMPTargetTriples.push_back(TT); 2666 } 2667 } 2668 2669 // Get OpenMP host file path if any and report if a non existent file is 2670 // found 2671 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) { 2672 Opts.OMPHostIRFile = A->getValue(); 2673 if (!llvm::sys::fs::exists(Opts.OMPHostIRFile)) 2674 Diags.Report(diag::err_drv_omp_host_ir_file_not_found) 2675 << Opts.OMPHostIRFile; 2676 } 2677 2678 // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options 2679 Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) && 2680 Args.hasArg(options::OPT_fopenmp_cuda_mode); 2681 2682 // Set CUDA support for parallel execution of target regions for OpenMP target 2683 // NVPTX/AMDGCN if specified in options. 2684 Opts.OpenMPCUDATargetParallel = 2685 Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) && 2686 Args.hasArg(options::OPT_fopenmp_cuda_parallel_target_regions); 2687 2688 // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options 2689 Opts.OpenMPCUDAForceFullRuntime = 2690 Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) && 2691 Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime); 2692 2693 // Record whether the __DEPRECATED define was requested. 2694 Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro, 2695 OPT_fno_deprecated_macro, 2696 Opts.Deprecated); 2697 2698 // FIXME: Eliminate this dependency. 2699 unsigned Opt = getOptimizationLevel(Args, IK, Diags), 2700 OptSize = getOptimizationLevelSize(Args); 2701 Opts.Optimize = Opt != 0; 2702 Opts.OptimizeSize = OptSize != 0; 2703 2704 // This is the __NO_INLINE__ define, which just depends on things like the 2705 // optimization level and -fno-inline, not actually whether the backend has 2706 // inlining enabled. 2707 Opts.NoInlineDefine = !Opts.Optimize; 2708 if (Arg *InlineArg = Args.getLastArg( 2709 options::OPT_finline_functions, options::OPT_finline_hint_functions, 2710 options::OPT_fno_inline_functions, options::OPT_fno_inline)) 2711 if (InlineArg->getOption().matches(options::OPT_fno_inline)) 2712 Opts.NoInlineDefine = true; 2713 2714 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) { 2715 StringRef Val = A->getValue(); 2716 if (Val == "fast") 2717 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast); 2718 else if (Val == "on") 2719 Opts.setDefaultFPContractMode(LangOptions::FPM_On); 2720 else if (Val == "off") 2721 Opts.setDefaultFPContractMode(LangOptions::FPM_Off); 2722 else if (Val == "fast-honor-pragmas") 2723 Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas); 2724 else 2725 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 2726 } 2727 2728 if (Args.hasArg(OPT_ftrapping_math)) { 2729 Opts.setFPExceptionMode(LangOptions::FPE_Strict); 2730 } 2731 2732 if (Args.hasArg(OPT_fno_trapping_math)) { 2733 Opts.setFPExceptionMode(LangOptions::FPE_Ignore); 2734 } 2735 2736 LangOptions::FPExceptionModeKind FPEB = LangOptions::FPE_Ignore; 2737 if (Arg *A = Args.getLastArg(OPT_ffp_exception_behavior_EQ)) { 2738 StringRef Val = A->getValue(); 2739 if (Val.equals("ignore")) 2740 FPEB = LangOptions::FPE_Ignore; 2741 else if (Val.equals("maytrap")) 2742 FPEB = LangOptions::FPE_MayTrap; 2743 else if (Val.equals("strict")) 2744 FPEB = LangOptions::FPE_Strict; 2745 else 2746 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 2747 } 2748 Opts.setFPExceptionMode(FPEB); 2749 2750 // Parse -fsanitize= arguments. 2751 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), 2752 Diags, Opts.Sanitize); 2753 Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist); 2754 std::vector<std::string> systemBlacklists = 2755 Args.getAllArgValues(OPT_fsanitize_system_blacklist); 2756 Opts.SanitizerBlacklistFiles.insert(Opts.SanitizerBlacklistFiles.end(), 2757 systemBlacklists.begin(), 2758 systemBlacklists.end()); 2759 2760 // -fxray-{always,never}-instrument= filenames. 2761 Opts.XRayAlwaysInstrumentFiles = 2762 Args.getAllArgValues(OPT_fxray_always_instrument); 2763 Opts.XRayNeverInstrumentFiles = 2764 Args.getAllArgValues(OPT_fxray_never_instrument); 2765 Opts.XRayAttrListFiles = Args.getAllArgValues(OPT_fxray_attr_list); 2766 2767 if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) { 2768 Opts.setClangABICompat(LangOptions::ClangABI::Latest); 2769 2770 StringRef Ver = A->getValue(); 2771 std::pair<StringRef, StringRef> VerParts = Ver.split('.'); 2772 unsigned Major, Minor = 0; 2773 2774 // Check the version number is valid: either 3.x (0 <= x <= 9) or 2775 // y or y.0 (4 <= y <= current version). 2776 if (!VerParts.first.startswith("0") && 2777 !VerParts.first.getAsInteger(10, Major) && 2778 3 <= Major && Major <= CLANG_VERSION_MAJOR && 2779 (Major == 3 ? VerParts.second.size() == 1 && 2780 !VerParts.second.getAsInteger(10, Minor) 2781 : VerParts.first.size() == Ver.size() || 2782 VerParts.second == "0")) { 2783 // Got a valid version number. 2784 if (Major == 3 && Minor <= 8) 2785 Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8); 2786 else if (Major <= 4) 2787 Opts.setClangABICompat(LangOptions::ClangABI::Ver4); 2788 else if (Major <= 6) 2789 Opts.setClangABICompat(LangOptions::ClangABI::Ver6); 2790 else if (Major <= 7) 2791 Opts.setClangABICompat(LangOptions::ClangABI::Ver7); 2792 else if (Major <= 9) 2793 Opts.setClangABICompat(LangOptions::ClangABI::Ver9); 2794 else if (Major <= 11) 2795 Opts.setClangABICompat(LangOptions::ClangABI::Ver11); 2796 } else if (Ver != "latest") { 2797 Diags.Report(diag::err_drv_invalid_value) 2798 << A->getAsString(Args) << A->getValue(); 2799 } 2800 } 2801 2802 if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) { 2803 StringRef SignScope = A->getValue(); 2804 2805 if (SignScope.equals_lower("none")) 2806 Opts.setSignReturnAddressScope( 2807 LangOptions::SignReturnAddressScopeKind::None); 2808 else if (SignScope.equals_lower("all")) 2809 Opts.setSignReturnAddressScope( 2810 LangOptions::SignReturnAddressScopeKind::All); 2811 else if (SignScope.equals_lower("non-leaf")) 2812 Opts.setSignReturnAddressScope( 2813 LangOptions::SignReturnAddressScopeKind::NonLeaf); 2814 else 2815 Diags.Report(diag::err_drv_invalid_value) 2816 << A->getAsString(Args) << SignScope; 2817 2818 if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) { 2819 StringRef SignKey = A->getValue(); 2820 if (!SignScope.empty() && !SignKey.empty()) { 2821 if (SignKey.equals_lower("a_key")) 2822 Opts.setSignReturnAddressKey( 2823 LangOptions::SignReturnAddressKeyKind::AKey); 2824 else if (SignKey.equals_lower("b_key")) 2825 Opts.setSignReturnAddressKey( 2826 LangOptions::SignReturnAddressKeyKind::BKey); 2827 else 2828 Diags.Report(diag::err_drv_invalid_value) 2829 << A->getAsString(Args) << SignKey; 2830 } 2831 } 2832 } 2833 2834 std::string ThreadModel = 2835 std::string(Args.getLastArgValue(OPT_mthread_model, "posix")); 2836 if (ThreadModel != "posix" && ThreadModel != "single") 2837 Diags.Report(diag::err_drv_invalid_value) 2838 << Args.getLastArg(OPT_mthread_model)->getAsString(Args) << ThreadModel; 2839 Opts.setThreadModel( 2840 llvm::StringSwitch<LangOptions::ThreadModelKind>(ThreadModel) 2841 .Case("posix", LangOptions::ThreadModelKind::POSIX) 2842 .Case("single", LangOptions::ThreadModelKind::Single)); 2843 } 2844 2845 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) { 2846 switch (Action) { 2847 case frontend::ASTDeclList: 2848 case frontend::ASTDump: 2849 case frontend::ASTPrint: 2850 case frontend::ASTView: 2851 case frontend::EmitAssembly: 2852 case frontend::EmitBC: 2853 case frontend::EmitHTML: 2854 case frontend::EmitLLVM: 2855 case frontend::EmitLLVMOnly: 2856 case frontend::EmitCodeGenOnly: 2857 case frontend::EmitObj: 2858 case frontend::FixIt: 2859 case frontend::GenerateModule: 2860 case frontend::GenerateModuleInterface: 2861 case frontend::GenerateHeaderModule: 2862 case frontend::GeneratePCH: 2863 case frontend::GenerateInterfaceStubs: 2864 case frontend::ParseSyntaxOnly: 2865 case frontend::ModuleFileInfo: 2866 case frontend::VerifyPCH: 2867 case frontend::PluginAction: 2868 case frontend::RewriteObjC: 2869 case frontend::RewriteTest: 2870 case frontend::RunAnalysis: 2871 case frontend::TemplightDump: 2872 case frontend::MigrateSource: 2873 return false; 2874 2875 case frontend::DumpCompilerOptions: 2876 case frontend::DumpRawTokens: 2877 case frontend::DumpTokens: 2878 case frontend::InitOnly: 2879 case frontend::PrintPreamble: 2880 case frontend::PrintPreprocessedInput: 2881 case frontend::RewriteMacros: 2882 case frontend::RunPreprocessorOnly: 2883 case frontend::PrintDependencyDirectivesSourceMinimizerOutput: 2884 return true; 2885 } 2886 llvm_unreachable("invalid frontend action"); 2887 } 2888 2889 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, 2890 DiagnosticsEngine &Diags, 2891 frontend::ActionKind Action) { 2892 Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) || 2893 Args.hasArg(OPT_pch_through_hdrstop_use); 2894 Opts.AllowPCHWithCompilerErrors = 2895 Args.hasArg(OPT_fallow_pch_with_errors, OPT_fallow_pcm_with_errors); 2896 2897 for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl)) 2898 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue()); 2899 2900 for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) { 2901 auto Split = StringRef(A).split('='); 2902 Opts.MacroPrefixMap.insert( 2903 {std::string(Split.first), std::string(Split.second)}); 2904 } 2905 2906 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) { 2907 StringRef Value(A->getValue()); 2908 size_t Comma = Value.find(','); 2909 unsigned Bytes = 0; 2910 unsigned EndOfLine = 0; 2911 2912 if (Comma == StringRef::npos || 2913 Value.substr(0, Comma).getAsInteger(10, Bytes) || 2914 Value.substr(Comma + 1).getAsInteger(10, EndOfLine)) 2915 Diags.Report(diag::err_drv_preamble_format); 2916 else { 2917 Opts.PrecompiledPreambleBytes.first = Bytes; 2918 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0); 2919 } 2920 } 2921 2922 // Add the __CET__ macro if a CFProtection option is set. 2923 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 2924 StringRef Name = A->getValue(); 2925 if (Name == "branch") 2926 Opts.addMacroDef("__CET__=1"); 2927 else if (Name == "return") 2928 Opts.addMacroDef("__CET__=2"); 2929 else if (Name == "full") 2930 Opts.addMacroDef("__CET__=3"); 2931 } 2932 2933 // Add macros from the command line. 2934 for (const auto *A : Args.filtered(OPT_D, OPT_U)) { 2935 if (A->getOption().matches(OPT_D)) 2936 Opts.addMacroDef(A->getValue()); 2937 else 2938 Opts.addMacroUndef(A->getValue()); 2939 } 2940 2941 Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros); 2942 2943 // Add the ordered list of -includes. 2944 for (const auto *A : Args.filtered(OPT_include)) 2945 Opts.Includes.emplace_back(A->getValue()); 2946 2947 for (const auto *A : Args.filtered(OPT_chain_include)) 2948 Opts.ChainedIncludes.emplace_back(A->getValue()); 2949 2950 for (const auto *A : Args.filtered(OPT_remap_file)) { 2951 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';'); 2952 2953 if (Split.second.empty()) { 2954 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args); 2955 continue; 2956 } 2957 2958 Opts.addRemappedFile(Split.first, Split.second); 2959 } 2960 2961 // Always avoid lexing editor placeholders when we're just running the 2962 // preprocessor as we never want to emit the 2963 // "editor placeholder in source file" error in PP only mode. 2964 if (isStrictlyPreprocessorAction(Action)) 2965 Opts.LexEditorPlaceholders = false; 2966 } 2967 2968 static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts, 2969 ArgList &Args, 2970 frontend::ActionKind Action) { 2971 if (isStrictlyPreprocessorAction(Action)) 2972 Opts.ShowCPP = !Args.hasArg(OPT_dM); 2973 else 2974 Opts.ShowCPP = 0; 2975 2976 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD); 2977 } 2978 2979 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args, 2980 DiagnosticsEngine &Diags) { 2981 Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature); 2982 Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ); 2983 Opts.AllowAMDGPUUnsafeFPAtomics = 2984 Args.hasFlag(options::OPT_munsafe_fp_atomics, 2985 options::OPT_mno_unsafe_fp_atomics, false); 2986 if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) { 2987 llvm::VersionTuple Version; 2988 if (Version.tryParse(A->getValue())) 2989 Diags.Report(diag::err_drv_invalid_value) 2990 << A->getAsString(Args) << A->getValue(); 2991 else 2992 Opts.SDKVersion = Version; 2993 } 2994 } 2995 2996 bool CompilerInvocation::parseSimpleArgs(const ArgList &Args, 2997 DiagnosticsEngine &Diags) { 2998 #define OPTION_WITH_MARSHALLING( \ 2999 PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 3000 HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ 3001 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \ 3002 TABLE_INDEX) \ 3003 if ((FLAGS)&options::CC1Option) { \ 3004 this->KEYPATH = MERGER(this->KEYPATH, DEFAULT_VALUE); \ 3005 if (IMPLIED_CHECK) \ 3006 this->KEYPATH = MERGER(this->KEYPATH, IMPLIED_VALUE); \ 3007 if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, Args, Diags)) \ 3008 this->KEYPATH = MERGER( \ 3009 this->KEYPATH, static_cast<decltype(this->KEYPATH)>(*MaybeValue)); \ 3010 } 3011 3012 #include "clang/Driver/Options.inc" 3013 #undef OPTION_WITH_MARSHALLING 3014 return true; 3015 } 3016 3017 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res, 3018 ArrayRef<const char *> CommandLineArgs, 3019 DiagnosticsEngine &Diags, 3020 const char *Argv0) { 3021 bool Success = true; 3022 3023 // Parse the arguments. 3024 const OptTable &Opts = getDriverOptTable(); 3025 const unsigned IncludedFlagsBitmask = options::CC1Option; 3026 unsigned MissingArgIndex, MissingArgCount; 3027 InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex, 3028 MissingArgCount, IncludedFlagsBitmask); 3029 LangOptions &LangOpts = *Res.getLangOpts(); 3030 3031 // Check for missing argument error. 3032 if (MissingArgCount) { 3033 Diags.Report(diag::err_drv_missing_argument) 3034 << Args.getArgString(MissingArgIndex) << MissingArgCount; 3035 Success = false; 3036 } 3037 3038 // Issue errors on unknown arguments. 3039 for (const auto *A : Args.filtered(OPT_UNKNOWN)) { 3040 auto ArgString = A->getAsString(Args); 3041 std::string Nearest; 3042 if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1) 3043 Diags.Report(diag::err_drv_unknown_argument) << ArgString; 3044 else 3045 Diags.Report(diag::err_drv_unknown_argument_with_suggestion) 3046 << ArgString << Nearest; 3047 Success = false; 3048 } 3049 3050 Success &= Res.parseSimpleArgs(Args, Diags); 3051 3052 Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags); 3053 ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args); 3054 if (!Res.getDependencyOutputOpts().OutputFile.empty() && 3055 Res.getDependencyOutputOpts().Targets.empty()) { 3056 Diags.Report(diag::err_fe_dependency_file_requires_MT); 3057 Success = false; 3058 } 3059 Success &= ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags, 3060 /*DefaultDiagColor=*/false); 3061 ParseCommentArgs(LangOpts.CommentOpts, Args); 3062 // FIXME: We shouldn't have to pass the DashX option around here 3063 InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, 3064 LangOpts.IsHeaderFile); 3065 ParseTargetArgs(Res.getTargetOpts(), Args, Diags); 3066 Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, 3067 Res.getTargetOpts(), Res.getFrontendOpts()); 3068 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, 3069 Res.getFileSystemOpts().WorkingDir); 3070 llvm::Triple T(Res.getTargetOpts().Triple); 3071 if (DashX.getFormat() == InputKind::Precompiled || 3072 DashX.getLanguage() == Language::LLVM_IR) { 3073 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the 3074 // PassManager in BackendUtil.cpp. They need to be initializd no matter 3075 // what the input type is. 3076 if (Args.hasArg(OPT_fobjc_arc)) 3077 LangOpts.ObjCAutoRefCount = 1; 3078 // PIClevel and PIELevel are needed during code generation and this should be 3079 // set regardless of the input type. 3080 LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags); 3081 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), 3082 Diags, LangOpts.Sanitize); 3083 } else { 3084 // Other LangOpts are only initialized when the input is not AST or LLVM IR. 3085 // FIXME: Should we really be calling this for an Language::Asm input? 3086 ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(), 3087 Res.getPreprocessorOpts(), Diags); 3088 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC) 3089 LangOpts.ObjCExceptions = 1; 3090 if (T.isOSDarwin() && DashX.isPreprocessed()) { 3091 // Supress the darwin-specific 'stdlibcxx-not-found' diagnostic for 3092 // preprocessed input as we don't expect it to be used with -std=libc++ 3093 // anyway. 3094 Res.getDiagnosticOpts().Warnings.push_back("no-stdlibcxx-not-found"); 3095 } 3096 } 3097 3098 if (LangOpts.CUDA) { 3099 // During CUDA device-side compilation, the aux triple is the 3100 // triple used for host compilation. 3101 if (LangOpts.CUDAIsDevice) 3102 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; 3103 } 3104 3105 // Set the triple of the host for OpenMP device compile. 3106 if (LangOpts.OpenMPIsDevice) 3107 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; 3108 3109 // FIXME: Override value name discarding when asan or msan is used because the 3110 // backend passes depend on the name of the alloca in order to print out 3111 // names. 3112 Res.getCodeGenOpts().DiscardValueNames &= 3113 !LangOpts.Sanitize.has(SanitizerKind::Address) && 3114 !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) && 3115 !LangOpts.Sanitize.has(SanitizerKind::Memory) && 3116 !LangOpts.Sanitize.has(SanitizerKind::KernelMemory); 3117 3118 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags, 3119 Res.getFrontendOpts().ProgramAction); 3120 ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, 3121 Res.getFrontendOpts().ProgramAction); 3122 3123 // Turn on -Wspir-compat for SPIR target. 3124 if (T.isSPIR()) 3125 Res.getDiagnosticOpts().Warnings.push_back("spir-compat"); 3126 3127 // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses. 3128 if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses && 3129 !Res.getLangOpts()->Sanitize.empty()) { 3130 Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false; 3131 Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored); 3132 } 3133 3134 // Store the command-line for using in the CodeView backend. 3135 Res.getCodeGenOpts().Argv0 = Argv0; 3136 Res.getCodeGenOpts().CommandLineArgs = CommandLineArgs; 3137 3138 FixupInvocation(Res, Diags, Args); 3139 3140 return Success; 3141 } 3142 3143 std::string CompilerInvocation::getModuleHash() const { 3144 // Note: For QoI reasons, the things we use as a hash here should all be 3145 // dumped via the -module-info flag. 3146 using llvm::hash_code; 3147 using llvm::hash_value; 3148 using llvm::hash_combine; 3149 using llvm::hash_combine_range; 3150 3151 // Start the signature with the compiler version. 3152 // FIXME: We'd rather use something more cryptographically sound than 3153 // CityHash, but this will do for now. 3154 hash_code code = hash_value(getClangFullRepositoryVersion()); 3155 3156 // Also include the serialization version, in case LLVM_APPEND_VC_REV is off 3157 // and getClangFullRepositoryVersion() doesn't include git revision. 3158 code = hash_combine(code, serialization::VERSION_MAJOR, 3159 serialization::VERSION_MINOR); 3160 3161 // Extend the signature with the language options 3162 #define LANGOPT(Name, Bits, Default, Description) \ 3163 code = hash_combine(code, LangOpts->Name); 3164 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 3165 code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name())); 3166 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 3167 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 3168 #include "clang/Basic/LangOptions.def" 3169 3170 for (StringRef Feature : LangOpts->ModuleFeatures) 3171 code = hash_combine(code, Feature); 3172 3173 code = hash_combine(code, LangOpts->ObjCRuntime); 3174 const auto &BCN = LangOpts->CommentOpts.BlockCommandNames; 3175 code = hash_combine(code, hash_combine_range(BCN.begin(), BCN.end())); 3176 3177 // Extend the signature with the target options. 3178 code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU, 3179 TargetOpts->TuneCPU, TargetOpts->ABI); 3180 for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten) 3181 code = hash_combine(code, FeatureAsWritten); 3182 3183 // Extend the signature with preprocessor options. 3184 const PreprocessorOptions &ppOpts = getPreprocessorOpts(); 3185 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts(); 3186 code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord); 3187 3188 for (const auto &I : getPreprocessorOpts().Macros) { 3189 // If we're supposed to ignore this macro for the purposes of modules, 3190 // don't put it into the hash. 3191 if (!hsOpts.ModulesIgnoreMacros.empty()) { 3192 // Check whether we're ignoring this macro. 3193 StringRef MacroDef = I.first; 3194 if (hsOpts.ModulesIgnoreMacros.count( 3195 llvm::CachedHashString(MacroDef.split('=').first))) 3196 continue; 3197 } 3198 3199 code = hash_combine(code, I.first, I.second); 3200 } 3201 3202 // Extend the signature with the sysroot and other header search options. 3203 code = hash_combine(code, hsOpts.Sysroot, 3204 hsOpts.ModuleFormat, 3205 hsOpts.UseDebugInfo, 3206 hsOpts.UseBuiltinIncludes, 3207 hsOpts.UseStandardSystemIncludes, 3208 hsOpts.UseStandardCXXIncludes, 3209 hsOpts.UseLibcxx, 3210 hsOpts.ModulesValidateDiagnosticOptions); 3211 code = hash_combine(code, hsOpts.ResourceDir); 3212 3213 if (hsOpts.ModulesStrictContextHash) { 3214 hash_code SHPC = hash_combine_range(hsOpts.SystemHeaderPrefixes.begin(), 3215 hsOpts.SystemHeaderPrefixes.end()); 3216 hash_code UEC = hash_combine_range(hsOpts.UserEntries.begin(), 3217 hsOpts.UserEntries.end()); 3218 code = hash_combine(code, hsOpts.SystemHeaderPrefixes.size(), SHPC, 3219 hsOpts.UserEntries.size(), UEC); 3220 3221 const DiagnosticOptions &diagOpts = getDiagnosticOpts(); 3222 #define DIAGOPT(Name, Bits, Default) \ 3223 code = hash_combine(code, diagOpts.Name); 3224 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 3225 code = hash_combine(code, diagOpts.get##Name()); 3226 #include "clang/Basic/DiagnosticOptions.def" 3227 #undef DIAGOPT 3228 #undef ENUM_DIAGOPT 3229 } 3230 3231 // Extend the signature with the user build path. 3232 code = hash_combine(code, hsOpts.ModuleUserBuildPath); 3233 3234 // Extend the signature with the module file extensions. 3235 const FrontendOptions &frontendOpts = getFrontendOpts(); 3236 for (const auto &ext : frontendOpts.ModuleFileExtensions) { 3237 code = ext->hashExtension(code); 3238 } 3239 3240 // When compiling with -gmodules, also hash -fdebug-prefix-map as it 3241 // affects the debug info in the PCM. 3242 if (getCodeGenOpts().DebugTypeExtRefs) 3243 for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap) 3244 code = hash_combine(code, KeyValue.first, KeyValue.second); 3245 3246 // Extend the signature with the enabled sanitizers, if at least one is 3247 // enabled. Sanitizers which cannot affect AST generation aren't hashed. 3248 SanitizerSet SanHash = LangOpts->Sanitize; 3249 SanHash.clear(getPPTransparentSanitizers()); 3250 if (!SanHash.empty()) 3251 code = hash_combine(code, SanHash.Mask); 3252 3253 return llvm::APInt(64, code).toString(36, /*Signed=*/false); 3254 } 3255 3256 void CompilerInvocation::generateCC1CommandLine( 3257 SmallVectorImpl<const char *> &Args, StringAllocator SA) const { 3258 // Capture the extracted value as a lambda argument to avoid potential issues 3259 // with lifetime extension of the reference. 3260 #define OPTION_WITH_MARSHALLING( \ 3261 PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 3262 HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ 3263 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \ 3264 TABLE_INDEX) \ 3265 if ((FLAGS)&options::CC1Option) { \ 3266 [&](const auto &Extracted) { \ 3267 if (ALWAYS_EMIT || \ 3268 (Extracted != \ 3269 static_cast<decltype(this->KEYPATH)>( \ 3270 (IMPLIED_CHECK) ? (IMPLIED_VALUE) : (DEFAULT_VALUE)))) \ 3271 DENORMALIZER(Args, SPELLING, SA, Option::KIND##Class, TABLE_INDEX, \ 3272 Extracted); \ 3273 }(EXTRACTOR(this->KEYPATH)); \ 3274 } 3275 3276 #include "clang/Driver/Options.inc" 3277 #undef OPTION_WITH_MARSHALLING 3278 } 3279 3280 IntrusiveRefCntPtr<llvm::vfs::FileSystem> 3281 clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI, 3282 DiagnosticsEngine &Diags) { 3283 return createVFSFromCompilerInvocation(CI, Diags, 3284 llvm::vfs::getRealFileSystem()); 3285 } 3286 3287 IntrusiveRefCntPtr<llvm::vfs::FileSystem> 3288 clang::createVFSFromCompilerInvocation( 3289 const CompilerInvocation &CI, DiagnosticsEngine &Diags, 3290 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) { 3291 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty()) 3292 return BaseFS; 3293 3294 IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS; 3295 // earlier vfs files are on the bottom 3296 for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) { 3297 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer = 3298 Result->getBufferForFile(File); 3299 if (!Buffer) { 3300 Diags.Report(diag::err_missing_vfs_overlay_file) << File; 3301 continue; 3302 } 3303 3304 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML( 3305 std::move(Buffer.get()), /*DiagHandler*/ nullptr, File, 3306 /*DiagContext*/ nullptr, Result); 3307 if (!FS) { 3308 Diags.Report(diag::err_invalid_vfs_overlay) << File; 3309 continue; 3310 } 3311 3312 Result = FS; 3313 } 3314 return Result; 3315 } 3316