Home | History | Annotate | Download | only in Frontend
      1 //===--- FrontendOptions.h --------------------------------------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 #ifndef LLVM_CLANG_FRONTEND_FRONTENDOPTIONS_H
     11 #define LLVM_CLANG_FRONTEND_FRONTENDOPTIONS_H
     12 
     13 #include "clang/Frontend/CommandLineSourceLoc.h"
     14 #include "clang/Serialization/ModuleFileExtension.h"
     15 #include "clang/Sema/CodeCompleteOptions.h"
     16 #include "llvm/ADT/StringRef.h"
     17 #include <string>
     18 #include <vector>
     19 #include <unordered_map>
     20 
     21 namespace llvm {
     22 class MemoryBuffer;
     23 }
     24 
     25 namespace clang {
     26 class FileEntry;
     27 
     28 namespace frontend {
     29   enum ActionKind {
     30     ASTDeclList,            ///< Parse ASTs and list Decl nodes.
     31     ASTDump,                ///< Parse ASTs and dump them.
     32     ASTPrint,               ///< Parse ASTs and print them.
     33     ASTView,                ///< Parse ASTs and view them in Graphviz.
     34     DumpRawTokens,          ///< Dump out raw tokens.
     35     DumpTokens,             ///< Dump out preprocessed tokens.
     36     EmitAssembly,           ///< Emit a .s file.
     37     EmitBC,                 ///< Emit a .bc file.
     38     EmitHTML,               ///< Translate input source into HTML.
     39     EmitLLVM,               ///< Emit a .ll file.
     40     EmitLLVMOnly,           ///< Generate LLVM IR, but do not emit anything.
     41     EmitCodeGenOnly,        ///< Generate machine code, but don't emit anything.
     42     EmitObj,                ///< Emit a .o file.
     43     FixIt,                  ///< Parse and apply any fixits to the source.
     44     GenerateModule,         ///< Generate pre-compiled module from a module map.
     45     GenerateModuleInterface,///< Generate pre-compiled module from a C++ module
     46                             ///< interface file.
     47     GeneratePCH,            ///< Generate pre-compiled header.
     48     GeneratePTH,            ///< Generate pre-tokenized header.
     49     InitOnly,               ///< Only execute frontend initialization.
     50     ModuleFileInfo,         ///< Dump information about a module file.
     51     VerifyPCH,              ///< Load and verify that a PCH file is usable.
     52     ParseSyntaxOnly,        ///< Parse and perform semantic analysis.
     53     PluginAction,           ///< Run a plugin action, \see ActionName.
     54     PrintDeclContext,       ///< Print DeclContext and their Decls.
     55     PrintPreamble,          ///< Print the "preamble" of the input file
     56     PrintPreprocessedInput, ///< -E mode.
     57     RewriteMacros,          ///< Expand macros but not \#includes.
     58     RewriteObjC,            ///< ObjC->C Rewriter.
     59     RewriteTest,            ///< Rewriter playground
     60     RunAnalysis,            ///< Run one or more source code analyses.
     61     MigrateSource,          ///< Run migrator.
     62     RunPreprocessorOnly     ///< Just lex, no output.
     63   };
     64 }
     65 
     66 /// The kind of a file that we've been handed as an input.
     67 class InputKind {
     68 private:
     69   unsigned Lang : 4;
     70   unsigned Fmt : 3;
     71   unsigned Preprocessed : 1;
     72 
     73 public:
     74   /// The language for the input, used to select and validate the language
     75   /// standard and possible actions.
     76   enum Language {
     77     Unknown,
     78 
     79     /// Assembly: we accept this only so that we can preprocess it.
     80     Asm,
     81 
     82     /// LLVM IR: we accept this so that we can run the optimizer on it,
     83     /// and compile it to assembly or object code.
     84     LLVM_IR,
     85 
     86     ///@{ Languages that the frontend can parse and compile.
     87     C,
     88     CXX,
     89     ObjC,
     90     ObjCXX,
     91     OpenCL,
     92     CUDA,
     93     RenderScript,
     94     ///@}
     95   };
     96 
     97   /// The input file format.
     98   enum Format {
     99     Source,
    100     ModuleMap,
    101     Precompiled
    102   };
    103 
    104   constexpr InputKind(Language L = Unknown, Format F = Source,
    105                       bool PP = false)
    106       : Lang(L), Fmt(F), Preprocessed(PP) {}
    107 
    108   Language getLanguage() const { return static_cast<Language>(Lang); }
    109   Format getFormat() const { return static_cast<Format>(Fmt); }
    110   bool isPreprocessed() const { return Preprocessed; }
    111 
    112   /// Is the input kind fully-unknown?
    113   bool isUnknown() const { return Lang == Unknown && Fmt == Source; }
    114 
    115   /// Is the language of the input some dialect of Objective-C?
    116   bool isObjectiveC() const { return Lang == ObjC || Lang == ObjCXX; }
    117 
    118   InputKind getPreprocessed() const {
    119     return InputKind(getLanguage(), getFormat(), true);
    120   }
    121   InputKind withFormat(Format F) const {
    122     return InputKind(getLanguage(), F, isPreprocessed());
    123   }
    124 };
    125 
    126 /// \brief An input file for the front end.
    127 class FrontendInputFile {
    128   /// \brief The file name, or "-" to read from standard input.
    129   std::string File;
    130 
    131   /// The input, if it comes from a buffer rather than a file. This object
    132   /// does not own the buffer, and the caller is responsible for ensuring
    133   /// that it outlives any users.
    134   llvm::MemoryBuffer *Buffer = nullptr;
    135 
    136   /// \brief The kind of input, e.g., C source, AST file, LLVM IR.
    137   InputKind Kind;
    138 
    139   /// \brief Whether we're dealing with a 'system' input (vs. a 'user' input).
    140   bool IsSystem = false;
    141 
    142 public:
    143   FrontendInputFile() { }
    144   FrontendInputFile(StringRef File, InputKind Kind, bool IsSystem = false)
    145     : File(File.str()), Kind(Kind), IsSystem(IsSystem) { }
    146   FrontendInputFile(llvm::MemoryBuffer *Buffer, InputKind Kind,
    147                     bool IsSystem = false)
    148     : Buffer(Buffer), Kind(Kind), IsSystem(IsSystem) { }
    149 
    150   InputKind getKind() const { return Kind; }
    151   bool isSystem() const { return IsSystem; }
    152 
    153   bool isEmpty() const { return File.empty() && Buffer == nullptr; }
    154   bool isFile() const { return !isBuffer(); }
    155   bool isBuffer() const { return Buffer != nullptr; }
    156   bool isPreprocessed() const { return Kind.isPreprocessed(); }
    157 
    158   StringRef getFile() const {
    159     assert(isFile());
    160     return File;
    161   }
    162   llvm::MemoryBuffer *getBuffer() const {
    163     assert(isBuffer());
    164     return Buffer;
    165   }
    166 };
    167 
    168 /// FrontendOptions - Options for controlling the behavior of the frontend.
    169 class FrontendOptions {
    170 public:
    171   unsigned DisableFree : 1;                ///< Disable memory freeing on exit.
    172   unsigned RelocatablePCH : 1;             ///< When generating PCH files,
    173                                            /// instruct the AST writer to create
    174                                            /// relocatable PCH files.
    175   unsigned ShowHelp : 1;                   ///< Show the -help text.
    176   unsigned ShowStats : 1;                  ///< Show frontend performance
    177                                            /// metrics and statistics.
    178   unsigned ShowTimers : 1;                 ///< Show timers for individual
    179                                            /// actions.
    180   unsigned ShowVersion : 1;                ///< Show the -version text.
    181   unsigned FixWhatYouCan : 1;              ///< Apply fixes even if there are
    182                                            /// unfixable errors.
    183   unsigned FixOnlyWarnings : 1;            ///< Apply fixes only for warnings.
    184   unsigned FixAndRecompile : 1;            ///< Apply fixes and recompile.
    185   unsigned FixToTemporaries : 1;           ///< Apply fixes to temporary files.
    186   unsigned ARCMTMigrateEmitARCErrors : 1;  /// Emit ARC errors even if the
    187                                            /// migrator can fix them
    188   unsigned SkipFunctionBodies : 1;         ///< Skip over function bodies to
    189                                            /// speed up parsing in cases you do
    190                                            /// not need them (e.g. with code
    191                                            /// completion).
    192   unsigned UseGlobalModuleIndex : 1;       ///< Whether we can use the
    193                                            ///< global module index if available.
    194   unsigned GenerateGlobalModuleIndex : 1;  ///< Whether we can generate the
    195                                            ///< global module index if needed.
    196   unsigned ASTDumpDecls : 1;               ///< Whether we include declaration
    197                                            ///< dumps in AST dumps.
    198   unsigned ASTDumpAll : 1;                 ///< Whether we deserialize all decls
    199                                            ///< when forming AST dumps.
    200   unsigned ASTDumpLookups : 1;             ///< Whether we include lookup table
    201                                            ///< dumps in AST dumps.
    202   unsigned BuildingImplicitModule : 1;     ///< Whether we are performing an
    203                                            ///< implicit module build.
    204   unsigned ModulesEmbedAllFiles : 1;       ///< Whether we should embed all used
    205                                            ///< files into the PCM file.
    206   unsigned IncludeTimestamps : 1;          ///< Whether timestamps should be
    207                                            ///< written to the produced PCH file.
    208 
    209   CodeCompleteOptions CodeCompleteOpts;
    210 
    211   enum {
    212     ARCMT_None,
    213     ARCMT_Check,
    214     ARCMT_Modify,
    215     ARCMT_Migrate
    216   } ARCMTAction;
    217 
    218   enum {
    219     ObjCMT_None = 0,
    220     /// \brief Enable migration to modern ObjC literals.
    221     ObjCMT_Literals = 0x1,
    222     /// \brief Enable migration to modern ObjC subscripting.
    223     ObjCMT_Subscripting = 0x2,
    224     /// \brief Enable migration to modern ObjC readonly property.
    225     ObjCMT_ReadonlyProperty = 0x4,
    226     /// \brief Enable migration to modern ObjC readwrite property.
    227     ObjCMT_ReadwriteProperty = 0x8,
    228     /// \brief Enable migration to modern ObjC property.
    229     ObjCMT_Property = (ObjCMT_ReadonlyProperty | ObjCMT_ReadwriteProperty),
    230     /// \brief Enable annotation of ObjCMethods of all kinds.
    231     ObjCMT_Annotation = 0x10,
    232     /// \brief Enable migration of ObjC methods to 'instancetype'.
    233     ObjCMT_Instancetype = 0x20,
    234     /// \brief Enable migration to NS_ENUM/NS_OPTIONS macros.
    235     ObjCMT_NsMacros = 0x40,
    236     /// \brief Enable migration to add conforming protocols.
    237     ObjCMT_ProtocolConformance = 0x80,
    238     /// \brief prefer 'atomic' property over 'nonatomic'.
    239     ObjCMT_AtomicProperty = 0x100,
    240     /// \brief annotate property with NS_RETURNS_INNER_POINTER
    241     ObjCMT_ReturnsInnerPointerProperty = 0x200,
    242     /// \brief use NS_NONATOMIC_IOSONLY for property 'atomic' attribute
    243     ObjCMT_NsAtomicIOSOnlyProperty = 0x400,
    244     /// \brief Enable inferring NS_DESIGNATED_INITIALIZER for ObjC methods.
    245     ObjCMT_DesignatedInitializer = 0x800,
    246     /// \brief Enable converting setter/getter expressions to property-dot syntx.
    247     ObjCMT_PropertyDotSyntax = 0x1000,
    248     ObjCMT_MigrateDecls = (ObjCMT_ReadonlyProperty | ObjCMT_ReadwriteProperty |
    249                            ObjCMT_Annotation | ObjCMT_Instancetype |
    250                            ObjCMT_NsMacros | ObjCMT_ProtocolConformance |
    251                            ObjCMT_NsAtomicIOSOnlyProperty |
    252                            ObjCMT_DesignatedInitializer),
    253     ObjCMT_MigrateAll = (ObjCMT_Literals | ObjCMT_Subscripting |
    254                          ObjCMT_MigrateDecls | ObjCMT_PropertyDotSyntax)
    255   };
    256   unsigned ObjCMTAction;
    257   std::string ObjCMTWhiteListPath;
    258 
    259   std::string MTMigrateDir;
    260   std::string ARCMTMigrateReportOut;
    261 
    262   /// The input files and their types.
    263   std::vector<FrontendInputFile> Inputs;
    264 
    265   /// When the input is a module map, the original module map file from which
    266   /// that map was inferred, if any (for umbrella modules).
    267   std::string OriginalModuleMap;
    268 
    269   /// The output file, if any.
    270   std::string OutputFile;
    271 
    272   /// If given, the new suffix for fix-it rewritten files.
    273   std::string FixItSuffix;
    274 
    275   /// If given, filter dumped AST Decl nodes by this substring.
    276   std::string ASTDumpFilter;
    277 
    278   /// If given, enable code completion at the provided location.
    279   ParsedSourceLocation CodeCompletionAt;
    280 
    281   /// The frontend action to perform.
    282   frontend::ActionKind ProgramAction;
    283 
    284   /// The name of the action to run when using a plugin action.
    285   std::string ActionName;
    286 
    287   /// Args to pass to the plugins
    288   std::unordered_map<std::string,std::vector<std::string>> PluginArgs;
    289 
    290   /// The list of plugin actions to run in addition to the normal action.
    291   std::vector<std::string> AddPluginActions;
    292 
    293   /// The list of plugins to load.
    294   std::vector<std::string> Plugins;
    295 
    296   /// The list of module file extensions.
    297   std::vector<std::shared_ptr<ModuleFileExtension>> ModuleFileExtensions;
    298 
    299   /// \brief The list of module map files to load before processing the input.
    300   std::vector<std::string> ModuleMapFiles;
    301 
    302   /// \brief The list of additional prebuilt module files to load before
    303   /// processing the input.
    304   std::vector<std::string> ModuleFiles;
    305 
    306   /// \brief The list of files to embed into the compiled module file.
    307   std::vector<std::string> ModulesEmbedFiles;
    308 
    309   /// \brief The list of AST files to merge.
    310   std::vector<std::string> ASTMergeFiles;
    311 
    312   /// \brief A list of arguments to forward to LLVM's option processing; this
    313   /// should only be used for debugging and experimental features.
    314   std::vector<std::string> LLVMArgs;
    315 
    316   /// \brief File name of the file that will provide record layouts
    317   /// (in the format produced by -fdump-record-layouts).
    318   std::string OverrideRecordLayoutsFile;
    319 
    320   /// \brief Auxiliary triple for CUDA compilation.
    321   std::string AuxTriple;
    322 
    323   /// \brief If non-empty, search the pch input file as if it was a header
    324   /// included by this file.
    325   std::string FindPchSource;
    326 
    327   /// Filename to write statistics to.
    328   std::string StatsFile;
    329 
    330 public:
    331   FrontendOptions() :
    332     DisableFree(false), RelocatablePCH(false), ShowHelp(false),
    333     ShowStats(false), ShowTimers(false), ShowVersion(false),
    334     FixWhatYouCan(false), FixOnlyWarnings(false), FixAndRecompile(false),
    335     FixToTemporaries(false), ARCMTMigrateEmitARCErrors(false),
    336     SkipFunctionBodies(false), UseGlobalModuleIndex(true),
    337     GenerateGlobalModuleIndex(true), ASTDumpDecls(false), ASTDumpLookups(false),
    338     BuildingImplicitModule(false), ModulesEmbedAllFiles(false),
    339     IncludeTimestamps(true), ARCMTAction(ARCMT_None),
    340     ObjCMTAction(ObjCMT_None), ProgramAction(frontend::ParseSyntaxOnly)
    341   {}
    342 
    343   /// getInputKindForExtension - Return the appropriate input kind for a file
    344   /// extension. For example, "c" would return InputKind::C.
    345   ///
    346   /// \return The input kind for the extension, or InputKind::Unknown if the
    347   /// extension is not recognized.
    348   static InputKind getInputKindForExtension(StringRef Extension);
    349 };
    350 
    351 }  // end namespace clang
    352 
    353 #endif
    354