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