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