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