1 //===- Tooling.cpp - Running clang standalone tools -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements functions to run clang tools standalone instead
11 // of running them as a plugin.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Tooling/Tooling.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/DiagnosticIDs.h"
18 #include "clang/Basic/DiagnosticOptions.h"
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Basic/FileSystemOptions.h"
21 #include "clang/Basic/LLVM.h"
22 #include "clang/Driver/Compilation.h"
23 #include "clang/Driver/Driver.h"
24 #include "clang/Driver/Job.h"
25 #include "clang/Driver/Options.h"
26 #include "clang/Driver/Tool.h"
27 #include "clang/Driver/ToolChain.h"
28 #include "clang/Frontend/ASTUnit.h"
29 #include "clang/Frontend/CompilerInstance.h"
30 #include "clang/Frontend/CompilerInvocation.h"
31 #include "clang/Frontend/FrontendDiagnostic.h"
32 #include "clang/Frontend/FrontendOptions.h"
33 #include "clang/Frontend/TextDiagnosticPrinter.h"
34 #include "clang/Lex/HeaderSearchOptions.h"
35 #include "clang/Lex/PreprocessorOptions.h"
36 #include "clang/Tooling/ArgumentsAdjusters.h"
37 #include "clang/Tooling/CompilationDatabase.h"
38 #include "llvm/ADT/ArrayRef.h"
39 #include "llvm/ADT/IntrusiveRefCntPtr.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/ADT/Twine.h"
43 #include "llvm/Option/ArgList.h"
44 #include "llvm/Option/OptTable.h"
45 #include "llvm/Option/Option.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/FileSystem.h"
50 #include "llvm/Support/Host.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/Path.h"
53 #include "llvm/Support/VirtualFileSystem.h"
54 #include "llvm/Support/raw_ostream.h"
59 #include <system_error>
63 #define DEBUG_TYPE "clang-tooling"
65 using namespace clang;
66 using namespace tooling;
68 ToolAction::~ToolAction() = default;
70 FrontendActionFactory::~FrontendActionFactory() = default;
72 // FIXME: This file contains structural duplication with other parts of the
73 // code that sets up a compiler to run tools on it, and we should refactor
74 // it to be based on the same framework.
76 /// Builds a clang driver initialized for running clang tools.
77 static driver::Driver *
78 newDriver(DiagnosticsEngine *Diagnostics, const char *BinaryName,
79 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
80 driver::Driver *CompilerDriver =
81 new driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(),
82 *Diagnostics, std::move(VFS));
83 CompilerDriver->setTitle("clang_based_tool");
84 return CompilerDriver;
87 /// Retrieves the clang CC1 specific flags out of the compilation's jobs.
89 /// Returns nullptr on error.
90 static const llvm::opt::ArgStringList *getCC1Arguments(
91 DiagnosticsEngine *Diagnostics, driver::Compilation *Compilation) {
92 // We expect to get back exactly one Command job, if we didn't something
93 // failed. Extract that job from the Compilation.
94 const driver::JobList &Jobs = Compilation->getJobs();
95 if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) {
96 SmallString<256> error_msg;
97 llvm::raw_svector_ostream error_stream(error_msg);
98 Jobs.Print(error_stream, "; ", true);
99 Diagnostics->Report(diag::err_fe_expected_compiler_job)
100 << error_stream.str();
104 // The one job we find should be to invoke clang again.
105 const auto &Cmd = cast<driver::Command>(*Jobs.begin());
106 if (StringRef(Cmd.getCreator().getName()) != "clang") {
107 Diagnostics->Report(diag::err_fe_expected_clang_command);
111 return &Cmd.getArguments();
117 /// Returns a clang build invocation initialized from the CC1 flags.
118 CompilerInvocation *newInvocation(
119 DiagnosticsEngine *Diagnostics, const llvm::opt::ArgStringList &CC1Args) {
120 assert(!CC1Args.empty() && "Must at least contain the program name!");
121 CompilerInvocation *Invocation = new CompilerInvocation;
122 CompilerInvocation::CreateFromArgs(
123 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(),
125 Invocation->getFrontendOpts().DisableFree = false;
126 Invocation->getCodeGenOpts().DisableFree = false;
130 bool runToolOnCode(FrontendAction *ToolAction, const Twine &Code,
131 const Twine &FileName,
132 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
133 return runToolOnCodeWithArgs(ToolAction, Code, std::vector<std::string>(),
134 FileName, "clang-tool",
135 std::move(PCHContainerOps));
138 } // namespace tooling
141 static std::vector<std::string>
142 getSyntaxOnlyToolArgs(const Twine &ToolName,
143 const std::vector<std::string> &ExtraArgs,
144 StringRef FileName) {
145 std::vector<std::string> Args;
146 Args.push_back(ToolName.str());
147 Args.push_back("-fsyntax-only");
148 Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
149 Args.push_back(FileName.str());
156 bool runToolOnCodeWithArgs(
157 FrontendAction *ToolAction, const Twine &Code,
158 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
159 const std::vector<std::string> &Args, const Twine &FileName,
160 const Twine &ToolName,
161 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
162 SmallString<16> FileNameStorage;
163 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
165 llvm::IntrusiveRefCntPtr<FileManager> Files(
166 new FileManager(FileSystemOptions(), VFS));
167 ArgumentsAdjuster Adjuster = getClangStripDependencyFileAdjuster();
168 ToolInvocation Invocation(
169 getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef),
170 ToolAction, Files.get(),
171 std::move(PCHContainerOps));
172 return Invocation.run();
175 bool runToolOnCodeWithArgs(
176 FrontendAction *ToolAction, const Twine &Code,
177 const std::vector<std::string> &Args, const Twine &FileName,
178 const Twine &ToolName,
179 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
180 const FileContentMappings &VirtualMappedFiles) {
181 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem(
182 new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
183 llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
184 new llvm::vfs::InMemoryFileSystem);
185 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
187 SmallString<1024> CodeStorage;
188 InMemoryFileSystem->addFile(FileName, 0,
189 llvm::MemoryBuffer::getMemBuffer(
190 Code.toNullTerminatedStringRef(CodeStorage)));
192 for (auto &FilenameWithContent : VirtualMappedFiles) {
193 InMemoryFileSystem->addFile(
194 FilenameWithContent.first, 0,
195 llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
198 return runToolOnCodeWithArgs(ToolAction, Code, OverlayFileSystem, Args,
202 llvm::Expected<std::string> getAbsolutePath(llvm::vfs::FileSystem &FS,
204 StringRef RelativePath(File);
205 // FIXME: Should '.\\' be accepted on Win32?
206 if (RelativePath.startswith("./")) {
207 RelativePath = RelativePath.substr(strlen("./"));
210 SmallString<1024> AbsolutePath = RelativePath;
211 if (auto EC = FS.makeAbsolute(AbsolutePath))
212 return llvm::errorCodeToError(EC);
213 llvm::sys::path::native(AbsolutePath);
214 return AbsolutePath.str();
217 std::string getAbsolutePath(StringRef File) {
218 return llvm::cantFail(getAbsolutePath(*llvm::vfs::getRealFileSystem(), File));
221 void addTargetAndModeForProgramName(std::vector<std::string> &CommandLine,
222 StringRef InvokedAs) {
223 if (!CommandLine.empty() && !InvokedAs.empty()) {
224 bool AlreadyHasTarget = false;
225 bool AlreadyHasMode = false;
226 // Skip CommandLine[0].
227 for (auto Token = ++CommandLine.begin(); Token != CommandLine.end();
229 StringRef TokenRef(*Token);
231 (TokenRef == "-target" || TokenRef.startswith("-target="));
232 AlreadyHasMode |= (TokenRef == "--driver-mode" ||
233 TokenRef.startswith("--driver-mode="));
236 driver::ToolChain::getTargetAndModeFromProgramName(InvokedAs);
237 if (!AlreadyHasMode && TargetMode.DriverMode) {
238 CommandLine.insert(++CommandLine.begin(), TargetMode.DriverMode);
240 if (!AlreadyHasTarget && TargetMode.TargetIsValid) {
241 CommandLine.insert(++CommandLine.begin(), {"-target",
242 TargetMode.TargetPrefix});
247 } // namespace tooling
252 class SingleFrontendActionFactory : public FrontendActionFactory {
253 FrontendAction *Action;
256 SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
258 FrontendAction *create() override { return Action; }
263 ToolInvocation::ToolInvocation(
264 std::vector<std::string> CommandLine, ToolAction *Action,
265 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
266 : CommandLine(std::move(CommandLine)), Action(Action), OwnsAction(false),
267 Files(Files), PCHContainerOps(std::move(PCHContainerOps)) {}
269 ToolInvocation::ToolInvocation(
270 std::vector<std::string> CommandLine, FrontendAction *FAction,
271 FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps)
272 : CommandLine(std::move(CommandLine)),
273 Action(new SingleFrontendActionFactory(FAction)), OwnsAction(true),
274 Files(Files), PCHContainerOps(std::move(PCHContainerOps)) {}
276 ToolInvocation::~ToolInvocation() {
281 void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) {
282 SmallString<1024> PathStorage;
283 llvm::sys::path::native(FilePath, PathStorage);
284 MappedFileContents[PathStorage] = Content;
287 bool ToolInvocation::run() {
288 std::vector<const char*> Argv;
289 for (const std::string &Str : CommandLine)
290 Argv.push_back(Str.c_str());
291 const char *const BinaryName = Argv[0];
292 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
293 unsigned MissingArgIndex, MissingArgCount;
294 std::unique_ptr<llvm::opt::OptTable> Opts = driver::createDriverOptTable();
295 llvm::opt::InputArgList ParsedArgs = Opts->ParseArgs(
296 ArrayRef<const char *>(Argv).slice(1), MissingArgIndex, MissingArgCount);
297 ParseDiagnosticArgs(*DiagOpts, ParsedArgs);
298 TextDiagnosticPrinter DiagnosticPrinter(
299 llvm::errs(), &*DiagOpts);
300 DiagnosticsEngine Diagnostics(
301 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
302 DiagConsumer ? DiagConsumer : &DiagnosticPrinter, false);
304 const std::unique_ptr<driver::Driver> Driver(
305 newDriver(&Diagnostics, BinaryName, Files->getVirtualFileSystem()));
306 // The "input file not found" diagnostics from the driver are useful.
307 // The driver is only aware of the VFS working directory, but some clients
308 // change this at the FileManager level instead.
309 // In this case the checks have false positives, so skip them.
310 if (!Files->getFileSystemOpts().WorkingDir.empty())
311 Driver->setCheckInputsExist(false);
312 const std::unique_ptr<driver::Compilation> Compilation(
313 Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
316 const llvm::opt::ArgStringList *const CC1Args = getCC1Arguments(
317 &Diagnostics, Compilation.get());
320 std::unique_ptr<CompilerInvocation> Invocation(
321 newInvocation(&Diagnostics, *CC1Args));
322 // FIXME: remove this when all users have migrated!
323 for (const auto &It : MappedFileContents) {
324 // Inject the code as the given file name into the preprocessor options.
325 std::unique_ptr<llvm::MemoryBuffer> Input =
326 llvm::MemoryBuffer::getMemBuffer(It.getValue());
327 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
330 return runInvocation(BinaryName, Compilation.get(), std::move(Invocation),
331 std::move(PCHContainerOps));
334 bool ToolInvocation::runInvocation(
335 const char *BinaryName, driver::Compilation *Compilation,
336 std::shared_ptr<CompilerInvocation> Invocation,
337 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
338 // Show the invocation, with -v.
339 if (Invocation->getHeaderSearchOpts().Verbose) {
340 llvm::errs() << "clang Invocation:\n";
341 Compilation->getJobs().Print(llvm::errs(), "\n", true);
342 llvm::errs() << "\n";
345 return Action->runInvocation(std::move(Invocation), Files,
346 std::move(PCHContainerOps), DiagConsumer);
349 bool FrontendActionFactory::runInvocation(
350 std::shared_ptr<CompilerInvocation> Invocation, FileManager *Files,
351 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
352 DiagnosticConsumer *DiagConsumer) {
353 // Create a compiler instance to handle the actual work.
354 CompilerInstance Compiler(std::move(PCHContainerOps));
355 Compiler.setInvocation(std::move(Invocation));
356 Compiler.setFileManager(Files);
358 // The FrontendAction can have lifetime requirements for Compiler or its
359 // members, and we need to ensure it's deleted earlier than Compiler. So we
360 // pass it to an std::unique_ptr declared after the Compiler variable.
361 std::unique_ptr<FrontendAction> ScopedToolAction(create());
363 // Create the compiler's actual diagnostics engine.
364 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
365 if (!Compiler.hasDiagnostics())
368 Compiler.createSourceManager(*Files);
370 const bool Success = Compiler.ExecuteAction(*ScopedToolAction);
372 Files->clearStatCache();
376 ClangTool::ClangTool(const CompilationDatabase &Compilations,
377 ArrayRef<std::string> SourcePaths,
378 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
379 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS)
380 : Compilations(Compilations), SourcePaths(SourcePaths),
381 PCHContainerOps(std::move(PCHContainerOps)),
382 OverlayFileSystem(new llvm::vfs::OverlayFileSystem(std::move(BaseFS))),
383 InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem),
384 Files(new FileManager(FileSystemOptions(), OverlayFileSystem)) {
385 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
386 appendArgumentsAdjuster(getClangStripOutputAdjuster());
387 appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
388 appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
391 ClangTool::~ClangTool() = default;
393 void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) {
394 MappedFileContents.push_back(std::make_pair(FilePath, Content));
397 void ClangTool::appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) {
398 ArgsAdjuster = combineAdjusters(std::move(ArgsAdjuster), std::move(Adjuster));
401 void ClangTool::clearArgumentsAdjusters() {
402 ArgsAdjuster = nullptr;
405 static void injectResourceDir(CommandLineArguments &Args, const char *Argv0,
407 // Allow users to override the resource dir.
408 for (StringRef Arg : Args)
409 if (Arg.startswith("-resource-dir"))
412 // If there's no override in place add our resource dir.
413 Args.push_back("-resource-dir=" +
414 CompilerInvocation::GetResourcesPath(Argv0, MainAddr));
417 int ClangTool::run(ToolAction *Action) {
418 // Exists solely for the purpose of lookup of the resource path.
419 // This just needs to be some symbol in the binary.
420 static int StaticSymbol;
422 // First insert all absolute paths into the in-memory VFS. These are global
423 // for all compile commands.
424 if (SeenWorkingDirectories.insert("/").second)
425 for (const auto &MappedFile : MappedFileContents)
426 if (llvm::sys::path::is_absolute(MappedFile.first))
427 InMemoryFileSystem->addFile(
429 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
431 bool ProcessingFailed = false;
432 bool FileSkipped = false;
433 // Compute all absolute paths before we run any actions, as those will change
434 // the working directory.
435 std::vector<std::string> AbsolutePaths;
436 AbsolutePaths.reserve(SourcePaths.size());
437 for (const auto &SourcePath : SourcePaths) {
438 auto AbsPath = getAbsolutePath(*OverlayFileSystem, SourcePath);
440 llvm::errs() << "Skipping " << SourcePath
441 << ". Error while getting an absolute path: "
442 << llvm::toString(AbsPath.takeError()) << "\n";
445 AbsolutePaths.push_back(std::move(*AbsPath));
448 // Remember the working directory in case we need to restore it.
449 std::string InitialWorkingDir;
451 if (auto CWD = OverlayFileSystem->getCurrentWorkingDirectory()) {
452 InitialWorkingDir = std::move(*CWD);
454 llvm::errs() << "Could not get working directory: "
455 << CWD.getError().message() << "\n";
459 for (llvm::StringRef File : AbsolutePaths) {
460 // Currently implementations of CompilationDatabase::getCompileCommands can
461 // change the state of the file system (e.g. prepare generated headers), so
462 // this method needs to run right before we invoke the tool, as the next
463 // file may require a different (incompatible) state of the file system.
465 // FIXME: Make the compilation database interface more explicit about the
466 // requirements to the order of invocation of its members.
467 std::vector<CompileCommand> CompileCommandsForFile =
468 Compilations.getCompileCommands(File);
469 if (CompileCommandsForFile.empty()) {
470 llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
474 for (CompileCommand &CompileCommand : CompileCommandsForFile) {
475 // FIXME: chdir is thread hostile; on the other hand, creating the same
476 // behavior as chdir is complex: chdir resolves the path once, thus
477 // guaranteeing that all subsequent relative path operations work
478 // on the same path the original chdir resulted in. This makes a
479 // difference for example on network filesystems, where symlinks might be
480 // switched during runtime of the tool. Fixing this depends on having a
481 // file system abstraction that allows openat() style interactions.
482 if (OverlayFileSystem->setCurrentWorkingDirectory(
483 CompileCommand.Directory))
484 llvm::report_fatal_error("Cannot chdir into \"" +
485 Twine(CompileCommand.Directory) + "\n!");
487 // Now fill the in-memory VFS with the relative file mappings so it will
488 // have the correct relative paths. We never remove mappings but that
490 if (SeenWorkingDirectories.insert(CompileCommand.Directory).second)
491 for (const auto &MappedFile : MappedFileContents)
492 if (!llvm::sys::path::is_absolute(MappedFile.first))
493 InMemoryFileSystem->addFile(
495 llvm::MemoryBuffer::getMemBuffer(MappedFile.second));
497 std::vector<std::string> CommandLine = CompileCommand.CommandLine;
499 CommandLine = ArgsAdjuster(CommandLine, CompileCommand.Filename);
500 assert(!CommandLine.empty());
502 // Add the resource dir based on the binary of this tool. argv[0] in the
503 // compilation database may refer to a different compiler and we want to
504 // pick up the very same standard library that compiler is using. The
505 // builtin headers in the resource dir need to match the exact clang
506 // version the tool is using.
507 // FIXME: On linux, GetMainExecutable is independent of the value of the
508 // first argument, thus allowing ClangTool and runToolOnCode to just
509 // pass in made-up names here. Make sure this works on other platforms.
510 injectResourceDir(CommandLine, "clang_tool", &StaticSymbol);
512 // FIXME: We need a callback mechanism for the tool writer to output a
513 // customized message for each file.
514 LLVM_DEBUG({ llvm::dbgs() << "Processing: " << File << ".\n"; });
515 ToolInvocation Invocation(std::move(CommandLine), Action, Files.get(),
517 Invocation.setDiagnosticConsumer(DiagConsumer);
519 if (!Invocation.run()) {
520 // FIXME: Diagnostics should be used instead.
521 llvm::errs() << "Error while processing " << File << ".\n";
522 ProcessingFailed = true;
527 if (!InitialWorkingDir.empty()) {
529 OverlayFileSystem->setCurrentWorkingDirectory(InitialWorkingDir))
530 llvm::errs() << "Error when trying to restore working dir: "
531 << EC.message() << "\n";
533 return ProcessingFailed ? 1 : (FileSkipped ? 2 : 0);
538 class ASTBuilderAction : public ToolAction {
539 std::vector<std::unique_ptr<ASTUnit>> &ASTs;
542 ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
544 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
546 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
547 DiagnosticConsumer *DiagConsumer) override {
548 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
549 Invocation, std::move(PCHContainerOps),
550 CompilerInstance::createDiagnostics(&Invocation->getDiagnosticOpts(),
552 /*ShouldOwnClient=*/false),
557 ASTs.push_back(std::move(AST));
564 int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
565 ASTBuilderAction Action(ASTs);
569 void ClangTool::setRestoreWorkingDir(bool RestoreCWD) {
570 this->RestoreCWD = RestoreCWD;
576 std::unique_ptr<ASTUnit>
577 buildASTFromCode(StringRef Code, StringRef FileName,
578 std::shared_ptr<PCHContainerOperations> PCHContainerOps) {
579 return buildASTFromCodeWithArgs(Code, std::vector<std::string>(), FileName,
580 "clang-tool", std::move(PCHContainerOps));
583 std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
584 StringRef Code, const std::vector<std::string> &Args, StringRef FileName,
585 StringRef ToolName, std::shared_ptr<PCHContainerOperations> PCHContainerOps,
586 ArgumentsAdjuster Adjuster) {
587 std::vector<std::unique_ptr<ASTUnit>> ASTs;
588 ASTBuilderAction Action(ASTs);
589 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem(
590 new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
591 llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
592 new llvm::vfs::InMemoryFileSystem);
593 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
594 llvm::IntrusiveRefCntPtr<FileManager> Files(
595 new FileManager(FileSystemOptions(), OverlayFileSystem));
597 ToolInvocation Invocation(
598 getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileName), FileName),
599 &Action, Files.get(), std::move(PCHContainerOps));
601 InMemoryFileSystem->addFile(FileName, 0,
602 llvm::MemoryBuffer::getMemBufferCopy(Code));
603 if (!Invocation.run())
606 assert(ASTs.size() == 1);
607 return std::move(ASTs[0]);
610 } // namespace tooling