clang 24.0.0git
SourceTransformationFrontendAction.cpp
Go to the documentation of this file.
1//===- SourceTransformationFrontendAction.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
25#include "llvm/ADT/StringRef.h"
26#include "llvm/Support/IOSandbox.h"
27#include "llvm/Support/Path.h"
28#include <memory>
29#include <string>
30#include <utility>
31#include <vector>
32
33using namespace clang;
34using namespace ssaf;
35
36namespace {
37
38/// Concrete `SourceEditEmitter` that buffers replacements until flushed.
39class AccumulatorSourceEditEmitter final : public SourceEditEmitter {
40public:
41 void addReplacement(clang::tooling::Replacement R) override {
42 Replacements.push_back(std::move(R));
43 }
44
45 std::vector<clang::tooling::Replacement> Replacements;
46};
47
48/// Concrete `TransformationReportEmitter` that buffers results until flushed.
49class AccumulatorReportEmitter final : public TransformationReportEmitter {
50public:
51 void addResult(StringRef RuleId, clang::SarifResultLevel Level,
52 clang::CharSourceRange Range, StringRef Message) override {
53 Results.push_back({RuleId.str(), Level, Range, Message.str()});
54 }
55
56 std::vector<ReportResult> Results;
57};
58
59/// Per-TU runner: owns the loaded `WPASuite`, the accumulator emitters, and
60/// the user-supplied `Transformation`. Inherits from `MultiplexConsumer` so
61/// the transformation's `ASTConsumer` virtuals are forwarded for free;
62/// serializes both outputs after the AST walk completes.
63class SourceTransformationRunner final : public MultiplexConsumer {
64public:
65 static std::unique_ptr<SourceTransformationRunner>
66 create(CompilerInstance &CI, StringRef InFile);
67
68private:
69 SourceTransformationRunner(WPASuite Suite, const SSAFOptions &Opts,
70 StringRef InFile);
71
72 void HandleTranslationUnit(ASTContext &Ctx) override;
73
74 WPASuite Suite;
75 AccumulatorSourceEditEmitter Edits;
76 AccumulatorReportEmitter Report;
77 const SSAFOptions &Opts;
78 std::string InFile;
79};
80
81} // namespace
82
83/// Returns the bare extension of \p Path (no leading dot), or `std::nullopt` if
84/// \p Path is empty or has no recognizable extension.
85static std::optional<StringRef> bareExtension(StringRef Path) {
86 StringRef Ext = llvm::sys::path::extension(Path);
87 if (!Ext.consume_front("."))
88 return std::nullopt;
89 return Ext;
90}
91
92/// Companion options required by `--ssaf-source-transformation=`. Values must
93/// match the `%select` branch order in
94/// `warn_ssaf_source_transformation_requires`.
96 STCompanion_WPAFile, // --ssaf-global-scope-analysis-result=
97 STCompanion_EditFile, // --ssaf-src-edit-file=
98 STCompanion_ReportFile, // --ssaf-transformation-report-file=
99 STCompanion_CompilationUnitId, // --ssaf-compilation-unit-id=
100};
101
102/// Options that depend on `--ssaf-source-transformation=` being set. Values
103/// must match the `%select` branch order in
104/// `warn_ssaf_option_ignored_without_source_transformation`.
106 STDependent_EditFile, // --ssaf-src-edit-file=
107 STDependent_ReportFile, // --ssaf-transformation-report-file=
108};
109
110/// Returns `true` if any orphan-option warning was reported. Every missing
111/// companion option fires its own diagnostic in a single pass so the user
112/// sees the full list of CLI mistakes at once.
114 const SSAFOptions &Opts) {
115 bool Reported = false;
116
117 if (!Opts.SourceTransformation.empty()) {
118 if (Opts.GlobalScopeAnalysisResult.empty()) {
119 Diags.Report(diag::warn_ssaf_source_transformation_requires)
121 Reported = true;
122 }
123 if (Opts.SrcEditFile.empty()) {
124 Diags.Report(diag::warn_ssaf_source_transformation_requires)
126 Reported = true;
127 }
128 if (Opts.TransformationReportFile.empty()) {
129 Diags.Report(diag::warn_ssaf_source_transformation_requires)
131 Reported = true;
132 }
133 if (Opts.CompilationUnitId.empty()) {
134 Diags.Report(diag::warn_ssaf_source_transformation_requires)
136 Reported = true;
137 }
138 } else {
139 if (!Opts.SrcEditFile.empty()) {
140 Diags.Report(diag::warn_ssaf_option_ignored_without_source_transformation)
142 Reported = true;
143 }
144 if (!Opts.TransformationReportFile.empty()) {
145 Diags.Report(diag::warn_ssaf_option_ignored_without_source_transformation)
147 Reported = true;
148 }
149 }
150
151 return Reported;
152}
153
154std::unique_ptr<SourceTransformationRunner>
155SourceTransformationRunner::create(CompilerInstance &CI, StringRef InFile) {
156 const SSAFOptions &Opts = CI.getSSAFOpts();
157 DiagnosticsEngine &Diags = CI.getDiagnostics();
158
159 if (reportOrphanOptionMisuse(Diags, Opts))
160 return nullptr;
161 if (Opts.SourceTransformation.empty())
162 return nullptr;
163
165 Diags.Report(diag::warn_ssaf_source_transformation_unknown_name)
166 << Opts.SourceTransformation;
167 return nullptr;
168 }
169
170 std::optional<StringRef> WPAExt =
172 std::unique_ptr<SerializationFormat> WPAFormat =
173 WPAExt && isFormatRegistered(*WPAExt) ? makeFormat(*WPAExt) : nullptr;
174 if (!WPAFormat) {
175 Diags.Report(diag::warn_ssaf_read_wpa_suite_failed)
176 << Opts.GlobalScopeAnalysisResult << "unknown serialization format";
177 return nullptr;
178 }
179 llvm::sys::sandbox::ScopedSetting Guard = llvm::sys::sandbox::scopedDisable();
180 llvm::Expected<WPASuite> SuiteOrErr =
181 WPAFormat->readWPASuite(Opts.GlobalScopeAnalysisResult);
182 if (!SuiteOrErr) {
183 Diags.Report(diag::warn_ssaf_read_wpa_suite_failed)
185 << llvm::toString(SuiteOrErr.takeError());
186 return nullptr;
187 }
188
189 return std::unique_ptr<SourceTransformationRunner>{
190 new SourceTransformationRunner(std::move(*SuiteOrErr), Opts, InFile)};
191}
192
193SourceTransformationRunner::SourceTransformationRunner(WPASuite Suite,
194 const SSAFOptions &Opts,
195 StringRef InFile)
196 : MultiplexConsumer(std::vector<std::unique_ptr<ASTConsumer>>{}),
197 Suite(std::move(Suite)), Opts(Opts), InFile(InFile) {
198 // The transformation must be constructed after Suite/Edits/Report start
199 // their lifetimes — those references are captured in its base ctor.
200 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
201 Consumers.push_back(makeTransformation(Opts.SourceTransformation, this->Suite,
202 Edits, Report));
203 assert(Consumers.front());
204 MultiplexConsumer::Consumers = std::move(Consumers);
205}
206
207void SourceTransformationRunner::HandleTranslationUnit(ASTContext &Ctx) {
208 // First, run the transformation.
210
211 llvm::sys::sandbox::ScopedSetting Guard = llvm::sys::sandbox::scopedDisable();
212
213 // Then serialize the source edits.
214 clang::tooling::TranslationUnitReplacements EditDoc;
215 EditDoc.MainSourceFile = InFile;
216 EditDoc.Replacements = std::move(Edits.Replacements);
217 if (auto Err = writeYAMLSourceEdits(EditDoc, Opts.SrcEditFile)) {
218 Ctx.getDiagnostics().Report(diag::warn_ssaf_write_src_edit_failed)
219 << Opts.SrcEditFile << llvm::toString(std::move(Err));
220 }
221
222 // And the transformation report.
223 ReportDocument ReportDoc{Opts.SourceTransformation, Ctx.getSourceManager(),
224 std::move(Report.Results)};
225 if (auto Err = writeSARIFTransformationReport(
226 ReportDoc, Opts.TransformationReportFile)) {
228 diag::warn_ssaf_write_transformation_report_failed)
229 << Opts.TransformationReportFile << llvm::toString(std::move(Err));
230 }
231}
232
234 default;
235
239
240std::unique_ptr<ASTConsumer>
242 StringRef InFile) {
243 auto WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
244 if (!WrappedConsumer)
245 return nullptr;
246
247 if (auto Runner = SourceTransformationRunner::create(CI, InFile)) {
248 CI.getCodeGenOpts().ClearASTBeforeBackend = false;
249 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
250 Consumers.reserve(2);
251 Consumers.push_back(std::move(WrappedConsumer));
252 Consumers.push_back(std::move(Runner));
253 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
254 }
255 return WrappedConsumer;
256}
SourceTransformationDependent
Options that depend on --ssaf-source-transformation= being set.
SourceTransformationCompanion
Companion options required by --ssaf-source-transformation=.
static bool reportOrphanOptionMisuse(DiagnosticsEngine &Diags, const SSAFOptions &Opts)
Returns true if any orphan-option warning was reported.
static std::optional< StringRef > bareExtension(StringRef Path)
Returns the bare extension of Path (no leading dot), or std::nullopt if Path is empty or has no recog...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
SourceManager & getSourceManager()
Definition ASTContext.h:869
DiagnosticsEngine & getDiagnostics() const
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
ssaf::SSAFOptions & getSSAFOpts()
CodeGenOptions & getCodeGenOpts()
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
void HandleTranslationUnit(ASTContext &Ctx) override
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
std::vector< std::unique_ptr< ASTConsumer > > Consumers
WrapperFrontendAction(std::unique_ptr< FrontendAction > WrappedAction)
Construct a WrapperFrontendAction from an existing action, taking ownership of it.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
std::unique_ptr< FrontendAction > WrappedAction
std::string SrcEditFile
Path of the source-edit output file produced by the source transformation.
Definition SSAFOptions.h:48
std::string TransformationReportFile
Path of the transformation-report output file produced by the source transformation.
Definition SSAFOptions.h:53
std::string CompilationUnitId
Stable identifier used as the name of the CompilationUnit BuildNamespace of every produced TU summary...
Definition SSAFOptions.h:32
std::string SourceTransformation
Name of the SSAF source transformation to run.
Definition SSAFOptions.h:38
std::string GlobalScopeAnalysisResult
Path of the WPASuite input consumed by the source transformation.
Definition SSAFOptions.h:43
SourceTransformationFrontendAction(std::unique_ptr< FrontendAction > WrappedAction)
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions &DiagOpts, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
std::unique_ptr< SerializationFormat > makeFormat(llvm::StringRef FormatName)
Try to instantiate a SerializationFormat with a given name.
llvm::Error writeSARIFTransformationReport(const ReportDocument &Doc, llvm::StringRef Path)
Writes Doc to Path as a SARIF JSON document.
llvm::Error writeYAMLSourceEdits(const clang::tooling::TranslationUnitReplacements &Doc, llvm::StringRef Path)
Writes Doc to Path as a YAML document compatible with clang-apply-replacements.
bool isFormatRegistered(llvm::StringRef FormatName)
Check if a SerializationFormat was registered with a given name.
std::unique_ptr< Transformation > makeTransformation(llvm::StringRef Name, const WPASuite &Suite, SourceEditEmitter &Edits, TransformationReportEmitter &Report)
Try to instantiate a Transformation with a given name.
bool isTransformationRegistered(llvm::StringRef Name)
Check if a Transformation was registered with a given name.
The JSON file list parser is used to communicate input to InstallAPI.
SarifResultLevel
The level of severity associated with a SarifResult.
Definition Sarif.h:165
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
std::string MainSourceFile
Name of the main source for the translation unit.
std::vector< Replacement > Replacements