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