1 //===- FrontendOptions.h ----------------------------------------*- C++ -*-===// 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 #ifndef LLVM_CLANG_FRONTEND_FRONTENDOPTIONS_H 10 #define LLVM_CLANG_FRONTEND_FRONTENDOPTIONS_H 11 12 #include "clang/AST/ASTDumperUtils.h" 13 #include "clang/Basic/LangStandard.h" 14 #include "clang/Frontend/CommandLineSourceLoc.h" 15 #include "clang/Sema/CodeCompleteOptions.h" 16 #include "clang/Serialization/ModuleFileExtension.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/Support/Compiler.h" 19 #include "llvm/Support/MemoryBuffer.h" 20 #include <cassert> 21 #include <map> 22 #include <memory> 23 #include <optional> 24 #include <string> 25 #include <vector> 26 27 namespace llvm { 28 29 class MemoryBuffer; 30 31 } // namespace llvm 32 33 namespace clang { 34 35 namespace frontend { 36 37 enum ActionKind { 38 /// Parse ASTs and list Decl nodes. 39 ASTDeclList, 40 41 /// Parse ASTs and dump them. 42 ASTDump, 43 44 /// Parse ASTs and print them. 45 ASTPrint, 46 47 /// Parse ASTs and view them in Graphviz. 48 ASTView, 49 50 /// Dump the compiler configuration. 51 DumpCompilerOptions, 52 53 /// Dump out raw tokens. 54 DumpRawTokens, 55 56 /// Dump out preprocessed tokens. 57 DumpTokens, 58 59 /// Emit a .s file. 60 EmitAssembly, 61 62 /// Emit a .bc file. 63 EmitBC, 64 65 /// Translate input source into HTML. 66 EmitHTML, 67 68 /// Emit a .cir file 69 EmitCIR, 70 71 /// Emit a .ll file. 72 EmitLLVM, 73 74 /// Generate LLVM IR, but do not emit anything. 75 EmitLLVMOnly, 76 77 /// Generate machine code, but don't emit anything. 78 EmitCodeGenOnly, 79 80 /// Emit a .o file. 81 EmitObj, 82 83 // Extract API information 84 ExtractAPI, 85 86 /// Parse and apply any fixits to the source. 87 FixIt, 88 89 /// Generate pre-compiled module from a module map. 90 GenerateModule, 91 92 /// Generate pre-compiled module from a standard C++ module interface unit. 93 GenerateModuleInterface, 94 95 /// Generate reduced module interface for a standard C++ module interface 96 /// unit. 97 GenerateReducedModuleInterface, 98 99 /// Generate a C++20 header unit module from a header file. 100 GenerateHeaderUnit, 101 102 /// Generate pre-compiled header. 103 GeneratePCH, 104 105 /// Generate Interface Stub Files. 106 GenerateInterfaceStubs, 107 108 /// Only execute frontend initialization. 109 InitOnly, 110 111 /// Dump information about a module file. 112 ModuleFileInfo, 113 114 /// Load and verify that a PCH file is usable. 115 VerifyPCH, 116 117 /// Parse and perform semantic analysis. 118 ParseSyntaxOnly, 119 120 /// Run a plugin action, \see ActionName. 121 PluginAction, 122 123 /// Print the "preamble" of the input file 124 PrintPreamble, 125 126 /// -E mode. 127 PrintPreprocessedInput, 128 129 /// Expand macros but not \#includes. 130 RewriteMacros, 131 132 /// ObjC->C Rewriter. 133 RewriteObjC, 134 135 /// Rewriter playground 136 RewriteTest, 137 138 /// Run one or more source code analyses. 139 RunAnalysis, 140 141 /// Dump template instantiations 142 TemplightDump, 143 144 /// Run migrator. 145 MigrateSource, 146 147 /// Just lex, no output. 148 RunPreprocessorOnly, 149 150 /// Print the output of the dependency directives source minimizer. 151 PrintDependencyDirectivesSourceMinimizerOutput 152 }; 153 154 } // namespace frontend 155 156 /// The kind of a file that we've been handed as an input. 157 class InputKind { 158 public: 159 /// The input file format. 160 enum Format { 161 Source, 162 ModuleMap, 163 Precompiled 164 }; 165 166 // If we are building a header unit, what kind it is; this affects whether 167 // we look for the file in the user or system include search paths before 168 // flagging a missing input. 169 enum HeaderUnitKind { 170 HeaderUnit_None, 171 HeaderUnit_User, 172 HeaderUnit_System, 173 HeaderUnit_Abs 174 }; 175 176 private: 177 Language Lang; 178 LLVM_PREFERRED_TYPE(Format) 179 unsigned Fmt : 3; 180 LLVM_PREFERRED_TYPE(bool) 181 unsigned Preprocessed : 1; 182 LLVM_PREFERRED_TYPE(HeaderUnitKind) 183 unsigned HeaderUnit : 3; 184 LLVM_PREFERRED_TYPE(bool) 185 unsigned IsHeader : 1; 186 187 public: 188 constexpr InputKind(Language L = Language::Unknown, Format F = Source, 189 bool PP = false, HeaderUnitKind HU = HeaderUnit_None, 190 bool HD = false) Lang(L)191 : Lang(L), Fmt(F), Preprocessed(PP), HeaderUnit(HU), IsHeader(HD) {} 192 getLanguage()193 Language getLanguage() const { return static_cast<Language>(Lang); } getFormat()194 Format getFormat() const { return static_cast<Format>(Fmt); } getHeaderUnitKind()195 HeaderUnitKind getHeaderUnitKind() const { 196 return static_cast<HeaderUnitKind>(HeaderUnit); 197 } isPreprocessed()198 bool isPreprocessed() const { return Preprocessed; } isHeader()199 bool isHeader() const { return IsHeader; } isHeaderUnit()200 bool isHeaderUnit() const { return HeaderUnit != HeaderUnit_None; } 201 202 /// Is the input kind fully-unknown? isUnknown()203 bool isUnknown() const { return Lang == Language::Unknown && Fmt == Source; } 204 205 /// Is the language of the input some dialect of Objective-C? isObjectiveC()206 bool isObjectiveC() const { 207 return Lang == Language::ObjC || Lang == Language::ObjCXX; 208 } 209 getPreprocessed()210 InputKind getPreprocessed() const { 211 return InputKind(getLanguage(), getFormat(), true, getHeaderUnitKind(), 212 isHeader()); 213 } 214 getHeader()215 InputKind getHeader() const { 216 return InputKind(getLanguage(), getFormat(), isPreprocessed(), 217 getHeaderUnitKind(), true); 218 } 219 withHeaderUnit(HeaderUnitKind HU)220 InputKind withHeaderUnit(HeaderUnitKind HU) const { 221 return InputKind(getLanguage(), getFormat(), isPreprocessed(), HU, 222 isHeader()); 223 } 224 withFormat(Format F)225 InputKind withFormat(Format F) const { 226 return InputKind(getLanguage(), F, isPreprocessed(), getHeaderUnitKind(), 227 isHeader()); 228 } 229 }; 230 231 /// An input file for the front end. 232 class FrontendInputFile { 233 /// The file name, or "-" to read from standard input. 234 std::string File; 235 236 /// The input, if it comes from a buffer rather than a file. This object 237 /// does not own the buffer, and the caller is responsible for ensuring 238 /// that it outlives any users. 239 std::optional<llvm::MemoryBufferRef> Buffer; 240 241 /// The kind of input, e.g., C source, AST file, LLVM IR. 242 InputKind Kind; 243 244 /// Whether we're dealing with a 'system' input (vs. a 'user' input). 245 bool IsSystem = false; 246 247 public: 248 FrontendInputFile() = default; 249 FrontendInputFile(StringRef File, InputKind Kind, bool IsSystem = false) 250 : File(File.str()), Kind(Kind), IsSystem(IsSystem) {} 251 FrontendInputFile(llvm::MemoryBufferRef Buffer, InputKind Kind, 252 bool IsSystem = false) Buffer(Buffer)253 : Buffer(Buffer), Kind(Kind), IsSystem(IsSystem) {} 254 getKind()255 InputKind getKind() const { return Kind; } isSystem()256 bool isSystem() const { return IsSystem; } 257 isEmpty()258 bool isEmpty() const { return File.empty() && Buffer == std::nullopt; } isFile()259 bool isFile() const { return !isBuffer(); } isBuffer()260 bool isBuffer() const { return Buffer != std::nullopt; } isPreprocessed()261 bool isPreprocessed() const { return Kind.isPreprocessed(); } isHeader()262 bool isHeader() const { return Kind.isHeader(); } getHeaderUnitKind()263 InputKind::HeaderUnitKind getHeaderUnitKind() const { 264 return Kind.getHeaderUnitKind(); 265 } 266 getFile()267 StringRef getFile() const { 268 assert(isFile()); 269 return File; 270 } 271 getBuffer()272 llvm::MemoryBufferRef getBuffer() const { 273 assert(isBuffer()); 274 return *Buffer; 275 } 276 }; 277 278 /// FrontendOptions - Options for controlling the behavior of the frontend. 279 class FrontendOptions { 280 public: 281 /// Disable memory freeing on exit. 282 LLVM_PREFERRED_TYPE(bool) 283 unsigned DisableFree : 1; 284 285 /// When generating PCH files, instruct the AST writer to create relocatable 286 /// PCH files. 287 LLVM_PREFERRED_TYPE(bool) 288 unsigned RelocatablePCH : 1; 289 290 /// Show the -help text. 291 LLVM_PREFERRED_TYPE(bool) 292 unsigned ShowHelp : 1; 293 294 /// Show frontend performance metrics and statistics. 295 LLVM_PREFERRED_TYPE(bool) 296 unsigned ShowStats : 1; 297 298 LLVM_PREFERRED_TYPE(bool) 299 unsigned AppendStats : 1; 300 301 /// print the supported cpus for the current target 302 LLVM_PREFERRED_TYPE(bool) 303 unsigned PrintSupportedCPUs : 1; 304 305 /// Print the supported extensions for the current target. 306 LLVM_PREFERRED_TYPE(bool) 307 unsigned PrintSupportedExtensions : 1; 308 309 /// Print the extensions enabled for the current target. 310 LLVM_PREFERRED_TYPE(bool) 311 unsigned PrintEnabledExtensions : 1; 312 313 /// Show the -version text. 314 LLVM_PREFERRED_TYPE(bool) 315 unsigned ShowVersion : 1; 316 317 /// Apply fixes even if there are unfixable errors. 318 LLVM_PREFERRED_TYPE(bool) 319 unsigned FixWhatYouCan : 1; 320 321 /// Apply fixes only for warnings. 322 LLVM_PREFERRED_TYPE(bool) 323 unsigned FixOnlyWarnings : 1; 324 325 /// Apply fixes and recompile. 326 LLVM_PREFERRED_TYPE(bool) 327 unsigned FixAndRecompile : 1; 328 329 /// Apply fixes to temporary files. 330 LLVM_PREFERRED_TYPE(bool) 331 unsigned FixToTemporaries : 1; 332 333 /// Emit ARC errors even if the migrator can fix them. 334 LLVM_PREFERRED_TYPE(bool) 335 unsigned ARCMTMigrateEmitARCErrors : 1; 336 337 /// Skip over function bodies to speed up parsing in cases you do not need 338 /// them (e.g. with code completion). 339 LLVM_PREFERRED_TYPE(bool) 340 unsigned SkipFunctionBodies : 1; 341 342 /// Whether we can use the global module index if available. 343 LLVM_PREFERRED_TYPE(bool) 344 unsigned UseGlobalModuleIndex : 1; 345 346 /// Whether we can generate the global module index if needed. 347 LLVM_PREFERRED_TYPE(bool) 348 unsigned GenerateGlobalModuleIndex : 1; 349 350 /// Whether we include declaration dumps in AST dumps. 351 LLVM_PREFERRED_TYPE(bool) 352 unsigned ASTDumpDecls : 1; 353 354 /// Whether we deserialize all decls when forming AST dumps. 355 LLVM_PREFERRED_TYPE(bool) 356 unsigned ASTDumpAll : 1; 357 358 /// Whether we include lookup table dumps in AST dumps. 359 LLVM_PREFERRED_TYPE(bool) 360 unsigned ASTDumpLookups : 1; 361 362 /// Whether we include declaration type dumps in AST dumps. 363 LLVM_PREFERRED_TYPE(bool) 364 unsigned ASTDumpDeclTypes : 1; 365 366 /// Whether we are performing an implicit module build. 367 LLVM_PREFERRED_TYPE(bool) 368 unsigned BuildingImplicitModule : 1; 369 370 /// Whether to use a filesystem lock when building implicit modules. 371 LLVM_PREFERRED_TYPE(bool) 372 unsigned BuildingImplicitModuleUsesLock : 1; 373 374 /// Whether we should embed all used files into the PCM file. 375 LLVM_PREFERRED_TYPE(bool) 376 unsigned ModulesEmbedAllFiles : 1; 377 378 /// Whether timestamps should be written to the produced PCH file. 379 LLVM_PREFERRED_TYPE(bool) 380 unsigned IncludeTimestamps : 1; 381 382 /// Should a temporary file be used during compilation. 383 LLVM_PREFERRED_TYPE(bool) 384 unsigned UseTemporary : 1; 385 386 /// When using -emit-module, treat the modulemap as a system module. 387 LLVM_PREFERRED_TYPE(bool) 388 unsigned IsSystemModule : 1; 389 390 /// Output (and read) PCM files regardless of compiler errors. 391 LLVM_PREFERRED_TYPE(bool) 392 unsigned AllowPCMWithCompilerErrors : 1; 393 394 /// Whether to share the FileManager when building modules. 395 LLVM_PREFERRED_TYPE(bool) 396 unsigned ModulesShareFileManager : 1; 397 398 /// Whether to emit symbol graph files as a side effect of compilation. 399 LLVM_PREFERRED_TYPE(bool) 400 unsigned EmitSymbolGraph : 1; 401 402 /// Whether to emit additional symbol graphs for extended modules. 403 LLVM_PREFERRED_TYPE(bool) 404 unsigned EmitExtensionSymbolGraphs : 1; 405 406 /// Whether to emit symbol labels for testing in generated symbol graphs 407 LLVM_PREFERRED_TYPE(bool) 408 unsigned EmitSymbolGraphSymbolLabelsForTesting : 1; 409 410 /// Whether to emit symbol labels for testing in generated symbol graphs 411 LLVM_PREFERRED_TYPE(bool) 412 unsigned EmitPrettySymbolGraphs : 1; 413 414 /// Whether to generate reduced BMI for C++20 named modules. 415 LLVM_PREFERRED_TYPE(bool) 416 unsigned GenReducedBMI : 1; 417 418 /// Use Clang IR pipeline to emit code 419 LLVM_PREFERRED_TYPE(bool) 420 unsigned UseClangIRPipeline : 1; 421 422 CodeCompleteOptions CodeCompleteOpts; 423 424 /// Specifies the output format of the AST. 425 ASTDumpOutputFormat ASTDumpFormat = ADOF_Default; 426 427 enum { 428 ARCMT_None, 429 ARCMT_Check, 430 ARCMT_Modify, 431 ARCMT_Migrate 432 } ARCMTAction = ARCMT_None; 433 434 enum { 435 ObjCMT_None = 0, 436 437 /// Enable migration to modern ObjC literals. 438 ObjCMT_Literals = 0x1, 439 440 /// Enable migration to modern ObjC subscripting. 441 ObjCMT_Subscripting = 0x2, 442 443 /// Enable migration to modern ObjC readonly property. 444 ObjCMT_ReadonlyProperty = 0x4, 445 446 /// Enable migration to modern ObjC readwrite property. 447 ObjCMT_ReadwriteProperty = 0x8, 448 449 /// Enable migration to modern ObjC property. 450 ObjCMT_Property = (ObjCMT_ReadonlyProperty | ObjCMT_ReadwriteProperty), 451 452 /// Enable annotation of ObjCMethods of all kinds. 453 ObjCMT_Annotation = 0x10, 454 455 /// Enable migration of ObjC methods to 'instancetype'. 456 ObjCMT_Instancetype = 0x20, 457 458 /// Enable migration to NS_ENUM/NS_OPTIONS macros. 459 ObjCMT_NsMacros = 0x40, 460 461 /// Enable migration to add conforming protocols. 462 ObjCMT_ProtocolConformance = 0x80, 463 464 /// prefer 'atomic' property over 'nonatomic'. 465 ObjCMT_AtomicProperty = 0x100, 466 467 /// annotate property with NS_RETURNS_INNER_POINTER 468 ObjCMT_ReturnsInnerPointerProperty = 0x200, 469 470 /// use NS_NONATOMIC_IOSONLY for property 'atomic' attribute 471 ObjCMT_NsAtomicIOSOnlyProperty = 0x400, 472 473 /// Enable inferring NS_DESIGNATED_INITIALIZER for ObjC methods. 474 ObjCMT_DesignatedInitializer = 0x800, 475 476 /// Enable converting setter/getter expressions to property-dot syntx. 477 ObjCMT_PropertyDotSyntax = 0x1000, 478 479 ObjCMT_MigrateDecls = (ObjCMT_ReadonlyProperty | ObjCMT_ReadwriteProperty | 480 ObjCMT_Annotation | ObjCMT_Instancetype | 481 ObjCMT_NsMacros | ObjCMT_ProtocolConformance | 482 ObjCMT_NsAtomicIOSOnlyProperty | 483 ObjCMT_DesignatedInitializer), 484 ObjCMT_MigrateAll = (ObjCMT_Literals | ObjCMT_Subscripting | 485 ObjCMT_MigrateDecls | ObjCMT_PropertyDotSyntax) 486 }; 487 unsigned ObjCMTAction = ObjCMT_None; 488 std::string ObjCMTAllowListPath; 489 490 std::string MTMigrateDir; 491 std::string ARCMTMigrateReportOut; 492 493 /// The input kind, either specified via -x argument or deduced from the input 494 /// file name. 495 InputKind DashX; 496 497 /// The input files and their types. 498 SmallVector<FrontendInputFile, 0> Inputs; 499 500 /// When the input is a module map, the original module map file from which 501 /// that map was inferred, if any (for umbrella modules). 502 std::string OriginalModuleMap; 503 504 /// The output file, if any. 505 std::string OutputFile; 506 507 /// If given, the new suffix for fix-it rewritten files. 508 std::string FixItSuffix; 509 510 /// If given, filter dumped AST Decl nodes by this substring. 511 std::string ASTDumpFilter; 512 513 /// If given, enable code completion at the provided location. 514 ParsedSourceLocation CodeCompletionAt; 515 516 /// The frontend action to perform. 517 frontend::ActionKind ProgramAction = frontend::ParseSyntaxOnly; 518 519 /// The name of the action to run when using a plugin action. 520 std::string ActionName; 521 522 // Currently this is only used as part of the `-extract-api` action. 523 /// The name of the product the input files belong too. 524 std::string ProductName; 525 526 // Currently this is only used as part of the `-extract-api` action. 527 // A comma separated list of files providing a list of APIs to 528 // ignore when extracting documentation. 529 std::vector<std::string> ExtractAPIIgnoresFileList; 530 531 // Location of output directory where symbol graph information would 532 // be dumped. This overrides regular -o output file specification 533 std::string SymbolGraphOutputDir; 534 535 /// Args to pass to the plugins 536 std::map<std::string, std::vector<std::string>> PluginArgs; 537 538 /// The list of plugin actions to run in addition to the normal action. 539 std::vector<std::string> AddPluginActions; 540 541 /// The list of plugins to load. 542 std::vector<std::string> Plugins; 543 544 /// The list of module file extensions. 545 std::vector<std::shared_ptr<ModuleFileExtension>> ModuleFileExtensions; 546 547 /// The list of module map files to load before processing the input. 548 std::vector<std::string> ModuleMapFiles; 549 550 /// The list of additional prebuilt module files to load before 551 /// processing the input. 552 std::vector<std::string> ModuleFiles; 553 554 /// The list of files to embed into the compiled module file. 555 std::vector<std::string> ModulesEmbedFiles; 556 557 /// The list of AST files to merge. 558 std::vector<std::string> ASTMergeFiles; 559 560 /// A list of arguments to forward to LLVM's option processing; this 561 /// should only be used for debugging and experimental features. 562 std::vector<std::string> LLVMArgs; 563 564 /// File name of the file that will provide record layouts 565 /// (in the format produced by -fdump-record-layouts). 566 std::string OverrideRecordLayoutsFile; 567 568 /// Auxiliary triple for CUDA/HIP compilation. 569 std::string AuxTriple; 570 571 /// Auxiliary target CPU for CUDA/HIP compilation. 572 std::optional<std::string> AuxTargetCPU; 573 574 /// Auxiliary target features for CUDA/HIP compilation. 575 std::optional<std::vector<std::string>> AuxTargetFeatures; 576 577 /// Filename to write statistics to. 578 std::string StatsFile; 579 580 /// Minimum time granularity (in microseconds) traced by time profiler. 581 unsigned TimeTraceGranularity; 582 583 /// Make time trace capture verbose event details (e.g. source filenames). 584 /// This can increase the size of the output by 2-3 times. 585 LLVM_PREFERRED_TYPE(bool) 586 unsigned TimeTraceVerbose : 1; 587 588 /// Path which stores the output files for -ftime-trace 589 std::string TimeTracePath; 590 591 /// Output Path for module output file. 592 std::string ModuleOutputPath; 593 594 public: FrontendOptions()595 FrontendOptions() 596 : DisableFree(false), RelocatablePCH(false), ShowHelp(false), 597 ShowStats(false), AppendStats(false), ShowVersion(false), 598 FixWhatYouCan(false), FixOnlyWarnings(false), FixAndRecompile(false), 599 FixToTemporaries(false), ARCMTMigrateEmitARCErrors(false), 600 SkipFunctionBodies(false), UseGlobalModuleIndex(true), 601 GenerateGlobalModuleIndex(true), ASTDumpDecls(false), 602 ASTDumpLookups(false), BuildingImplicitModule(false), 603 BuildingImplicitModuleUsesLock(true), ModulesEmbedAllFiles(false), 604 IncludeTimestamps(true), UseTemporary(true), 605 AllowPCMWithCompilerErrors(false), ModulesShareFileManager(true), 606 EmitSymbolGraph(false), EmitExtensionSymbolGraphs(false), 607 EmitSymbolGraphSymbolLabelsForTesting(false), 608 EmitPrettySymbolGraphs(false), GenReducedBMI(false), 609 UseClangIRPipeline(false), TimeTraceGranularity(500), 610 TimeTraceVerbose(false) {} 611 612 /// getInputKindForExtension - Return the appropriate input kind for a file 613 /// extension. For example, "c" would return Language::C. 614 /// 615 /// \return The input kind for the extension, or Language::Unknown if the 616 /// extension is not recognized. 617 static InputKind getInputKindForExtension(StringRef Extension); 618 }; 619 620 } // namespace clang 621 622 #endif // LLVM_CLANG_FRONTEND_FRONTENDOPTIONS_H 623