1//===-- FrontendAction.h - Generic Frontend Action Interface ----*- 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/// \file
10/// Defines the clang::FrontendAction interface and various convenience
11/// abstract classes (clang::ASTFrontendAction, clang::PluginASTAction,
12/// clang::PreprocessorFrontendAction, and clang::WrapperFrontendAction)
13/// derived from it.
14///
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_FRONTEND_FRONTENDACTION_H
18#define LLVM_CLANG_FRONTEND_FRONTENDACTION_H
19
20#include "clang/AST/ASTConsumer.h"
21#include "clang/Basic/LLVM.h"
22#include "clang/Basic/LangOptions.h"
23#include "clang/Frontend/CompilerInstance.h"
24#include "clang/Frontend/FrontendOptions.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/Support/Error.h"
27#include <memory>
28#include <string>
29#include <vector>
30
31namespace clang {
32class ASTMergeAction;
33class ASTUnit;
34class CompilerInstance;
35
36/// Abstract base class for actions which can be performed by the frontend.
37class FrontendAction {
38 FrontendInputFile CurrentInput;
39 std::unique_ptr<ASTUnit> CurrentASTUnit;
40 CompilerInstance *Instance;
41 friend class ASTMergeAction;
42 friend class WrapperFrontendAction;
43
44private:
45 std::unique_ptr<ASTConsumer> CreateWrappedASTConsumer(CompilerInstance &CI,
46 StringRef InFile);
47
48protected:
49 /// @name Implementation Action Interface
50 /// @{
51
52 /// Prepare to execute the action on the given CompilerInstance.
53 ///
54 /// This is called before executing the action on any inputs, and can modify
55 /// the configuration as needed (including adjusting the input list).
56 virtual bool PrepareToExecuteAction(CompilerInstance &CI) { return true; }
57
58 /// Create the AST consumer object for this action, if supported.
59 ///
60 /// This routine is called as part of BeginSourceFile(), which will
61 /// fail if the AST consumer cannot be created. This will not be called if the
62 /// action has indicated that it only uses the preprocessor.
63 ///
64 /// \param CI - The current compiler instance, provided as a convenience, see
65 /// getCompilerInstance().
66 ///
67 /// \param InFile - The current input file, provided as a convenience, see
68 /// getCurrentFile().
69 ///
70 /// \return The new AST consumer, or null on failure.
71 virtual std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
72 StringRef InFile) = 0;
73
74 /// Callback before starting processing a single input, giving the
75 /// opportunity to modify the CompilerInvocation or do some other action
76 /// before BeginSourceFileAction is called.
77 ///
78 /// \return True on success; on failure BeginSourceFileAction(),
79 /// ExecuteAction() and EndSourceFileAction() will not be called.
80 virtual bool BeginInvocation(CompilerInstance &CI) { return true; }
81
82 /// Callback at the start of processing a single input.
83 ///
84 /// \return True on success; on failure ExecutionAction() and
85 /// EndSourceFileAction() will not be called.
86 virtual bool BeginSourceFileAction(CompilerInstance &CI);
87
88 /// Callback to run the program action, using the initialized
89 /// compiler instance.
90 ///
91 /// This is guaranteed to only be called between BeginSourceFileAction()
92 /// and EndSourceFileAction().
93 virtual void ExecuteAction() = 0;
94
95 /// Callback at the end of processing a single input.
96 ///
97 /// This is guaranteed to only be called following a successful call to
98 /// BeginSourceFileAction (and BeginSourceFile).
99 virtual void EndSourceFileAction();
100
101 /// Callback at the end of processing a single input, to determine
102 /// if the output files should be erased or not.
103 ///
104 /// By default it returns true if a compiler error occurred.
105 /// This is guaranteed to only be called following a successful call to
106 /// BeginSourceFileAction (and BeginSourceFile).
107 virtual bool shouldEraseOutputFiles();
108
109 /// @}
110
111public:
112 FrontendAction();
113 virtual ~FrontendAction();
114
115 /// @name Compiler Instance Access
116 /// @{
117
118 CompilerInstance &getCompilerInstance() const {
119 assert(Instance && "Compiler instance not registered!");
120 return *Instance;
121 }
122
123 void setCompilerInstance(CompilerInstance *Value) { Instance = Value; }
124
125 /// @}
126 /// @name Current File Information
127 /// @{
128
129 bool isCurrentFileAST() const {
130 assert(!CurrentInput.isEmpty() && "No current file!");
131 return (bool)CurrentASTUnit;
132 }
133
134 const FrontendInputFile &getCurrentInput() const {
135 return CurrentInput;
136 }
137
138 StringRef getCurrentFile() const {
139 assert(!CurrentInput.isEmpty() && "No current file!");
140 return CurrentInput.getFile();
141 }
142
143 StringRef getCurrentFileOrBufferName() const {
144 assert(!CurrentInput.isEmpty() && "No current file!");
145 return CurrentInput.isFile()
146 ? CurrentInput.getFile()
147 : CurrentInput.getBuffer().getBufferIdentifier();
148 }
149
150 InputKind getCurrentFileKind() const {
151 assert(!CurrentInput.isEmpty() && "No current file!");
152 return CurrentInput.getKind();
153 }
154
155 ASTUnit &getCurrentASTUnit() const {
156 assert(CurrentASTUnit && "No current AST unit!");
157 return *CurrentASTUnit;
158 }
159
160 Module *getCurrentModule() const;
161
162 std::unique_ptr<ASTUnit> takeCurrentASTUnit();
163
164 void setCurrentInput(const FrontendInputFile &CurrentInput,
165 std::unique_ptr<ASTUnit> AST = nullptr);
166
167 /// @}
168 /// @name Supported Modes
169 /// @{
170
171 /// Is this action invoked on a model file?
172 ///
173 /// Model files are incomplete translation units that relies on type
174 /// information from another translation unit. Check ParseModelFileAction for
175 /// details.
176 virtual bool isModelParsingAction() const { return false; }
177
178 /// Does this action only use the preprocessor?
179 ///
180 /// If so no AST context will be created and this action will be invalid
181 /// with AST file inputs.
182 virtual bool usesPreprocessorOnly() const = 0;
183
184 /// For AST-based actions, the kind of translation unit we're handling.
185 virtual TranslationUnitKind getTranslationUnitKind();
186
187 /// Does this action support use with PCH?
188 virtual bool hasPCHSupport() const { return true; }
189
190 /// Does this action support use with AST files?
191 virtual bool hasASTFileSupport() const { return true; }
192
193 /// Does this action support use with IR files?
194 virtual bool hasIRSupport() const { return false; }
195
196 /// Does this action support use with code completion?
197 virtual bool hasCodeCompletionSupport() const { return false; }
198
199 /// @}
200 /// @name Public Action Interface
201 /// @{
202
203 /// Prepare the action to execute on the given compiler instance.
204 bool PrepareToExecute(CompilerInstance &CI) {
205 return PrepareToExecuteAction(CI);
206 }
207
208 /// Prepare the action for processing the input file \p Input.
209 ///
210 /// This is run after the options and frontend have been initialized,
211 /// but prior to executing any per-file processing.
212 ///
213 /// \param CI - The compiler instance this action is being run from. The
214 /// action may store and use this object up until the matching EndSourceFile
215 /// action.
216 ///
217 /// \param Input - The input filename and kind. Some input kinds are handled
218 /// specially, for example AST inputs, since the AST file itself contains
219 /// several objects which would normally be owned by the
220 /// CompilerInstance. When processing AST input files, these objects should
221 /// generally not be initialized in the CompilerInstance -- they will
222 /// automatically be shared with the AST file in between
223 /// BeginSourceFile() and EndSourceFile().
224 ///
225 /// \return True on success; on failure the compilation of this file should
226 /// be aborted and neither Execute() nor EndSourceFile() should be called.
227 bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input);
228
229 /// Set the source manager's main input file, and run the action.
230 llvm::Error Execute();
231
232 /// Perform any per-file post processing, deallocate per-file
233 /// objects, and run statistics and output file cleanup code.
234 virtual void EndSourceFile();
235
236 /// @}
237};
238
239/// Abstract base class to use for AST consumer-based frontend actions.
240class ASTFrontendAction : public FrontendAction {
241protected:
242 /// Implement the ExecuteAction interface by running Sema on
243 /// the already-initialized AST consumer.
244 ///
245 /// This will also take care of instantiating a code completion consumer if
246 /// the user requested it and the action supports it.
247 void ExecuteAction() override;
248
249public:
250 ASTFrontendAction() {}
251 bool usesPreprocessorOnly() const override { return false; }
252};
253
254class PluginASTAction : public ASTFrontendAction {
255 virtual void anchor();
256public:
257 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
258 StringRef InFile) override = 0;
259
260 /// Parse the given plugin command line arguments.
261 ///
262 /// \param CI - The compiler instance, for use in reporting diagnostics.
263 /// \return True if the parsing succeeded; otherwise the plugin will be
264 /// destroyed and no action run. The plugin is responsible for using the
265 /// CompilerInstance's Diagnostic object to report errors.
266 virtual bool ParseArgs(const CompilerInstance &CI,
267 const std::vector<std::string> &arg) = 0;
268
269 enum ActionType {
270 CmdlineBeforeMainAction, ///< Execute the action before the main action if
271 ///< on the command line
272 CmdlineAfterMainAction, ///< Execute the action after the main action if on
273 ///< the command line
274 ReplaceAction, ///< Replace the main action
275 AddBeforeMainAction, ///< Execute the action before the main action
276 AddAfterMainAction ///< Execute the action after the main action
277 };
278 /// Get the action type for this plugin
279 ///
280 /// \return The action type. By default we use CmdlineAfterMainAction.
281 virtual ActionType getActionType() { return CmdlineAfterMainAction; }
282};
283
284/// Abstract base class to use for preprocessor-based frontend actions.
285class PreprocessorFrontendAction : public FrontendAction {
286protected:
287 /// Provide a default implementation which returns aborts;
288 /// this method should never be called by FrontendAction clients.
289 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
290 StringRef InFile) override;
291
292public:
293 bool usesPreprocessorOnly() const override { return true; }
294};
295
296/// A frontend action which simply wraps some other runtime-specified
297/// frontend action.
298///
299/// Deriving from this class allows an action to inject custom logic around
300/// some existing action's behavior. It implements every virtual method in
301/// the FrontendAction interface by forwarding to the wrapped action.
302class WrapperFrontendAction : public FrontendAction {
303protected:
304 std::unique_ptr<FrontendAction> WrappedAction;
305
306 bool PrepareToExecuteAction(CompilerInstance &CI) override;
307 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
308 StringRef InFile) override;
309 bool BeginInvocation(CompilerInstance &CI) override;
310 bool BeginSourceFileAction(CompilerInstance &CI) override;
311 void ExecuteAction() override;
312 void EndSourceFile() override;
313 void EndSourceFileAction() override;
314 bool shouldEraseOutputFiles() override;
315
316public:
317 /// Construct a WrapperFrontendAction from an existing action, taking
318 /// ownership of it.
319 WrapperFrontendAction(std::unique_ptr<FrontendAction> WrappedAction);
320
321 bool usesPreprocessorOnly() const override;
322 TranslationUnitKind getTranslationUnitKind() override;
323 bool hasPCHSupport() const override;
324 bool hasASTFileSupport() const override;
325 bool hasIRSupport() const override;
326 bool hasCodeCompletionSupport() const override;
327};
328
329} // end namespace clang
330
331#endif
332