blob: b513446a543ddc98959e67ef1f5ed2908e2f2f84 [file] [log] [blame]
Manuel Klimekcb971c62012-04-04 12:07:46 +00001//===--- CompilationDatabase.cpp - ----------------------------------------===//
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//
Daniel Jasper7fd90b02012-08-24 05:50:27 +000010// This file contains implementations of the CompilationDatabase base class
11// and the FixedCompilationDatabase.
Manuel Klimekcb971c62012-04-04 12:07:46 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Tooling/CompilationDatabase.h"
Edwin Vanec8f03422013-11-17 16:08:04 +000016#include "clang/Basic/Diagnostic.h"
17#include "clang/Driver/Action.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070018#include "clang/Driver/Compilation.h"
Edwin Vanec8f03422013-11-17 16:08:04 +000019#include "clang/Driver/Driver.h"
20#include "clang/Driver/DriverDiagnostic.h"
21#include "clang/Driver/Job.h"
Edwin Vanec8f03422013-11-17 16:08:04 +000022#include "clang/Frontend/TextDiagnosticPrinter.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070023#include "clang/Tooling/CompilationDatabasePluginRegistry.h"
24#include "clang/Tooling/Tooling.h"
25#include "llvm/ADT/SmallString.h"
Edwin Vanec8f03422013-11-17 16:08:04 +000026#include "llvm/Option/Arg.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070027#include "llvm/Support/Host.h"
28#include "llvm/Support/Path.h"
29#include "llvm/Support/system_error.h"
30#include <sstream>
Edwin Vanec8f03422013-11-17 16:08:04 +000031
Manuel Klimekcb971c62012-04-04 12:07:46 +000032namespace clang {
33namespace tooling {
34
Manuel Klimekcb971c62012-04-04 12:07:46 +000035CompilationDatabase::~CompilationDatabase() {}
36
37CompilationDatabase *
38CompilationDatabase::loadFromDirectory(StringRef BuildDirectory,
39 std::string &ErrorMessage) {
Daniel Jasper7fd90b02012-08-24 05:50:27 +000040 std::stringstream ErrorStream;
41 for (CompilationDatabasePluginRegistry::iterator
42 It = CompilationDatabasePluginRegistry::begin(),
43 Ie = CompilationDatabasePluginRegistry::end();
44 It != Ie; ++It) {
45 std::string DatabaseErrorMessage;
Stephen Hines651f13c2014-04-23 16:59:28 -070046 std::unique_ptr<CompilationDatabasePlugin> Plugin(It->instantiate());
Daniel Jasper7fd90b02012-08-24 05:50:27 +000047 if (CompilationDatabase *DB =
48 Plugin->loadFromDirectory(BuildDirectory, DatabaseErrorMessage))
49 return DB;
50 else
51 ErrorStream << It->getName() << ": " << DatabaseErrorMessage << "\n";
Manuel Klimekcb971c62012-04-04 12:07:46 +000052 }
Daniel Jasper7fd90b02012-08-24 05:50:27 +000053 ErrorMessage = ErrorStream.str();
54 return NULL;
Manuel Klimekcb971c62012-04-04 12:07:46 +000055}
56
Arnaud A. de Grandmaison4187df52012-07-10 16:56:35 +000057static CompilationDatabase *
Daniel Jasper7fd90b02012-08-24 05:50:27 +000058findCompilationDatabaseFromDirectory(StringRef Directory,
59 std::string &ErrorMessage) {
60 std::stringstream ErrorStream;
Daniel Jasper3d210782012-10-15 13:12:24 +000061 bool HasErrorMessage = false;
Arnaud A. de Grandmaison4187df52012-07-10 16:56:35 +000062 while (!Directory.empty()) {
63 std::string LoadErrorMessage;
64
65 if (CompilationDatabase *DB =
66 CompilationDatabase::loadFromDirectory(Directory, LoadErrorMessage))
67 return DB;
Daniel Jasper3d210782012-10-15 13:12:24 +000068
69 if (!HasErrorMessage) {
70 ErrorStream << "No compilation database found in " << Directory.str()
71 << " or any parent directory\n" << LoadErrorMessage;
72 HasErrorMessage = true;
73 }
Arnaud A. de Grandmaison4187df52012-07-10 16:56:35 +000074
75 Directory = llvm::sys::path::parent_path(Directory);
76 }
Daniel Jasper7fd90b02012-08-24 05:50:27 +000077 ErrorMessage = ErrorStream.str();
Arnaud A. de Grandmaison4187df52012-07-10 16:56:35 +000078 return NULL;
79}
80
Manuel Klimek8fa2fb82012-07-10 13:10:51 +000081CompilationDatabase *
82CompilationDatabase::autoDetectFromSource(StringRef SourceFile,
83 std::string &ErrorMessage) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000084 SmallString<1024> AbsolutePath(getAbsolutePath(SourceFile));
Manuel Klimek8fa2fb82012-07-10 13:10:51 +000085 StringRef Directory = llvm::sys::path::parent_path(AbsolutePath);
Arnaud A. de Grandmaison4187df52012-07-10 16:56:35 +000086
Daniel Jasper7fd90b02012-08-24 05:50:27 +000087 CompilationDatabase *DB = findCompilationDatabaseFromDirectory(Directory,
88 ErrorMessage);
Arnaud A. de Grandmaison4187df52012-07-10 16:56:35 +000089
90 if (!DB)
91 ErrorMessage = ("Could not auto-detect compilation database for file \"" +
Daniel Jasper7fd90b02012-08-24 05:50:27 +000092 SourceFile + "\"\n" + ErrorMessage).str();
Arnaud A. de Grandmaison4187df52012-07-10 16:56:35 +000093 return DB;
94}
95
96CompilationDatabase *
97CompilationDatabase::autoDetectFromDirectory(StringRef SourceDir,
98 std::string &ErrorMessage) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000099 SmallString<1024> AbsolutePath(getAbsolutePath(SourceDir));
Arnaud A. de Grandmaison4187df52012-07-10 16:56:35 +0000100
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000101 CompilationDatabase *DB = findCompilationDatabaseFromDirectory(AbsolutePath,
102 ErrorMessage);
Arnaud A. de Grandmaison4187df52012-07-10 16:56:35 +0000103
104 if (!DB)
105 ErrorMessage = ("Could not auto-detect compilation database from directory \"" +
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000106 SourceDir + "\"\n" + ErrorMessage).str();
Arnaud A. de Grandmaison4187df52012-07-10 16:56:35 +0000107 return DB;
Manuel Klimek8fa2fb82012-07-10 13:10:51 +0000108}
109
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000110CompilationDatabasePlugin::~CompilationDatabasePlugin() {}
111
Edwin Vanec8f03422013-11-17 16:08:04 +0000112// Helper for recursively searching through a chain of actions and collecting
113// all inputs, direct and indirect, of compile jobs.
114struct CompileJobAnalyzer {
115 void run(const driver::Action *A) {
116 runImpl(A, false);
117 }
118
119 SmallVector<std::string, 2> Inputs;
120
121private:
122
123 void runImpl(const driver::Action *A, bool Collect) {
124 bool CollectChildren = Collect;
125 switch (A->getKind()) {
126 case driver::Action::CompileJobClass:
127 CollectChildren = true;
128 break;
129
130 case driver::Action::InputClass: {
131 if (Collect) {
132 const driver::InputAction *IA = cast<driver::InputAction>(A);
133 Inputs.push_back(IA->getInputArg().getSpelling());
134 }
135 } break;
136
137 default:
138 // Don't care about others
139 ;
140 }
141
142 for (driver::ActionList::const_iterator I = A->begin(), E = A->end();
143 I != E; ++I)
144 runImpl(*I, CollectChildren);
145 }
146};
147
148// Special DiagnosticConsumer that looks for warn_drv_input_file_unused
149// diagnostics from the driver and collects the option strings for those unused
150// options.
151class UnusedInputDiagConsumer : public DiagnosticConsumer {
152public:
153 UnusedInputDiagConsumer() : Other(0) {}
154
155 // Useful for debugging, chain diagnostics to another consumer after
156 // recording for our own purposes.
157 UnusedInputDiagConsumer(DiagnosticConsumer *Other) : Other(Other) {}
158
159 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
Stephen Hines651f13c2014-04-23 16:59:28 -0700160 const Diagnostic &Info) override {
Edwin Vanec8f03422013-11-17 16:08:04 +0000161 if (Info.getID() == clang::diag::warn_drv_input_file_unused) {
162 // Arg 1 for this diagnostic is the option that didn't get used.
163 UnusedInputs.push_back(Info.getArgStdStr(0));
164 }
165 if (Other)
166 Other->HandleDiagnostic(DiagLevel, Info);
167 }
168
169 DiagnosticConsumer *Other;
170 SmallVector<std::string, 2> UnusedInputs;
171};
172
173// Unary functor for asking "Given a StringRef S1, does there exist a string
174// S2 in Arr where S1 == S2?"
175struct MatchesAny {
176 MatchesAny(ArrayRef<std::string> Arr) : Arr(Arr) {}
177 bool operator() (StringRef S) {
178 for (const std::string *I = Arr.begin(), *E = Arr.end(); I != E; ++I)
179 if (*I == S)
180 return true;
181 return false;
182 }
183private:
184 ArrayRef<std::string> Arr;
185};
186
187/// \brief Strips any positional args and possible argv[0] from a command-line
188/// provided by the user to construct a FixedCompilationDatabase.
189///
190/// FixedCompilationDatabase requires a command line to be in this format as it
191/// constructs the command line for each file by appending the name of the file
192/// to be compiled. FixedCompilationDatabase also adds its own argv[0] to the
193/// start of the command line although its value is not important as it's just
194/// ignored by the Driver invoked by the ClangTool using the
195/// FixedCompilationDatabase.
196///
197/// FIXME: This functionality should probably be made available by
198/// clang::driver::Driver although what the interface should look like is not
199/// clear.
200///
201/// \param[in] Args Args as provided by the user.
NAKAMURA Takumif2e479e2013-11-17 18:05:49 +0000202/// \return Resulting stripped command line.
203/// \li true if successful.
Edwin Vanec8f03422013-11-17 16:08:04 +0000204/// \li false if \c Args cannot be used for compilation jobs (e.g.
205/// contains an option like -E or -version).
Stephen Hines651f13c2014-04-23 16:59:28 -0700206static bool stripPositionalArgs(std::vector<const char *> Args,
207 std::vector<std::string> &Result) {
Edwin Vanec8f03422013-11-17 16:08:04 +0000208 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
209 UnusedInputDiagConsumer DiagClient;
210 DiagnosticsEngine Diagnostics(
211 IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()),
212 &*DiagOpts, &DiagClient, false);
213
214 // Neither clang executable nor default image name are required since the
215 // jobs the driver builds will not be executed.
Stephen Hines651f13c2014-04-23 16:59:28 -0700216 std::unique_ptr<driver::Driver> NewDriver(new driver::Driver(
Edwin Vanec8f03422013-11-17 16:08:04 +0000217 /* ClangExecutable= */ "", llvm::sys::getDefaultTargetTriple(),
218 /* DefaultImageName= */ "", Diagnostics));
219 NewDriver->setCheckInputsExist(false);
220
221 // This becomes the new argv[0]. The value is actually not important as it
222 // isn't used for invoking Tools.
223 Args.insert(Args.begin(), "clang-tool");
224
225 // By adding -c, we force the driver to treat compilation as the last phase.
226 // It will then issue warnings via Diagnostics about un-used options that
227 // would have been used for linking. If the user provided a compiler name as
228 // the original argv[0], this will be treated as a linker input thanks to
229 // insertng a new argv[0] above. All un-used options get collected by
230 // UnusedInputdiagConsumer and get stripped out later.
231 Args.push_back("-c");
232
233 // Put a dummy C++ file on to ensure there's at least one compile job for the
234 // driver to construct. If the user specified some other argument that
235 // prevents compilation, e.g. -E or something like -version, we may still end
236 // up with no jobs but then this is the user's fault.
237 Args.push_back("placeholder.cpp");
238
Stephen Hines651f13c2014-04-23 16:59:28 -0700239 // Remove -no-integrated-as; it's not used for syntax checking,
240 // and it confuses targets which don't support this option.
241 std::remove_if(Args.begin(), Args.end(),
242 MatchesAny(std::string("-no-integrated-as")));
243
244 const std::unique_ptr<driver::Compilation> Compilation(
Edwin Vanec8f03422013-11-17 16:08:04 +0000245 NewDriver->BuildCompilation(Args));
246
247 const driver::JobList &Jobs = Compilation->getJobs();
248
249 CompileJobAnalyzer CompileAnalyzer;
250
251 for (driver::JobList::const_iterator I = Jobs.begin(), E = Jobs.end(); I != E;
252 ++I) {
253 if ((*I)->getKind() == driver::Job::CommandClass) {
254 const driver::Command *Cmd = cast<driver::Command>(*I);
255 // Collect only for Assemble jobs. If we do all jobs we get duplicates
256 // since Link jobs point to Assemble jobs as inputs.
257 if (Cmd->getSource().getKind() == driver::Action::AssembleJobClass)
258 CompileAnalyzer.run(&Cmd->getSource());
259 }
260 }
261
262 if (CompileAnalyzer.Inputs.empty()) {
263 // No compile jobs found.
264 // FIXME: Emit a warning of some kind?
265 return false;
266 }
267
268 // Remove all compilation input files from the command line. This is
269 // necessary so that getCompileCommands() can construct a command line for
270 // each file.
271 std::vector<const char *>::iterator End = std::remove_if(
272 Args.begin(), Args.end(), MatchesAny(CompileAnalyzer.Inputs));
273
274 // Remove all inputs deemed unused for compilation.
275 End = std::remove_if(Args.begin(), End, MatchesAny(DiagClient.UnusedInputs));
276
277 // Remove the -c add above as well. It will be at the end right now.
Stephen Hines651f13c2014-04-23 16:59:28 -0700278 assert(strcmp(*(End - 1), "-c") == 0);
Edwin Vanec8f03422013-11-17 16:08:04 +0000279 --End;
280
281 Result = std::vector<std::string>(Args.begin() + 1, End);
282 return true;
283}
284
Manuel Klimek30318e62012-04-18 07:41:50 +0000285FixedCompilationDatabase *
286FixedCompilationDatabase::loadFromCommandLine(int &Argc,
287 const char **Argv,
288 Twine Directory) {
289 const char **DoubleDash = std::find(Argv, Argv + Argc, StringRef("--"));
290 if (DoubleDash == Argv + Argc)
291 return NULL;
Edwin Vanec8f03422013-11-17 16:08:04 +0000292 std::vector<const char *> CommandLine(DoubleDash + 1, Argv + Argc);
Manuel Klimek30318e62012-04-18 07:41:50 +0000293 Argc = DoubleDash - Argv;
Edwin Vanec8f03422013-11-17 16:08:04 +0000294
295 std::vector<std::string> StrippedArgs;
296 if (!stripPositionalArgs(CommandLine, StrippedArgs))
297 return 0;
298 return new FixedCompilationDatabase(Directory, StrippedArgs);
Manuel Klimek30318e62012-04-18 07:41:50 +0000299}
300
301FixedCompilationDatabase::
302FixedCompilationDatabase(Twine Directory, ArrayRef<std::string> CommandLine) {
303 std::vector<std::string> ToolCommandLine(1, "clang-tool");
304 ToolCommandLine.insert(ToolCommandLine.end(),
305 CommandLine.begin(), CommandLine.end());
Stephen Hines651f13c2014-04-23 16:59:28 -0700306 CompileCommands.push_back(
307 CompileCommand(Directory, std::move(ToolCommandLine)));
Manuel Klimek30318e62012-04-18 07:41:50 +0000308}
309
310std::vector<CompileCommand>
311FixedCompilationDatabase::getCompileCommands(StringRef FilePath) const {
312 std::vector<CompileCommand> Result(CompileCommands);
313 Result[0].CommandLine.push_back(FilePath);
314 return Result;
315}
316
Manuel Klimeka3c70962012-07-13 12:31:45 +0000317std::vector<std::string>
318FixedCompilationDatabase::getAllFiles() const {
319 return std::vector<std::string>();
320}
321
Argyrios Kyrtzidis7e96bfb2012-12-04 07:26:44 +0000322std::vector<CompileCommand>
323FixedCompilationDatabase::getAllCompileCommands() const {
324 return std::vector<CompileCommand>();
325}
326
Daniel Jasper7fd90b02012-08-24 05:50:27 +0000327// This anchor is used to force the linker to link in the generated object file
328// and thus register the JSONCompilationDatabasePlugin.
329extern volatile int JSONAnchorSource;
330static int JSONAnchorDest = JSONAnchorSource;
Manuel Klimekcb971c62012-04-04 12:07:46 +0000331
332} // end namespace tooling
333} // end namespace clang