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