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/Diagnostic.h" 16 #include "clang/Basic/DiagnosticDriver.h" 17 #include "clang/Basic/DiagnosticOptions.h" 18 #include "clang/Basic/FileSystemOptions.h" 19 #include "clang/Basic/LLVM.h" 20 #include "clang/Basic/LangOptions.h" 21 #include "clang/Basic/LangStandard.h" 22 #include "clang/Basic/ObjCRuntime.h" 23 #include "clang/Basic/Sanitizers.h" 24 #include "clang/Basic/SourceLocation.h" 25 #include "clang/Basic/TargetOptions.h" 26 #include "clang/Basic/Version.h" 27 #include "clang/Basic/Visibility.h" 28 #include "clang/Basic/XRayInstr.h" 29 #include "clang/Config/config.h" 30 #include "clang/Driver/Driver.h" 31 #include "clang/Driver/DriverDiagnostic.h" 32 #include "clang/Driver/Options.h" 33 #include "clang/Frontend/CommandLineSourceLoc.h" 34 #include "clang/Frontend/DependencyOutputOptions.h" 35 #include "clang/Frontend/FrontendDiagnostic.h" 36 #include "clang/Frontend/FrontendOptions.h" 37 #include "clang/Frontend/FrontendPluginRegistry.h" 38 #include "clang/Frontend/MigratorOptions.h" 39 #include "clang/Frontend/PreprocessorOutputOptions.h" 40 #include "clang/Frontend/TextDiagnosticBuffer.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/DenseSet.h" 52 #include "llvm/ADT/FloatingPointMode.h" 53 #include "llvm/ADT/Hashing.h" 54 #include "llvm/ADT/STLExtras.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/Twine.h" 60 #include "llvm/Config/llvm-config.h" 61 #include "llvm/Frontend/Debug/Options.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/HashBuilder.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 "llvm/TargetParser/Host.h" 89 #include "llvm/TargetParser/Triple.h" 90 #include <algorithm> 91 #include <atomic> 92 #include <cassert> 93 #include <cstddef> 94 #include <cstring> 95 #include <ctime> 96 #include <fstream> 97 #include <limits> 98 #include <memory> 99 #include <optional> 100 #include <string> 101 #include <tuple> 102 #include <type_traits> 103 #include <utility> 104 #include <vector> 105 106 using namespace clang; 107 using namespace driver; 108 using namespace options; 109 using namespace llvm::opt; 110 111 //===----------------------------------------------------------------------===// 112 // Helpers. 113 //===----------------------------------------------------------------------===// 114 115 // Parse misexpect tolerance argument value. 116 // Valid option values are integers in the range [0, 100) 117 static Expected<std::optional<uint32_t>> parseToleranceOption(StringRef Arg) { 118 uint32_t Val; 119 if (Arg.getAsInteger(10, Val)) 120 return llvm::createStringError(llvm::inconvertibleErrorCode(), 121 "Not an integer: %s", Arg.data()); 122 return Val; 123 } 124 125 //===----------------------------------------------------------------------===// 126 // Initialization. 127 //===----------------------------------------------------------------------===// 128 129 namespace { 130 template <class T> std::shared_ptr<T> make_shared_copy(const T &X) { 131 return std::make_shared<T>(X); 132 } 133 134 template <class T> 135 llvm::IntrusiveRefCntPtr<T> makeIntrusiveRefCntCopy(const T &X) { 136 return llvm::makeIntrusiveRefCnt<T>(X); 137 } 138 } // namespace 139 140 CompilerInvocationBase::CompilerInvocationBase() 141 : LangOpts(std::make_shared<LangOptions>()), 142 TargetOpts(std::make_shared<TargetOptions>()), 143 DiagnosticOpts(llvm::makeIntrusiveRefCnt<DiagnosticOptions>()), 144 HSOpts(std::make_shared<HeaderSearchOptions>()), 145 PPOpts(std::make_shared<PreprocessorOptions>()), 146 AnalyzerOpts(llvm::makeIntrusiveRefCnt<AnalyzerOptions>()), 147 MigratorOpts(std::make_shared<MigratorOptions>()), 148 CodeGenOpts(std::make_shared<CodeGenOptions>()), 149 FSOpts(std::make_shared<FileSystemOptions>()), 150 FrontendOpts(std::make_shared<FrontendOptions>()), 151 DependencyOutputOpts(std::make_shared<DependencyOutputOptions>()), 152 PreprocessorOutputOpts(std::make_shared<PreprocessorOutputOptions>()) {} 153 154 CompilerInvocationBase & 155 CompilerInvocationBase::deep_copy_assign(const CompilerInvocationBase &X) { 156 if (this != &X) { 157 LangOpts = make_shared_copy(X.getLangOpts()); 158 TargetOpts = make_shared_copy(X.getTargetOpts()); 159 DiagnosticOpts = makeIntrusiveRefCntCopy(X.getDiagnosticOpts()); 160 HSOpts = make_shared_copy(X.getHeaderSearchOpts()); 161 PPOpts = make_shared_copy(X.getPreprocessorOpts()); 162 AnalyzerOpts = makeIntrusiveRefCntCopy(X.getAnalyzerOpts()); 163 MigratorOpts = make_shared_copy(X.getMigratorOpts()); 164 CodeGenOpts = make_shared_copy(X.getCodeGenOpts()); 165 FSOpts = make_shared_copy(X.getFileSystemOpts()); 166 FrontendOpts = make_shared_copy(X.getFrontendOpts()); 167 DependencyOutputOpts = make_shared_copy(X.getDependencyOutputOpts()); 168 PreprocessorOutputOpts = make_shared_copy(X.getPreprocessorOutputOpts()); 169 } 170 return *this; 171 } 172 173 CompilerInvocationBase & 174 CompilerInvocationBase::shallow_copy_assign(const CompilerInvocationBase &X) { 175 if (this != &X) { 176 LangOpts = X.LangOpts; 177 TargetOpts = X.TargetOpts; 178 DiagnosticOpts = X.DiagnosticOpts; 179 HSOpts = X.HSOpts; 180 PPOpts = X.PPOpts; 181 AnalyzerOpts = X.AnalyzerOpts; 182 MigratorOpts = X.MigratorOpts; 183 CodeGenOpts = X.CodeGenOpts; 184 FSOpts = X.FSOpts; 185 FrontendOpts = X.FrontendOpts; 186 DependencyOutputOpts = X.DependencyOutputOpts; 187 PreprocessorOutputOpts = X.PreprocessorOutputOpts; 188 } 189 return *this; 190 } 191 192 namespace { 193 template <typename T> 194 T &ensureOwned(std::shared_ptr<T> &Storage) { 195 if (Storage.use_count() > 1) 196 Storage = std::make_shared<T>(*Storage); 197 return *Storage; 198 } 199 200 template <typename T> 201 T &ensureOwned(llvm::IntrusiveRefCntPtr<T> &Storage) { 202 if (Storage.useCount() > 1) 203 Storage = llvm::makeIntrusiveRefCnt<T>(*Storage); 204 return *Storage; 205 } 206 } // namespace 207 208 LangOptions &CowCompilerInvocation::getMutLangOpts() { 209 return ensureOwned(LangOpts); 210 } 211 212 TargetOptions &CowCompilerInvocation::getMutTargetOpts() { 213 return ensureOwned(TargetOpts); 214 } 215 216 DiagnosticOptions &CowCompilerInvocation::getMutDiagnosticOpts() { 217 return ensureOwned(DiagnosticOpts); 218 } 219 220 HeaderSearchOptions &CowCompilerInvocation::getMutHeaderSearchOpts() { 221 return ensureOwned(HSOpts); 222 } 223 224 PreprocessorOptions &CowCompilerInvocation::getMutPreprocessorOpts() { 225 return ensureOwned(PPOpts); 226 } 227 228 AnalyzerOptions &CowCompilerInvocation::getMutAnalyzerOpts() { 229 return ensureOwned(AnalyzerOpts); 230 } 231 232 MigratorOptions &CowCompilerInvocation::getMutMigratorOpts() { 233 return ensureOwned(MigratorOpts); 234 } 235 236 CodeGenOptions &CowCompilerInvocation::getMutCodeGenOpts() { 237 return ensureOwned(CodeGenOpts); 238 } 239 240 FileSystemOptions &CowCompilerInvocation::getMutFileSystemOpts() { 241 return ensureOwned(FSOpts); 242 } 243 244 FrontendOptions &CowCompilerInvocation::getMutFrontendOpts() { 245 return ensureOwned(FrontendOpts); 246 } 247 248 DependencyOutputOptions &CowCompilerInvocation::getMutDependencyOutputOpts() { 249 return ensureOwned(DependencyOutputOpts); 250 } 251 252 PreprocessorOutputOptions & 253 CowCompilerInvocation::getMutPreprocessorOutputOpts() { 254 return ensureOwned(PreprocessorOutputOpts); 255 } 256 257 //===----------------------------------------------------------------------===// 258 // Normalizers 259 //===----------------------------------------------------------------------===// 260 261 using ArgumentConsumer = CompilerInvocation::ArgumentConsumer; 262 263 #define SIMPLE_ENUM_VALUE_TABLE 264 #include "clang/Driver/Options.inc" 265 #undef SIMPLE_ENUM_VALUE_TABLE 266 267 static std::optional<bool> normalizeSimpleFlag(OptSpecifier Opt, 268 unsigned TableIndex, 269 const ArgList &Args, 270 DiagnosticsEngine &Diags) { 271 if (Args.hasArg(Opt)) 272 return true; 273 return std::nullopt; 274 } 275 276 static std::optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt, 277 unsigned, 278 const ArgList &Args, 279 DiagnosticsEngine &) { 280 if (Args.hasArg(Opt)) 281 return false; 282 return std::nullopt; 283 } 284 285 /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but 286 /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with 287 /// unnecessary template instantiations and just ignore it with a variadic 288 /// argument. 289 static void denormalizeSimpleFlag(ArgumentConsumer Consumer, 290 const Twine &Spelling, Option::OptionClass, 291 unsigned, /*T*/...) { 292 Consumer(Spelling); 293 } 294 295 template <typename T> static constexpr bool is_uint64_t_convertible() { 296 return !std::is_same_v<T, uint64_t> && llvm::is_integral_or_enum<T>::value; 297 } 298 299 template <typename T, 300 std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false> 301 static auto makeFlagToValueNormalizer(T Value) { 302 return [Value](OptSpecifier Opt, unsigned, const ArgList &Args, 303 DiagnosticsEngine &) -> std::optional<T> { 304 if (Args.hasArg(Opt)) 305 return Value; 306 return std::nullopt; 307 }; 308 } 309 310 template <typename T, 311 std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false> 312 static auto makeFlagToValueNormalizer(T Value) { 313 return makeFlagToValueNormalizer(uint64_t(Value)); 314 } 315 316 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue, 317 OptSpecifier OtherOpt) { 318 return [Value, OtherValue, 319 OtherOpt](OptSpecifier Opt, unsigned, const ArgList &Args, 320 DiagnosticsEngine &) -> std::optional<bool> { 321 if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) { 322 return A->getOption().matches(Opt) ? Value : OtherValue; 323 } 324 return std::nullopt; 325 }; 326 } 327 328 static auto makeBooleanOptionDenormalizer(bool Value) { 329 return [Value](ArgumentConsumer Consumer, const Twine &Spelling, 330 Option::OptionClass, unsigned, bool KeyPath) { 331 if (KeyPath == Value) 332 Consumer(Spelling); 333 }; 334 } 335 336 static void denormalizeStringImpl(ArgumentConsumer Consumer, 337 const Twine &Spelling, 338 Option::OptionClass OptClass, unsigned, 339 const Twine &Value) { 340 switch (OptClass) { 341 case Option::SeparateClass: 342 case Option::JoinedOrSeparateClass: 343 case Option::JoinedAndSeparateClass: 344 Consumer(Spelling); 345 Consumer(Value); 346 break; 347 case Option::JoinedClass: 348 case Option::CommaJoinedClass: 349 Consumer(Spelling + Value); 350 break; 351 default: 352 llvm_unreachable("Cannot denormalize an option with option class " 353 "incompatible with string denormalization."); 354 } 355 } 356 357 template <typename T> 358 static void denormalizeString(ArgumentConsumer Consumer, const Twine &Spelling, 359 Option::OptionClass OptClass, unsigned TableIndex, 360 T Value) { 361 denormalizeStringImpl(Consumer, Spelling, OptClass, TableIndex, Twine(Value)); 362 } 363 364 static std::optional<SimpleEnumValue> 365 findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) { 366 for (int I = 0, E = Table.Size; I != E; ++I) 367 if (Name == Table.Table[I].Name) 368 return Table.Table[I]; 369 370 return std::nullopt; 371 } 372 373 static std::optional<SimpleEnumValue> 374 findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) { 375 for (int I = 0, E = Table.Size; I != E; ++I) 376 if (Value == Table.Table[I].Value) 377 return Table.Table[I]; 378 379 return std::nullopt; 380 } 381 382 static std::optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt, 383 unsigned TableIndex, 384 const ArgList &Args, 385 DiagnosticsEngine &Diags) { 386 assert(TableIndex < SimpleEnumValueTablesSize); 387 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex]; 388 389 auto *Arg = Args.getLastArg(Opt); 390 if (!Arg) 391 return std::nullopt; 392 393 StringRef ArgValue = Arg->getValue(); 394 if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue)) 395 return MaybeEnumVal->Value; 396 397 Diags.Report(diag::err_drv_invalid_value) 398 << Arg->getAsString(Args) << ArgValue; 399 return std::nullopt; 400 } 401 402 static void denormalizeSimpleEnumImpl(ArgumentConsumer Consumer, 403 const Twine &Spelling, 404 Option::OptionClass OptClass, 405 unsigned TableIndex, unsigned Value) { 406 assert(TableIndex < SimpleEnumValueTablesSize); 407 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex]; 408 if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) { 409 denormalizeString(Consumer, Spelling, OptClass, TableIndex, 410 MaybeEnumVal->Name); 411 } else { 412 llvm_unreachable("The simple enum value was not correctly defined in " 413 "the tablegen option description"); 414 } 415 } 416 417 template <typename T> 418 static void denormalizeSimpleEnum(ArgumentConsumer Consumer, 419 const Twine &Spelling, 420 Option::OptionClass OptClass, 421 unsigned TableIndex, T Value) { 422 return denormalizeSimpleEnumImpl(Consumer, Spelling, OptClass, TableIndex, 423 static_cast<unsigned>(Value)); 424 } 425 426 static std::optional<std::string> normalizeString(OptSpecifier Opt, 427 int TableIndex, 428 const ArgList &Args, 429 DiagnosticsEngine &Diags) { 430 auto *Arg = Args.getLastArg(Opt); 431 if (!Arg) 432 return std::nullopt; 433 return std::string(Arg->getValue()); 434 } 435 436 template <typename IntTy> 437 static std::optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int, 438 const ArgList &Args, 439 DiagnosticsEngine &Diags) { 440 auto *Arg = Args.getLastArg(Opt); 441 if (!Arg) 442 return std::nullopt; 443 IntTy Res; 444 if (StringRef(Arg->getValue()).getAsInteger(0, Res)) { 445 Diags.Report(diag::err_drv_invalid_int_value) 446 << Arg->getAsString(Args) << Arg->getValue(); 447 return std::nullopt; 448 } 449 return Res; 450 } 451 452 static std::optional<std::vector<std::string>> 453 normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args, 454 DiagnosticsEngine &) { 455 return Args.getAllArgValues(Opt); 456 } 457 458 static void denormalizeStringVector(ArgumentConsumer Consumer, 459 const Twine &Spelling, 460 Option::OptionClass OptClass, 461 unsigned TableIndex, 462 const std::vector<std::string> &Values) { 463 switch (OptClass) { 464 case Option::CommaJoinedClass: { 465 std::string CommaJoinedValue; 466 if (!Values.empty()) { 467 CommaJoinedValue.append(Values.front()); 468 for (const std::string &Value : llvm::drop_begin(Values, 1)) { 469 CommaJoinedValue.append(","); 470 CommaJoinedValue.append(Value); 471 } 472 } 473 denormalizeString(Consumer, Spelling, Option::OptionClass::JoinedClass, 474 TableIndex, CommaJoinedValue); 475 break; 476 } 477 case Option::JoinedClass: 478 case Option::SeparateClass: 479 case Option::JoinedOrSeparateClass: 480 for (const std::string &Value : Values) 481 denormalizeString(Consumer, Spelling, OptClass, TableIndex, Value); 482 break; 483 default: 484 llvm_unreachable("Cannot denormalize an option with option class " 485 "incompatible with string vector denormalization."); 486 } 487 } 488 489 static std::optional<std::string> normalizeTriple(OptSpecifier Opt, 490 int TableIndex, 491 const ArgList &Args, 492 DiagnosticsEngine &Diags) { 493 auto *Arg = Args.getLastArg(Opt); 494 if (!Arg) 495 return std::nullopt; 496 return llvm::Triple::normalize(Arg->getValue()); 497 } 498 499 template <typename T, typename U> 500 static T mergeForwardValue(T KeyPath, U Value) { 501 return static_cast<T>(Value); 502 } 503 504 template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) { 505 return KeyPath | Value; 506 } 507 508 template <typename T> static T extractForwardValue(T KeyPath) { 509 return KeyPath; 510 } 511 512 template <typename T, typename U, U Value> 513 static T extractMaskValue(T KeyPath) { 514 return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T(); 515 } 516 517 #define PARSE_OPTION_WITH_MARSHALLING( \ 518 ARGS, DIAGS, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, \ 519 FLAGS, VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES, SHOULD_PARSE, \ 520 ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, \ 521 NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX) \ 522 if ((VISIBILITY)&options::CC1Option) { \ 523 KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE); \ 524 if (IMPLIED_CHECK) \ 525 KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE); \ 526 if (SHOULD_PARSE) \ 527 if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS)) \ 528 KEYPATH = \ 529 MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue)); \ 530 } 531 532 // Capture the extracted value as a lambda argument to avoid potential issues 533 // with lifetime extension of the reference. 534 #define GENERATE_OPTION_WITH_MARSHALLING( \ 535 CONSUMER, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, \ 536 VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES, SHOULD_PARSE, ALWAYS_EMIT, \ 537 KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \ 538 DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX) \ 539 if ((VISIBILITY)&options::CC1Option) { \ 540 [&](const auto &Extracted) { \ 541 if (ALWAYS_EMIT || \ 542 (Extracted != \ 543 static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE) \ 544 : (DEFAULT_VALUE)))) \ 545 DENORMALIZER(CONSUMER, SPELLING, Option::KIND##Class, TABLE_INDEX, \ 546 Extracted); \ 547 }(EXTRACTOR(KEYPATH)); \ 548 } 549 550 static StringRef GetInputKindName(InputKind IK); 551 552 static bool FixupInvocation(CompilerInvocation &Invocation, 553 DiagnosticsEngine &Diags, const ArgList &Args, 554 InputKind IK) { 555 unsigned NumErrorsBefore = Diags.getNumErrors(); 556 557 LangOptions &LangOpts = Invocation.getLangOpts(); 558 CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts(); 559 TargetOptions &TargetOpts = Invocation.getTargetOpts(); 560 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts(); 561 CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument; 562 CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents; 563 CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents; 564 CodeGenOpts.DisableFree = FrontendOpts.DisableFree; 565 FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex; 566 if (FrontendOpts.ShowStats) 567 CodeGenOpts.ClearASTBeforeBackend = false; 568 LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage(); 569 LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables; 570 LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening; 571 LangOpts.CurrentModule = LangOpts.ModuleName; 572 573 llvm::Triple T(TargetOpts.Triple); 574 llvm::Triple::ArchType Arch = T.getArch(); 575 576 CodeGenOpts.CodeModel = TargetOpts.CodeModel; 577 CodeGenOpts.LargeDataThreshold = TargetOpts.LargeDataThreshold; 578 579 if (LangOpts.getExceptionHandling() != 580 LangOptions::ExceptionHandlingKind::None && 581 T.isWindowsMSVCEnvironment()) 582 Diags.Report(diag::err_fe_invalid_exception_model) 583 << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str(); 584 585 if (LangOpts.AppleKext && !LangOpts.CPlusPlus) 586 Diags.Report(diag::warn_c_kext); 587 588 if (LangOpts.NewAlignOverride && 589 !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) { 590 Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ); 591 Diags.Report(diag::err_fe_invalid_alignment) 592 << A->getAsString(Args) << A->getValue(); 593 LangOpts.NewAlignOverride = 0; 594 } 595 596 // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host. 597 if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost) 598 Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device" 599 << "-fsycl-is-host"; 600 601 if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus) 602 Diags.Report(diag::err_drv_argument_not_allowed_with) 603 << "-fgnu89-inline" << GetInputKindName(IK); 604 605 if (Args.hasArg(OPT_hlsl_entrypoint) && !LangOpts.HLSL) 606 Diags.Report(diag::err_drv_argument_not_allowed_with) 607 << "-hlsl-entry" << GetInputKindName(IK); 608 609 if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP) 610 Diags.Report(diag::warn_ignored_hip_only_option) 611 << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args); 612 613 if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP) 614 Diags.Report(diag::warn_ignored_hip_only_option) 615 << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args); 616 617 // When these options are used, the compiler is allowed to apply 618 // optimizations that may affect the final result. For example 619 // (x+y)+z is transformed to x+(y+z) but may not give the same 620 // final result; it's not value safe. 621 // Another example can be to simplify x/x to 1.0 but x could be 0.0, INF 622 // or NaN. Final result may then differ. An error is issued when the eval 623 // method is set with one of these options. 624 if (Args.hasArg(OPT_ffp_eval_method_EQ)) { 625 if (LangOpts.ApproxFunc) 626 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 0; 627 if (LangOpts.AllowFPReassoc) 628 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 1; 629 if (LangOpts.AllowRecip) 630 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 2; 631 } 632 633 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0. 634 // This option should be deprecated for CL > 1.0 because 635 // this option was added for compatibility with OpenCL 1.0. 636 if (Args.getLastArg(OPT_cl_strict_aliasing) && 637 (LangOpts.getOpenCLCompatibleVersion() > 100)) 638 Diags.Report(diag::warn_option_invalid_ocl_version) 639 << LangOpts.getOpenCLVersionString() 640 << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args); 641 642 if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) { 643 auto DefaultCC = LangOpts.getDefaultCallingConv(); 644 645 bool emitError = (DefaultCC == LangOptions::DCC_FastCall || 646 DefaultCC == LangOptions::DCC_StdCall) && 647 Arch != llvm::Triple::x86; 648 emitError |= (DefaultCC == LangOptions::DCC_VectorCall || 649 DefaultCC == LangOptions::DCC_RegCall) && 650 !T.isX86(); 651 if (emitError) 652 Diags.Report(diag::err_drv_argument_not_allowed_with) 653 << A->getSpelling() << T.getTriple(); 654 } 655 656 return Diags.getNumErrors() == NumErrorsBefore; 657 } 658 659 //===----------------------------------------------------------------------===// 660 // Deserialization (from args) 661 //===----------------------------------------------------------------------===// 662 663 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK, 664 DiagnosticsEngine &Diags) { 665 unsigned DefaultOpt = 0; 666 if ((IK.getLanguage() == Language::OpenCL || 667 IK.getLanguage() == Language::OpenCLCXX) && 668 !Args.hasArg(OPT_cl_opt_disable)) 669 DefaultOpt = 2; 670 671 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 672 if (A->getOption().matches(options::OPT_O0)) 673 return 0; 674 675 if (A->getOption().matches(options::OPT_Ofast)) 676 return 3; 677 678 assert(A->getOption().matches(options::OPT_O)); 679 680 StringRef S(A->getValue()); 681 if (S == "s" || S == "z") 682 return 2; 683 684 if (S == "g") 685 return 1; 686 687 return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags); 688 } 689 690 return DefaultOpt; 691 } 692 693 static unsigned getOptimizationLevelSize(ArgList &Args) { 694 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 695 if (A->getOption().matches(options::OPT_O)) { 696 switch (A->getValue()[0]) { 697 default: 698 return 0; 699 case 's': 700 return 1; 701 case 'z': 702 return 2; 703 } 704 } 705 } 706 return 0; 707 } 708 709 static void GenerateArg(ArgumentConsumer Consumer, 710 llvm::opt::OptSpecifier OptSpecifier) { 711 Option Opt = getDriverOptTable().getOption(OptSpecifier); 712 denormalizeSimpleFlag(Consumer, Opt.getPrefixedName(), 713 Option::OptionClass::FlagClass, 0); 714 } 715 716 static void GenerateArg(ArgumentConsumer Consumer, 717 llvm::opt::OptSpecifier OptSpecifier, 718 const Twine &Value) { 719 Option Opt = getDriverOptTable().getOption(OptSpecifier); 720 denormalizeString(Consumer, Opt.getPrefixedName(), Opt.getKind(), 0, Value); 721 } 722 723 // Parse command line arguments into CompilerInvocation. 724 using ParseFn = 725 llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>, 726 DiagnosticsEngine &, const char *)>; 727 728 // Generate command line arguments from CompilerInvocation. 729 using GenerateFn = llvm::function_ref<void( 730 CompilerInvocation &, SmallVectorImpl<const char *> &, 731 CompilerInvocation::StringAllocator)>; 732 733 /// May perform round-trip of command line arguments. By default, the round-trip 734 /// is enabled in assert builds. This can be overwritten at run-time via the 735 /// "-round-trip-args" and "-no-round-trip-args" command line flags, or via the 736 /// ForceRoundTrip parameter. 737 /// 738 /// During round-trip, the command line arguments are parsed into a dummy 739 /// CompilerInvocation, which is used to generate the command line arguments 740 /// again. The real CompilerInvocation is then created by parsing the generated 741 /// arguments, not the original ones. This (in combination with tests covering 742 /// argument behavior) ensures the generated command line is complete (doesn't 743 /// drop/mangle any arguments). 744 /// 745 /// Finally, we check the command line that was used to create the real 746 /// CompilerInvocation instance. By default, we compare it to the command line 747 /// the real CompilerInvocation generates. This checks whether the generator is 748 /// deterministic. If \p CheckAgainstOriginalInvocation is enabled, we instead 749 /// compare it to the original command line to verify the original command-line 750 /// was canonical and can round-trip exactly. 751 static bool RoundTrip(ParseFn Parse, GenerateFn Generate, 752 CompilerInvocation &RealInvocation, 753 CompilerInvocation &DummyInvocation, 754 ArrayRef<const char *> CommandLineArgs, 755 DiagnosticsEngine &Diags, const char *Argv0, 756 bool CheckAgainstOriginalInvocation = false, 757 bool ForceRoundTrip = false) { 758 #ifndef NDEBUG 759 bool DoRoundTripDefault = true; 760 #else 761 bool DoRoundTripDefault = false; 762 #endif 763 764 bool DoRoundTrip = DoRoundTripDefault; 765 if (ForceRoundTrip) { 766 DoRoundTrip = true; 767 } else { 768 for (const auto *Arg : CommandLineArgs) { 769 if (Arg == StringRef("-round-trip-args")) 770 DoRoundTrip = true; 771 if (Arg == StringRef("-no-round-trip-args")) 772 DoRoundTrip = false; 773 } 774 } 775 776 // If round-trip was not requested, simply run the parser with the real 777 // invocation diagnostics. 778 if (!DoRoundTrip) 779 return Parse(RealInvocation, CommandLineArgs, Diags, Argv0); 780 781 // Serializes quoted (and potentially escaped) arguments. 782 auto SerializeArgs = [](ArrayRef<const char *> Args) { 783 std::string Buffer; 784 llvm::raw_string_ostream OS(Buffer); 785 for (const char *Arg : Args) { 786 llvm::sys::printArg(OS, Arg, /*Quote=*/true); 787 OS << ' '; 788 } 789 OS.flush(); 790 return Buffer; 791 }; 792 793 // Setup a dummy DiagnosticsEngine. 794 DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions()); 795 DummyDiags.setClient(new TextDiagnosticBuffer()); 796 797 // Run the first parse on the original arguments with the dummy invocation and 798 // diagnostics. 799 if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) || 800 DummyDiags.getNumWarnings() != 0) { 801 // If the first parse did not succeed, it must be user mistake (invalid 802 // command line arguments). We won't be able to generate arguments that 803 // would reproduce the same result. Let's fail again with the real 804 // invocation and diagnostics, so all side-effects of parsing are visible. 805 unsigned NumWarningsBefore = Diags.getNumWarnings(); 806 auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0); 807 if (!Success || Diags.getNumWarnings() != NumWarningsBefore) 808 return Success; 809 810 // Parse with original options and diagnostics succeeded even though it 811 // shouldn't have. Something is off. 812 Diags.Report(diag::err_cc1_round_trip_fail_then_ok); 813 Diags.Report(diag::note_cc1_round_trip_original) 814 << SerializeArgs(CommandLineArgs); 815 return false; 816 } 817 818 // Setup string allocator. 819 llvm::BumpPtrAllocator Alloc; 820 llvm::StringSaver StringPool(Alloc); 821 auto SA = [&StringPool](const Twine &Arg) { 822 return StringPool.save(Arg).data(); 823 }; 824 825 // Generate arguments from the dummy invocation. If Generate is the 826 // inverse of Parse, the newly generated arguments must have the same 827 // semantics as the original. 828 SmallVector<const char *> GeneratedArgs; 829 Generate(DummyInvocation, GeneratedArgs, SA); 830 831 // Run the second parse, now on the generated arguments, and with the real 832 // invocation and diagnostics. The result is what we will end up using for the 833 // rest of compilation, so if Generate is not inverse of Parse, something down 834 // the line will break. 835 bool Success2 = Parse(RealInvocation, GeneratedArgs, Diags, Argv0); 836 837 // The first parse on original arguments succeeded, but second parse of 838 // generated arguments failed. Something must be wrong with the generator. 839 if (!Success2) { 840 Diags.Report(diag::err_cc1_round_trip_ok_then_fail); 841 Diags.Report(diag::note_cc1_round_trip_generated) 842 << 1 << SerializeArgs(GeneratedArgs); 843 return false; 844 } 845 846 SmallVector<const char *> ComparisonArgs; 847 if (CheckAgainstOriginalInvocation) 848 // Compare against original arguments. 849 ComparisonArgs.assign(CommandLineArgs.begin(), CommandLineArgs.end()); 850 else 851 // Generate arguments again, this time from the options we will end up using 852 // for the rest of the compilation. 853 Generate(RealInvocation, ComparisonArgs, SA); 854 855 // Compares two lists of arguments. 856 auto Equal = [](const ArrayRef<const char *> A, 857 const ArrayRef<const char *> B) { 858 return std::equal(A.begin(), A.end(), B.begin(), B.end(), 859 [](const char *AElem, const char *BElem) { 860 return StringRef(AElem) == StringRef(BElem); 861 }); 862 }; 863 864 // If we generated different arguments from what we assume are two 865 // semantically equivalent CompilerInvocations, the Generate function may 866 // be non-deterministic. 867 if (!Equal(GeneratedArgs, ComparisonArgs)) { 868 Diags.Report(diag::err_cc1_round_trip_mismatch); 869 Diags.Report(diag::note_cc1_round_trip_generated) 870 << 1 << SerializeArgs(GeneratedArgs); 871 Diags.Report(diag::note_cc1_round_trip_generated) 872 << 2 << SerializeArgs(ComparisonArgs); 873 return false; 874 } 875 876 Diags.Report(diag::remark_cc1_round_trip_generated) 877 << 1 << SerializeArgs(GeneratedArgs); 878 Diags.Report(diag::remark_cc1_round_trip_generated) 879 << 2 << SerializeArgs(ComparisonArgs); 880 881 return Success2; 882 } 883 884 bool CompilerInvocation::checkCC1RoundTrip(ArrayRef<const char *> Args, 885 DiagnosticsEngine &Diags, 886 const char *Argv0) { 887 CompilerInvocation DummyInvocation1, DummyInvocation2; 888 return RoundTrip( 889 [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs, 890 DiagnosticsEngine &Diags, const char *Argv0) { 891 return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0); 892 }, 893 [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args, 894 StringAllocator SA) { 895 Args.push_back("-cc1"); 896 Invocation.generateCC1CommandLine(Args, SA); 897 }, 898 DummyInvocation1, DummyInvocation2, Args, Diags, Argv0, 899 /*CheckAgainstOriginalInvocation=*/true, /*ForceRoundTrip=*/true); 900 } 901 902 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, 903 OptSpecifier GroupWithValue, 904 std::vector<std::string> &Diagnostics) { 905 for (auto *A : Args.filtered(Group)) { 906 if (A->getOption().getKind() == Option::FlagClass) { 907 // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add 908 // its name (minus the "W" or "R" at the beginning) to the diagnostics. 909 Diagnostics.push_back( 910 std::string(A->getOption().getName().drop_front(1))); 911 } else if (A->getOption().matches(GroupWithValue)) { 912 // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic 913 // group. Add only the group name to the diagnostics. 914 Diagnostics.push_back( 915 std::string(A->getOption().getName().drop_front(1).rtrim("=-"))); 916 } else { 917 // Otherwise, add its value (for OPT_W_Joined and similar). 918 Diagnostics.push_back(A->getValue()); 919 } 920 } 921 } 922 923 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr, 924 // it won't verify the input. 925 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, 926 DiagnosticsEngine *Diags); 927 928 static void getAllNoBuiltinFuncValues(ArgList &Args, 929 std::vector<std::string> &Funcs) { 930 std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_); 931 auto BuiltinEnd = llvm::partition(Values, Builtin::Context::isBuiltinFunc); 932 Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd); 933 } 934 935 static void GenerateAnalyzerArgs(const AnalyzerOptions &Opts, 936 ArgumentConsumer Consumer) { 937 const AnalyzerOptions *AnalyzerOpts = &Opts; 938 939 #define ANALYZER_OPTION_WITH_MARSHALLING(...) \ 940 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 941 #include "clang/Driver/Options.inc" 942 #undef ANALYZER_OPTION_WITH_MARSHALLING 943 944 if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) { 945 switch (Opts.AnalysisConstraintsOpt) { 946 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \ 947 case NAME##Model: \ 948 GenerateArg(Consumer, OPT_analyzer_constraints, CMDFLAG); \ 949 break; 950 #include "clang/StaticAnalyzer/Core/Analyses.def" 951 default: 952 llvm_unreachable("Tried to generate unknown analysis constraint."); 953 } 954 } 955 956 if (Opts.AnalysisDiagOpt != PD_HTML) { 957 switch (Opts.AnalysisDiagOpt) { 958 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \ 959 case PD_##NAME: \ 960 GenerateArg(Consumer, OPT_analyzer_output, CMDFLAG); \ 961 break; 962 #include "clang/StaticAnalyzer/Core/Analyses.def" 963 default: 964 llvm_unreachable("Tried to generate unknown analysis diagnostic client."); 965 } 966 } 967 968 if (Opts.AnalysisPurgeOpt != PurgeStmt) { 969 switch (Opts.AnalysisPurgeOpt) { 970 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \ 971 case NAME: \ 972 GenerateArg(Consumer, OPT_analyzer_purge, CMDFLAG); \ 973 break; 974 #include "clang/StaticAnalyzer/Core/Analyses.def" 975 default: 976 llvm_unreachable("Tried to generate unknown analysis purge mode."); 977 } 978 } 979 980 if (Opts.InliningMode != NoRedundancy) { 981 switch (Opts.InliningMode) { 982 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \ 983 case NAME: \ 984 GenerateArg(Consumer, OPT_analyzer_inlining_mode, CMDFLAG); \ 985 break; 986 #include "clang/StaticAnalyzer/Core/Analyses.def" 987 default: 988 llvm_unreachable("Tried to generate unknown analysis inlining mode."); 989 } 990 } 991 992 for (const auto &CP : Opts.CheckersAndPackages) { 993 OptSpecifier Opt = 994 CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker; 995 GenerateArg(Consumer, Opt, CP.first); 996 } 997 998 AnalyzerOptions ConfigOpts; 999 parseAnalyzerConfigs(ConfigOpts, nullptr); 1000 1001 // Sort options by key to avoid relying on StringMap iteration order. 1002 SmallVector<std::pair<StringRef, StringRef>, 4> SortedConfigOpts; 1003 for (const auto &C : Opts.Config) 1004 SortedConfigOpts.emplace_back(C.getKey(), C.getValue()); 1005 llvm::sort(SortedConfigOpts, llvm::less_first()); 1006 1007 for (const auto &[Key, Value] : SortedConfigOpts) { 1008 // Don't generate anything that came from parseAnalyzerConfigs. It would be 1009 // redundant and may not be valid on the command line. 1010 auto Entry = ConfigOpts.Config.find(Key); 1011 if (Entry != ConfigOpts.Config.end() && Entry->getValue() == Value) 1012 continue; 1013 1014 GenerateArg(Consumer, OPT_analyzer_config, Key + "=" + Value); 1015 } 1016 1017 // Nothing to generate for FullCompilerInvocation. 1018 } 1019 1020 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, 1021 DiagnosticsEngine &Diags) { 1022 unsigned NumErrorsBefore = Diags.getNumErrors(); 1023 1024 AnalyzerOptions *AnalyzerOpts = &Opts; 1025 1026 #define ANALYZER_OPTION_WITH_MARSHALLING(...) \ 1027 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 1028 #include "clang/Driver/Options.inc" 1029 #undef ANALYZER_OPTION_WITH_MARSHALLING 1030 1031 if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) { 1032 StringRef Name = A->getValue(); 1033 AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name) 1034 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \ 1035 .Case(CMDFLAG, NAME##Model) 1036 #include "clang/StaticAnalyzer/Core/Analyses.def" 1037 .Default(NumConstraints); 1038 if (Value == NumConstraints) { 1039 Diags.Report(diag::err_drv_invalid_value) 1040 << A->getAsString(Args) << Name; 1041 } else { 1042 #ifndef LLVM_WITH_Z3 1043 if (Value == AnalysisConstraints::Z3ConstraintsModel) { 1044 Diags.Report(diag::err_analyzer_not_built_with_z3); 1045 } 1046 #endif // LLVM_WITH_Z3 1047 Opts.AnalysisConstraintsOpt = Value; 1048 } 1049 } 1050 1051 if (Arg *A = Args.getLastArg(OPT_analyzer_output)) { 1052 StringRef Name = A->getValue(); 1053 AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name) 1054 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \ 1055 .Case(CMDFLAG, PD_##NAME) 1056 #include "clang/StaticAnalyzer/Core/Analyses.def" 1057 .Default(NUM_ANALYSIS_DIAG_CLIENTS); 1058 if (Value == NUM_ANALYSIS_DIAG_CLIENTS) { 1059 Diags.Report(diag::err_drv_invalid_value) 1060 << A->getAsString(Args) << Name; 1061 } else { 1062 Opts.AnalysisDiagOpt = Value; 1063 } 1064 } 1065 1066 if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) { 1067 StringRef Name = A->getValue(); 1068 AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name) 1069 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \ 1070 .Case(CMDFLAG, NAME) 1071 #include "clang/StaticAnalyzer/Core/Analyses.def" 1072 .Default(NumPurgeModes); 1073 if (Value == NumPurgeModes) { 1074 Diags.Report(diag::err_drv_invalid_value) 1075 << A->getAsString(Args) << Name; 1076 } else { 1077 Opts.AnalysisPurgeOpt = Value; 1078 } 1079 } 1080 1081 if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) { 1082 StringRef Name = A->getValue(); 1083 AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name) 1084 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \ 1085 .Case(CMDFLAG, NAME) 1086 #include "clang/StaticAnalyzer/Core/Analyses.def" 1087 .Default(NumInliningModes); 1088 if (Value == NumInliningModes) { 1089 Diags.Report(diag::err_drv_invalid_value) 1090 << A->getAsString(Args) << Name; 1091 } else { 1092 Opts.InliningMode = Value; 1093 } 1094 } 1095 1096 Opts.CheckersAndPackages.clear(); 1097 for (const Arg *A : 1098 Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) { 1099 A->claim(); 1100 bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker; 1101 // We can have a list of comma separated checker names, e.g: 1102 // '-analyzer-checker=cocoa,unix' 1103 StringRef CheckerAndPackageList = A->getValue(); 1104 SmallVector<StringRef, 16> CheckersAndPackages; 1105 CheckerAndPackageList.split(CheckersAndPackages, ","); 1106 for (const StringRef &CheckerOrPackage : CheckersAndPackages) 1107 Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage), 1108 IsEnabled); 1109 } 1110 1111 // Go through the analyzer configuration options. 1112 for (const auto *A : Args.filtered(OPT_analyzer_config)) { 1113 1114 // We can have a list of comma separated config names, e.g: 1115 // '-analyzer-config key1=val1,key2=val2' 1116 StringRef configList = A->getValue(); 1117 SmallVector<StringRef, 4> configVals; 1118 configList.split(configVals, ","); 1119 for (const auto &configVal : configVals) { 1120 StringRef key, val; 1121 std::tie(key, val) = configVal.split("="); 1122 if (val.empty()) { 1123 Diags.Report(SourceLocation(), 1124 diag::err_analyzer_config_no_value) << configVal; 1125 break; 1126 } 1127 if (val.contains('=')) { 1128 Diags.Report(SourceLocation(), 1129 diag::err_analyzer_config_multiple_values) 1130 << configVal; 1131 break; 1132 } 1133 1134 // TODO: Check checker options too, possibly in CheckerRegistry. 1135 // Leave unknown non-checker configs unclaimed. 1136 if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) { 1137 if (Opts.ShouldEmitErrorsOnInvalidConfigValue) 1138 Diags.Report(diag::err_analyzer_config_unknown) << key; 1139 continue; 1140 } 1141 1142 A->claim(); 1143 Opts.Config[key] = std::string(val); 1144 } 1145 } 1146 1147 if (Opts.ShouldEmitErrorsOnInvalidConfigValue) 1148 parseAnalyzerConfigs(Opts, &Diags); 1149 else 1150 parseAnalyzerConfigs(Opts, nullptr); 1151 1152 llvm::raw_string_ostream os(Opts.FullCompilerInvocation); 1153 for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) { 1154 if (i != 0) 1155 os << " "; 1156 os << Args.getArgString(i); 1157 } 1158 os.flush(); 1159 1160 return Diags.getNumErrors() == NumErrorsBefore; 1161 } 1162 1163 static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config, 1164 StringRef OptionName, StringRef DefaultVal) { 1165 return Config.insert({OptionName, std::string(DefaultVal)}).first->second; 1166 } 1167 1168 static void initOption(AnalyzerOptions::ConfigTable &Config, 1169 DiagnosticsEngine *Diags, 1170 StringRef &OptionField, StringRef Name, 1171 StringRef DefaultVal) { 1172 // String options may be known to invalid (e.g. if the expected string is a 1173 // file name, but the file does not exist), those will have to be checked in 1174 // parseConfigs. 1175 OptionField = getStringOption(Config, Name, DefaultVal); 1176 } 1177 1178 static void initOption(AnalyzerOptions::ConfigTable &Config, 1179 DiagnosticsEngine *Diags, 1180 bool &OptionField, StringRef Name, bool DefaultVal) { 1181 auto PossiblyInvalidVal = 1182 llvm::StringSwitch<std::optional<bool>>( 1183 getStringOption(Config, Name, (DefaultVal ? "true" : "false"))) 1184 .Case("true", true) 1185 .Case("false", false) 1186 .Default(std::nullopt); 1187 1188 if (!PossiblyInvalidVal) { 1189 if (Diags) 1190 Diags->Report(diag::err_analyzer_config_invalid_input) 1191 << Name << "a boolean"; 1192 else 1193 OptionField = DefaultVal; 1194 } else 1195 OptionField = *PossiblyInvalidVal; 1196 } 1197 1198 static void initOption(AnalyzerOptions::ConfigTable &Config, 1199 DiagnosticsEngine *Diags, 1200 unsigned &OptionField, StringRef Name, 1201 unsigned DefaultVal) { 1202 1203 OptionField = DefaultVal; 1204 bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal)) 1205 .getAsInteger(0, OptionField); 1206 if (Diags && HasFailed) 1207 Diags->Report(diag::err_analyzer_config_invalid_input) 1208 << Name << "an unsigned"; 1209 } 1210 1211 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, 1212 DiagnosticsEngine *Diags) { 1213 // TODO: There's no need to store the entire configtable, it'd be plenty 1214 // enough to store checker options. 1215 1216 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \ 1217 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL); 1218 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(...) 1219 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def" 1220 1221 assert(AnOpts.UserMode == "shallow" || AnOpts.UserMode == "deep"); 1222 const bool InShallowMode = AnOpts.UserMode == "shallow"; 1223 1224 #define ANALYZER_OPTION(...) 1225 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \ 1226 SHALLOW_VAL, DEEP_VAL) \ 1227 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, \ 1228 InShallowMode ? SHALLOW_VAL : DEEP_VAL); 1229 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def" 1230 1231 // At this point, AnalyzerOptions is configured. Let's validate some options. 1232 1233 // FIXME: Here we try to validate the silenced checkers or packages are valid. 1234 // The current approach only validates the registered checkers which does not 1235 // contain the runtime enabled checkers and optimally we would validate both. 1236 if (!AnOpts.RawSilencedCheckersAndPackages.empty()) { 1237 std::vector<StringRef> Checkers = 1238 AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true); 1239 std::vector<StringRef> Packages = 1240 AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true); 1241 1242 SmallVector<StringRef, 16> CheckersAndPackages; 1243 AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";"); 1244 1245 for (const StringRef &CheckerOrPackage : CheckersAndPackages) { 1246 if (Diags) { 1247 bool IsChecker = CheckerOrPackage.contains('.'); 1248 bool IsValidName = IsChecker 1249 ? llvm::is_contained(Checkers, CheckerOrPackage) 1250 : llvm::is_contained(Packages, CheckerOrPackage); 1251 1252 if (!IsValidName) 1253 Diags->Report(diag::err_unknown_analyzer_checker_or_package) 1254 << CheckerOrPackage; 1255 } 1256 1257 AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage); 1258 } 1259 } 1260 1261 if (!Diags) 1262 return; 1263 1264 if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions) 1265 Diags->Report(diag::err_analyzer_config_invalid_input) 1266 << "track-conditions-debug" << "'track-conditions' to also be enabled"; 1267 1268 if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir)) 1269 Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir" 1270 << "a filename"; 1271 1272 if (!AnOpts.ModelPath.empty() && 1273 !llvm::sys::fs::is_directory(AnOpts.ModelPath)) 1274 Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path" 1275 << "a filename"; 1276 } 1277 1278 /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`. 1279 static void 1280 GenerateOptimizationRemark(ArgumentConsumer Consumer, OptSpecifier OptEQ, 1281 StringRef Name, 1282 const CodeGenOptions::OptRemark &Remark) { 1283 if (Remark.hasValidPattern()) { 1284 GenerateArg(Consumer, OptEQ, Remark.Pattern); 1285 } else if (Remark.Kind == CodeGenOptions::RK_Enabled) { 1286 GenerateArg(Consumer, OPT_R_Joined, Name); 1287 } else if (Remark.Kind == CodeGenOptions::RK_Disabled) { 1288 GenerateArg(Consumer, OPT_R_Joined, StringRef("no-") + Name); 1289 } 1290 } 1291 1292 /// Parse a remark command line argument. It may be missing, disabled/enabled by 1293 /// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'. 1294 /// On top of that, it can be disabled/enabled globally by '-R[no-]everything'. 1295 static CodeGenOptions::OptRemark 1296 ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args, 1297 OptSpecifier OptEQ, StringRef Name) { 1298 CodeGenOptions::OptRemark Result; 1299 1300 auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A, 1301 StringRef Pattern) { 1302 Result.Pattern = Pattern.str(); 1303 1304 std::string RegexError; 1305 Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern); 1306 if (!Result.Regex->isValid(RegexError)) { 1307 Diags.Report(diag::err_drv_optimization_remark_pattern) 1308 << RegexError << A->getAsString(Args); 1309 return false; 1310 } 1311 1312 return true; 1313 }; 1314 1315 for (Arg *A : Args) { 1316 if (A->getOption().matches(OPT_R_Joined)) { 1317 StringRef Value = A->getValue(); 1318 1319 if (Value == Name) 1320 Result.Kind = CodeGenOptions::RK_Enabled; 1321 else if (Value == "everything") 1322 Result.Kind = CodeGenOptions::RK_EnabledEverything; 1323 else if (Value.split('-') == std::make_pair(StringRef("no"), Name)) 1324 Result.Kind = CodeGenOptions::RK_Disabled; 1325 else if (Value == "no-everything") 1326 Result.Kind = CodeGenOptions::RK_DisabledEverything; 1327 else 1328 continue; 1329 1330 if (Result.Kind == CodeGenOptions::RK_Disabled || 1331 Result.Kind == CodeGenOptions::RK_DisabledEverything) { 1332 Result.Pattern = ""; 1333 Result.Regex = nullptr; 1334 } else { 1335 InitializeResultPattern(A, ".*"); 1336 } 1337 } else if (A->getOption().matches(OptEQ)) { 1338 Result.Kind = CodeGenOptions::RK_WithPattern; 1339 if (!InitializeResultPattern(A, A->getValue())) 1340 return CodeGenOptions::OptRemark(); 1341 } 1342 } 1343 1344 return Result; 1345 } 1346 1347 static bool parseDiagnosticLevelMask(StringRef FlagName, 1348 const std::vector<std::string> &Levels, 1349 DiagnosticsEngine &Diags, 1350 DiagnosticLevelMask &M) { 1351 bool Success = true; 1352 for (const auto &Level : Levels) { 1353 DiagnosticLevelMask const PM = 1354 llvm::StringSwitch<DiagnosticLevelMask>(Level) 1355 .Case("note", DiagnosticLevelMask::Note) 1356 .Case("remark", DiagnosticLevelMask::Remark) 1357 .Case("warning", DiagnosticLevelMask::Warning) 1358 .Case("error", DiagnosticLevelMask::Error) 1359 .Default(DiagnosticLevelMask::None); 1360 if (PM == DiagnosticLevelMask::None) { 1361 Success = false; 1362 Diags.Report(diag::err_drv_invalid_value) << FlagName << Level; 1363 } 1364 M = M | PM; 1365 } 1366 return Success; 1367 } 1368 1369 static void parseSanitizerKinds(StringRef FlagName, 1370 const std::vector<std::string> &Sanitizers, 1371 DiagnosticsEngine &Diags, SanitizerSet &S) { 1372 for (const auto &Sanitizer : Sanitizers) { 1373 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false); 1374 if (K == SanitizerMask()) 1375 Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer; 1376 else 1377 S.set(K, true); 1378 } 1379 } 1380 1381 static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) { 1382 SmallVector<StringRef, 4> Values; 1383 serializeSanitizerSet(S, Values); 1384 return Values; 1385 } 1386 1387 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle, 1388 ArgList &Args, DiagnosticsEngine &D, 1389 XRayInstrSet &S) { 1390 llvm::SmallVector<StringRef, 2> BundleParts; 1391 llvm::SplitString(Bundle, BundleParts, ","); 1392 for (const auto &B : BundleParts) { 1393 auto Mask = parseXRayInstrValue(B); 1394 if (Mask == XRayInstrKind::None) 1395 if (B != "none") 1396 D.Report(diag::err_drv_invalid_value) << FlagName << Bundle; 1397 else 1398 S.Mask = Mask; 1399 else if (Mask == XRayInstrKind::All) 1400 S.Mask = Mask; 1401 else 1402 S.set(Mask, true); 1403 } 1404 } 1405 1406 static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) { 1407 llvm::SmallVector<StringRef, 2> BundleParts; 1408 serializeXRayInstrValue(S, BundleParts); 1409 std::string Buffer; 1410 llvm::raw_string_ostream OS(Buffer); 1411 llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ","); 1412 return Buffer; 1413 } 1414 1415 // Set the profile kind using fprofile-instrument-use-path. 1416 static void setPGOUseInstrumentor(CodeGenOptions &Opts, 1417 const Twine &ProfileName, 1418 llvm::vfs::FileSystem &FS, 1419 DiagnosticsEngine &Diags) { 1420 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName, FS); 1421 if (auto E = ReaderOrErr.takeError()) { 1422 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1423 "Error in reading profile %0: %1"); 1424 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 1425 Diags.Report(DiagID) << ProfileName.str() << EI.message(); 1426 }); 1427 return; 1428 } 1429 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader = 1430 std::move(ReaderOrErr.get()); 1431 // Currently memprof profiles are only added at the IR level. Mark the profile 1432 // type as IR in that case as well and the subsequent matching needs to detect 1433 // which is available (might be one or both). 1434 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) { 1435 if (PGOReader->hasCSIRLevelProfile()) 1436 Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr); 1437 else 1438 Opts.setProfileUse(CodeGenOptions::ProfileIRInstr); 1439 } else 1440 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr); 1441 } 1442 1443 void CompilerInvocationBase::GenerateCodeGenArgs(const CodeGenOptions &Opts, 1444 ArgumentConsumer Consumer, 1445 const llvm::Triple &T, 1446 const std::string &OutputFile, 1447 const LangOptions *LangOpts) { 1448 const CodeGenOptions &CodeGenOpts = Opts; 1449 1450 if (Opts.OptimizationLevel == 0) 1451 GenerateArg(Consumer, OPT_O0); 1452 else 1453 GenerateArg(Consumer, OPT_O, Twine(Opts.OptimizationLevel)); 1454 1455 #define CODEGEN_OPTION_WITH_MARSHALLING(...) \ 1456 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 1457 #include "clang/Driver/Options.inc" 1458 #undef CODEGEN_OPTION_WITH_MARSHALLING 1459 1460 if (Opts.OptimizationLevel > 0) { 1461 if (Opts.Inlining == CodeGenOptions::NormalInlining) 1462 GenerateArg(Consumer, OPT_finline_functions); 1463 else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining) 1464 GenerateArg(Consumer, OPT_finline_hint_functions); 1465 else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining) 1466 GenerateArg(Consumer, OPT_fno_inline); 1467 } 1468 1469 if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0) 1470 GenerateArg(Consumer, OPT_fdirect_access_external_data); 1471 else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0) 1472 GenerateArg(Consumer, OPT_fno_direct_access_external_data); 1473 1474 std::optional<StringRef> DebugInfoVal; 1475 switch (Opts.DebugInfo) { 1476 case llvm::codegenoptions::DebugLineTablesOnly: 1477 DebugInfoVal = "line-tables-only"; 1478 break; 1479 case llvm::codegenoptions::DebugDirectivesOnly: 1480 DebugInfoVal = "line-directives-only"; 1481 break; 1482 case llvm::codegenoptions::DebugInfoConstructor: 1483 DebugInfoVal = "constructor"; 1484 break; 1485 case llvm::codegenoptions::LimitedDebugInfo: 1486 DebugInfoVal = "limited"; 1487 break; 1488 case llvm::codegenoptions::FullDebugInfo: 1489 DebugInfoVal = "standalone"; 1490 break; 1491 case llvm::codegenoptions::UnusedTypeInfo: 1492 DebugInfoVal = "unused-types"; 1493 break; 1494 case llvm::codegenoptions::NoDebugInfo: // default value 1495 DebugInfoVal = std::nullopt; 1496 break; 1497 case llvm::codegenoptions::LocTrackingOnly: // implied value 1498 DebugInfoVal = std::nullopt; 1499 break; 1500 } 1501 if (DebugInfoVal) 1502 GenerateArg(Consumer, OPT_debug_info_kind_EQ, *DebugInfoVal); 1503 1504 for (const auto &Prefix : Opts.DebugPrefixMap) 1505 GenerateArg(Consumer, OPT_fdebug_prefix_map_EQ, 1506 Prefix.first + "=" + Prefix.second); 1507 1508 for (const auto &Prefix : Opts.CoveragePrefixMap) 1509 GenerateArg(Consumer, OPT_fcoverage_prefix_map_EQ, 1510 Prefix.first + "=" + Prefix.second); 1511 1512 if (Opts.NewStructPathTBAA) 1513 GenerateArg(Consumer, OPT_new_struct_path_tbaa); 1514 1515 if (Opts.OptimizeSize == 1) 1516 GenerateArg(Consumer, OPT_O, "s"); 1517 else if (Opts.OptimizeSize == 2) 1518 GenerateArg(Consumer, OPT_O, "z"); 1519 1520 // SimplifyLibCalls is set only in the absence of -fno-builtin and 1521 // -ffreestanding. We'll consider that when generating them. 1522 1523 // NoBuiltinFuncs are generated by LangOptions. 1524 1525 if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1) 1526 GenerateArg(Consumer, OPT_funroll_loops); 1527 else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1) 1528 GenerateArg(Consumer, OPT_fno_unroll_loops); 1529 1530 if (!Opts.BinutilsVersion.empty()) 1531 GenerateArg(Consumer, OPT_fbinutils_version_EQ, Opts.BinutilsVersion); 1532 1533 if (Opts.DebugNameTable == 1534 static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU)) 1535 GenerateArg(Consumer, OPT_ggnu_pubnames); 1536 else if (Opts.DebugNameTable == 1537 static_cast<unsigned>( 1538 llvm::DICompileUnit::DebugNameTableKind::Default)) 1539 GenerateArg(Consumer, OPT_gpubnames); 1540 1541 auto TNK = Opts.getDebugSimpleTemplateNames(); 1542 if (TNK != llvm::codegenoptions::DebugTemplateNamesKind::Full) { 1543 if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Simple) 1544 GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "simple"); 1545 else if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Mangled) 1546 GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "mangled"); 1547 } 1548 // ProfileInstrumentUsePath is marshalled automatically, no need to generate 1549 // it or PGOUseInstrumentor. 1550 1551 if (Opts.TimePasses) { 1552 if (Opts.TimePassesPerRun) 1553 GenerateArg(Consumer, OPT_ftime_report_EQ, "per-pass-run"); 1554 else 1555 GenerateArg(Consumer, OPT_ftime_report); 1556 } 1557 1558 if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO) 1559 GenerateArg(Consumer, OPT_flto_EQ, "full"); 1560 1561 if (Opts.PrepareForThinLTO) 1562 GenerateArg(Consumer, OPT_flto_EQ, "thin"); 1563 1564 if (!Opts.ThinLTOIndexFile.empty()) 1565 GenerateArg(Consumer, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile); 1566 1567 if (Opts.SaveTempsFilePrefix == OutputFile) 1568 GenerateArg(Consumer, OPT_save_temps_EQ, "obj"); 1569 1570 StringRef MemProfileBasename("memprof.profraw"); 1571 if (!Opts.MemoryProfileOutput.empty()) { 1572 if (Opts.MemoryProfileOutput == MemProfileBasename) { 1573 GenerateArg(Consumer, OPT_fmemory_profile); 1574 } else { 1575 size_t ArgLength = 1576 Opts.MemoryProfileOutput.size() - MemProfileBasename.size(); 1577 GenerateArg(Consumer, OPT_fmemory_profile_EQ, 1578 Opts.MemoryProfileOutput.substr(0, ArgLength)); 1579 } 1580 } 1581 1582 if (memcmp(Opts.CoverageVersion, "408*", 4) != 0) 1583 GenerateArg(Consumer, OPT_coverage_version_EQ, 1584 StringRef(Opts.CoverageVersion, 4)); 1585 1586 // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely 1587 // '-fembed_bitcode', which does not map to any CompilerInvocation field and 1588 // won't be generated.) 1589 1590 if (Opts.XRayInstrumentationBundle.Mask != XRayInstrKind::All) { 1591 std::string InstrBundle = 1592 serializeXRayInstrumentationBundle(Opts.XRayInstrumentationBundle); 1593 if (!InstrBundle.empty()) 1594 GenerateArg(Consumer, OPT_fxray_instrumentation_bundle, InstrBundle); 1595 } 1596 1597 if (Opts.CFProtectionReturn && Opts.CFProtectionBranch) 1598 GenerateArg(Consumer, OPT_fcf_protection_EQ, "full"); 1599 else if (Opts.CFProtectionReturn) 1600 GenerateArg(Consumer, OPT_fcf_protection_EQ, "return"); 1601 else if (Opts.CFProtectionBranch) 1602 GenerateArg(Consumer, OPT_fcf_protection_EQ, "branch"); 1603 1604 if (Opts.FunctionReturnThunks) 1605 GenerateArg(Consumer, OPT_mfunction_return_EQ, "thunk-extern"); 1606 1607 for (const auto &F : Opts.LinkBitcodeFiles) { 1608 bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded && 1609 F.PropagateAttrs && F.Internalize; 1610 GenerateArg(Consumer, 1611 Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file, 1612 F.Filename); 1613 } 1614 1615 if (Opts.EmulatedTLS) 1616 GenerateArg(Consumer, OPT_femulated_tls); 1617 1618 if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE()) 1619 GenerateArg(Consumer, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str()); 1620 1621 if ((Opts.FPDenormalMode != Opts.FP32DenormalMode) || 1622 (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE())) 1623 GenerateArg(Consumer, OPT_fdenormal_fp_math_f32_EQ, 1624 Opts.FP32DenormalMode.str()); 1625 1626 if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) { 1627 OptSpecifier Opt = 1628 T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return; 1629 GenerateArg(Consumer, Opt); 1630 } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) { 1631 OptSpecifier Opt = 1632 T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return; 1633 GenerateArg(Consumer, Opt); 1634 } 1635 1636 if (Opts.EnableAIXExtendedAltivecABI) 1637 GenerateArg(Consumer, OPT_mabi_EQ_vec_extabi); 1638 1639 if (Opts.XCOFFReadOnlyPointers) 1640 GenerateArg(Consumer, OPT_mxcoff_roptr); 1641 1642 if (!Opts.OptRecordPasses.empty()) 1643 GenerateArg(Consumer, OPT_opt_record_passes, Opts.OptRecordPasses); 1644 1645 if (!Opts.OptRecordFormat.empty()) 1646 GenerateArg(Consumer, OPT_opt_record_format, Opts.OptRecordFormat); 1647 1648 GenerateOptimizationRemark(Consumer, OPT_Rpass_EQ, "pass", 1649 Opts.OptimizationRemark); 1650 1651 GenerateOptimizationRemark(Consumer, OPT_Rpass_missed_EQ, "pass-missed", 1652 Opts.OptimizationRemarkMissed); 1653 1654 GenerateOptimizationRemark(Consumer, OPT_Rpass_analysis_EQ, "pass-analysis", 1655 Opts.OptimizationRemarkAnalysis); 1656 1657 GenerateArg(Consumer, OPT_fdiagnostics_hotness_threshold_EQ, 1658 Opts.DiagnosticsHotnessThreshold 1659 ? Twine(*Opts.DiagnosticsHotnessThreshold) 1660 : "auto"); 1661 1662 GenerateArg(Consumer, OPT_fdiagnostics_misexpect_tolerance_EQ, 1663 Twine(*Opts.DiagnosticsMisExpectTolerance)); 1664 1665 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover)) 1666 GenerateArg(Consumer, OPT_fsanitize_recover_EQ, Sanitizer); 1667 1668 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap)) 1669 GenerateArg(Consumer, OPT_fsanitize_trap_EQ, Sanitizer); 1670 1671 if (!Opts.EmitVersionIdentMetadata) 1672 GenerateArg(Consumer, OPT_Qn); 1673 1674 switch (Opts.FiniteLoops) { 1675 case CodeGenOptions::FiniteLoopsKind::Language: 1676 break; 1677 case CodeGenOptions::FiniteLoopsKind::Always: 1678 GenerateArg(Consumer, OPT_ffinite_loops); 1679 break; 1680 case CodeGenOptions::FiniteLoopsKind::Never: 1681 GenerateArg(Consumer, OPT_fno_finite_loops); 1682 break; 1683 } 1684 } 1685 1686 bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, 1687 InputKind IK, 1688 DiagnosticsEngine &Diags, 1689 const llvm::Triple &T, 1690 const std::string &OutputFile, 1691 const LangOptions &LangOptsRef) { 1692 unsigned NumErrorsBefore = Diags.getNumErrors(); 1693 1694 unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags); 1695 // TODO: This could be done in Driver 1696 unsigned MaxOptLevel = 3; 1697 if (OptimizationLevel > MaxOptLevel) { 1698 // If the optimization level is not supported, fall back on the default 1699 // optimization 1700 Diags.Report(diag::warn_drv_optimization_value) 1701 << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel; 1702 OptimizationLevel = MaxOptLevel; 1703 } 1704 Opts.OptimizationLevel = OptimizationLevel; 1705 1706 // The key paths of codegen options defined in Options.td start with 1707 // "CodeGenOpts.". Let's provide the expected variable name and type. 1708 CodeGenOptions &CodeGenOpts = Opts; 1709 // Some codegen options depend on language options. Let's provide the expected 1710 // variable name and type. 1711 const LangOptions *LangOpts = &LangOptsRef; 1712 1713 #define CODEGEN_OPTION_WITH_MARSHALLING(...) \ 1714 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 1715 #include "clang/Driver/Options.inc" 1716 #undef CODEGEN_OPTION_WITH_MARSHALLING 1717 1718 // At O0 we want to fully disable inlining outside of cases marked with 1719 // 'alwaysinline' that are required for correctness. 1720 if (Opts.OptimizationLevel == 0) { 1721 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining); 1722 } else if (const Arg *A = Args.getLastArg(options::OPT_finline_functions, 1723 options::OPT_finline_hint_functions, 1724 options::OPT_fno_inline_functions, 1725 options::OPT_fno_inline)) { 1726 // Explicit inlining flags can disable some or all inlining even at 1727 // optimization levels above zero. 1728 if (A->getOption().matches(options::OPT_finline_functions)) 1729 Opts.setInlining(CodeGenOptions::NormalInlining); 1730 else if (A->getOption().matches(options::OPT_finline_hint_functions)) 1731 Opts.setInlining(CodeGenOptions::OnlyHintInlining); 1732 else 1733 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining); 1734 } else { 1735 Opts.setInlining(CodeGenOptions::NormalInlining); 1736 } 1737 1738 // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to 1739 // -fdirect-access-external-data. 1740 Opts.DirectAccessExternalData = 1741 Args.hasArg(OPT_fdirect_access_external_data) || 1742 (!Args.hasArg(OPT_fno_direct_access_external_data) && 1743 LangOpts->PICLevel == 0); 1744 1745 if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) { 1746 unsigned Val = 1747 llvm::StringSwitch<unsigned>(A->getValue()) 1748 .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly) 1749 .Case("line-directives-only", 1750 llvm::codegenoptions::DebugDirectivesOnly) 1751 .Case("constructor", llvm::codegenoptions::DebugInfoConstructor) 1752 .Case("limited", llvm::codegenoptions::LimitedDebugInfo) 1753 .Case("standalone", llvm::codegenoptions::FullDebugInfo) 1754 .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo) 1755 .Default(~0U); 1756 if (Val == ~0U) 1757 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 1758 << A->getValue(); 1759 else 1760 Opts.setDebugInfo(static_cast<llvm::codegenoptions::DebugInfoKind>(Val)); 1761 } 1762 1763 // If -fuse-ctor-homing is set and limited debug info is already on, then use 1764 // constructor homing, and vice versa for -fno-use-ctor-homing. 1765 if (const Arg *A = 1766 Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) { 1767 if (A->getOption().matches(OPT_fuse_ctor_homing) && 1768 Opts.getDebugInfo() == llvm::codegenoptions::LimitedDebugInfo) 1769 Opts.setDebugInfo(llvm::codegenoptions::DebugInfoConstructor); 1770 if (A->getOption().matches(OPT_fno_use_ctor_homing) && 1771 Opts.getDebugInfo() == llvm::codegenoptions::DebugInfoConstructor) 1772 Opts.setDebugInfo(llvm::codegenoptions::LimitedDebugInfo); 1773 } 1774 1775 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) { 1776 auto Split = StringRef(Arg).split('='); 1777 Opts.DebugPrefixMap.emplace_back(Split.first, Split.second); 1778 } 1779 1780 for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) { 1781 auto Split = StringRef(Arg).split('='); 1782 Opts.CoveragePrefixMap.emplace_back(Split.first, Split.second); 1783 } 1784 1785 const llvm::Triple::ArchType DebugEntryValueArchs[] = { 1786 llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64, 1787 llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips, 1788 llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el}; 1789 1790 if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() && 1791 llvm::is_contained(DebugEntryValueArchs, T.getArch())) 1792 Opts.EmitCallSiteInfo = true; 1793 1794 if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) { 1795 Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export) 1796 << Opts.DIBugsReportFilePath; 1797 Opts.DIBugsReportFilePath = ""; 1798 } 1799 1800 Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) && 1801 Args.hasArg(OPT_new_struct_path_tbaa); 1802 Opts.OptimizeSize = getOptimizationLevelSize(Args); 1803 Opts.SimplifyLibCalls = !LangOpts->NoBuiltin; 1804 if (Opts.SimplifyLibCalls) 1805 Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs; 1806 Opts.UnrollLoops = 1807 Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops, 1808 (Opts.OptimizationLevel > 1)); 1809 Opts.BinutilsVersion = 1810 std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ)); 1811 1812 Opts.DebugNameTable = static_cast<unsigned>( 1813 Args.hasArg(OPT_ggnu_pubnames) 1814 ? llvm::DICompileUnit::DebugNameTableKind::GNU 1815 : Args.hasArg(OPT_gpubnames) 1816 ? llvm::DICompileUnit::DebugNameTableKind::Default 1817 : llvm::DICompileUnit::DebugNameTableKind::None); 1818 if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) { 1819 StringRef Value = A->getValue(); 1820 if (Value != "simple" && Value != "mangled") 1821 Diags.Report(diag::err_drv_unsupported_option_argument) 1822 << A->getSpelling() << A->getValue(); 1823 Opts.setDebugSimpleTemplateNames( 1824 StringRef(A->getValue()) == "simple" 1825 ? llvm::codegenoptions::DebugTemplateNamesKind::Simple 1826 : llvm::codegenoptions::DebugTemplateNamesKind::Mangled); 1827 } 1828 1829 if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) { 1830 Opts.TimePasses = true; 1831 1832 // -ftime-report= is only for new pass manager. 1833 if (A->getOption().getID() == OPT_ftime_report_EQ) { 1834 StringRef Val = A->getValue(); 1835 if (Val == "per-pass") 1836 Opts.TimePassesPerRun = false; 1837 else if (Val == "per-pass-run") 1838 Opts.TimePassesPerRun = true; 1839 else 1840 Diags.Report(diag::err_drv_invalid_value) 1841 << A->getAsString(Args) << A->getValue(); 1842 } 1843 } 1844 1845 Opts.PrepareForLTO = false; 1846 Opts.PrepareForThinLTO = false; 1847 if (Arg *A = Args.getLastArg(OPT_flto_EQ)) { 1848 Opts.PrepareForLTO = true; 1849 StringRef S = A->getValue(); 1850 if (S == "thin") 1851 Opts.PrepareForThinLTO = true; 1852 else if (S != "full") 1853 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S; 1854 if (Args.hasArg(OPT_funified_lto)) 1855 Opts.PrepareForThinLTO = true; 1856 } 1857 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) { 1858 if (IK.getLanguage() != Language::LLVM_IR) 1859 Diags.Report(diag::err_drv_argument_only_allowed_with) 1860 << A->getAsString(Args) << "-x ir"; 1861 Opts.ThinLTOIndexFile = 1862 std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ)); 1863 } 1864 if (Arg *A = Args.getLastArg(OPT_save_temps_EQ)) 1865 Opts.SaveTempsFilePrefix = 1866 llvm::StringSwitch<std::string>(A->getValue()) 1867 .Case("obj", OutputFile) 1868 .Default(llvm::sys::path::filename(OutputFile).str()); 1869 1870 // The memory profile runtime appends the pid to make this name more unique. 1871 const char *MemProfileBasename = "memprof.profraw"; 1872 if (Args.hasArg(OPT_fmemory_profile_EQ)) { 1873 SmallString<128> Path( 1874 std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ))); 1875 llvm::sys::path::append(Path, MemProfileBasename); 1876 Opts.MemoryProfileOutput = std::string(Path); 1877 } else if (Args.hasArg(OPT_fmemory_profile)) 1878 Opts.MemoryProfileOutput = MemProfileBasename; 1879 1880 memcpy(Opts.CoverageVersion, "408*", 4); 1881 if (Opts.CoverageNotesFile.size() || Opts.CoverageDataFile.size()) { 1882 if (Args.hasArg(OPT_coverage_version_EQ)) { 1883 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ); 1884 if (CoverageVersion.size() != 4) { 1885 Diags.Report(diag::err_drv_invalid_value) 1886 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args) 1887 << CoverageVersion; 1888 } else { 1889 memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4); 1890 } 1891 } 1892 } 1893 // FIXME: For backend options that are not yet recorded as function 1894 // attributes in the IR, keep track of them so we can embed them in a 1895 // separate data section and use them when building the bitcode. 1896 for (const auto &A : Args) { 1897 // Do not encode output and input. 1898 if (A->getOption().getID() == options::OPT_o || 1899 A->getOption().getID() == options::OPT_INPUT || 1900 A->getOption().getID() == options::OPT_x || 1901 A->getOption().getID() == options::OPT_fembed_bitcode || 1902 A->getOption().matches(options::OPT_W_Group)) 1903 continue; 1904 ArgStringList ASL; 1905 A->render(Args, ASL); 1906 for (const auto &arg : ASL) { 1907 StringRef ArgStr(arg); 1908 Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end()); 1909 // using \00 to separate each commandline options. 1910 Opts.CmdArgs.push_back('\0'); 1911 } 1912 } 1913 1914 auto XRayInstrBundles = 1915 Args.getAllArgValues(OPT_fxray_instrumentation_bundle); 1916 if (XRayInstrBundles.empty()) 1917 Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All; 1918 else 1919 for (const auto &A : XRayInstrBundles) 1920 parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args, 1921 Diags, Opts.XRayInstrumentationBundle); 1922 1923 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 1924 StringRef Name = A->getValue(); 1925 if (Name == "full") { 1926 Opts.CFProtectionReturn = 1; 1927 Opts.CFProtectionBranch = 1; 1928 } else if (Name == "return") 1929 Opts.CFProtectionReturn = 1; 1930 else if (Name == "branch") 1931 Opts.CFProtectionBranch = 1; 1932 else if (Name != "none") 1933 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 1934 } 1935 1936 if (const Arg *A = Args.getLastArg(OPT_mfunction_return_EQ)) { 1937 auto Val = llvm::StringSwitch<llvm::FunctionReturnThunksKind>(A->getValue()) 1938 .Case("keep", llvm::FunctionReturnThunksKind::Keep) 1939 .Case("thunk-extern", llvm::FunctionReturnThunksKind::Extern) 1940 .Default(llvm::FunctionReturnThunksKind::Invalid); 1941 // SystemZ might want to add support for "expolines." 1942 if (!T.isX86()) 1943 Diags.Report(diag::err_drv_argument_not_allowed_with) 1944 << A->getSpelling() << T.getTriple(); 1945 else if (Val == llvm::FunctionReturnThunksKind::Invalid) 1946 Diags.Report(diag::err_drv_invalid_value) 1947 << A->getAsString(Args) << A->getValue(); 1948 else if (Val == llvm::FunctionReturnThunksKind::Extern && 1949 Args.getLastArgValue(OPT_mcmodel_EQ).equals("large")) 1950 Diags.Report(diag::err_drv_argument_not_allowed_with) 1951 << A->getAsString(Args) 1952 << Args.getLastArg(OPT_mcmodel_EQ)->getAsString(Args); 1953 else 1954 Opts.FunctionReturnThunks = static_cast<unsigned>(Val); 1955 } 1956 1957 for (auto *A : 1958 Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) { 1959 CodeGenOptions::BitcodeFileToLink F; 1960 F.Filename = A->getValue(); 1961 if (A->getOption().matches(OPT_mlink_builtin_bitcode)) { 1962 F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded; 1963 // When linking CUDA bitcode, propagate function attributes so that 1964 // e.g. libdevice gets fast-math attrs if we're building with fast-math. 1965 F.PropagateAttrs = true; 1966 F.Internalize = true; 1967 } 1968 Opts.LinkBitcodeFiles.push_back(F); 1969 } 1970 1971 if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) { 1972 if (T.isOSAIX()) { 1973 StringRef Name = A->getValue(); 1974 if (Name == "local-dynamic") 1975 Diags.Report(diag::err_aix_unsupported_tls_model) << Name; 1976 } 1977 } 1978 1979 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) { 1980 StringRef Val = A->getValue(); 1981 Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val); 1982 Opts.FP32DenormalMode = Opts.FPDenormalMode; 1983 if (!Opts.FPDenormalMode.isValid()) 1984 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 1985 } 1986 1987 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) { 1988 StringRef Val = A->getValue(); 1989 Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val); 1990 if (!Opts.FP32DenormalMode.isValid()) 1991 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 1992 } 1993 1994 // X86_32 has -fppc-struct-return and -freg-struct-return. 1995 // PPC32 has -maix-struct-return and -msvr4-struct-return. 1996 if (Arg *A = 1997 Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return, 1998 OPT_maix_struct_return, OPT_msvr4_struct_return)) { 1999 // TODO: We might want to consider enabling these options on AIX in the 2000 // future. 2001 if (T.isOSAIX()) 2002 Diags.Report(diag::err_drv_unsupported_opt_for_target) 2003 << A->getSpelling() << T.str(); 2004 2005 const Option &O = A->getOption(); 2006 if (O.matches(OPT_fpcc_struct_return) || 2007 O.matches(OPT_maix_struct_return)) { 2008 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack); 2009 } else { 2010 assert(O.matches(OPT_freg_struct_return) || 2011 O.matches(OPT_msvr4_struct_return)); 2012 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs); 2013 } 2014 } 2015 2016 if (Arg *A = Args.getLastArg(OPT_mxcoff_roptr)) { 2017 if (!T.isOSAIX()) 2018 Diags.Report(diag::err_drv_unsupported_opt_for_target) 2019 << A->getSpelling() << T.str(); 2020 2021 // Since the storage mapping class is specified per csect, 2022 // without using data sections, it is less effective to use read-only 2023 // pointers. Using read-only pointers may cause other RO variables in the 2024 // same csect to become RW when the linker acts upon `-bforceimprw`; 2025 // therefore, we require that separate data sections 2026 // are used when `-mxcoff-roptr` is in effect. We respect the setting of 2027 // data-sections since we have not found reasons to do otherwise that 2028 // overcome the user surprise of not respecting the setting. 2029 if (!Args.hasFlag(OPT_fdata_sections, OPT_fno_data_sections, false)) 2030 Diags.Report(diag::err_roptr_requires_data_sections); 2031 2032 Opts.XCOFFReadOnlyPointers = true; 2033 } 2034 2035 if (Arg *A = Args.getLastArg(OPT_mabi_EQ_quadword_atomics)) { 2036 if (!T.isOSAIX() || T.isPPC32()) 2037 Diags.Report(diag::err_drv_unsupported_opt_for_target) 2038 << A->getSpelling() << T.str(); 2039 } 2040 2041 bool NeedLocTracking = false; 2042 2043 if (!Opts.OptRecordFile.empty()) 2044 NeedLocTracking = true; 2045 2046 if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) { 2047 Opts.OptRecordPasses = A->getValue(); 2048 NeedLocTracking = true; 2049 } 2050 2051 if (Arg *A = Args.getLastArg(OPT_opt_record_format)) { 2052 Opts.OptRecordFormat = A->getValue(); 2053 NeedLocTracking = true; 2054 } 2055 2056 Opts.OptimizationRemark = 2057 ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass"); 2058 2059 Opts.OptimizationRemarkMissed = 2060 ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed"); 2061 2062 Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark( 2063 Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis"); 2064 2065 NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() || 2066 Opts.OptimizationRemarkMissed.hasValidPattern() || 2067 Opts.OptimizationRemarkAnalysis.hasValidPattern(); 2068 2069 bool UsingSampleProfile = !Opts.SampleProfileFile.empty(); 2070 bool UsingProfile = 2071 UsingSampleProfile || !Opts.ProfileInstrumentUsePath.empty(); 2072 2073 if (Opts.DiagnosticsWithHotness && !UsingProfile && 2074 // An IR file will contain PGO as metadata 2075 IK.getLanguage() != Language::LLVM_IR) 2076 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) 2077 << "-fdiagnostics-show-hotness"; 2078 2079 // Parse remarks hotness threshold. Valid value is either integer or 'auto'. 2080 if (auto *arg = 2081 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) { 2082 auto ResultOrErr = 2083 llvm::remarks::parseHotnessThresholdOption(arg->getValue()); 2084 2085 if (!ResultOrErr) { 2086 Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold) 2087 << "-fdiagnostics-hotness-threshold="; 2088 } else { 2089 Opts.DiagnosticsHotnessThreshold = *ResultOrErr; 2090 if ((!Opts.DiagnosticsHotnessThreshold || 2091 *Opts.DiagnosticsHotnessThreshold > 0) && 2092 !UsingProfile) 2093 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) 2094 << "-fdiagnostics-hotness-threshold="; 2095 } 2096 } 2097 2098 if (auto *arg = 2099 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) { 2100 auto ResultOrErr = parseToleranceOption(arg->getValue()); 2101 2102 if (!ResultOrErr) { 2103 Diags.Report(diag::err_drv_invalid_diagnotics_misexpect_tolerance) 2104 << "-fdiagnostics-misexpect-tolerance="; 2105 } else { 2106 Opts.DiagnosticsMisExpectTolerance = *ResultOrErr; 2107 if ((!Opts.DiagnosticsMisExpectTolerance || 2108 *Opts.DiagnosticsMisExpectTolerance > 0) && 2109 !UsingProfile) 2110 Diags.Report(diag::warn_drv_diagnostics_misexpect_requires_pgo) 2111 << "-fdiagnostics-misexpect-tolerance="; 2112 } 2113 } 2114 2115 // If the user requested to use a sample profile for PGO, then the 2116 // backend will need to track source location information so the profile 2117 // can be incorporated into the IR. 2118 if (UsingSampleProfile) 2119 NeedLocTracking = true; 2120 2121 if (!Opts.StackUsageOutput.empty()) 2122 NeedLocTracking = true; 2123 2124 // If the user requested a flag that requires source locations available in 2125 // the backend, make sure that the backend tracks source location information. 2126 if (NeedLocTracking && 2127 Opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo) 2128 Opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly); 2129 2130 // Parse -fsanitize-recover= arguments. 2131 // FIXME: Report unrecoverable sanitizers incorrectly specified here. 2132 parseSanitizerKinds("-fsanitize-recover=", 2133 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags, 2134 Opts.SanitizeRecover); 2135 parseSanitizerKinds("-fsanitize-trap=", 2136 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags, 2137 Opts.SanitizeTrap); 2138 2139 Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true); 2140 2141 if (Args.hasArg(options::OPT_ffinite_loops)) 2142 Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always; 2143 else if (Args.hasArg(options::OPT_fno_finite_loops)) 2144 Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never; 2145 2146 Opts.EmitIEEENaNCompliantInsts = Args.hasFlag( 2147 options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee, true); 2148 if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs) 2149 Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans); 2150 2151 return Diags.getNumErrors() == NumErrorsBefore; 2152 } 2153 2154 static void GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts, 2155 ArgumentConsumer Consumer) { 2156 const DependencyOutputOptions &DependencyOutputOpts = Opts; 2157 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \ 2158 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 2159 #include "clang/Driver/Options.inc" 2160 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING 2161 2162 if (Opts.ShowIncludesDest != ShowIncludesDestination::None) 2163 GenerateArg(Consumer, OPT_show_includes); 2164 2165 for (const auto &Dep : Opts.ExtraDeps) { 2166 switch (Dep.second) { 2167 case EDK_SanitizeIgnorelist: 2168 // Sanitizer ignorelist arguments are generated from LanguageOptions. 2169 continue; 2170 case EDK_ModuleFile: 2171 // Module file arguments are generated from FrontendOptions and 2172 // HeaderSearchOptions. 2173 continue; 2174 case EDK_ProfileList: 2175 // Profile list arguments are generated from LanguageOptions via the 2176 // marshalling infrastructure. 2177 continue; 2178 case EDK_DepFileEntry: 2179 GenerateArg(Consumer, OPT_fdepfile_entry, Dep.first); 2180 break; 2181 } 2182 } 2183 } 2184 2185 static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts, 2186 ArgList &Args, DiagnosticsEngine &Diags, 2187 frontend::ActionKind Action, 2188 bool ShowLineMarkers) { 2189 unsigned NumErrorsBefore = Diags.getNumErrors(); 2190 2191 DependencyOutputOptions &DependencyOutputOpts = Opts; 2192 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \ 2193 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 2194 #include "clang/Driver/Options.inc" 2195 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING 2196 2197 if (Args.hasArg(OPT_show_includes)) { 2198 // Writing both /showIncludes and preprocessor output to stdout 2199 // would produce interleaved output, so use stderr for /showIncludes. 2200 // This behaves the same as cl.exe, when /E, /EP or /P are passed. 2201 if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers) 2202 Opts.ShowIncludesDest = ShowIncludesDestination::Stderr; 2203 else 2204 Opts.ShowIncludesDest = ShowIncludesDestination::Stdout; 2205 } else { 2206 Opts.ShowIncludesDest = ShowIncludesDestination::None; 2207 } 2208 2209 // Add sanitizer ignorelists as extra dependencies. 2210 // They won't be discovered by the regular preprocessor, so 2211 // we let make / ninja to know about this implicit dependency. 2212 if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) { 2213 for (const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) { 2214 StringRef Val = A->getValue(); 2215 if (!Val.contains('=')) 2216 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist); 2217 } 2218 if (Opts.IncludeSystemHeaders) { 2219 for (const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) { 2220 StringRef Val = A->getValue(); 2221 if (!Val.contains('=')) 2222 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist); 2223 } 2224 } 2225 } 2226 2227 // -fprofile-list= dependencies. 2228 for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ)) 2229 Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList); 2230 2231 // Propagate the extra dependencies. 2232 for (const auto *A : Args.filtered(OPT_fdepfile_entry)) 2233 Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry); 2234 2235 // Only the -fmodule-file=<file> form. 2236 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 2237 StringRef Val = A->getValue(); 2238 if (!Val.contains('=')) 2239 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile); 2240 } 2241 2242 // Check for invalid combinations of header-include-format 2243 // and header-include-filtering. 2244 if ((Opts.HeaderIncludeFormat == HIFMT_Textual && 2245 Opts.HeaderIncludeFiltering != HIFIL_None) || 2246 (Opts.HeaderIncludeFormat == HIFMT_JSON && 2247 Opts.HeaderIncludeFiltering != HIFIL_Only_Direct_System)) 2248 Diags.Report(diag::err_drv_print_header_env_var_combination_cc1) 2249 << Args.getLastArg(OPT_header_include_format_EQ)->getValue() 2250 << Args.getLastArg(OPT_header_include_filtering_EQ)->getValue(); 2251 2252 return Diags.getNumErrors() == NumErrorsBefore; 2253 } 2254 2255 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) { 2256 // Color diagnostics default to auto ("on" if terminal supports) in the driver 2257 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color. 2258 // Support both clang's -f[no-]color-diagnostics and gcc's 2259 // -f[no-]diagnostics-colors[=never|always|auto]. 2260 enum { 2261 Colors_On, 2262 Colors_Off, 2263 Colors_Auto 2264 } ShowColors = DefaultColor ? Colors_Auto : Colors_Off; 2265 for (auto *A : Args) { 2266 const Option &O = A->getOption(); 2267 if (O.matches(options::OPT_fcolor_diagnostics)) { 2268 ShowColors = Colors_On; 2269 } else if (O.matches(options::OPT_fno_color_diagnostics)) { 2270 ShowColors = Colors_Off; 2271 } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) { 2272 StringRef Value(A->getValue()); 2273 if (Value == "always") 2274 ShowColors = Colors_On; 2275 else if (Value == "never") 2276 ShowColors = Colors_Off; 2277 else if (Value == "auto") 2278 ShowColors = Colors_Auto; 2279 } 2280 } 2281 return ShowColors == Colors_On || 2282 (ShowColors == Colors_Auto && 2283 llvm::sys::Process::StandardErrHasColors()); 2284 } 2285 2286 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes, 2287 DiagnosticsEngine &Diags) { 2288 bool Success = true; 2289 for (const auto &Prefix : VerifyPrefixes) { 2290 // Every prefix must start with a letter and contain only alphanumeric 2291 // characters, hyphens, and underscores. 2292 auto BadChar = llvm::find_if(Prefix, [](char C) { 2293 return !isAlphanumeric(C) && C != '-' && C != '_'; 2294 }); 2295 if (BadChar != Prefix.end() || !isLetter(Prefix[0])) { 2296 Success = false; 2297 Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix; 2298 Diags.Report(diag::note_drv_verify_prefix_spelling); 2299 } 2300 } 2301 return Success; 2302 } 2303 2304 static void GenerateFileSystemArgs(const FileSystemOptions &Opts, 2305 ArgumentConsumer Consumer) { 2306 const FileSystemOptions &FileSystemOpts = Opts; 2307 2308 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \ 2309 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 2310 #include "clang/Driver/Options.inc" 2311 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING 2312 } 2313 2314 static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args, 2315 DiagnosticsEngine &Diags) { 2316 unsigned NumErrorsBefore = Diags.getNumErrors(); 2317 2318 FileSystemOptions &FileSystemOpts = Opts; 2319 2320 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \ 2321 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 2322 #include "clang/Driver/Options.inc" 2323 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING 2324 2325 return Diags.getNumErrors() == NumErrorsBefore; 2326 } 2327 2328 static void GenerateMigratorArgs(const MigratorOptions &Opts, 2329 ArgumentConsumer Consumer) { 2330 const MigratorOptions &MigratorOpts = Opts; 2331 #define MIGRATOR_OPTION_WITH_MARSHALLING(...) \ 2332 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 2333 #include "clang/Driver/Options.inc" 2334 #undef MIGRATOR_OPTION_WITH_MARSHALLING 2335 } 2336 2337 static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args, 2338 DiagnosticsEngine &Diags) { 2339 unsigned NumErrorsBefore = Diags.getNumErrors(); 2340 2341 MigratorOptions &MigratorOpts = Opts; 2342 2343 #define MIGRATOR_OPTION_WITH_MARSHALLING(...) \ 2344 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 2345 #include "clang/Driver/Options.inc" 2346 #undef MIGRATOR_OPTION_WITH_MARSHALLING 2347 2348 return Diags.getNumErrors() == NumErrorsBefore; 2349 } 2350 2351 void CompilerInvocationBase::GenerateDiagnosticArgs( 2352 const DiagnosticOptions &Opts, ArgumentConsumer Consumer, 2353 bool DefaultDiagColor) { 2354 const DiagnosticOptions *DiagnosticOpts = &Opts; 2355 #define DIAG_OPTION_WITH_MARSHALLING(...) \ 2356 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 2357 #include "clang/Driver/Options.inc" 2358 #undef DIAG_OPTION_WITH_MARSHALLING 2359 2360 if (!Opts.DiagnosticSerializationFile.empty()) 2361 GenerateArg(Consumer, OPT_diagnostic_serialized_file, 2362 Opts.DiagnosticSerializationFile); 2363 2364 if (Opts.ShowColors) 2365 GenerateArg(Consumer, OPT_fcolor_diagnostics); 2366 2367 if (Opts.VerifyDiagnostics && 2368 llvm::is_contained(Opts.VerifyPrefixes, "expected")) 2369 GenerateArg(Consumer, OPT_verify); 2370 2371 for (const auto &Prefix : Opts.VerifyPrefixes) 2372 if (Prefix != "expected") 2373 GenerateArg(Consumer, OPT_verify_EQ, Prefix); 2374 2375 DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected(); 2376 if (VIU == DiagnosticLevelMask::None) { 2377 // This is the default, don't generate anything. 2378 } else if (VIU == DiagnosticLevelMask::All) { 2379 GenerateArg(Consumer, OPT_verify_ignore_unexpected); 2380 } else { 2381 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0) 2382 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "note"); 2383 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0) 2384 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "remark"); 2385 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0) 2386 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "warning"); 2387 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0) 2388 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "error"); 2389 } 2390 2391 for (const auto &Warning : Opts.Warnings) { 2392 // This option is automatically generated from UndefPrefixes. 2393 if (Warning == "undef-prefix") 2394 continue; 2395 Consumer(StringRef("-W") + Warning); 2396 } 2397 2398 for (const auto &Remark : Opts.Remarks) { 2399 // These arguments are generated from OptimizationRemark fields of 2400 // CodeGenOptions. 2401 StringRef IgnoredRemarks[] = {"pass", "no-pass", 2402 "pass-analysis", "no-pass-analysis", 2403 "pass-missed", "no-pass-missed"}; 2404 if (llvm::is_contained(IgnoredRemarks, Remark)) 2405 continue; 2406 2407 Consumer(StringRef("-R") + Remark); 2408 } 2409 } 2410 2411 std::unique_ptr<DiagnosticOptions> 2412 clang::CreateAndPopulateDiagOpts(ArrayRef<const char *> Argv) { 2413 auto DiagOpts = std::make_unique<DiagnosticOptions>(); 2414 unsigned MissingArgIndex, MissingArgCount; 2415 InputArgList Args = getDriverOptTable().ParseArgs( 2416 Argv.slice(1), MissingArgIndex, MissingArgCount); 2417 2418 bool ShowColors = true; 2419 if (std::optional<std::string> NoColor = 2420 llvm::sys::Process::GetEnv("NO_COLOR"); 2421 NoColor && !NoColor->empty()) { 2422 // If the user set the NO_COLOR environment variable, we'll honor that 2423 // unless the command line overrides it. 2424 ShowColors = false; 2425 } 2426 2427 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs. 2428 // Any errors that would be diagnosed here will also be diagnosed later, 2429 // when the DiagnosticsEngine actually exists. 2430 (void)ParseDiagnosticArgs(*DiagOpts, Args, /*Diags=*/nullptr, ShowColors); 2431 return DiagOpts; 2432 } 2433 2434 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args, 2435 DiagnosticsEngine *Diags, 2436 bool DefaultDiagColor) { 2437 std::optional<DiagnosticsEngine> IgnoringDiags; 2438 if (!Diags) { 2439 IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(), 2440 new IgnoringDiagConsumer()); 2441 Diags = &*IgnoringDiags; 2442 } 2443 2444 unsigned NumErrorsBefore = Diags->getNumErrors(); 2445 2446 // The key paths of diagnostic options defined in Options.td start with 2447 // "DiagnosticOpts->". Let's provide the expected variable name and type. 2448 DiagnosticOptions *DiagnosticOpts = &Opts; 2449 2450 #define DIAG_OPTION_WITH_MARSHALLING(...) \ 2451 PARSE_OPTION_WITH_MARSHALLING(Args, *Diags, __VA_ARGS__) 2452 #include "clang/Driver/Options.inc" 2453 #undef DIAG_OPTION_WITH_MARSHALLING 2454 2455 llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes); 2456 2457 if (Arg *A = 2458 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags)) 2459 Opts.DiagnosticSerializationFile = A->getValue(); 2460 Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor); 2461 2462 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ); 2463 Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ); 2464 if (Args.hasArg(OPT_verify)) 2465 Opts.VerifyPrefixes.push_back("expected"); 2466 // Keep VerifyPrefixes in its original order for the sake of diagnostics, and 2467 // then sort it to prepare for fast lookup using std::binary_search. 2468 if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags)) 2469 Opts.VerifyDiagnostics = false; 2470 else 2471 llvm::sort(Opts.VerifyPrefixes); 2472 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None; 2473 parseDiagnosticLevelMask( 2474 "-verify-ignore-unexpected=", 2475 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask); 2476 if (Args.hasArg(OPT_verify_ignore_unexpected)) 2477 DiagMask = DiagnosticLevelMask::All; 2478 Opts.setVerifyIgnoreUnexpected(DiagMask); 2479 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) { 2480 Diags->Report(diag::warn_ignoring_ftabstop_value) 2481 << Opts.TabStop << DiagnosticOptions::DefaultTabStop; 2482 Opts.TabStop = DiagnosticOptions::DefaultTabStop; 2483 } 2484 2485 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings); 2486 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks); 2487 2488 return Diags->getNumErrors() == NumErrorsBefore; 2489 } 2490 2491 /// Parse the argument to the -ftest-module-file-extension 2492 /// command-line argument. 2493 /// 2494 /// \returns true on error, false on success. 2495 static bool parseTestModuleFileExtensionArg(StringRef Arg, 2496 std::string &BlockName, 2497 unsigned &MajorVersion, 2498 unsigned &MinorVersion, 2499 bool &Hashed, 2500 std::string &UserInfo) { 2501 SmallVector<StringRef, 5> Args; 2502 Arg.split(Args, ':', 5); 2503 if (Args.size() < 5) 2504 return true; 2505 2506 BlockName = std::string(Args[0]); 2507 if (Args[1].getAsInteger(10, MajorVersion)) return true; 2508 if (Args[2].getAsInteger(10, MinorVersion)) return true; 2509 if (Args[3].getAsInteger(2, Hashed)) return true; 2510 if (Args.size() > 4) 2511 UserInfo = std::string(Args[4]); 2512 return false; 2513 } 2514 2515 /// Return a table that associates command line option specifiers with the 2516 /// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is 2517 /// intentionally missing, as this case is handled separately from other 2518 /// frontend options. 2519 static const auto &getFrontendActionTable() { 2520 static const std::pair<frontend::ActionKind, unsigned> Table[] = { 2521 {frontend::ASTDeclList, OPT_ast_list}, 2522 2523 {frontend::ASTDump, OPT_ast_dump_all_EQ}, 2524 {frontend::ASTDump, OPT_ast_dump_all}, 2525 {frontend::ASTDump, OPT_ast_dump_EQ}, 2526 {frontend::ASTDump, OPT_ast_dump}, 2527 {frontend::ASTDump, OPT_ast_dump_lookups}, 2528 {frontend::ASTDump, OPT_ast_dump_decl_types}, 2529 2530 {frontend::ASTPrint, OPT_ast_print}, 2531 {frontend::ASTView, OPT_ast_view}, 2532 {frontend::DumpCompilerOptions, OPT_compiler_options_dump}, 2533 {frontend::DumpRawTokens, OPT_dump_raw_tokens}, 2534 {frontend::DumpTokens, OPT_dump_tokens}, 2535 {frontend::EmitAssembly, OPT_S}, 2536 {frontend::EmitBC, OPT_emit_llvm_bc}, 2537 {frontend::EmitHTML, OPT_emit_html}, 2538 {frontend::EmitLLVM, OPT_emit_llvm}, 2539 {frontend::EmitLLVMOnly, OPT_emit_llvm_only}, 2540 {frontend::EmitCodeGenOnly, OPT_emit_codegen_only}, 2541 {frontend::EmitObj, OPT_emit_obj}, 2542 {frontend::ExtractAPI, OPT_extract_api}, 2543 2544 {frontend::FixIt, OPT_fixit_EQ}, 2545 {frontend::FixIt, OPT_fixit}, 2546 2547 {frontend::GenerateModule, OPT_emit_module}, 2548 {frontend::GenerateModuleInterface, OPT_emit_module_interface}, 2549 {frontend::GenerateHeaderUnit, OPT_emit_header_unit}, 2550 {frontend::GeneratePCH, OPT_emit_pch}, 2551 {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs}, 2552 {frontend::InitOnly, OPT_init_only}, 2553 {frontend::ParseSyntaxOnly, OPT_fsyntax_only}, 2554 {frontend::ModuleFileInfo, OPT_module_file_info}, 2555 {frontend::VerifyPCH, OPT_verify_pch}, 2556 {frontend::PrintPreamble, OPT_print_preamble}, 2557 {frontend::PrintPreprocessedInput, OPT_E}, 2558 {frontend::TemplightDump, OPT_templight_dump}, 2559 {frontend::RewriteMacros, OPT_rewrite_macros}, 2560 {frontend::RewriteObjC, OPT_rewrite_objc}, 2561 {frontend::RewriteTest, OPT_rewrite_test}, 2562 {frontend::RunAnalysis, OPT_analyze}, 2563 {frontend::MigrateSource, OPT_migrate}, 2564 {frontend::RunPreprocessorOnly, OPT_Eonly}, 2565 {frontend::PrintDependencyDirectivesSourceMinimizerOutput, 2566 OPT_print_dependency_directives_minimized_source}, 2567 }; 2568 2569 return Table; 2570 } 2571 2572 /// Maps command line option to frontend action. 2573 static std::optional<frontend::ActionKind> 2574 getFrontendAction(OptSpecifier &Opt) { 2575 for (const auto &ActionOpt : getFrontendActionTable()) 2576 if (ActionOpt.second == Opt.getID()) 2577 return ActionOpt.first; 2578 2579 return std::nullopt; 2580 } 2581 2582 /// Maps frontend action to command line option. 2583 static std::optional<OptSpecifier> 2584 getProgramActionOpt(frontend::ActionKind ProgramAction) { 2585 for (const auto &ActionOpt : getFrontendActionTable()) 2586 if (ActionOpt.first == ProgramAction) 2587 return OptSpecifier(ActionOpt.second); 2588 2589 return std::nullopt; 2590 } 2591 2592 static void GenerateFrontendArgs(const FrontendOptions &Opts, 2593 ArgumentConsumer Consumer, bool IsHeader) { 2594 const FrontendOptions &FrontendOpts = Opts; 2595 #define FRONTEND_OPTION_WITH_MARSHALLING(...) \ 2596 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 2597 #include "clang/Driver/Options.inc" 2598 #undef FRONTEND_OPTION_WITH_MARSHALLING 2599 2600 std::optional<OptSpecifier> ProgramActionOpt = 2601 getProgramActionOpt(Opts.ProgramAction); 2602 2603 // Generating a simple flag covers most frontend actions. 2604 std::function<void()> GenerateProgramAction = [&]() { 2605 GenerateArg(Consumer, *ProgramActionOpt); 2606 }; 2607 2608 if (!ProgramActionOpt) { 2609 // PluginAction is the only program action handled separately. 2610 assert(Opts.ProgramAction == frontend::PluginAction && 2611 "Frontend action without option."); 2612 GenerateProgramAction = [&]() { 2613 GenerateArg(Consumer, OPT_plugin, Opts.ActionName); 2614 }; 2615 } 2616 2617 // FIXME: Simplify the complex 'AST dump' command line. 2618 if (Opts.ProgramAction == frontend::ASTDump) { 2619 GenerateProgramAction = [&]() { 2620 // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via 2621 // marshalling infrastructure. 2622 2623 if (Opts.ASTDumpFormat != ADOF_Default) { 2624 StringRef Format; 2625 switch (Opts.ASTDumpFormat) { 2626 case ADOF_Default: 2627 llvm_unreachable("Default AST dump format."); 2628 case ADOF_JSON: 2629 Format = "json"; 2630 break; 2631 } 2632 2633 if (Opts.ASTDumpAll) 2634 GenerateArg(Consumer, OPT_ast_dump_all_EQ, Format); 2635 if (Opts.ASTDumpDecls) 2636 GenerateArg(Consumer, OPT_ast_dump_EQ, Format); 2637 } else { 2638 if (Opts.ASTDumpAll) 2639 GenerateArg(Consumer, OPT_ast_dump_all); 2640 if (Opts.ASTDumpDecls) 2641 GenerateArg(Consumer, OPT_ast_dump); 2642 } 2643 }; 2644 } 2645 2646 if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) { 2647 GenerateProgramAction = [&]() { 2648 GenerateArg(Consumer, OPT_fixit_EQ, Opts.FixItSuffix); 2649 }; 2650 } 2651 2652 GenerateProgramAction(); 2653 2654 for (const auto &PluginArgs : Opts.PluginArgs) { 2655 Option Opt = getDriverOptTable().getOption(OPT_plugin_arg); 2656 for (const auto &PluginArg : PluginArgs.second) 2657 denormalizeString(Consumer, 2658 Opt.getPrefix() + Opt.getName() + PluginArgs.first, 2659 Opt.getKind(), 0, PluginArg); 2660 } 2661 2662 for (const auto &Ext : Opts.ModuleFileExtensions) 2663 if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get())) 2664 GenerateArg(Consumer, OPT_ftest_module_file_extension_EQ, TestExt->str()); 2665 2666 if (!Opts.CodeCompletionAt.FileName.empty()) 2667 GenerateArg(Consumer, OPT_code_completion_at, 2668 Opts.CodeCompletionAt.ToString()); 2669 2670 for (const auto &Plugin : Opts.Plugins) 2671 GenerateArg(Consumer, OPT_load, Plugin); 2672 2673 // ASTDumpDecls and ASTDumpAll already handled with ProgramAction. 2674 2675 for (const auto &ModuleFile : Opts.ModuleFiles) 2676 GenerateArg(Consumer, OPT_fmodule_file, ModuleFile); 2677 2678 if (Opts.AuxTargetCPU) 2679 GenerateArg(Consumer, OPT_aux_target_cpu, *Opts.AuxTargetCPU); 2680 2681 if (Opts.AuxTargetFeatures) 2682 for (const auto &Feature : *Opts.AuxTargetFeatures) 2683 GenerateArg(Consumer, OPT_aux_target_feature, Feature); 2684 2685 { 2686 StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : ""; 2687 StringRef ModuleMap = 2688 Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : ""; 2689 StringRef HeaderUnit = ""; 2690 switch (Opts.DashX.getHeaderUnitKind()) { 2691 case InputKind::HeaderUnit_None: 2692 break; 2693 case InputKind::HeaderUnit_User: 2694 HeaderUnit = "-user"; 2695 break; 2696 case InputKind::HeaderUnit_System: 2697 HeaderUnit = "-system"; 2698 break; 2699 case InputKind::HeaderUnit_Abs: 2700 HeaderUnit = "-header-unit"; 2701 break; 2702 } 2703 StringRef Header = IsHeader ? "-header" : ""; 2704 2705 StringRef Lang; 2706 switch (Opts.DashX.getLanguage()) { 2707 case Language::C: 2708 Lang = "c"; 2709 break; 2710 case Language::OpenCL: 2711 Lang = "cl"; 2712 break; 2713 case Language::OpenCLCXX: 2714 Lang = "clcpp"; 2715 break; 2716 case Language::CUDA: 2717 Lang = "cuda"; 2718 break; 2719 case Language::HIP: 2720 Lang = "hip"; 2721 break; 2722 case Language::CXX: 2723 Lang = "c++"; 2724 break; 2725 case Language::ObjC: 2726 Lang = "objective-c"; 2727 break; 2728 case Language::ObjCXX: 2729 Lang = "objective-c++"; 2730 break; 2731 case Language::RenderScript: 2732 Lang = "renderscript"; 2733 break; 2734 case Language::Asm: 2735 Lang = "assembler-with-cpp"; 2736 break; 2737 case Language::Unknown: 2738 assert(Opts.DashX.getFormat() == InputKind::Precompiled && 2739 "Generating -x argument for unknown language (not precompiled)."); 2740 Lang = "ast"; 2741 break; 2742 case Language::LLVM_IR: 2743 Lang = "ir"; 2744 break; 2745 case Language::HLSL: 2746 Lang = "hlsl"; 2747 break; 2748 } 2749 2750 GenerateArg(Consumer, OPT_x, 2751 Lang + HeaderUnit + Header + ModuleMap + Preprocessed); 2752 } 2753 2754 // OPT_INPUT has a unique class, generate it directly. 2755 for (const auto &Input : Opts.Inputs) 2756 Consumer(Input.getFile()); 2757 } 2758 2759 static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, 2760 DiagnosticsEngine &Diags, bool &IsHeaderFile) { 2761 unsigned NumErrorsBefore = Diags.getNumErrors(); 2762 2763 FrontendOptions &FrontendOpts = Opts; 2764 2765 #define FRONTEND_OPTION_WITH_MARSHALLING(...) \ 2766 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 2767 #include "clang/Driver/Options.inc" 2768 #undef FRONTEND_OPTION_WITH_MARSHALLING 2769 2770 Opts.ProgramAction = frontend::ParseSyntaxOnly; 2771 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) { 2772 OptSpecifier Opt = OptSpecifier(A->getOption().getID()); 2773 std::optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt); 2774 assert(ProgramAction && "Option specifier not in Action_Group."); 2775 2776 if (ProgramAction == frontend::ASTDump && 2777 (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) { 2778 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue()) 2779 .CaseLower("default", ADOF_Default) 2780 .CaseLower("json", ADOF_JSON) 2781 .Default(std::numeric_limits<unsigned>::max()); 2782 2783 if (Val != std::numeric_limits<unsigned>::max()) 2784 Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val); 2785 else { 2786 Diags.Report(diag::err_drv_invalid_value) 2787 << A->getAsString(Args) << A->getValue(); 2788 Opts.ASTDumpFormat = ADOF_Default; 2789 } 2790 } 2791 2792 if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ) 2793 Opts.FixItSuffix = A->getValue(); 2794 2795 if (ProgramAction == frontend::GenerateInterfaceStubs) { 2796 StringRef ArgStr = 2797 Args.hasArg(OPT_interface_stub_version_EQ) 2798 ? Args.getLastArgValue(OPT_interface_stub_version_EQ) 2799 : "ifs-v1"; 2800 if (ArgStr == "experimental-yaml-elf-v1" || 2801 ArgStr == "experimental-ifs-v1" || ArgStr == "experimental-ifs-v2" || 2802 ArgStr == "experimental-tapi-elf-v1") { 2803 std::string ErrorMessage = 2804 "Invalid interface stub format: " + ArgStr.str() + 2805 " is deprecated."; 2806 Diags.Report(diag::err_drv_invalid_value) 2807 << "Must specify a valid interface stub format type, ie: " 2808 "-interface-stub-version=ifs-v1" 2809 << ErrorMessage; 2810 ProgramAction = frontend::ParseSyntaxOnly; 2811 } else if (!ArgStr.startswith("ifs-")) { 2812 std::string ErrorMessage = 2813 "Invalid interface stub format: " + ArgStr.str() + "."; 2814 Diags.Report(diag::err_drv_invalid_value) 2815 << "Must specify a valid interface stub format type, ie: " 2816 "-interface-stub-version=ifs-v1" 2817 << ErrorMessage; 2818 ProgramAction = frontend::ParseSyntaxOnly; 2819 } 2820 } 2821 2822 Opts.ProgramAction = *ProgramAction; 2823 } 2824 2825 if (const Arg* A = Args.getLastArg(OPT_plugin)) { 2826 Opts.Plugins.emplace_back(A->getValue(0)); 2827 Opts.ProgramAction = frontend::PluginAction; 2828 Opts.ActionName = A->getValue(); 2829 } 2830 for (const auto *AA : Args.filtered(OPT_plugin_arg)) 2831 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1)); 2832 2833 for (const std::string &Arg : 2834 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) { 2835 std::string BlockName; 2836 unsigned MajorVersion; 2837 unsigned MinorVersion; 2838 bool Hashed; 2839 std::string UserInfo; 2840 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion, 2841 MinorVersion, Hashed, UserInfo)) { 2842 Diags.Report(diag::err_test_module_file_extension_format) << Arg; 2843 2844 continue; 2845 } 2846 2847 // Add the testing module file extension. 2848 Opts.ModuleFileExtensions.push_back( 2849 std::make_shared<TestModuleFileExtension>( 2850 BlockName, MajorVersion, MinorVersion, Hashed, UserInfo)); 2851 } 2852 2853 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) { 2854 Opts.CodeCompletionAt = 2855 ParsedSourceLocation::FromString(A->getValue()); 2856 if (Opts.CodeCompletionAt.FileName.empty()) 2857 Diags.Report(diag::err_drv_invalid_value) 2858 << A->getAsString(Args) << A->getValue(); 2859 } 2860 2861 Opts.Plugins = Args.getAllArgValues(OPT_load); 2862 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ); 2863 Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ); 2864 // Only the -fmodule-file=<file> form. 2865 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 2866 StringRef Val = A->getValue(); 2867 if (!Val.contains('=')) 2868 Opts.ModuleFiles.push_back(std::string(Val)); 2869 } 2870 2871 if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule) 2872 Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module" 2873 << "-emit-module"; 2874 2875 if (Args.hasArg(OPT_aux_target_cpu)) 2876 Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu)); 2877 if (Args.hasArg(OPT_aux_target_feature)) 2878 Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature); 2879 2880 if (Opts.ARCMTAction != FrontendOptions::ARCMT_None && 2881 Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) { 2882 Diags.Report(diag::err_drv_argument_not_allowed_with) 2883 << "ARC migration" << "ObjC migration"; 2884 } 2885 2886 InputKind DashX(Language::Unknown); 2887 if (const Arg *A = Args.getLastArg(OPT_x)) { 2888 StringRef XValue = A->getValue(); 2889 2890 // Parse suffixes: 2891 // '<lang>(-[{header-unit,user,system}-]header|[-module-map][-cpp-output])'. 2892 // FIXME: Supporting '<lang>-header-cpp-output' would be useful. 2893 bool Preprocessed = XValue.consume_back("-cpp-output"); 2894 bool ModuleMap = XValue.consume_back("-module-map"); 2895 // Detect and consume the header indicator. 2896 bool IsHeader = 2897 XValue != "precompiled-header" && XValue.consume_back("-header"); 2898 2899 // If we have c++-{user,system}-header, that indicates a header unit input 2900 // likewise, if the user put -fmodule-header together with a header with an 2901 // absolute path (header-unit-header). 2902 InputKind::HeaderUnitKind HUK = InputKind::HeaderUnit_None; 2903 if (IsHeader || Preprocessed) { 2904 if (XValue.consume_back("-header-unit")) 2905 HUK = InputKind::HeaderUnit_Abs; 2906 else if (XValue.consume_back("-system")) 2907 HUK = InputKind::HeaderUnit_System; 2908 else if (XValue.consume_back("-user")) 2909 HUK = InputKind::HeaderUnit_User; 2910 } 2911 2912 // The value set by this processing is an un-preprocessed source which is 2913 // not intended to be a module map or header unit. 2914 IsHeaderFile = IsHeader && !Preprocessed && !ModuleMap && 2915 HUK == InputKind::HeaderUnit_None; 2916 2917 // Principal languages. 2918 DashX = llvm::StringSwitch<InputKind>(XValue) 2919 .Case("c", Language::C) 2920 .Case("cl", Language::OpenCL) 2921 .Case("clcpp", Language::OpenCLCXX) 2922 .Case("cuda", Language::CUDA) 2923 .Case("hip", Language::HIP) 2924 .Case("c++", Language::CXX) 2925 .Case("objective-c", Language::ObjC) 2926 .Case("objective-c++", Language::ObjCXX) 2927 .Case("renderscript", Language::RenderScript) 2928 .Case("hlsl", Language::HLSL) 2929 .Default(Language::Unknown); 2930 2931 // "objc[++]-cpp-output" is an acceptable synonym for 2932 // "objective-c[++]-cpp-output". 2933 if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap && 2934 HUK == InputKind::HeaderUnit_None) 2935 DashX = llvm::StringSwitch<InputKind>(XValue) 2936 .Case("objc", Language::ObjC) 2937 .Case("objc++", Language::ObjCXX) 2938 .Default(Language::Unknown); 2939 2940 // Some special cases cannot be combined with suffixes. 2941 if (DashX.isUnknown() && !Preprocessed && !IsHeaderFile && !ModuleMap && 2942 HUK == InputKind::HeaderUnit_None) 2943 DashX = llvm::StringSwitch<InputKind>(XValue) 2944 .Case("cpp-output", InputKind(Language::C).getPreprocessed()) 2945 .Case("assembler-with-cpp", Language::Asm) 2946 .Cases("ast", "pcm", "precompiled-header", 2947 InputKind(Language::Unknown, InputKind::Precompiled)) 2948 .Case("ir", Language::LLVM_IR) 2949 .Default(Language::Unknown); 2950 2951 if (DashX.isUnknown()) 2952 Diags.Report(diag::err_drv_invalid_value) 2953 << A->getAsString(Args) << A->getValue(); 2954 2955 if (Preprocessed) 2956 DashX = DashX.getPreprocessed(); 2957 // A regular header is considered mutually exclusive with a header unit. 2958 if (HUK != InputKind::HeaderUnit_None) { 2959 DashX = DashX.withHeaderUnit(HUK); 2960 IsHeaderFile = true; 2961 } else if (IsHeaderFile) 2962 DashX = DashX.getHeader(); 2963 if (ModuleMap) 2964 DashX = DashX.withFormat(InputKind::ModuleMap); 2965 } 2966 2967 // '-' is the default input if none is given. 2968 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT); 2969 Opts.Inputs.clear(); 2970 if (Inputs.empty()) 2971 Inputs.push_back("-"); 2972 2973 if (DashX.getHeaderUnitKind() != InputKind::HeaderUnit_None && 2974 Inputs.size() > 1) 2975 Diags.Report(diag::err_drv_header_unit_extra_inputs) << Inputs[1]; 2976 2977 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { 2978 InputKind IK = DashX; 2979 if (IK.isUnknown()) { 2980 IK = FrontendOptions::getInputKindForExtension( 2981 StringRef(Inputs[i]).rsplit('.').second); 2982 // FIXME: Warn on this? 2983 if (IK.isUnknown()) 2984 IK = Language::C; 2985 // FIXME: Remove this hack. 2986 if (i == 0) 2987 DashX = IK; 2988 } 2989 2990 bool IsSystem = false; 2991 2992 // The -emit-module action implicitly takes a module map. 2993 if (Opts.ProgramAction == frontend::GenerateModule && 2994 IK.getFormat() == InputKind::Source) { 2995 IK = IK.withFormat(InputKind::ModuleMap); 2996 IsSystem = Opts.IsSystemModule; 2997 } 2998 2999 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem); 3000 } 3001 3002 Opts.DashX = DashX; 3003 3004 return Diags.getNumErrors() == NumErrorsBefore; 3005 } 3006 3007 std::string CompilerInvocation::GetResourcesPath(const char *Argv0, 3008 void *MainAddr) { 3009 std::string ClangExecutable = 3010 llvm::sys::fs::getMainExecutable(Argv0, MainAddr); 3011 return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR); 3012 } 3013 3014 static void GenerateHeaderSearchArgs(const HeaderSearchOptions &Opts, 3015 ArgumentConsumer Consumer) { 3016 const HeaderSearchOptions *HeaderSearchOpts = &Opts; 3017 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \ 3018 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 3019 #include "clang/Driver/Options.inc" 3020 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING 3021 3022 if (Opts.UseLibcxx) 3023 GenerateArg(Consumer, OPT_stdlib_EQ, "libc++"); 3024 3025 if (!Opts.ModuleCachePath.empty()) 3026 GenerateArg(Consumer, OPT_fmodules_cache_path, Opts.ModuleCachePath); 3027 3028 for (const auto &File : Opts.PrebuiltModuleFiles) 3029 GenerateArg(Consumer, OPT_fmodule_file, File.first + "=" + File.second); 3030 3031 for (const auto &Path : Opts.PrebuiltModulePaths) 3032 GenerateArg(Consumer, OPT_fprebuilt_module_path, Path); 3033 3034 for (const auto &Macro : Opts.ModulesIgnoreMacros) 3035 GenerateArg(Consumer, OPT_fmodules_ignore_macro, Macro.val()); 3036 3037 auto Matches = [](const HeaderSearchOptions::Entry &Entry, 3038 llvm::ArrayRef<frontend::IncludeDirGroup> Groups, 3039 std::optional<bool> IsFramework, 3040 std::optional<bool> IgnoreSysRoot) { 3041 return llvm::is_contained(Groups, Entry.Group) && 3042 (!IsFramework || (Entry.IsFramework == *IsFramework)) && 3043 (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot)); 3044 }; 3045 3046 auto It = Opts.UserEntries.begin(); 3047 auto End = Opts.UserEntries.end(); 3048 3049 // Add -I..., -F..., and -index-header-map options in order. 3050 for (; It < End && Matches(*It, {frontend::IndexHeaderMap, frontend::Angled}, 3051 std::nullopt, true); 3052 ++It) { 3053 OptSpecifier Opt = [It, Matches]() { 3054 if (Matches(*It, frontend::IndexHeaderMap, true, true)) 3055 return OPT_F; 3056 if (Matches(*It, frontend::IndexHeaderMap, false, true)) 3057 return OPT_I; 3058 if (Matches(*It, frontend::Angled, true, true)) 3059 return OPT_F; 3060 if (Matches(*It, frontend::Angled, false, true)) 3061 return OPT_I; 3062 llvm_unreachable("Unexpected HeaderSearchOptions::Entry."); 3063 }(); 3064 3065 if (It->Group == frontend::IndexHeaderMap) 3066 GenerateArg(Consumer, OPT_index_header_map); 3067 GenerateArg(Consumer, Opt, It->Path); 3068 }; 3069 3070 // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may 3071 // have already been generated as "-I[xx]yy". If that's the case, their 3072 // position on command line was such that this has no semantic impact on 3073 // include paths. 3074 for (; It < End && 3075 Matches(*It, {frontend::After, frontend::Angled}, false, true); 3076 ++It) { 3077 OptSpecifier Opt = 3078 It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore; 3079 GenerateArg(Consumer, Opt, It->Path); 3080 } 3081 3082 // Note: Some paths that came from "-idirafter=xxyy" may have already been 3083 // generated as "-iwithprefix=xxyy". If that's the case, their position on 3084 // command line was such that this has no semantic impact on include paths. 3085 for (; It < End && Matches(*It, {frontend::After}, false, true); ++It) 3086 GenerateArg(Consumer, OPT_idirafter, It->Path); 3087 for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It) 3088 GenerateArg(Consumer, OPT_iquote, It->Path); 3089 for (; It < End && Matches(*It, {frontend::System}, false, std::nullopt); 3090 ++It) 3091 GenerateArg(Consumer, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot, 3092 It->Path); 3093 for (; It < End && Matches(*It, {frontend::System}, true, true); ++It) 3094 GenerateArg(Consumer, OPT_iframework, It->Path); 3095 for (; It < End && Matches(*It, {frontend::System}, true, false); ++It) 3096 GenerateArg(Consumer, OPT_iframeworkwithsysroot, It->Path); 3097 3098 // Add the paths for the various language specific isystem flags. 3099 for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It) 3100 GenerateArg(Consumer, OPT_c_isystem, It->Path); 3101 for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It) 3102 GenerateArg(Consumer, OPT_cxx_isystem, It->Path); 3103 for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It) 3104 GenerateArg(Consumer, OPT_objc_isystem, It->Path); 3105 for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It) 3106 GenerateArg(Consumer, OPT_objcxx_isystem, It->Path); 3107 3108 // Add the internal paths from a driver that detects standard include paths. 3109 // Note: Some paths that came from "-internal-isystem" arguments may have 3110 // already been generated as "-isystem". If that's the case, their position on 3111 // command line was such that this has no semantic impact on include paths. 3112 for (; It < End && 3113 Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true); 3114 ++It) { 3115 OptSpecifier Opt = It->Group == frontend::System 3116 ? OPT_internal_isystem 3117 : OPT_internal_externc_isystem; 3118 GenerateArg(Consumer, Opt, It->Path); 3119 } 3120 3121 assert(It == End && "Unhandled HeaderSearchOption::Entry."); 3122 3123 // Add the path prefixes which are implicitly treated as being system headers. 3124 for (const auto &P : Opts.SystemHeaderPrefixes) { 3125 OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix 3126 : OPT_no_system_header_prefix; 3127 GenerateArg(Consumer, Opt, P.Prefix); 3128 } 3129 3130 for (const std::string &F : Opts.VFSOverlayFiles) 3131 GenerateArg(Consumer, OPT_ivfsoverlay, F); 3132 } 3133 3134 static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, 3135 DiagnosticsEngine &Diags, 3136 const std::string &WorkingDir) { 3137 unsigned NumErrorsBefore = Diags.getNumErrors(); 3138 3139 HeaderSearchOptions *HeaderSearchOpts = &Opts; 3140 3141 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \ 3142 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 3143 #include "clang/Driver/Options.inc" 3144 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING 3145 3146 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ)) 3147 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0); 3148 3149 // Canonicalize -fmodules-cache-path before storing it. 3150 SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path)); 3151 if (!(P.empty() || llvm::sys::path::is_absolute(P))) { 3152 if (WorkingDir.empty()) 3153 llvm::sys::fs::make_absolute(P); 3154 else 3155 llvm::sys::fs::make_absolute(WorkingDir, P); 3156 } 3157 llvm::sys::path::remove_dots(P); 3158 Opts.ModuleCachePath = std::string(P.str()); 3159 3160 // Only the -fmodule-file=<name>=<file> form. 3161 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 3162 StringRef Val = A->getValue(); 3163 if (Val.contains('=')) { 3164 auto Split = Val.split('='); 3165 Opts.PrebuiltModuleFiles.insert( 3166 {std::string(Split.first), std::string(Split.second)}); 3167 } 3168 } 3169 for (const auto *A : Args.filtered(OPT_fprebuilt_module_path)) 3170 Opts.AddPrebuiltModulePath(A->getValue()); 3171 3172 for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) { 3173 StringRef MacroDef = A->getValue(); 3174 Opts.ModulesIgnoreMacros.insert( 3175 llvm::CachedHashString(MacroDef.split('=').first)); 3176 } 3177 3178 // Add -I..., -F..., and -index-header-map options in order. 3179 bool IsIndexHeaderMap = false; 3180 bool IsSysrootSpecified = 3181 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot); 3182 for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) { 3183 if (A->getOption().matches(OPT_index_header_map)) { 3184 // -index-header-map applies to the next -I or -F. 3185 IsIndexHeaderMap = true; 3186 continue; 3187 } 3188 3189 frontend::IncludeDirGroup Group = 3190 IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled; 3191 3192 bool IsFramework = A->getOption().matches(OPT_F); 3193 std::string Path = A->getValue(); 3194 3195 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') { 3196 SmallString<32> Buffer; 3197 llvm::sys::path::append(Buffer, Opts.Sysroot, 3198 llvm::StringRef(A->getValue()).substr(1)); 3199 Path = std::string(Buffer.str()); 3200 } 3201 3202 Opts.AddPath(Path, Group, IsFramework, 3203 /*IgnoreSysroot*/ true); 3204 IsIndexHeaderMap = false; 3205 } 3206 3207 // Add -iprefix/-iwithprefix/-iwithprefixbefore options. 3208 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix. 3209 for (const auto *A : 3210 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) { 3211 if (A->getOption().matches(OPT_iprefix)) 3212 Prefix = A->getValue(); 3213 else if (A->getOption().matches(OPT_iwithprefix)) 3214 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true); 3215 else 3216 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true); 3217 } 3218 3219 for (const auto *A : Args.filtered(OPT_idirafter)) 3220 Opts.AddPath(A->getValue(), frontend::After, false, true); 3221 for (const auto *A : Args.filtered(OPT_iquote)) 3222 Opts.AddPath(A->getValue(), frontend::Quoted, false, true); 3223 for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot)) 3224 Opts.AddPath(A->getValue(), frontend::System, false, 3225 !A->getOption().matches(OPT_iwithsysroot)); 3226 for (const auto *A : Args.filtered(OPT_iframework)) 3227 Opts.AddPath(A->getValue(), frontend::System, true, true); 3228 for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot)) 3229 Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true, 3230 /*IgnoreSysRoot=*/false); 3231 3232 // Add the paths for the various language specific isystem flags. 3233 for (const auto *A : Args.filtered(OPT_c_isystem)) 3234 Opts.AddPath(A->getValue(), frontend::CSystem, false, true); 3235 for (const auto *A : Args.filtered(OPT_cxx_isystem)) 3236 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true); 3237 for (const auto *A : Args.filtered(OPT_objc_isystem)) 3238 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true); 3239 for (const auto *A : Args.filtered(OPT_objcxx_isystem)) 3240 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true); 3241 3242 // Add the internal paths from a driver that detects standard include paths. 3243 for (const auto *A : 3244 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) { 3245 frontend::IncludeDirGroup Group = frontend::System; 3246 if (A->getOption().matches(OPT_internal_externc_isystem)) 3247 Group = frontend::ExternCSystem; 3248 Opts.AddPath(A->getValue(), Group, false, true); 3249 } 3250 3251 // Add the path prefixes which are implicitly treated as being system headers. 3252 for (const auto *A : 3253 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix)) 3254 Opts.AddSystemHeaderPrefix( 3255 A->getValue(), A->getOption().matches(OPT_system_header_prefix)); 3256 3257 for (const auto *A : Args.filtered(OPT_ivfsoverlay, OPT_vfsoverlay)) 3258 Opts.AddVFSOverlayFile(A->getValue()); 3259 3260 return Diags.getNumErrors() == NumErrorsBefore; 3261 } 3262 3263 /// Check if input file kind and language standard are compatible. 3264 static bool IsInputCompatibleWithStandard(InputKind IK, 3265 const LangStandard &S) { 3266 switch (IK.getLanguage()) { 3267 case Language::Unknown: 3268 case Language::LLVM_IR: 3269 llvm_unreachable("should not parse language flags for this input"); 3270 3271 case Language::C: 3272 case Language::ObjC: 3273 case Language::RenderScript: 3274 return S.getLanguage() == Language::C; 3275 3276 case Language::OpenCL: 3277 return S.getLanguage() == Language::OpenCL || 3278 S.getLanguage() == Language::OpenCLCXX; 3279 3280 case Language::OpenCLCXX: 3281 return S.getLanguage() == Language::OpenCLCXX; 3282 3283 case Language::CXX: 3284 case Language::ObjCXX: 3285 return S.getLanguage() == Language::CXX; 3286 3287 case Language::CUDA: 3288 // FIXME: What -std= values should be permitted for CUDA compilations? 3289 return S.getLanguage() == Language::CUDA || 3290 S.getLanguage() == Language::CXX; 3291 3292 case Language::HIP: 3293 return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP; 3294 3295 case Language::Asm: 3296 // Accept (and ignore) all -std= values. 3297 // FIXME: The -std= value is not ignored; it affects the tokenization 3298 // and preprocessing rules if we're preprocessing this asm input. 3299 return true; 3300 3301 case Language::HLSL: 3302 return S.getLanguage() == Language::HLSL; 3303 } 3304 3305 llvm_unreachable("unexpected input language"); 3306 } 3307 3308 /// Get language name for given input kind. 3309 static StringRef GetInputKindName(InputKind IK) { 3310 switch (IK.getLanguage()) { 3311 case Language::C: 3312 return "C"; 3313 case Language::ObjC: 3314 return "Objective-C"; 3315 case Language::CXX: 3316 return "C++"; 3317 case Language::ObjCXX: 3318 return "Objective-C++"; 3319 case Language::OpenCL: 3320 return "OpenCL"; 3321 case Language::OpenCLCXX: 3322 return "C++ for OpenCL"; 3323 case Language::CUDA: 3324 return "CUDA"; 3325 case Language::RenderScript: 3326 return "RenderScript"; 3327 case Language::HIP: 3328 return "HIP"; 3329 3330 case Language::Asm: 3331 return "Asm"; 3332 case Language::LLVM_IR: 3333 return "LLVM IR"; 3334 3335 case Language::HLSL: 3336 return "HLSL"; 3337 3338 case Language::Unknown: 3339 break; 3340 } 3341 llvm_unreachable("unknown input language"); 3342 } 3343 3344 void CompilerInvocationBase::GenerateLangArgs(const LangOptions &Opts, 3345 ArgumentConsumer Consumer, 3346 const llvm::Triple &T, 3347 InputKind IK) { 3348 if (IK.getFormat() == InputKind::Precompiled || 3349 IK.getLanguage() == Language::LLVM_IR) { 3350 if (Opts.ObjCAutoRefCount) 3351 GenerateArg(Consumer, OPT_fobjc_arc); 3352 if (Opts.PICLevel != 0) 3353 GenerateArg(Consumer, OPT_pic_level, Twine(Opts.PICLevel)); 3354 if (Opts.PIE) 3355 GenerateArg(Consumer, OPT_pic_is_pie); 3356 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize)) 3357 GenerateArg(Consumer, OPT_fsanitize_EQ, Sanitizer); 3358 3359 return; 3360 } 3361 3362 OptSpecifier StdOpt; 3363 switch (Opts.LangStd) { 3364 case LangStandard::lang_opencl10: 3365 case LangStandard::lang_opencl11: 3366 case LangStandard::lang_opencl12: 3367 case LangStandard::lang_opencl20: 3368 case LangStandard::lang_opencl30: 3369 case LangStandard::lang_openclcpp10: 3370 case LangStandard::lang_openclcpp2021: 3371 StdOpt = OPT_cl_std_EQ; 3372 break; 3373 default: 3374 StdOpt = OPT_std_EQ; 3375 break; 3376 } 3377 3378 auto LangStandard = LangStandard::getLangStandardForKind(Opts.LangStd); 3379 GenerateArg(Consumer, StdOpt, LangStandard.getName()); 3380 3381 if (Opts.IncludeDefaultHeader) 3382 GenerateArg(Consumer, OPT_finclude_default_header); 3383 if (Opts.DeclareOpenCLBuiltins) 3384 GenerateArg(Consumer, OPT_fdeclare_opencl_builtins); 3385 3386 const LangOptions *LangOpts = &Opts; 3387 3388 #define LANG_OPTION_WITH_MARSHALLING(...) \ 3389 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 3390 #include "clang/Driver/Options.inc" 3391 #undef LANG_OPTION_WITH_MARSHALLING 3392 3393 // The '-fcf-protection=' option is generated by CodeGenOpts generator. 3394 3395 if (Opts.ObjC) { 3396 GenerateArg(Consumer, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString()); 3397 3398 if (Opts.GC == LangOptions::GCOnly) 3399 GenerateArg(Consumer, OPT_fobjc_gc_only); 3400 else if (Opts.GC == LangOptions::HybridGC) 3401 GenerateArg(Consumer, OPT_fobjc_gc); 3402 else if (Opts.ObjCAutoRefCount == 1) 3403 GenerateArg(Consumer, OPT_fobjc_arc); 3404 3405 if (Opts.ObjCWeakRuntime) 3406 GenerateArg(Consumer, OPT_fobjc_runtime_has_weak); 3407 3408 if (Opts.ObjCWeak) 3409 GenerateArg(Consumer, OPT_fobjc_weak); 3410 3411 if (Opts.ObjCSubscriptingLegacyRuntime) 3412 GenerateArg(Consumer, OPT_fobjc_subscripting_legacy_runtime); 3413 } 3414 3415 if (Opts.GNUCVersion != 0) { 3416 unsigned Major = Opts.GNUCVersion / 100 / 100; 3417 unsigned Minor = (Opts.GNUCVersion / 100) % 100; 3418 unsigned Patch = Opts.GNUCVersion % 100; 3419 GenerateArg(Consumer, OPT_fgnuc_version_EQ, 3420 Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch)); 3421 } 3422 3423 if (Opts.IgnoreXCOFFVisibility) 3424 GenerateArg(Consumer, OPT_mignore_xcoff_visibility); 3425 3426 if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) { 3427 GenerateArg(Consumer, OPT_ftrapv); 3428 GenerateArg(Consumer, OPT_ftrapv_handler, Opts.OverflowHandler); 3429 } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) { 3430 GenerateArg(Consumer, OPT_fwrapv); 3431 } 3432 3433 if (Opts.MSCompatibilityVersion != 0) { 3434 unsigned Major = Opts.MSCompatibilityVersion / 10000000; 3435 unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100; 3436 unsigned Subminor = Opts.MSCompatibilityVersion % 100000; 3437 GenerateArg(Consumer, OPT_fms_compatibility_version, 3438 Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor)); 3439 } 3440 3441 if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS()) { 3442 if (!Opts.Trigraphs) 3443 GenerateArg(Consumer, OPT_fno_trigraphs); 3444 } else { 3445 if (Opts.Trigraphs) 3446 GenerateArg(Consumer, OPT_ftrigraphs); 3447 } 3448 3449 if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200)) 3450 GenerateArg(Consumer, OPT_fblocks); 3451 3452 if (Opts.ConvergentFunctions && 3453 !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice)) 3454 GenerateArg(Consumer, OPT_fconvergent_functions); 3455 3456 if (Opts.NoBuiltin && !Opts.Freestanding) 3457 GenerateArg(Consumer, OPT_fno_builtin); 3458 3459 if (!Opts.NoBuiltin) 3460 for (const auto &Func : Opts.NoBuiltinFuncs) 3461 GenerateArg(Consumer, OPT_fno_builtin_, Func); 3462 3463 if (Opts.LongDoubleSize == 128) 3464 GenerateArg(Consumer, OPT_mlong_double_128); 3465 else if (Opts.LongDoubleSize == 64) 3466 GenerateArg(Consumer, OPT_mlong_double_64); 3467 else if (Opts.LongDoubleSize == 80) 3468 GenerateArg(Consumer, OPT_mlong_double_80); 3469 3470 // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='. 3471 3472 // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or 3473 // '-fopenmp-targets='. 3474 if (Opts.OpenMP && !Opts.OpenMPSimd) { 3475 GenerateArg(Consumer, OPT_fopenmp); 3476 3477 if (Opts.OpenMP != 51) 3478 GenerateArg(Consumer, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP)); 3479 3480 if (!Opts.OpenMPUseTLS) 3481 GenerateArg(Consumer, OPT_fnoopenmp_use_tls); 3482 3483 if (Opts.OpenMPIsTargetDevice) 3484 GenerateArg(Consumer, OPT_fopenmp_is_target_device); 3485 3486 if (Opts.OpenMPIRBuilder) 3487 GenerateArg(Consumer, OPT_fopenmp_enable_irbuilder); 3488 } 3489 3490 if (Opts.OpenMPSimd) { 3491 GenerateArg(Consumer, OPT_fopenmp_simd); 3492 3493 if (Opts.OpenMP != 51) 3494 GenerateArg(Consumer, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP)); 3495 } 3496 3497 if (Opts.OpenMPThreadSubscription) 3498 GenerateArg(Consumer, OPT_fopenmp_assume_threads_oversubscription); 3499 3500 if (Opts.OpenMPTeamSubscription) 3501 GenerateArg(Consumer, OPT_fopenmp_assume_teams_oversubscription); 3502 3503 if (Opts.OpenMPTargetDebug != 0) 3504 GenerateArg(Consumer, OPT_fopenmp_target_debug_EQ, 3505 Twine(Opts.OpenMPTargetDebug)); 3506 3507 if (Opts.OpenMPCUDANumSMs != 0) 3508 GenerateArg(Consumer, OPT_fopenmp_cuda_number_of_sm_EQ, 3509 Twine(Opts.OpenMPCUDANumSMs)); 3510 3511 if (Opts.OpenMPCUDABlocksPerSM != 0) 3512 GenerateArg(Consumer, OPT_fopenmp_cuda_blocks_per_sm_EQ, 3513 Twine(Opts.OpenMPCUDABlocksPerSM)); 3514 3515 if (Opts.OpenMPCUDAReductionBufNum != 1024) 3516 GenerateArg(Consumer, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ, 3517 Twine(Opts.OpenMPCUDAReductionBufNum)); 3518 3519 if (!Opts.OMPTargetTriples.empty()) { 3520 std::string Targets; 3521 llvm::raw_string_ostream OS(Targets); 3522 llvm::interleave( 3523 Opts.OMPTargetTriples, OS, 3524 [&OS](const llvm::Triple &T) { OS << T.str(); }, ","); 3525 GenerateArg(Consumer, OPT_fopenmp_targets_EQ, OS.str()); 3526 } 3527 3528 if (!Opts.OMPHostIRFile.empty()) 3529 GenerateArg(Consumer, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile); 3530 3531 if (Opts.OpenMPCUDAMode) 3532 GenerateArg(Consumer, OPT_fopenmp_cuda_mode); 3533 3534 // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are 3535 // generated from CodeGenOptions. 3536 3537 if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast) 3538 GenerateArg(Consumer, OPT_ffp_contract, "fast"); 3539 else if (Opts.DefaultFPContractMode == LangOptions::FPM_On) 3540 GenerateArg(Consumer, OPT_ffp_contract, "on"); 3541 else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off) 3542 GenerateArg(Consumer, OPT_ffp_contract, "off"); 3543 else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas) 3544 GenerateArg(Consumer, OPT_ffp_contract, "fast-honor-pragmas"); 3545 3546 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize)) 3547 GenerateArg(Consumer, OPT_fsanitize_EQ, Sanitizer); 3548 3549 // Conflating '-fsanitize-system-ignorelist' and '-fsanitize-ignorelist'. 3550 for (const std::string &F : Opts.NoSanitizeFiles) 3551 GenerateArg(Consumer, OPT_fsanitize_ignorelist_EQ, F); 3552 3553 switch (Opts.getClangABICompat()) { 3554 case LangOptions::ClangABI::Ver3_8: 3555 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "3.8"); 3556 break; 3557 case LangOptions::ClangABI::Ver4: 3558 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "4.0"); 3559 break; 3560 case LangOptions::ClangABI::Ver6: 3561 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "6.0"); 3562 break; 3563 case LangOptions::ClangABI::Ver7: 3564 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "7.0"); 3565 break; 3566 case LangOptions::ClangABI::Ver9: 3567 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "9.0"); 3568 break; 3569 case LangOptions::ClangABI::Ver11: 3570 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "11.0"); 3571 break; 3572 case LangOptions::ClangABI::Ver12: 3573 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "12.0"); 3574 break; 3575 case LangOptions::ClangABI::Ver14: 3576 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "14.0"); 3577 break; 3578 case LangOptions::ClangABI::Ver15: 3579 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "15.0"); 3580 break; 3581 case LangOptions::ClangABI::Ver17: 3582 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "17.0"); 3583 break; 3584 case LangOptions::ClangABI::Latest: 3585 break; 3586 } 3587 3588 if (Opts.getSignReturnAddressScope() == 3589 LangOptions::SignReturnAddressScopeKind::All) 3590 GenerateArg(Consumer, OPT_msign_return_address_EQ, "all"); 3591 else if (Opts.getSignReturnAddressScope() == 3592 LangOptions::SignReturnAddressScopeKind::NonLeaf) 3593 GenerateArg(Consumer, OPT_msign_return_address_EQ, "non-leaf"); 3594 3595 if (Opts.getSignReturnAddressKey() == 3596 LangOptions::SignReturnAddressKeyKind::BKey) 3597 GenerateArg(Consumer, OPT_msign_return_address_key_EQ, "b_key"); 3598 3599 if (Opts.CXXABI) 3600 GenerateArg(Consumer, OPT_fcxx_abi_EQ, 3601 TargetCXXABI::getSpelling(*Opts.CXXABI)); 3602 3603 if (Opts.RelativeCXXABIVTables) 3604 GenerateArg(Consumer, OPT_fexperimental_relative_cxx_abi_vtables); 3605 else 3606 GenerateArg(Consumer, OPT_fno_experimental_relative_cxx_abi_vtables); 3607 3608 if (Opts.UseTargetPathSeparator) 3609 GenerateArg(Consumer, OPT_ffile_reproducible); 3610 else 3611 GenerateArg(Consumer, OPT_fno_file_reproducible); 3612 3613 for (const auto &MP : Opts.MacroPrefixMap) 3614 GenerateArg(Consumer, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second); 3615 3616 if (!Opts.RandstructSeed.empty()) 3617 GenerateArg(Consumer, OPT_frandomize_layout_seed_EQ, Opts.RandstructSeed); 3618 } 3619 3620 bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args, 3621 InputKind IK, const llvm::Triple &T, 3622 std::vector<std::string> &Includes, 3623 DiagnosticsEngine &Diags) { 3624 unsigned NumErrorsBefore = Diags.getNumErrors(); 3625 3626 if (IK.getFormat() == InputKind::Precompiled || 3627 IK.getLanguage() == Language::LLVM_IR) { 3628 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the 3629 // PassManager in BackendUtil.cpp. They need to be initialized no matter 3630 // what the input type is. 3631 if (Args.hasArg(OPT_fobjc_arc)) 3632 Opts.ObjCAutoRefCount = 1; 3633 // PICLevel and PIELevel are needed during code generation and this should 3634 // be set regardless of the input type. 3635 Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags); 3636 Opts.PIE = Args.hasArg(OPT_pic_is_pie); 3637 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), 3638 Diags, Opts.Sanitize); 3639 3640 return Diags.getNumErrors() == NumErrorsBefore; 3641 } 3642 3643 // Other LangOpts are only initialized when the input is not AST or LLVM IR. 3644 // FIXME: Should we really be parsing this for an Language::Asm input? 3645 3646 // FIXME: Cleanup per-file based stuff. 3647 LangStandard::Kind LangStd = LangStandard::lang_unspecified; 3648 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) { 3649 LangStd = LangStandard::getLangKind(A->getValue()); 3650 if (LangStd == LangStandard::lang_unspecified) { 3651 Diags.Report(diag::err_drv_invalid_value) 3652 << A->getAsString(Args) << A->getValue(); 3653 // Report supported standards with short description. 3654 for (unsigned KindValue = 0; 3655 KindValue != LangStandard::lang_unspecified; 3656 ++KindValue) { 3657 const LangStandard &Std = LangStandard::getLangStandardForKind( 3658 static_cast<LangStandard::Kind>(KindValue)); 3659 if (IsInputCompatibleWithStandard(IK, Std)) { 3660 auto Diag = Diags.Report(diag::note_drv_use_standard); 3661 Diag << Std.getName() << Std.getDescription(); 3662 unsigned NumAliases = 0; 3663 #define LANGSTANDARD(id, name, lang, desc, features) 3664 #define LANGSTANDARD_ALIAS(id, alias) \ 3665 if (KindValue == LangStandard::lang_##id) ++NumAliases; 3666 #define LANGSTANDARD_ALIAS_DEPR(id, alias) 3667 #include "clang/Basic/LangStandards.def" 3668 Diag << NumAliases; 3669 #define LANGSTANDARD(id, name, lang, desc, features) 3670 #define LANGSTANDARD_ALIAS(id, alias) \ 3671 if (KindValue == LangStandard::lang_##id) Diag << alias; 3672 #define LANGSTANDARD_ALIAS_DEPR(id, alias) 3673 #include "clang/Basic/LangStandards.def" 3674 } 3675 } 3676 } else { 3677 // Valid standard, check to make sure language and standard are 3678 // compatible. 3679 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); 3680 if (!IsInputCompatibleWithStandard(IK, Std)) { 3681 Diags.Report(diag::err_drv_argument_not_allowed_with) 3682 << A->getAsString(Args) << GetInputKindName(IK); 3683 } 3684 } 3685 } 3686 3687 // -cl-std only applies for OpenCL language standards. 3688 // Override the -std option in this case. 3689 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) { 3690 LangStandard::Kind OpenCLLangStd 3691 = llvm::StringSwitch<LangStandard::Kind>(A->getValue()) 3692 .Cases("cl", "CL", LangStandard::lang_opencl10) 3693 .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10) 3694 .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11) 3695 .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12) 3696 .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20) 3697 .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30) 3698 .Cases("clc++", "CLC++", LangStandard::lang_openclcpp10) 3699 .Cases("clc++1.0", "CLC++1.0", LangStandard::lang_openclcpp10) 3700 .Cases("clc++2021", "CLC++2021", LangStandard::lang_openclcpp2021) 3701 .Default(LangStandard::lang_unspecified); 3702 3703 if (OpenCLLangStd == LangStandard::lang_unspecified) { 3704 Diags.Report(diag::err_drv_invalid_value) 3705 << A->getAsString(Args) << A->getValue(); 3706 } 3707 else 3708 LangStd = OpenCLLangStd; 3709 } 3710 3711 // These need to be parsed now. They are used to set OpenCL defaults. 3712 Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header); 3713 Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins); 3714 3715 LangOptions::setLangDefaults(Opts, IK.getLanguage(), T, Includes, LangStd); 3716 3717 // The key paths of codegen options defined in Options.td start with 3718 // "LangOpts->". Let's provide the expected variable name and type. 3719 LangOptions *LangOpts = &Opts; 3720 3721 #define LANG_OPTION_WITH_MARSHALLING(...) \ 3722 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 3723 #include "clang/Driver/Options.inc" 3724 #undef LANG_OPTION_WITH_MARSHALLING 3725 3726 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 3727 StringRef Name = A->getValue(); 3728 if (Name == "full" || Name == "branch") { 3729 Opts.CFProtectionBranch = 1; 3730 } 3731 } 3732 3733 if ((Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host)) && 3734 !Args.hasArg(OPT_sycl_std_EQ)) { 3735 // If the user supplied -fsycl-is-device or -fsycl-is-host, but failed to 3736 // provide -sycl-std=, we want to default it to whatever the default SYCL 3737 // version is. I could not find a way to express this with the options 3738 // tablegen because we still want this value to be SYCL_None when the user 3739 // is not in device or host mode. 3740 Opts.setSYCLVersion(LangOptions::SYCL_Default); 3741 } 3742 3743 if (Opts.ObjC) { 3744 if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) { 3745 StringRef value = arg->getValue(); 3746 if (Opts.ObjCRuntime.tryParse(value)) 3747 Diags.Report(diag::err_drv_unknown_objc_runtime) << value; 3748 } 3749 3750 if (Args.hasArg(OPT_fobjc_gc_only)) 3751 Opts.setGC(LangOptions::GCOnly); 3752 else if (Args.hasArg(OPT_fobjc_gc)) 3753 Opts.setGC(LangOptions::HybridGC); 3754 else if (Args.hasArg(OPT_fobjc_arc)) { 3755 Opts.ObjCAutoRefCount = 1; 3756 if (!Opts.ObjCRuntime.allowsARC()) 3757 Diags.Report(diag::err_arc_unsupported_on_runtime); 3758 } 3759 3760 // ObjCWeakRuntime tracks whether the runtime supports __weak, not 3761 // whether the feature is actually enabled. This is predominantly 3762 // determined by -fobjc-runtime, but we allow it to be overridden 3763 // from the command line for testing purposes. 3764 if (Args.hasArg(OPT_fobjc_runtime_has_weak)) 3765 Opts.ObjCWeakRuntime = 1; 3766 else 3767 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak(); 3768 3769 // ObjCWeak determines whether __weak is actually enabled. 3770 // Note that we allow -fno-objc-weak to disable this even in ARC mode. 3771 if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) { 3772 if (!weakArg->getOption().matches(OPT_fobjc_weak)) { 3773 assert(!Opts.ObjCWeak); 3774 } else if (Opts.getGC() != LangOptions::NonGC) { 3775 Diags.Report(diag::err_objc_weak_with_gc); 3776 } else if (!Opts.ObjCWeakRuntime) { 3777 Diags.Report(diag::err_objc_weak_unsupported); 3778 } else { 3779 Opts.ObjCWeak = 1; 3780 } 3781 } else if (Opts.ObjCAutoRefCount) { 3782 Opts.ObjCWeak = Opts.ObjCWeakRuntime; 3783 } 3784 3785 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime)) 3786 Opts.ObjCSubscriptingLegacyRuntime = 3787 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX); 3788 } 3789 3790 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) { 3791 // Check that the version has 1 to 3 components and the minor and patch 3792 // versions fit in two decimal digits. 3793 VersionTuple GNUCVer; 3794 bool Invalid = GNUCVer.tryParse(A->getValue()); 3795 unsigned Major = GNUCVer.getMajor(); 3796 unsigned Minor = GNUCVer.getMinor().value_or(0); 3797 unsigned Patch = GNUCVer.getSubminor().value_or(0); 3798 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) { 3799 Diags.Report(diag::err_drv_invalid_value) 3800 << A->getAsString(Args) << A->getValue(); 3801 } 3802 Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch; 3803 } 3804 3805 if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility))) 3806 Opts.IgnoreXCOFFVisibility = 1; 3807 3808 if (Args.hasArg(OPT_ftrapv)) { 3809 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping); 3810 // Set the handler, if one is specified. 3811 Opts.OverflowHandler = 3812 std::string(Args.getLastArgValue(OPT_ftrapv_handler)); 3813 } 3814 else if (Args.hasArg(OPT_fwrapv)) 3815 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined); 3816 3817 Opts.MSCompatibilityVersion = 0; 3818 if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) { 3819 VersionTuple VT; 3820 if (VT.tryParse(A->getValue())) 3821 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 3822 << A->getValue(); 3823 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 + 3824 VT.getMinor().value_or(0) * 100000 + 3825 VT.getSubminor().value_or(0); 3826 } 3827 3828 // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs 3829 // is specified, or -std is set to a conforming mode. 3830 // Trigraphs are disabled by default in c++1z onwards. 3831 // For z/OS, trigraphs are enabled by default (without regard to the above). 3832 Opts.Trigraphs = 3833 (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS(); 3834 Opts.Trigraphs = 3835 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs); 3836 3837 Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL 3838 && Opts.OpenCLVersion == 200); 3839 3840 Opts.ConvergentFunctions = Args.hasArg(OPT_fconvergent_functions) || 3841 Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || 3842 Opts.SYCLIsDevice; 3843 3844 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding; 3845 if (!Opts.NoBuiltin) 3846 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs); 3847 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) { 3848 if (A->getOption().matches(options::OPT_mlong_double_64)) 3849 Opts.LongDoubleSize = 64; 3850 else if (A->getOption().matches(options::OPT_mlong_double_80)) 3851 Opts.LongDoubleSize = 80; 3852 else if (A->getOption().matches(options::OPT_mlong_double_128)) 3853 Opts.LongDoubleSize = 128; 3854 else 3855 Opts.LongDoubleSize = 0; 3856 } 3857 if (Opts.FastRelaxedMath || Opts.CLUnsafeMath) 3858 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast); 3859 3860 llvm::sort(Opts.ModuleFeatures); 3861 3862 // -mrtd option 3863 if (Arg *A = Args.getLastArg(OPT_mrtd)) { 3864 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None) 3865 Diags.Report(diag::err_drv_argument_not_allowed_with) 3866 << A->getSpelling() << "-fdefault-calling-conv"; 3867 else { 3868 if (T.getArch() != llvm::Triple::x86) 3869 Diags.Report(diag::err_drv_argument_not_allowed_with) 3870 << A->getSpelling() << T.getTriple(); 3871 else 3872 Opts.setDefaultCallingConv(LangOptions::DCC_StdCall); 3873 } 3874 } 3875 3876 // Check if -fopenmp is specified and set default version to 5.0. 3877 Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 51 : 0; 3878 // Check if -fopenmp-simd is specified. 3879 bool IsSimdSpecified = 3880 Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd, 3881 /*Default=*/false); 3882 Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified; 3883 Opts.OpenMPUseTLS = 3884 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls); 3885 Opts.OpenMPIsTargetDevice = 3886 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_target_device); 3887 Opts.OpenMPIRBuilder = 3888 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder); 3889 bool IsTargetSpecified = 3890 Opts.OpenMPIsTargetDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ); 3891 3892 Opts.ConvergentFunctions = 3893 Opts.ConvergentFunctions || Opts.OpenMPIsTargetDevice; 3894 3895 if (Opts.OpenMP || Opts.OpenMPSimd) { 3896 if (int Version = getLastArgIntValue( 3897 Args, OPT_fopenmp_version_EQ, 3898 (IsSimdSpecified || IsTargetSpecified) ? 51 : Opts.OpenMP, Diags)) 3899 Opts.OpenMP = Version; 3900 // Provide diagnostic when a given target is not expected to be an OpenMP 3901 // device or host. 3902 if (!Opts.OpenMPIsTargetDevice) { 3903 switch (T.getArch()) { 3904 default: 3905 break; 3906 // Add unsupported host targets here: 3907 case llvm::Triple::nvptx: 3908 case llvm::Triple::nvptx64: 3909 Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str(); 3910 break; 3911 } 3912 } 3913 } 3914 3915 // Set the flag to prevent the implementation from emitting device exception 3916 // handling code for those requiring so. 3917 if ((Opts.OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN())) || 3918 Opts.OpenCLCPlusPlus) { 3919 3920 Opts.Exceptions = 0; 3921 Opts.CXXExceptions = 0; 3922 } 3923 if (Opts.OpenMPIsTargetDevice && T.isNVPTX()) { 3924 Opts.OpenMPCUDANumSMs = 3925 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ, 3926 Opts.OpenMPCUDANumSMs, Diags); 3927 Opts.OpenMPCUDABlocksPerSM = 3928 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ, 3929 Opts.OpenMPCUDABlocksPerSM, Diags); 3930 Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue( 3931 Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ, 3932 Opts.OpenMPCUDAReductionBufNum, Diags); 3933 } 3934 3935 // Set the value of the debugging flag used in the new offloading device RTL. 3936 // Set either by a specific value or to a default if not specified. 3937 if (Opts.OpenMPIsTargetDevice && (Args.hasArg(OPT_fopenmp_target_debug) || 3938 Args.hasArg(OPT_fopenmp_target_debug_EQ))) { 3939 Opts.OpenMPTargetDebug = getLastArgIntValue( 3940 Args, OPT_fopenmp_target_debug_EQ, Opts.OpenMPTargetDebug, Diags); 3941 if (!Opts.OpenMPTargetDebug && Args.hasArg(OPT_fopenmp_target_debug)) 3942 Opts.OpenMPTargetDebug = 1; 3943 } 3944 3945 if (Opts.OpenMPIsTargetDevice) { 3946 if (Args.hasArg(OPT_fopenmp_assume_teams_oversubscription)) 3947 Opts.OpenMPTeamSubscription = true; 3948 if (Args.hasArg(OPT_fopenmp_assume_threads_oversubscription)) 3949 Opts.OpenMPThreadSubscription = true; 3950 } 3951 3952 // Get the OpenMP target triples if any. 3953 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) { 3954 enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit }; 3955 auto getArchPtrSize = [](const llvm::Triple &T) { 3956 if (T.isArch16Bit()) 3957 return Arch16Bit; 3958 if (T.isArch32Bit()) 3959 return Arch32Bit; 3960 assert(T.isArch64Bit() && "Expected 64-bit architecture"); 3961 return Arch64Bit; 3962 }; 3963 3964 for (unsigned i = 0; i < A->getNumValues(); ++i) { 3965 llvm::Triple TT(A->getValue(i)); 3966 3967 if (TT.getArch() == llvm::Triple::UnknownArch || 3968 !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() || 3969 TT.getArch() == llvm::Triple::nvptx || 3970 TT.getArch() == llvm::Triple::nvptx64 || 3971 TT.getArch() == llvm::Triple::amdgcn || 3972 TT.getArch() == llvm::Triple::x86 || 3973 TT.getArch() == llvm::Triple::x86_64)) 3974 Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i); 3975 else if (getArchPtrSize(T) != getArchPtrSize(TT)) 3976 Diags.Report(diag::err_drv_incompatible_omp_arch) 3977 << A->getValue(i) << T.str(); 3978 else 3979 Opts.OMPTargetTriples.push_back(TT); 3980 } 3981 } 3982 3983 // Get OpenMP host file path if any and report if a non existent file is 3984 // found 3985 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) { 3986 Opts.OMPHostIRFile = A->getValue(); 3987 if (!llvm::sys::fs::exists(Opts.OMPHostIRFile)) 3988 Diags.Report(diag::err_drv_omp_host_ir_file_not_found) 3989 << Opts.OMPHostIRFile; 3990 } 3991 3992 // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options 3993 Opts.OpenMPCUDAMode = Opts.OpenMPIsTargetDevice && 3994 (T.isNVPTX() || T.isAMDGCN()) && 3995 Args.hasArg(options::OPT_fopenmp_cuda_mode); 3996 3997 // FIXME: Eliminate this dependency. 3998 unsigned Opt = getOptimizationLevel(Args, IK, Diags), 3999 OptSize = getOptimizationLevelSize(Args); 4000 Opts.Optimize = Opt != 0; 4001 Opts.OptimizeSize = OptSize != 0; 4002 4003 // This is the __NO_INLINE__ define, which just depends on things like the 4004 // optimization level and -fno-inline, not actually whether the backend has 4005 // inlining enabled. 4006 Opts.NoInlineDefine = !Opts.Optimize; 4007 if (Arg *InlineArg = Args.getLastArg( 4008 options::OPT_finline_functions, options::OPT_finline_hint_functions, 4009 options::OPT_fno_inline_functions, options::OPT_fno_inline)) 4010 if (InlineArg->getOption().matches(options::OPT_fno_inline)) 4011 Opts.NoInlineDefine = true; 4012 4013 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) { 4014 StringRef Val = A->getValue(); 4015 if (Val == "fast") 4016 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast); 4017 else if (Val == "on") 4018 Opts.setDefaultFPContractMode(LangOptions::FPM_On); 4019 else if (Val == "off") 4020 Opts.setDefaultFPContractMode(LangOptions::FPM_Off); 4021 else if (Val == "fast-honor-pragmas") 4022 Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas); 4023 else 4024 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 4025 } 4026 4027 // Parse -fsanitize= arguments. 4028 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), 4029 Diags, Opts.Sanitize); 4030 Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_ignorelist_EQ); 4031 std::vector<std::string> systemIgnorelists = 4032 Args.getAllArgValues(OPT_fsanitize_system_ignorelist_EQ); 4033 Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(), 4034 systemIgnorelists.begin(), 4035 systemIgnorelists.end()); 4036 4037 if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) { 4038 Opts.setClangABICompat(LangOptions::ClangABI::Latest); 4039 4040 StringRef Ver = A->getValue(); 4041 std::pair<StringRef, StringRef> VerParts = Ver.split('.'); 4042 unsigned Major, Minor = 0; 4043 4044 // Check the version number is valid: either 3.x (0 <= x <= 9) or 4045 // y or y.0 (4 <= y <= current version). 4046 if (!VerParts.first.startswith("0") && 4047 !VerParts.first.getAsInteger(10, Major) && 4048 3 <= Major && Major <= CLANG_VERSION_MAJOR && 4049 (Major == 3 ? VerParts.second.size() == 1 && 4050 !VerParts.second.getAsInteger(10, Minor) 4051 : VerParts.first.size() == Ver.size() || 4052 VerParts.second == "0")) { 4053 // Got a valid version number. 4054 if (Major == 3 && Minor <= 8) 4055 Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8); 4056 else if (Major <= 4) 4057 Opts.setClangABICompat(LangOptions::ClangABI::Ver4); 4058 else if (Major <= 6) 4059 Opts.setClangABICompat(LangOptions::ClangABI::Ver6); 4060 else if (Major <= 7) 4061 Opts.setClangABICompat(LangOptions::ClangABI::Ver7); 4062 else if (Major <= 9) 4063 Opts.setClangABICompat(LangOptions::ClangABI::Ver9); 4064 else if (Major <= 11) 4065 Opts.setClangABICompat(LangOptions::ClangABI::Ver11); 4066 else if (Major <= 12) 4067 Opts.setClangABICompat(LangOptions::ClangABI::Ver12); 4068 else if (Major <= 14) 4069 Opts.setClangABICompat(LangOptions::ClangABI::Ver14); 4070 else if (Major <= 15) 4071 Opts.setClangABICompat(LangOptions::ClangABI::Ver15); 4072 else if (Major <= 17) 4073 Opts.setClangABICompat(LangOptions::ClangABI::Ver17); 4074 } else if (Ver != "latest") { 4075 Diags.Report(diag::err_drv_invalid_value) 4076 << A->getAsString(Args) << A->getValue(); 4077 } 4078 } 4079 4080 if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) { 4081 StringRef SignScope = A->getValue(); 4082 4083 if (SignScope.equals_insensitive("none")) 4084 Opts.setSignReturnAddressScope( 4085 LangOptions::SignReturnAddressScopeKind::None); 4086 else if (SignScope.equals_insensitive("all")) 4087 Opts.setSignReturnAddressScope( 4088 LangOptions::SignReturnAddressScopeKind::All); 4089 else if (SignScope.equals_insensitive("non-leaf")) 4090 Opts.setSignReturnAddressScope( 4091 LangOptions::SignReturnAddressScopeKind::NonLeaf); 4092 else 4093 Diags.Report(diag::err_drv_invalid_value) 4094 << A->getAsString(Args) << SignScope; 4095 4096 if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) { 4097 StringRef SignKey = A->getValue(); 4098 if (!SignScope.empty() && !SignKey.empty()) { 4099 if (SignKey.equals_insensitive("a_key")) 4100 Opts.setSignReturnAddressKey( 4101 LangOptions::SignReturnAddressKeyKind::AKey); 4102 else if (SignKey.equals_insensitive("b_key")) 4103 Opts.setSignReturnAddressKey( 4104 LangOptions::SignReturnAddressKeyKind::BKey); 4105 else 4106 Diags.Report(diag::err_drv_invalid_value) 4107 << A->getAsString(Args) << SignKey; 4108 } 4109 } 4110 } 4111 4112 // The value can be empty, which indicates the system default should be used. 4113 StringRef CXXABI = Args.getLastArgValue(OPT_fcxx_abi_EQ); 4114 if (!CXXABI.empty()) { 4115 if (!TargetCXXABI::isABI(CXXABI)) { 4116 Diags.Report(diag::err_invalid_cxx_abi) << CXXABI; 4117 } else { 4118 auto Kind = TargetCXXABI::getKind(CXXABI); 4119 if (!TargetCXXABI::isSupportedCXXABI(T, Kind)) 4120 Diags.Report(diag::err_unsupported_cxx_abi) << CXXABI << T.str(); 4121 else 4122 Opts.CXXABI = Kind; 4123 } 4124 } 4125 4126 Opts.RelativeCXXABIVTables = 4127 Args.hasFlag(options::OPT_fexperimental_relative_cxx_abi_vtables, 4128 options::OPT_fno_experimental_relative_cxx_abi_vtables, 4129 TargetCXXABI::usesRelativeVTables(T)); 4130 4131 // RTTI is on by default. 4132 bool HasRTTI = Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti, true); 4133 Opts.OmitVTableRTTI = 4134 Args.hasFlag(options::OPT_fexperimental_omit_vtable_rtti, 4135 options::OPT_fno_experimental_omit_vtable_rtti, false); 4136 if (Opts.OmitVTableRTTI && HasRTTI) 4137 Diags.Report(diag::err_drv_using_omit_rtti_component_without_no_rtti); 4138 4139 for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) { 4140 auto Split = StringRef(A).split('='); 4141 Opts.MacroPrefixMap.insert( 4142 {std::string(Split.first), std::string(Split.second)}); 4143 } 4144 4145 Opts.UseTargetPathSeparator = 4146 !Args.getLastArg(OPT_fno_file_reproducible) && 4147 (Args.getLastArg(OPT_ffile_compilation_dir_EQ) || 4148 Args.getLastArg(OPT_fmacro_prefix_map_EQ) || 4149 Args.getLastArg(OPT_ffile_reproducible)); 4150 4151 // Error if -mvscale-min is unbounded. 4152 if (Arg *A = Args.getLastArg(options::OPT_mvscale_min_EQ)) { 4153 unsigned VScaleMin; 4154 if (StringRef(A->getValue()).getAsInteger(10, VScaleMin) || VScaleMin == 0) 4155 Diags.Report(diag::err_cc1_unbounded_vscale_min); 4156 } 4157 4158 if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_file_EQ)) { 4159 std::ifstream SeedFile(A->getValue(0)); 4160 4161 if (!SeedFile.is_open()) 4162 Diags.Report(diag::err_drv_cannot_open_randomize_layout_seed_file) 4163 << A->getValue(0); 4164 4165 std::getline(SeedFile, Opts.RandstructSeed); 4166 } 4167 4168 if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_EQ)) 4169 Opts.RandstructSeed = A->getValue(0); 4170 4171 // Validate options for HLSL 4172 if (Opts.HLSL) { 4173 // TODO: Revisit restricting SPIR-V to logical once we've figured out how to 4174 // handle PhysicalStorageBuffer64 memory model 4175 if (T.isDXIL() || T.isSPIRVLogical()) { 4176 enum { ShaderModel, ShaderStage }; 4177 if (T.getOSName().empty()) { 4178 Diags.Report(diag::err_drv_hlsl_bad_shader_required_in_target) 4179 << ShaderModel << T.str(); 4180 } else if (!T.isShaderModelOS() || T.getOSVersion() == VersionTuple(0)) { 4181 Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported) 4182 << ShaderModel << T.getOSName() << T.str(); 4183 } else if (T.getEnvironmentName().empty()) { 4184 Diags.Report(diag::err_drv_hlsl_bad_shader_required_in_target) 4185 << ShaderStage << T.str(); 4186 } else if (!T.isShaderStageEnvironment()) { 4187 Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported) 4188 << ShaderStage << T.getEnvironmentName() << T.str(); 4189 } 4190 } else 4191 Diags.Report(diag::err_drv_hlsl_unsupported_target) << T.str(); 4192 } 4193 4194 return Diags.getNumErrors() == NumErrorsBefore; 4195 } 4196 4197 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) { 4198 switch (Action) { 4199 case frontend::ASTDeclList: 4200 case frontend::ASTDump: 4201 case frontend::ASTPrint: 4202 case frontend::ASTView: 4203 case frontend::EmitAssembly: 4204 case frontend::EmitBC: 4205 case frontend::EmitHTML: 4206 case frontend::EmitLLVM: 4207 case frontend::EmitLLVMOnly: 4208 case frontend::EmitCodeGenOnly: 4209 case frontend::EmitObj: 4210 case frontend::ExtractAPI: 4211 case frontend::FixIt: 4212 case frontend::GenerateModule: 4213 case frontend::GenerateModuleInterface: 4214 case frontend::GenerateHeaderUnit: 4215 case frontend::GeneratePCH: 4216 case frontend::GenerateInterfaceStubs: 4217 case frontend::ParseSyntaxOnly: 4218 case frontend::ModuleFileInfo: 4219 case frontend::VerifyPCH: 4220 case frontend::PluginAction: 4221 case frontend::RewriteObjC: 4222 case frontend::RewriteTest: 4223 case frontend::RunAnalysis: 4224 case frontend::TemplightDump: 4225 case frontend::MigrateSource: 4226 return false; 4227 4228 case frontend::DumpCompilerOptions: 4229 case frontend::DumpRawTokens: 4230 case frontend::DumpTokens: 4231 case frontend::InitOnly: 4232 case frontend::PrintPreamble: 4233 case frontend::PrintPreprocessedInput: 4234 case frontend::RewriteMacros: 4235 case frontend::RunPreprocessorOnly: 4236 case frontend::PrintDependencyDirectivesSourceMinimizerOutput: 4237 return true; 4238 } 4239 llvm_unreachable("invalid frontend action"); 4240 } 4241 4242 static void GeneratePreprocessorArgs(const PreprocessorOptions &Opts, 4243 ArgumentConsumer Consumer, 4244 const LangOptions &LangOpts, 4245 const FrontendOptions &FrontendOpts, 4246 const CodeGenOptions &CodeGenOpts) { 4247 const PreprocessorOptions *PreprocessorOpts = &Opts; 4248 4249 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \ 4250 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 4251 #include "clang/Driver/Options.inc" 4252 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING 4253 4254 if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate) 4255 GenerateArg(Consumer, OPT_pch_through_hdrstop_use); 4256 4257 for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn) 4258 GenerateArg(Consumer, OPT_error_on_deserialized_pch_decl, D); 4259 4260 if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false)) 4261 GenerateArg(Consumer, OPT_preamble_bytes_EQ, 4262 Twine(Opts.PrecompiledPreambleBytes.first) + "," + 4263 (Opts.PrecompiledPreambleBytes.second ? "1" : "0")); 4264 4265 for (const auto &M : Opts.Macros) { 4266 // Don't generate __CET__ macro definitions. They are implied by the 4267 // -fcf-protection option that is generated elsewhere. 4268 if (M.first == "__CET__=1" && !M.second && 4269 !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch) 4270 continue; 4271 if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn && 4272 !CodeGenOpts.CFProtectionBranch) 4273 continue; 4274 if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn && 4275 CodeGenOpts.CFProtectionBranch) 4276 continue; 4277 4278 GenerateArg(Consumer, M.second ? OPT_U : OPT_D, M.first); 4279 } 4280 4281 for (const auto &I : Opts.Includes) { 4282 // Don't generate OpenCL includes. They are implied by other flags that are 4283 // generated elsewhere. 4284 if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader && 4285 ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") || 4286 I == "opencl-c.h")) 4287 continue; 4288 // Don't generate HLSL includes. They are implied by other flags that are 4289 // generated elsewhere. 4290 if (LangOpts.HLSL && I == "hlsl.h") 4291 continue; 4292 4293 GenerateArg(Consumer, OPT_include, I); 4294 } 4295 4296 for (const auto &CI : Opts.ChainedIncludes) 4297 GenerateArg(Consumer, OPT_chain_include, CI); 4298 4299 for (const auto &RF : Opts.RemappedFiles) 4300 GenerateArg(Consumer, OPT_remap_file, RF.first + ";" + RF.second); 4301 4302 if (Opts.SourceDateEpoch) 4303 GenerateArg(Consumer, OPT_source_date_epoch, Twine(*Opts.SourceDateEpoch)); 4304 4305 // Don't handle LexEditorPlaceholders. It is implied by the action that is 4306 // generated elsewhere. 4307 } 4308 4309 static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, 4310 DiagnosticsEngine &Diags, 4311 frontend::ActionKind Action, 4312 const FrontendOptions &FrontendOpts) { 4313 unsigned NumErrorsBefore = Diags.getNumErrors(); 4314 4315 PreprocessorOptions *PreprocessorOpts = &Opts; 4316 4317 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \ 4318 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 4319 #include "clang/Driver/Options.inc" 4320 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING 4321 4322 Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) || 4323 Args.hasArg(OPT_pch_through_hdrstop_use); 4324 4325 for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl)) 4326 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue()); 4327 4328 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) { 4329 StringRef Value(A->getValue()); 4330 size_t Comma = Value.find(','); 4331 unsigned Bytes = 0; 4332 unsigned EndOfLine = 0; 4333 4334 if (Comma == StringRef::npos || 4335 Value.substr(0, Comma).getAsInteger(10, Bytes) || 4336 Value.substr(Comma + 1).getAsInteger(10, EndOfLine)) 4337 Diags.Report(diag::err_drv_preamble_format); 4338 else { 4339 Opts.PrecompiledPreambleBytes.first = Bytes; 4340 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0); 4341 } 4342 } 4343 4344 // Add the __CET__ macro if a CFProtection option is set. 4345 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 4346 StringRef Name = A->getValue(); 4347 if (Name == "branch") 4348 Opts.addMacroDef("__CET__=1"); 4349 else if (Name == "return") 4350 Opts.addMacroDef("__CET__=2"); 4351 else if (Name == "full") 4352 Opts.addMacroDef("__CET__=3"); 4353 } 4354 4355 // Add macros from the command line. 4356 for (const auto *A : Args.filtered(OPT_D, OPT_U)) { 4357 if (A->getOption().matches(OPT_D)) 4358 Opts.addMacroDef(A->getValue()); 4359 else 4360 Opts.addMacroUndef(A->getValue()); 4361 } 4362 4363 // Add the ordered list of -includes. 4364 for (const auto *A : Args.filtered(OPT_include)) 4365 Opts.Includes.emplace_back(A->getValue()); 4366 4367 for (const auto *A : Args.filtered(OPT_chain_include)) 4368 Opts.ChainedIncludes.emplace_back(A->getValue()); 4369 4370 for (const auto *A : Args.filtered(OPT_remap_file)) { 4371 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';'); 4372 4373 if (Split.second.empty()) { 4374 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args); 4375 continue; 4376 } 4377 4378 Opts.addRemappedFile(Split.first, Split.second); 4379 } 4380 4381 if (const Arg *A = Args.getLastArg(OPT_source_date_epoch)) { 4382 StringRef Epoch = A->getValue(); 4383 // SOURCE_DATE_EPOCH, if specified, must be a non-negative decimal integer. 4384 // On time64 systems, pick 253402300799 (the UNIX timestamp of 4385 // 9999-12-31T23:59:59Z) as the upper bound. 4386 const uint64_t MaxTimestamp = 4387 std::min<uint64_t>(std::numeric_limits<time_t>::max(), 253402300799); 4388 uint64_t V; 4389 if (Epoch.getAsInteger(10, V) || V > MaxTimestamp) { 4390 Diags.Report(diag::err_fe_invalid_source_date_epoch) 4391 << Epoch << MaxTimestamp; 4392 } else { 4393 Opts.SourceDateEpoch = V; 4394 } 4395 } 4396 4397 // Always avoid lexing editor placeholders when we're just running the 4398 // preprocessor as we never want to emit the 4399 // "editor placeholder in source file" error in PP only mode. 4400 if (isStrictlyPreprocessorAction(Action)) 4401 Opts.LexEditorPlaceholders = false; 4402 4403 return Diags.getNumErrors() == NumErrorsBefore; 4404 } 4405 4406 static void 4407 GeneratePreprocessorOutputArgs(const PreprocessorOutputOptions &Opts, 4408 ArgumentConsumer Consumer, 4409 frontend::ActionKind Action) { 4410 const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts; 4411 4412 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \ 4413 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 4414 #include "clang/Driver/Options.inc" 4415 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING 4416 4417 bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP; 4418 if (Generate_dM) 4419 GenerateArg(Consumer, OPT_dM); 4420 if (!Generate_dM && Opts.ShowMacros) 4421 GenerateArg(Consumer, OPT_dD); 4422 if (Opts.DirectivesOnly) 4423 GenerateArg(Consumer, OPT_fdirectives_only); 4424 } 4425 4426 static bool ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts, 4427 ArgList &Args, DiagnosticsEngine &Diags, 4428 frontend::ActionKind Action) { 4429 unsigned NumErrorsBefore = Diags.getNumErrors(); 4430 4431 PreprocessorOutputOptions &PreprocessorOutputOpts = Opts; 4432 4433 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \ 4434 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 4435 #include "clang/Driver/Options.inc" 4436 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING 4437 4438 Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM); 4439 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD); 4440 Opts.DirectivesOnly = Args.hasArg(OPT_fdirectives_only); 4441 4442 return Diags.getNumErrors() == NumErrorsBefore; 4443 } 4444 4445 static void GenerateTargetArgs(const TargetOptions &Opts, 4446 ArgumentConsumer Consumer) { 4447 const TargetOptions *TargetOpts = &Opts; 4448 #define TARGET_OPTION_WITH_MARSHALLING(...) \ 4449 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 4450 #include "clang/Driver/Options.inc" 4451 #undef TARGET_OPTION_WITH_MARSHALLING 4452 4453 if (!Opts.SDKVersion.empty()) 4454 GenerateArg(Consumer, OPT_target_sdk_version_EQ, 4455 Opts.SDKVersion.getAsString()); 4456 if (!Opts.DarwinTargetVariantSDKVersion.empty()) 4457 GenerateArg(Consumer, OPT_darwin_target_variant_sdk_version_EQ, 4458 Opts.DarwinTargetVariantSDKVersion.getAsString()); 4459 } 4460 4461 static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args, 4462 DiagnosticsEngine &Diags) { 4463 unsigned NumErrorsBefore = Diags.getNumErrors(); 4464 4465 TargetOptions *TargetOpts = &Opts; 4466 4467 #define TARGET_OPTION_WITH_MARSHALLING(...) \ 4468 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 4469 #include "clang/Driver/Options.inc" 4470 #undef TARGET_OPTION_WITH_MARSHALLING 4471 4472 if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) { 4473 llvm::VersionTuple Version; 4474 if (Version.tryParse(A->getValue())) 4475 Diags.Report(diag::err_drv_invalid_value) 4476 << A->getAsString(Args) << A->getValue(); 4477 else 4478 Opts.SDKVersion = Version; 4479 } 4480 if (Arg *A = 4481 Args.getLastArg(options::OPT_darwin_target_variant_sdk_version_EQ)) { 4482 llvm::VersionTuple Version; 4483 if (Version.tryParse(A->getValue())) 4484 Diags.Report(diag::err_drv_invalid_value) 4485 << A->getAsString(Args) << A->getValue(); 4486 else 4487 Opts.DarwinTargetVariantSDKVersion = Version; 4488 } 4489 4490 return Diags.getNumErrors() == NumErrorsBefore; 4491 } 4492 4493 bool CompilerInvocation::CreateFromArgsImpl( 4494 CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs, 4495 DiagnosticsEngine &Diags, const char *Argv0) { 4496 unsigned NumErrorsBefore = Diags.getNumErrors(); 4497 4498 // Parse the arguments. 4499 const OptTable &Opts = getDriverOptTable(); 4500 llvm::opt::Visibility VisibilityMask(options::CC1Option); 4501 unsigned MissingArgIndex, MissingArgCount; 4502 InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex, 4503 MissingArgCount, VisibilityMask); 4504 LangOptions &LangOpts = Res.getLangOpts(); 4505 4506 // Check for missing argument error. 4507 if (MissingArgCount) 4508 Diags.Report(diag::err_drv_missing_argument) 4509 << Args.getArgString(MissingArgIndex) << MissingArgCount; 4510 4511 // Issue errors on unknown arguments. 4512 for (const auto *A : Args.filtered(OPT_UNKNOWN)) { 4513 auto ArgString = A->getAsString(Args); 4514 std::string Nearest; 4515 if (Opts.findNearest(ArgString, Nearest, VisibilityMask) > 1) 4516 Diags.Report(diag::err_drv_unknown_argument) << ArgString; 4517 else 4518 Diags.Report(diag::err_drv_unknown_argument_with_suggestion) 4519 << ArgString << Nearest; 4520 } 4521 4522 ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags); 4523 ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags); 4524 ParseAnalyzerArgs(Res.getAnalyzerOpts(), Args, Diags); 4525 ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags, 4526 /*DefaultDiagColor=*/false); 4527 ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, LangOpts.IsHeaderFile); 4528 // FIXME: We shouldn't have to pass the DashX option around here 4529 InputKind DashX = Res.getFrontendOpts().DashX; 4530 ParseTargetArgs(Res.getTargetOpts(), Args, Diags); 4531 llvm::Triple T(Res.getTargetOpts().Triple); 4532 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags, 4533 Res.getFileSystemOpts().WorkingDir); 4534 4535 ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes, 4536 Diags); 4537 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC) 4538 LangOpts.ObjCExceptions = 1; 4539 4540 for (auto Warning : Res.getDiagnosticOpts().Warnings) { 4541 if (Warning == "misexpect" && 4542 !Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation())) { 4543 Res.getCodeGenOpts().MisExpect = true; 4544 } 4545 } 4546 4547 if (LangOpts.CUDA) { 4548 // During CUDA device-side compilation, the aux triple is the 4549 // triple used for host compilation. 4550 if (LangOpts.CUDAIsDevice) 4551 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; 4552 } 4553 4554 // Set the triple of the host for OpenMP device compile. 4555 if (LangOpts.OpenMPIsTargetDevice) 4556 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; 4557 4558 ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T, 4559 Res.getFrontendOpts().OutputFile, LangOpts); 4560 4561 // FIXME: Override value name discarding when asan or msan is used because the 4562 // backend passes depend on the name of the alloca in order to print out 4563 // names. 4564 Res.getCodeGenOpts().DiscardValueNames &= 4565 !LangOpts.Sanitize.has(SanitizerKind::Address) && 4566 !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) && 4567 !LangOpts.Sanitize.has(SanitizerKind::Memory) && 4568 !LangOpts.Sanitize.has(SanitizerKind::KernelMemory); 4569 4570 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags, 4571 Res.getFrontendOpts().ProgramAction, 4572 Res.getFrontendOpts()); 4573 ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, Diags, 4574 Res.getFrontendOpts().ProgramAction); 4575 4576 ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args, Diags, 4577 Res.getFrontendOpts().ProgramAction, 4578 Res.getPreprocessorOutputOpts().ShowLineMarkers); 4579 if (!Res.getDependencyOutputOpts().OutputFile.empty() && 4580 Res.getDependencyOutputOpts().Targets.empty()) 4581 Diags.Report(diag::err_fe_dependency_file_requires_MT); 4582 4583 // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses. 4584 if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses && 4585 !Res.getLangOpts().Sanitize.empty()) { 4586 Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false; 4587 Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored); 4588 } 4589 4590 // Store the command-line for using in the CodeView backend. 4591 if (Res.getCodeGenOpts().CodeViewCommandLine) { 4592 Res.getCodeGenOpts().Argv0 = Argv0; 4593 append_range(Res.getCodeGenOpts().CommandLineArgs, CommandLineArgs); 4594 } 4595 4596 // Set PGOOptions. Need to create a temporary VFS to read the profile 4597 // to determine the PGO type. 4598 if (!Res.getCodeGenOpts().ProfileInstrumentUsePath.empty()) { 4599 auto FS = 4600 createVFSFromOverlayFiles(Res.getHeaderSearchOpts().VFSOverlayFiles, 4601 Diags, llvm::vfs::getRealFileSystem()); 4602 setPGOUseInstrumentor(Res.getCodeGenOpts(), 4603 Res.getCodeGenOpts().ProfileInstrumentUsePath, *FS, 4604 Diags); 4605 } 4606 4607 FixupInvocation(Res, Diags, Args, DashX); 4608 4609 return Diags.getNumErrors() == NumErrorsBefore; 4610 } 4611 4612 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Invocation, 4613 ArrayRef<const char *> CommandLineArgs, 4614 DiagnosticsEngine &Diags, 4615 const char *Argv0) { 4616 CompilerInvocation DummyInvocation; 4617 4618 return RoundTrip( 4619 [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs, 4620 DiagnosticsEngine &Diags, const char *Argv0) { 4621 return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0); 4622 }, 4623 [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args, 4624 StringAllocator SA) { 4625 Args.push_back("-cc1"); 4626 Invocation.generateCC1CommandLine(Args, SA); 4627 }, 4628 Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0); 4629 } 4630 4631 std::string CompilerInvocation::getModuleHash() const { 4632 // FIXME: Consider using SHA1 instead of MD5. 4633 llvm::HashBuilder<llvm::MD5, llvm::support::endianness::native> HBuilder; 4634 4635 // Note: For QoI reasons, the things we use as a hash here should all be 4636 // dumped via the -module-info flag. 4637 4638 // Start the signature with the compiler version. 4639 HBuilder.add(getClangFullRepositoryVersion()); 4640 4641 // Also include the serialization version, in case LLVM_APPEND_VC_REV is off 4642 // and getClangFullRepositoryVersion() doesn't include git revision. 4643 HBuilder.add(serialization::VERSION_MAJOR, serialization::VERSION_MINOR); 4644 4645 // Extend the signature with the language options 4646 #define LANGOPT(Name, Bits, Default, Description) HBuilder.add(LangOpts->Name); 4647 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 4648 HBuilder.add(static_cast<unsigned>(LangOpts->get##Name())); 4649 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 4650 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 4651 #include "clang/Basic/LangOptions.def" 4652 4653 HBuilder.addRange(getLangOpts().ModuleFeatures); 4654 4655 HBuilder.add(getLangOpts().ObjCRuntime); 4656 HBuilder.addRange(getLangOpts().CommentOpts.BlockCommandNames); 4657 4658 // Extend the signature with the target options. 4659 HBuilder.add(getTargetOpts().Triple, getTargetOpts().CPU, 4660 getTargetOpts().TuneCPU, getTargetOpts().ABI); 4661 HBuilder.addRange(getTargetOpts().FeaturesAsWritten); 4662 4663 // Extend the signature with preprocessor options. 4664 const PreprocessorOptions &ppOpts = getPreprocessorOpts(); 4665 HBuilder.add(ppOpts.UsePredefines, ppOpts.DetailedRecord); 4666 4667 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts(); 4668 for (const auto &Macro : getPreprocessorOpts().Macros) { 4669 // If we're supposed to ignore this macro for the purposes of modules, 4670 // don't put it into the hash. 4671 if (!hsOpts.ModulesIgnoreMacros.empty()) { 4672 // Check whether we're ignoring this macro. 4673 StringRef MacroDef = Macro.first; 4674 if (hsOpts.ModulesIgnoreMacros.count( 4675 llvm::CachedHashString(MacroDef.split('=').first))) 4676 continue; 4677 } 4678 4679 HBuilder.add(Macro); 4680 } 4681 4682 // Extend the signature with the sysroot and other header search options. 4683 HBuilder.add(hsOpts.Sysroot, hsOpts.ModuleFormat, hsOpts.UseDebugInfo, 4684 hsOpts.UseBuiltinIncludes, hsOpts.UseStandardSystemIncludes, 4685 hsOpts.UseStandardCXXIncludes, hsOpts.UseLibcxx, 4686 hsOpts.ModulesValidateDiagnosticOptions); 4687 HBuilder.add(hsOpts.ResourceDir); 4688 4689 if (hsOpts.ModulesStrictContextHash) { 4690 HBuilder.addRange(hsOpts.SystemHeaderPrefixes); 4691 HBuilder.addRange(hsOpts.UserEntries); 4692 4693 const DiagnosticOptions &diagOpts = getDiagnosticOpts(); 4694 #define DIAGOPT(Name, Bits, Default) HBuilder.add(diagOpts.Name); 4695 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 4696 HBuilder.add(diagOpts.get##Name()); 4697 #include "clang/Basic/DiagnosticOptions.def" 4698 #undef DIAGOPT 4699 #undef ENUM_DIAGOPT 4700 } 4701 4702 // Extend the signature with the user build path. 4703 HBuilder.add(hsOpts.ModuleUserBuildPath); 4704 4705 // Extend the signature with the module file extensions. 4706 for (const auto &ext : getFrontendOpts().ModuleFileExtensions) 4707 ext->hashExtension(HBuilder); 4708 4709 // When compiling with -gmodules, also hash -fdebug-prefix-map as it 4710 // affects the debug info in the PCM. 4711 if (getCodeGenOpts().DebugTypeExtRefs) 4712 HBuilder.addRange(getCodeGenOpts().DebugPrefixMap); 4713 4714 // Extend the signature with the enabled sanitizers, if at least one is 4715 // enabled. Sanitizers which cannot affect AST generation aren't hashed. 4716 SanitizerSet SanHash = getLangOpts().Sanitize; 4717 SanHash.clear(getPPTransparentSanitizers()); 4718 if (!SanHash.empty()) 4719 HBuilder.add(SanHash.Mask); 4720 4721 llvm::MD5::MD5Result Result; 4722 HBuilder.getHasher().final(Result); 4723 uint64_t Hash = Result.high() ^ Result.low(); 4724 return toString(llvm::APInt(64, Hash), 36, /*Signed=*/false); 4725 } 4726 4727 void CompilerInvocationBase::generateCC1CommandLine( 4728 ArgumentConsumer Consumer) const { 4729 llvm::Triple T(getTargetOpts().Triple); 4730 4731 GenerateFileSystemArgs(getFileSystemOpts(), Consumer); 4732 GenerateMigratorArgs(getMigratorOpts(), Consumer); 4733 GenerateAnalyzerArgs(getAnalyzerOpts(), Consumer); 4734 GenerateDiagnosticArgs(getDiagnosticOpts(), Consumer, 4735 /*DefaultDiagColor=*/false); 4736 GenerateFrontendArgs(getFrontendOpts(), Consumer, getLangOpts().IsHeaderFile); 4737 GenerateTargetArgs(getTargetOpts(), Consumer); 4738 GenerateHeaderSearchArgs(getHeaderSearchOpts(), Consumer); 4739 GenerateLangArgs(getLangOpts(), Consumer, T, getFrontendOpts().DashX); 4740 GenerateCodeGenArgs(getCodeGenOpts(), Consumer, T, 4741 getFrontendOpts().OutputFile, &getLangOpts()); 4742 GeneratePreprocessorArgs(getPreprocessorOpts(), Consumer, getLangOpts(), 4743 getFrontendOpts(), getCodeGenOpts()); 4744 GeneratePreprocessorOutputArgs(getPreprocessorOutputOpts(), Consumer, 4745 getFrontendOpts().ProgramAction); 4746 GenerateDependencyOutputArgs(getDependencyOutputOpts(), Consumer); 4747 } 4748 4749 std::vector<std::string> CompilerInvocationBase::getCC1CommandLine() const { 4750 std::vector<std::string> Args{"-cc1"}; 4751 generateCC1CommandLine( 4752 [&Args](const Twine &Arg) { Args.push_back(Arg.str()); }); 4753 return Args; 4754 } 4755 4756 void CompilerInvocation::resetNonModularOptions() { 4757 getLangOpts().resetNonModularOptions(); 4758 getPreprocessorOpts().resetNonModularOptions(); 4759 } 4760 4761 void CompilerInvocation::clearImplicitModuleBuildOptions() { 4762 getLangOpts().ImplicitModules = false; 4763 getHeaderSearchOpts().ImplicitModuleMaps = false; 4764 getHeaderSearchOpts().ModuleCachePath.clear(); 4765 getHeaderSearchOpts().ModulesValidateOncePerBuildSession = false; 4766 getHeaderSearchOpts().BuildSessionTimestamp = 0; 4767 // The specific values we canonicalize to for pruning don't affect behaviour, 4768 /// so use the default values so they may be dropped from the command-line. 4769 getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60; 4770 getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60; 4771 } 4772 4773 IntrusiveRefCntPtr<llvm::vfs::FileSystem> 4774 clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI, 4775 DiagnosticsEngine &Diags) { 4776 return createVFSFromCompilerInvocation(CI, Diags, 4777 llvm::vfs::getRealFileSystem()); 4778 } 4779 4780 IntrusiveRefCntPtr<llvm::vfs::FileSystem> 4781 clang::createVFSFromCompilerInvocation( 4782 const CompilerInvocation &CI, DiagnosticsEngine &Diags, 4783 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) { 4784 return createVFSFromOverlayFiles(CI.getHeaderSearchOpts().VFSOverlayFiles, 4785 Diags, std::move(BaseFS)); 4786 } 4787 4788 IntrusiveRefCntPtr<llvm::vfs::FileSystem> clang::createVFSFromOverlayFiles( 4789 ArrayRef<std::string> VFSOverlayFiles, DiagnosticsEngine &Diags, 4790 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) { 4791 if (VFSOverlayFiles.empty()) 4792 return BaseFS; 4793 4794 IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS; 4795 // earlier vfs files are on the bottom 4796 for (const auto &File : VFSOverlayFiles) { 4797 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer = 4798 Result->getBufferForFile(File); 4799 if (!Buffer) { 4800 Diags.Report(diag::err_missing_vfs_overlay_file) << File; 4801 continue; 4802 } 4803 4804 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML( 4805 std::move(Buffer.get()), /*DiagHandler*/ nullptr, File, 4806 /*DiagContext*/ nullptr, Result); 4807 if (!FS) { 4808 Diags.Report(diag::err_invalid_vfs_overlay) << File; 4809 continue; 4810 } 4811 4812 Result = FS; 4813 } 4814 return Result; 4815 } 4816