clang 23.0.0git
DependencyScanningTool.cpp
Go to the documentation of this file.
1//===- DependencyScanningTool.cpp - clang-scan-deps service ---------------===//
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
14#include "clang/Driver/Driver.h"
15#include "clang/Driver/Tool.h"
19#include "llvm/ADT/ScopeExit.h"
20#include "llvm/ADT/SmallVectorExtras.h"
21#include "llvm/ADT/iterator.h"
22#include "llvm/TargetParser/Host.h"
23#include <optional>
24
25using namespace clang;
26using namespace tooling;
27using namespace dependencies;
28
29namespace {
30/// Prints out all of the gathered dependencies into a string.
31class MakeDependencyPrinterConsumer : public DependencyConsumer {
32public:
33 void handleBuildCommand(Command) override {}
34
35 void
36 handleDependencyOutputOpts(const DependencyOutputOptions &Opts) override {
37 this->Opts = std::make_unique<DependencyOutputOptions>(Opts);
38 }
39
40 void handleFileDependency(StringRef File) override {
41 SmallString<128> NormalizedFile = File;
42 llvm::sys::path::remove_dots(NormalizedFile, /*remove_dot_dot=*/true);
43 Dependencies.emplace_back(NormalizedFile.str());
44 }
45
46 // These are ignored for the make format as it can't support the full
47 // set of deps, and handleFileDependency handles enough for implicitly
48 // built modules to work.
49 void handlePrebuiltModuleDependency(PrebuiltModuleDep PMD) override {}
50 void handleModuleDependency(ModuleDeps MD) override {
51 MD.forEachFileDep([this](StringRef File) {
52 DependenciesFromModules.push_back(std::string(File));
53 });
54 }
55 void handleDirectModuleDependency(ModuleID ID) override {}
56 void handleVisibleModule(std::string ModuleName) override {}
57 void handleContextHash(std::string Hash) override {}
58
59 void printDependencies(std::string &S) {
60 assert(Opts && "Handled dependency output options.");
61
62 class DependencyPrinter : public DependencyFileGenerator {
63 public:
64 DependencyPrinter(DependencyOutputOptions &Opts,
65 ArrayRef<std::string> Dependencies,
66 ArrayRef<std::string> ModuleDependencies)
67 : DependencyFileGenerator(Opts) {
68 for (const auto &Dep : Dependencies)
69 addDependency(Dep);
70 for (const auto &Dep : ModuleDependencies)
71 addDependency(Dep);
72 }
73
74 void printDependencies(std::string &S) {
75 llvm::raw_string_ostream OS(S);
76 outputDependencyFile(OS);
77 }
78 };
79
80 DependencyPrinter Generator(*Opts, Dependencies, DependenciesFromModules);
81 Generator.printDependencies(S);
82 }
83
84protected:
85 std::unique_ptr<DependencyOutputOptions> Opts;
86 std::vector<std::string> Dependencies;
87 std::vector<std::string> DependenciesFromModules;
88};
89} // anonymous namespace
90
91static std::pair<std::unique_ptr<driver::Driver>,
92 std::unique_ptr<driver::Compilation>>
95 llvm::BumpPtrAllocator &Alloc) {
97 Argv.reserve(ArgStrs.size());
98 for (const std::string &Arg : ArgStrs)
99 Argv.push_back(Arg.c_str());
100
101 std::unique_ptr<driver::Driver> Driver = std::make_unique<driver::Driver>(
102 Argv[0], llvm::sys::getDefaultTargetTriple(), Diags,
103 "clang LLVM compiler", FS);
104 Driver->setTitle("clang_based_tool");
105
106 bool CLMode = driver::IsClangCL(
107 driver::getDriverMode(Argv[0], ArrayRef(Argv).slice(1)));
108
109 if (llvm::Error E =
110 driver::expandResponseFiles(Argv, CLMode, Alloc, FS.get())) {
111 Diags.Report(diag::err_drv_expand_response_file)
112 << llvm::toString(std::move(E));
113 return std::make_pair(nullptr, nullptr);
114 }
115
116 std::unique_ptr<driver::Compilation> Compilation(
117 Driver->BuildCompilation(Argv));
118 if (!Compilation)
119 return std::make_pair(nullptr, nullptr);
120
121 if (Compilation->containsError())
122 return std::make_pair(nullptr, nullptr);
123
124 if (Compilation->getJobs().empty()) {
125 Diags.Report(diag::err_fe_expected_compiler_job)
126 << llvm::join(ArgStrs, " ");
127 return std::make_pair(nullptr, nullptr);
128 }
129
130 return std::make_pair(std::move(Driver), std::move(Compilation));
131}
132
133/// Constructs the full frontend command line, including executable, for the
134/// given driver \c Cmd.
137 const auto &Args = Cmd.getArguments();
139 Out.reserve(Args.size() + 1);
140 Out.emplace_back(Cmd.getExecutable());
141 llvm::append_range(Out, Args);
142 return Out;
143}
144
146 DependencyScanningWorker &Worker, StringRef WorkingDirectory,
147 ArrayRef<std::string> CommandLine, DependencyConsumer &Consumer,
148 DependencyActionController &Controller, DiagnosticConsumer &DiagConsumer,
151 if (OverlayFS) {
152 FS = OverlayFS;
153 } else {
154 FS = &Worker.getVFS();
155 FS->setCurrentWorkingDirectory(WorkingDirectory);
156 }
157
158 // Compilation holds a non-owning a reference to the Driver, hence we need to
159 // keep the Driver alive when we use Compilation. Arguments to commands may be
160 // owned by Alloc when expanded from response files.
161 llvm::BumpPtrAllocator Alloc;
162 auto DiagEngineWithDiagOpts =
163 DiagnosticsEngineWithDiagOpts(CommandLine, FS, DiagConsumer);
164 const auto [Driver, Compilation] = buildCompilation(
165 CommandLine, *DiagEngineWithDiagOpts.DiagEngine, FS, Alloc);
166 if (!Compilation)
167 return false;
168
169 SmallVector<SmallVector<std::string, 0>> FrontendCommandLines;
170 for (const auto &Cmd : Compilation->getJobs())
171 FrontendCommandLines.push_back(buildCC1CommandLine(Cmd));
172 SmallVector<ArrayRef<std::string>> FrontendCommandLinesView(
173 FrontendCommandLines.begin(), FrontendCommandLines.end());
174
175 return Worker.computeDependencies(WorkingDirectory, FrontendCommandLinesView,
176 Consumer, Controller, DiagConsumer,
177 OverlayFS);
178}
179
180static llvm::Error makeErrorFromDiagnosticsOS(
181 TextDiagnosticsPrinterWithOutput &DiagPrinterWithOS) {
182 return llvm::make_error<llvm::StringError>(
183 DiagPrinterWithOS.DiagnosticsOS.str(), llvm::inconvertibleErrorCode());
184}
185
187 DependencyScanningWorker &Worker, StringRef WorkingDirectory,
188 ArrayRef<std::string> CommandLine, DependencyConsumer &Consumer,
189 DependencyActionController &Controller, DiagnosticConsumer &DiagConsumer,
191 const auto IsCC1Input = (CommandLine.size() >= 2 && CommandLine[1] == "-cc1");
192 return IsCC1Input ? Worker.computeDependencies(WorkingDirectory, CommandLine,
193 Consumer, Controller,
194 DiagConsumer, OverlayFS)
196 Worker, WorkingDirectory, CommandLine, Consumer,
197 Controller, DiagConsumer, OverlayFS);
198}
199
201 ArrayRef<std::string> CommandLine, StringRef CWD,
202 LookupModuleOutputCallback LookupModuleOutput,
203 DiagnosticConsumer &DiagConsumer) {
204 MakeDependencyPrinterConsumer DepConsumer;
205 CallbackActionController Controller(LookupModuleOutput);
206 if (!computeDependencies(Worker, CWD, CommandLine, DepConsumer, Controller,
207 DiagConsumer))
208 return std::nullopt;
209 std::string Output;
210 DepConsumer.printDependencies(Output);
211 return Output;
212}
213
215 const CompileCommand &Command, StringRef CWD, std::string &MakeformatOutput,
216 std::string &MakeformatOutputPath, DiagnosticConsumer &DiagConsumer) {
217 class P1689ModuleDependencyPrinterConsumer
218 : public MakeDependencyPrinterConsumer {
219 public:
220 P1689ModuleDependencyPrinterConsumer(P1689Rule &Rule,
221 const CompileCommand &Command)
222 : Filename(Command.Filename), Rule(Rule) {
223 Rule.PrimaryOutput = Command.Output;
224 }
225
226 void handleProvidedAndRequiredStdCXXModules(
227 std::optional<P1689ModuleInfo> Provided,
228 std::vector<P1689ModuleInfo> Requires) override {
229 Rule.Provides = std::move(Provided);
230 if (Rule.Provides)
231 Rule.Provides->SourcePath = Filename.str();
232 Rule.Requires = std::move(Requires);
233 }
234
235 StringRef getMakeFormatDependencyOutputPath() {
237 return {};
238 return Opts->OutputFile;
239 }
240
241 private:
242 StringRef Filename;
243 P1689Rule &Rule;
244 };
245
246 class P1689ActionController : public DependencyActionController {
247 public:
248 // The lookupModuleOutput is for clang modules. P1689 format don't need it.
249 std::string lookupModuleOutput(const ModuleDeps &,
250 ModuleOutputKind Kind) override {
251 return "";
252 }
253
254 std::unique_ptr<DependencyActionController> clone() const override {
255 return std::make_unique<P1689ActionController>();
256 }
257 };
258
259 P1689Rule Rule;
260 P1689ModuleDependencyPrinterConsumer Consumer(Rule, Command);
261 P1689ActionController Controller;
262 if (!computeDependencies(Worker, CWD, Command.CommandLine, Consumer,
263 Controller, DiagConsumer))
264 return std::nullopt;
265
266 MakeformatOutputPath = Consumer.getMakeFormatDependencyOutputPath();
267 if (!MakeformatOutputPath.empty())
268 Consumer.printDependencies(MakeformatOutput);
269 return Rule;
270}
271
272static std::pair<IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem>,
273 std::vector<std::string>>
275 ArrayRef<std::string> CommandLine,
276 StringRef WorkingDirectory,
277 llvm::MemoryBufferRef TUBuffer) {
278 // Reset what might have been modified in the previous worker invocation.
279 BaseFS->setCurrentWorkingDirectory(WorkingDirectory);
280
281 auto OverlayFS =
282 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(BaseFS);
283 auto InMemoryFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
284 InMemoryFS->setCurrentWorkingDirectory(WorkingDirectory);
285 auto InputPath = TUBuffer.getBufferIdentifier();
286 InMemoryFS->addFile(
287 InputPath, 0, llvm::MemoryBuffer::getMemBufferCopy(TUBuffer.getBuffer()));
288 IntrusiveRefCntPtr<llvm::vfs::FileSystem> InMemoryOverlay = InMemoryFS;
289
290 OverlayFS->pushOverlay(InMemoryOverlay);
291 std::vector<std::string> ModifiedCommandLine(CommandLine);
292 ModifiedCommandLine.emplace_back(InputPath);
293
294 return std::make_pair(OverlayFS, ModifiedCommandLine);
295}
296
297static std::pair<IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem>,
298 std::vector<std::string>>
300 ArrayRef<std::string> CommandLine,
301 StringRef WorkingDirectory) {
302 // Reset what might have been modified in the previous worker invocation.
303 BaseFS->setCurrentWorkingDirectory(WorkingDirectory);
304
305 // If we're scanning based on a module name alone, we don't expect the client
306 // to provide us with an input file. However, the driver really wants to have
307 // one. Let's just make it up to make the driver happy.
308 auto OverlayFS =
309 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(BaseFS);
310 auto InMemoryFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
311 InMemoryFS->setCurrentWorkingDirectory(WorkingDirectory);
312 StringRef FakeInputPath("module-include.input");
313 // The fake input buffer is read-only, and it is used to produce
314 // unique source locations for the diagnostics. Therefore sharing
315 // this global buffer across threads is ok.
316 static const std::string FakeInput(
318 InMemoryFS->addFile(FakeInputPath, 0,
319 llvm::MemoryBuffer::getMemBuffer(FakeInput));
320 IntrusiveRefCntPtr<llvm::vfs::FileSystem> InMemoryOverlay = InMemoryFS;
321 OverlayFS->pushOverlay(InMemoryOverlay);
322
323 std::vector<std::string> ModifiedCommandLine(CommandLine);
324 ModifiedCommandLine.emplace_back(FakeInputPath);
325
326 return std::make_pair(OverlayFS, ModifiedCommandLine);
327}
328
329std::optional<TranslationUnitDeps>
331 ArrayRef<std::string> CommandLine, StringRef CWD,
332 DiagnosticConsumer &DiagConsumer,
333 const llvm::DenseSet<ModuleID> &AlreadySeen,
334 LookupModuleOutputCallback LookupModuleOutput,
335 std::optional<llvm::MemoryBufferRef> TUBuffer) {
336 FullDependencyConsumer Consumer(AlreadySeen);
337 CallbackActionController Controller(LookupModuleOutput);
338
339 // If we are scanning from a TUBuffer, create an overlay filesystem with the
340 // input as an in-memory file and add it to the command line.
342 std::vector<std::string> CommandLineWithTUBufferInput;
343 if (TUBuffer) {
344 std::tie(OverlayFS, CommandLineWithTUBufferInput) =
345 initVFSForTUBufferScanning(&Worker.getVFS(), CommandLine, CWD,
346 *TUBuffer);
347 CommandLine = CommandLineWithTUBufferInput;
348 }
349
350 if (!computeDependencies(Worker, CWD, CommandLine, Consumer, Controller,
351 DiagConsumer, OverlayFS))
352 return std::nullopt;
353 return Consumer.takeTranslationUnitDeps();
354}
355
358 StringRef ModuleName, ArrayRef<std::string> CommandLine, StringRef CWD,
359 const llvm::DenseSet<ModuleID> &AlreadySeen,
360 DependencyActionController &Controller) {
361 auto MaybeCIWithContext = CompilerInstanceWithContext::initializeOrError(
362 *this, CWD, CommandLine, Controller);
363 if (auto Error = MaybeCIWithContext.takeError())
364 return Error;
365
366 return MaybeCIWithContext->computeDependenciesByNameOrError(
367 ModuleName, AlreadySeen, Controller);
368}
369
370static std::optional<SmallVector<std::string, 0>> getFirstCC1CommandLine(
371 ArrayRef<std::string> CommandLine, DiagnosticsEngine &Diags,
373 // Compilation holds a non-owning a reference to the Driver, hence we need to
374 // keep the Driver alive when we use Compilation. Arguments to commands may be
375 // owned by Alloc when expanded from response files.
376 llvm::BumpPtrAllocator Alloc;
377 const auto [Driver, Compilation] =
378 buildCompilation(CommandLine, Diags, OverlayFS, Alloc);
379 if (!Compilation)
380 return std::nullopt;
381
382 const auto IsClangCmd = [](const driver::Command &Cmd) {
383 return StringRef(Cmd.getCreator().getName()) == "clang";
384 };
385
386 const auto &Jobs = Compilation->getJobs();
387 if (const auto It = llvm::find_if(Jobs, IsClangCmd); It != Jobs.end())
388 return buildCC1CommandLine(*It);
389 return std::nullopt;
390}
391
392std::optional<CompilerInstanceWithContext>
394 DependencyScanningTool &Tool, StringRef CWD,
395 ArrayRef<std::string> CommandLine, DependencyActionController &Controller,
396 DiagnosticConsumer &DC) {
397 auto [OverlayFS, ModifiedCommandLine] =
398 initVFSForByNameScanning(&Tool.Worker.getVFS(), CommandLine, CWD);
399 auto DiagEngineWithCmdAndOpts =
400 std::make_unique<DiagnosticsEngineWithDiagOpts>(ModifiedCommandLine,
401 OverlayFS, DC);
402
403 if (CommandLine.size() >= 2 && CommandLine[1] == "-cc1") {
404 // The input command line is already a -cc1 invocation; initialize the
405 // compiler instance directly from it.
406 CompilerInstanceWithContext CIWithContext(Tool.Worker, CWD, CommandLine);
407 if (!CIWithContext.initialize(
408 Controller, std::move(DiagEngineWithCmdAndOpts), OverlayFS))
409 return std::nullopt;
410 return std::move(CIWithContext);
411 }
412
413 // The input command line is either a driver-style command line, or
414 // ill-formed. In this case, we will first call the Driver to build a -cc1
415 // command line for this compilation or diagnose any ill-formed input.
416 const auto MaybeFirstCC1 = getFirstCC1CommandLine(
417 ModifiedCommandLine, *DiagEngineWithCmdAndOpts->DiagEngine, OverlayFS);
418 if (!MaybeFirstCC1)
419 return std::nullopt;
420
421 std::vector<std::string> CC1CommandLine(MaybeFirstCC1->begin(),
422 MaybeFirstCC1->end());
423 CompilerInstanceWithContext CIWithContext(Tool.Worker, CWD,
424 std::move(CC1CommandLine));
425 if (!CIWithContext.initialize(Controller, std::move(DiagEngineWithCmdAndOpts),
426 OverlayFS))
427 return std::nullopt;
428 return std::move(CIWithContext);
429}
430
433 DependencyScanningTool &Tool, StringRef CWD,
434 ArrayRef<std::string> CommandLine, DependencyActionController &Controller) {
435 auto DiagPrinterWithOS =
436 std::make_unique<TextDiagnosticsPrinterWithOutput>(CommandLine);
437
438 auto Result = initializeFromCommandline(Tool, CWD, CommandLine, Controller,
439 DiagPrinterWithOS->DiagPrinter);
440 if (Result) {
441 Result->DiagPrinterWithOS = std::move(DiagPrinterWithOS);
442 return std::move(*Result);
443 }
444 return makeErrorFromDiagnosticsOS(*DiagPrinterWithOS);
445}
446
449 StringRef ModuleName, const llvm::DenseSet<ModuleID> &AlreadySeen,
450 DependencyActionController &Controller) {
451 FullDependencyConsumer Consumer(AlreadySeen);
452 // We need to clear the DiagnosticOutput so that each by-name lookup
453 // has a clean diagnostics buffer.
454 DiagPrinterWithOS->DiagnosticOutput.clear();
455 if (computeDependencies(ModuleName, Consumer, Controller))
456 return Consumer.takeTranslationUnitDeps();
457 return makeErrorFromDiagnosticsOS(*DiagPrinterWithOS);
458}
459
460bool CompilerInstanceWithContext::initialize(
461 DependencyActionController &Controller,
462 std::unique_ptr<DiagnosticsEngineWithDiagOpts> DiagEngineWithDiagOpts,
464 assert(DiagEngineWithDiagOpts && "Valid diagnostics engine required!");
465 DiagEngineWithCmdAndOpts = std::move(DiagEngineWithDiagOpts);
466 DiagConsumer = DiagEngineWithCmdAndOpts->DiagEngine->getClient();
467
468#ifndef NDEBUG
469 assert(OverlayFS && "OverlayFS required!");
470 bool SawDepFS = false;
471 OverlayFS->visit([&](llvm::vfs::FileSystem &VFS) {
472 SawDepFS |= &VFS == Worker.DepFS.get();
473 });
474 assert(SawDepFS && "OverlayFS not based on DepFS");
475#endif
476
477 OriginalInvocation = createCompilerInvocation(
478 CommandLine, *DiagEngineWithCmdAndOpts->DiagEngine);
479 if (!OriginalInvocation) {
480 DiagEngineWithCmdAndOpts->DiagEngine->Report(
481 diag::err_fe_expected_compiler_job)
482 << llvm::join(CommandLine, " ");
483 return false;
484 }
485
486 if (any(Worker.Service.getOpts().OptimizeArgs &
487 ScanningOptimizations::Macros))
488 canonicalizeDefines(OriginalInvocation->getPreprocessorOpts());
489
490 // Create the CompilerInstance.
491 std::shared_ptr<ModuleCache> ModCache =
492 makeInProcessModuleCache(Worker.Service.getModuleCacheEntries());
493 CIPtr = std::make_unique<CompilerInstance>(
494 createScanCompilerInvocation(*OriginalInvocation, Worker.Service,
495 Controller),
496 Worker.PCHContainerOps, std::move(ModCache));
497 auto &CI = *CIPtr;
498
500 CI, OverlayFS, DiagEngineWithCmdAndOpts->DiagEngine->getClient(),
501 Worker.Service, Worker.DepFS);
502
503 StableDirs = getInitialStableDirs(CI);
504 auto MaybePrebuiltModulesASTMap =
505 computePrebuiltModulesASTMap(CI, StableDirs);
506 if (!MaybePrebuiltModulesASTMap)
507 return false;
508
509 PrebuiltModuleASTMap = std::move(*MaybePrebuiltModulesASTMap);
510 OutputOpts = createDependencyOutputOptions(*OriginalInvocation);
511
512 // We do not create the target in initializeScanCompilerInstance because
513 // setting it here is unique for by-name lookups. We create the target only
514 // once here, and the information is reused for all computeDependencies calls.
515 // We do not need to call createTarget explicitly if we go through
516 // CompilerInstance::ExecuteAction to perform scanning.
517 CI.createTarget();
518
519 return true;
520}
521
523 StringRef ModuleName, DependencyConsumer &Consumer,
524 DependencyActionController &Controller) {
525 if (SrcLocOffset >= MaxNumOfQueries)
526 llvm::report_fatal_error("exceeded maximum by-name scans for worker");
527
528 assert(CIPtr && "CIPtr must be initialized before calling this method");
529 auto &CI = *CIPtr;
530
531 // We need to reset the diagnostics, so that the diagnostics issued
532 // during a previous computeDependencies call do not affect the current call.
533 // If we do not reset, we may inherit fatal errors from a previous call.
534 CI.getDiagnostics().Reset();
535
536 // We create this cleanup object because computeDependencies may exit
537 // early with errors.
538 llvm::scope_exit CleanUp([&]() {
539 CI.clearDependencyCollectors();
540 // The preprocessor may not be created at the entry of this method,
541 // but it must have been created when this method returns, whether
542 // there are errors during scanning or not.
543 CI.getPreprocessor().removePPCallbacks();
544 });
545
547 CI, std::make_unique<DependencyOutputOptions>(*OutputOpts), Consumer,
548 Worker.Service,
549 /* The MDC's constructor makes a copy of the OriginalInvocation, so
550 we can pass it in without worrying that it might be changed across
551 invocations of computeDependencies. */
552 *OriginalInvocation, Controller, PrebuiltModuleASTMap, StableDirs);
553
554 CompilerInvocation ModuleInvocation(*OriginalInvocation);
555 if (!Controller.initialize(CI, ModuleInvocation))
556 return false;
557
558 if (!SrcLocOffset) {
559 // When SrcLocOffset is zero, we are at the beginning of the fake source
560 // file. In this case, we call BeginSourceFile to initialize.
561 std::unique_ptr<FrontendAction> Action =
562 std::make_unique<PreprocessOnlyAction>();
563 auto *InputFile = CI.getFrontendOpts().Inputs.begin();
564 bool ActionBeginSucceeded = Action->BeginSourceFile(CI, *InputFile);
565 assert(ActionBeginSucceeded && "Action BeginSourceFile must succeed");
566 (void)ActionBeginSucceeded;
567 }
568
569 Preprocessor &PP = CI.getPreprocessor();
571 FileID MainFileID = SM.getMainFileID();
572 SourceLocation FileStart = SM.getLocForStartOfFile(MainFileID);
573 SourceLocation IDLocation = FileStart.getLocWithOffset(SrcLocOffset);
574 PPCallbacks *CB = nullptr;
575 if (!SrcLocOffset) {
576 // We need to call EnterSourceFile when SrcLocOffset is zero to initialize
577 // the preprocessor.
578 bool PPFailed = PP.EnterSourceFile(MainFileID, nullptr, SourceLocation());
579 assert(!PPFailed && "Preprocess must be able to enter the main file.");
580 (void)PPFailed;
581 CB = MDC->getPPCallbacks();
582 } else {
583 // When SrcLocOffset is non-zero, the preprocessor has already been
584 // initialized through a previous call of computeDependencies. We want to
585 // preserve the PP's state, hence we do not call EnterSourceFile again.
586 MDC->attachToPreprocessor(PP);
587 CB = MDC->getPPCallbacks();
588
589 FileID PrevFID;
590 SrcMgr::CharacteristicKind FileType = SM.getFileCharacteristic(IDLocation);
591 CB->LexedFileChanged(MainFileID,
593 FileType, PrevFID, IDLocation);
594 }
595
596 // FIXME: Scan modules asynchronously here as well.
597
598 SrcLocOffset++;
600 IdentifierInfo *ModuleID = PP.getIdentifierInfo(ModuleName);
601 Path.emplace_back(IDLocation, ModuleID);
602 auto ModResult = CI.loadModule(IDLocation, Path, Module::Hidden, false);
603
604 assert(CB && "Must have PPCallbacks after module loading");
605 CB->moduleImport(SourceLocation(), Path, ModResult);
606 // Note that we are calling the CB's EndOfMainFile function, which
607 // forwards the results to the dependency consumer.
608 // It does not indicate the end of processing the fake file.
609 CB->EndOfMainFile();
610
611 if (!ModResult)
612 return false;
613
614 if (CI.getDiagnostics().hasErrorOccurred())
615 return false;
616
617 MDC->applyDiscoveredDependencies(ModuleInvocation);
618
619 if (!Controller.finalize(CI, ModuleInvocation))
620 return false;
621
622 Consumer.handleBuildCommand(
623 {CommandLine[0], ModuleInvocation.getCC1CommandLine()});
624
625 return true;
626}
Defines the Diagnostic-related interfaces.
static std::pair< std::unique_ptr< driver::Driver >, std::unique_ptr< driver::Compilation > > buildCompilation(ArrayRef< std::string > ArgStrs, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS, llvm::BumpPtrAllocator &Alloc)
static std::pair< IntrusiveRefCntPtr< llvm::vfs::OverlayFileSystem >, std::vector< std::string > > initVFSForTUBufferScanning(IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS, ArrayRef< std::string > CommandLine, StringRef WorkingDirectory, llvm::MemoryBufferRef TUBuffer)
static llvm::Error makeErrorFromDiagnosticsOS(TextDiagnosticsPrinterWithOutput &DiagPrinterWithOS)
static std::pair< IntrusiveRefCntPtr< llvm::vfs::OverlayFileSystem >, std::vector< std::string > > initVFSForByNameScanning(IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS, ArrayRef< std::string > CommandLine, StringRef WorkingDirectory)
static SmallVector< std::string, 0 > buildCC1CommandLine(const driver::Command &Cmd)
Constructs the full frontend command line, including executable, for the given driver Cmd.
static bool computeDependenciesForDriverCommandLine(DependencyScanningWorker &Worker, StringRef WorkingDirectory, ArrayRef< std::string > CommandLine, DependencyConsumer &Consumer, DependencyActionController &Controller, DiagnosticConsumer &DiagConsumer, IntrusiveRefCntPtr< llvm::vfs::OverlayFileSystem > OverlayFS)
static std::optional< SmallVector< std::string, 0 > > getFirstCC1CommandLine(ArrayRef< std::string > CommandLine, DiagnosticsEngine &Diags, llvm::IntrusiveRefCntPtr< llvm::vfs::OverlayFileSystem > OverlayFS)
#define SM(sm)
Defines the clang::Preprocessor interface.
std::vector< std::string > getCC1CommandLine() const
Generate cc1-compatible command line arguments from this instance, wrapping the result as a std::vect...
Helper class for holding the data necessary to invoke the compiler.
DependencyOutputFormat OutputFormat
The format for the dependency file.
std::string OutputFile
The file to write dependency output to.
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:233
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
One of these records is kept for each identifier that is lexed.
@ Hidden
All of the names in this module are hidden.
Definition Module.h:606
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition PPCallbacks.h:37
virtual void EndOfMainFile()
Callback invoked when the end of the main file is reached.
virtual void LexedFileChanged(FileID FID, LexedFileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID, SourceLocation Loc)
Callback invoked whenever the Lexer moves to a different file for lexing.
Definition PPCallbacks.h:72
virtual void moduleImport(SourceLocation ImportLoc, ModuleIdPath Path, const Module *Imported)
Callback invoked whenever there was an explicit module-import syntax.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
bool EnterSourceFile(FileID FID, ConstSearchDirIterator Dir, SourceLocation Loc, bool IsFirstIncludeOfFile=true)
Add a source file to the top of the include stack and start lexing tokens from it instead of the curr...
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceManager & getSourceManager() const
Encodes a location in the source.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
A simple dependency action controller that uses a callback.
Dependency scanner callbacks that are used during scanning to influence the behaviour of the scan - f...
virtual bool initialize(CompilerInstance &ScanInstance, CompilerInvocation &NewInvocation)
Initializes the scan instance and modifies the resulting TU invocation.
virtual bool finalize(CompilerInstance &ScanInstance, CompilerInvocation &NewInvocation)
Finalizes the scan instance and modifies the resulting TU invocation.
An individual dependency scanning worker that is able to run on its own thread.
Command - An executable path/name and argument vector to execute.
Definition Job.h:106
const llvm::opt::ArgStringList & getArguments() const
Definition Job.h:224
const char * getExecutable() const
Definition Job.h:222
static std::optional< CompilerInstanceWithContext > initializeFromCommandline(DependencyScanningTool &Tool, StringRef CWD, ArrayRef< std::string > CommandLine, dependencies::DependencyActionController &Controller, DiagnosticConsumer &DC)
Initialize the tool's compiler instance from the commandline.
static llvm::Expected< CompilerInstanceWithContext > initializeOrError(DependencyScanningTool &Tool, StringRef CWD, ArrayRef< std::string > CommandLine, dependencies::DependencyActionController &Controller)
Initializing the context and the compiler instance.
bool computeDependencies(StringRef ModuleName, dependencies::DependencyConsumer &Consumer, dependencies::DependencyActionController &Controller)
llvm::Expected< dependencies::TranslationUnitDeps > computeDependenciesByNameOrError(StringRef ModuleName, const llvm::DenseSet< dependencies::ModuleID > &AlreadySeen, dependencies::DependencyActionController &Controller)
Computes the dependeny for the module named ModuleName.
The high-level implementation of the dependency discovery tool that runs on an individual worker thre...
std::optional< std::string > getDependencyFile(ArrayRef< std::string > CommandLine, StringRef CWD, dependencies::LookupModuleOutputCallback LookupModuleOutput, DiagnosticConsumer &DiagConsumer)
Print out the dependency information into a string using the dependency file format that is specified...
std::optional< dependencies::TranslationUnitDeps > getTranslationUnitDependencies(ArrayRef< std::string > CommandLine, StringRef CWD, DiagnosticConsumer &DiagConsumer, const llvm::DenseSet< dependencies::ModuleID > &AlreadySeen, dependencies::LookupModuleOutputCallback LookupModuleOutput, std::optional< llvm::MemoryBufferRef > TUBuffer=std::nullopt)
Given a Clang driver command-line for a translation unit, gather the modular dependencies and return ...
std::optional< P1689Rule > getP1689ModuleDependencyFile(const CompileCommand &Command, StringRef CWD, std::string &MakeformatOutput, std::string &MakeformatOutputPath, DiagnosticConsumer &DiagConsumer)
Collect the module dependency in P1689 format for C++20 named modules.
llvm::Expected< dependencies::TranslationUnitDeps > getModuleDependencies(StringRef ModuleName, ArrayRef< std::string > CommandLine, StringRef CWD, const llvm::DenseSet< dependencies::ModuleID > &AlreadySeen, dependencies::DependencyActionController &Controller)
Given a compilation context specified via the Clang driver command-line, gather modular dependencies ...
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
SmallVector< StringRef > getInitialStableDirs(const CompilerInstance &ScanInstance)
llvm::function_ref< std::string(const ModuleDeps &, ModuleOutputKind)> LookupModuleOutputCallback
A callback to lookup module outputs for "-fmodule-file=", "-o" etc.
@ VFS
Remove unused -ivfsoverlay arguments.
std::shared_ptr< CompilerInvocation > createScanCompilerInvocation(const CompilerInvocation &Invocation, const DependencyScanningService &Service, DependencyActionController &Controller)
Creates a CompilerInvocation suitable for the dependency scanner.
void initializeScanCompilerInstance(CompilerInstance &ScanInstance, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS, DiagnosticConsumer *DiagConsumer, DependencyScanningService &Service, IntrusiveRefCntPtr< DependencyScanningWorkerFilesystem > DepFS)
ModuleOutputKind
An output from a module compilation, such as the path of the module file.
std::unique_ptr< CompilerInvocation > createCompilerInvocation(ArrayRef< std::string > CommandLine, DiagnosticsEngine &Diags)
void canonicalizeDefines(PreprocessorOptions &PPOpts)
Canonicalizes command-line macro defines (e.g. removing "-DX -UX").
std::unique_ptr< DependencyOutputOptions > createDependencyOutputOptions(const CompilerInvocation &Invocation)
Creates dependency output options to be reported to the dependency consumer, deducing missing informa...
std::shared_ptr< ModuleDepCollector > initializeScanInstanceDependencyCollector(CompilerInstance &ScanInstance, std::unique_ptr< DependencyOutputOptions > DepOutputOpts, DependencyConsumer &Consumer, DependencyScanningService &Service, CompilerInvocation &Inv, DependencyActionController &Controller, PrebuiltModulesAttrsMap PrebuiltModulesASTMap, SmallVector< StringRef > &StableDirs)
Create the dependency collector that will collect the produced dependencies.
std::optional< PrebuiltModulesAttrsMap > computePrebuiltModulesASTMap(CompilerInstance &ScanInstance, SmallVector< StringRef > &StableDirs)
std::shared_ptr< ModuleCache > makeInProcessModuleCache(ModuleCacheEntries &Entries)
llvm::StringRef getDriverMode(StringRef ProgName, ArrayRef< const char * > Args)
Returns the driver mode option's value, i.e.
Definition Driver.cpp:7411
llvm::Error expandResponseFiles(SmallVectorImpl< const char * > &Args, bool ClangCLMode, llvm::BumpPtrAllocator &Alloc, llvm::vfs::FileSystem *FS=nullptr)
Expand response files from a clang driver or cc1 invocation.
Definition Driver.cpp:7428
bool IsClangCL(StringRef DriverMode)
Checks whether the value produced by getDriverMode is for CL mode.
Definition Driver.cpp:7426
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool computeDependencies(dependencies::DependencyScanningWorker &Worker, StringRef WorkingDirectory, ArrayRef< std::string > CommandLine, dependencies::DependencyConsumer &Consumer, dependencies::DependencyActionController &Controller, DiagnosticConsumer &DiagConsumer, llvm::IntrusiveRefCntPtr< llvm::vfs::OverlayFileSystem > OverlayFS=nullptr)
Run the dependency scanning worker for the given driver or frontend command-line, and report the disc...
std::shared_ptr< MatchComputation< T > > Generator
Definition RewriteRule.h:65
The JSON file list parser is used to communicate input to InstallAPI.
@ Worker
'worker' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
int __ovld __cnfn any(char)
Returns 1 if the most significant bit in any component of x is set; otherwise returns 0.
A command-line tool invocation that is part of building a TU.
void forEachFileDep(llvm::function_ref< void(StringRef)> Cb) const
Invokes Cb for all file dependencies of this module.
This is used to identify a specific module.
Specifies the working directory and command of a compilation.