1 //===- ModuleDepCollector.cpp - Callbacks to collect deps -------*- 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 #include "clang/Tooling/DependencyScanning/ModuleDepCollector.h"
10 
11 #include "clang/Frontend/CompilerInstance.h"
12 #include "clang/Lex/Preprocessor.h"
13 #include "clang/Tooling/DependencyScanning/DependencyScanningWorker.h"
14 #include "llvm/Support/StringSaver.h"
15 
16 using namespace clang;
17 using namespace tooling;
18 using namespace dependencies;
19 
20 static void optimizeHeaderSearchOpts(HeaderSearchOptions &Opts,
21                                      ASTReader &Reader,
22                                      const serialization::ModuleFile &MF) {
23   // Only preserve search paths that were used during the dependency scan.
24   std::vector<HeaderSearchOptions::Entry> Entries = Opts.UserEntries;
25   Opts.UserEntries.clear();
26 
27   llvm::BitVector SearchPathUsage(Entries.size());
28   llvm::DenseSet<const serialization::ModuleFile *> Visited;
29   std::function<void(const serialization::ModuleFile *)> VisitMF =
30       [&](const serialization::ModuleFile *MF) {
31         SearchPathUsage |= MF->SearchPathUsage;
32         Visited.insert(MF);
33         for (const serialization::ModuleFile *Import : MF->Imports)
34           if (!Visited.contains(Import))
35             VisitMF(Import);
36       };
37   VisitMF(&MF);
38 
39   for (auto Idx : SearchPathUsage.set_bits())
40     Opts.UserEntries.push_back(Entries[Idx]);
41 }
42 
43 CompilerInvocation ModuleDepCollector::makeInvocationForModuleBuildWithoutPaths(
44     const ModuleDeps &Deps,
45     llvm::function_ref<void(CompilerInvocation &)> Optimize) const {
46   // Make a deep copy of the original Clang invocation.
47   CompilerInvocation CI(OriginalInvocation);
48 
49   CI.getLangOpts()->resetNonModularOptions();
50   CI.getPreprocessorOpts().resetNonModularOptions();
51 
52   // Remove options incompatible with explicit module build or are likely to
53   // differ between identical modules discovered from different translation
54   // units.
55   CI.getFrontendOpts().Inputs.clear();
56   CI.getFrontendOpts().OutputFile.clear();
57   CI.getCodeGenOpts().MainFileName.clear();
58   CI.getCodeGenOpts().DwarfDebugFlags.clear();
59 
60   CI.getFrontendOpts().ProgramAction = frontend::GenerateModule;
61   CI.getLangOpts()->ModuleName = Deps.ID.ModuleName;
62   CI.getFrontendOpts().IsSystemModule = Deps.IsSystem;
63 
64   // Disable implicit modules and canonicalize options that are only used by
65   // implicit modules.
66   CI.getLangOpts()->ImplicitModules = false;
67   CI.getHeaderSearchOpts().ImplicitModuleMaps = false;
68   CI.getHeaderSearchOpts().ModuleCachePath.clear();
69   CI.getHeaderSearchOpts().ModulesValidateOncePerBuildSession = false;
70   CI.getHeaderSearchOpts().BuildSessionTimestamp = 0;
71   // The specific values we canonicalize to for pruning don't affect behaviour,
72   /// so use the default values so they will be dropped from the command-line.
73   CI.getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60;
74   CI.getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60;
75 
76   // Report the prebuilt modules this module uses.
77   for (const auto &PrebuiltModule : Deps.PrebuiltModuleDeps)
78     CI.getFrontendOpts().ModuleFiles.push_back(PrebuiltModule.PCMFile);
79 
80   CI.getFrontendOpts().ModuleMapFiles = Deps.ModuleMapFileDeps;
81 
82   Optimize(CI);
83 
84   // The original invocation probably didn't have strict context hash enabled.
85   // We will use the context hash of this invocation to distinguish between
86   // multiple incompatible versions of the same module and will use it when
87   // reporting dependencies to the clients. Let's make sure we're using
88   // **strict** context hash in order to prevent accidental sharing of
89   // incompatible modules (e.g. with differences in search paths).
90   CI.getHeaderSearchOpts().ModulesStrictContextHash = true;
91 
92   return CI;
93 }
94 
95 static std::vector<std::string>
96 serializeCompilerInvocation(const CompilerInvocation &CI) {
97   // Set up string allocator.
98   llvm::BumpPtrAllocator Alloc;
99   llvm::StringSaver Strings(Alloc);
100   auto SA = [&Strings](const Twine &Arg) { return Strings.save(Arg).data(); };
101 
102   // Synthesize full command line from the CompilerInvocation, including "-cc1".
103   SmallVector<const char *, 32> Args{"-cc1"};
104   CI.generateCC1CommandLine(Args, SA);
105 
106   // Convert arguments to the return type.
107   return std::vector<std::string>{Args.begin(), Args.end()};
108 }
109 
110 std::vector<std::string> ModuleDeps::getCanonicalCommandLine(
111     std::function<StringRef(ModuleID)> LookupPCMPath) const {
112   CompilerInvocation CI(BuildInvocation);
113   FrontendOptions &FrontendOpts = CI.getFrontendOpts();
114 
115   InputKind ModuleMapInputKind(FrontendOpts.DashX.getLanguage(),
116                                InputKind::Format::ModuleMap);
117   FrontendOpts.Inputs.emplace_back(ClangModuleMapFile, ModuleMapInputKind);
118   FrontendOpts.OutputFile = std::string(LookupPCMPath(ID));
119 
120   for (ModuleID MID : ClangModuleDeps)
121     FrontendOpts.ModuleFiles.emplace_back(LookupPCMPath(MID));
122 
123   return serializeCompilerInvocation(CI);
124 }
125 
126 std::vector<std::string>
127 ModuleDeps::getCanonicalCommandLineWithoutModulePaths() const {
128   return serializeCompilerInvocation(BuildInvocation);
129 }
130 
131 void ModuleDepCollectorPP::FileChanged(SourceLocation Loc,
132                                        FileChangeReason Reason,
133                                        SrcMgr::CharacteristicKind FileType,
134                                        FileID PrevFID) {
135   if (Reason != PPCallbacks::EnterFile)
136     return;
137 
138   // This has to be delayed as the context hash can change at the start of
139   // `CompilerInstance::ExecuteAction`.
140   if (MDC.ContextHash.empty()) {
141     MDC.ContextHash = MDC.ScanInstance.getInvocation().getModuleHash();
142     MDC.Consumer.handleContextHash(MDC.ContextHash);
143   }
144 
145   SourceManager &SM = MDC.ScanInstance.getSourceManager();
146 
147   // Dependency generation really does want to go all the way to the
148   // file entry for a source location to find out what is depended on.
149   // We do not want #line markers to affect dependency generation!
150   if (Optional<StringRef> Filename =
151           SM.getNonBuiltinFilenameForID(SM.getFileID(SM.getExpansionLoc(Loc))))
152     MDC.FileDeps.push_back(
153         std::string(llvm::sys::path::remove_leading_dotslash(*Filename)));
154 }
155 
156 void ModuleDepCollectorPP::InclusionDirective(
157     SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName,
158     bool IsAngled, CharSourceRange FilenameRange, Optional<FileEntryRef> File,
159     StringRef SearchPath, StringRef RelativePath, const Module *Imported,
160     SrcMgr::CharacteristicKind FileType) {
161   if (!File && !Imported) {
162     // This is a non-modular include that HeaderSearch failed to find. Add it
163     // here as `FileChanged` will never see it.
164     MDC.FileDeps.push_back(std::string(FileName));
165   }
166   handleImport(Imported);
167 }
168 
169 void ModuleDepCollectorPP::moduleImport(SourceLocation ImportLoc,
170                                         ModuleIdPath Path,
171                                         const Module *Imported) {
172   handleImport(Imported);
173 }
174 
175 void ModuleDepCollectorPP::handleImport(const Module *Imported) {
176   if (!Imported)
177     return;
178 
179   const Module *TopLevelModule = Imported->getTopLevelModule();
180 
181   if (MDC.isPrebuiltModule(TopLevelModule))
182     DirectPrebuiltModularDeps.insert(TopLevelModule);
183   else
184     DirectModularDeps.insert(TopLevelModule);
185 }
186 
187 void ModuleDepCollectorPP::EndOfMainFile() {
188   FileID MainFileID = MDC.ScanInstance.getSourceManager().getMainFileID();
189   MDC.MainFile = std::string(MDC.ScanInstance.getSourceManager()
190                                  .getFileEntryForID(MainFileID)
191                                  ->getName());
192 
193   if (!MDC.ScanInstance.getPreprocessorOpts().ImplicitPCHInclude.empty())
194     MDC.FileDeps.push_back(
195         MDC.ScanInstance.getPreprocessorOpts().ImplicitPCHInclude);
196 
197   for (const Module *M : DirectModularDeps) {
198     // A top-level module might not be actually imported as a module when
199     // -fmodule-name is used to compile a translation unit that imports this
200     // module. In that case it can be skipped. The appropriate header
201     // dependencies will still be reported as expected.
202     if (!M->getASTFile())
203       continue;
204     handleTopLevelModule(M);
205   }
206 
207   MDC.Consumer.handleDependencyOutputOpts(*MDC.Opts);
208 
209   for (auto &&I : MDC.ModularDeps)
210     MDC.Consumer.handleModuleDependency(*I.second);
211 
212   for (auto &&I : MDC.FileDeps)
213     MDC.Consumer.handleFileDependency(I);
214 
215   for (auto &&I : DirectPrebuiltModularDeps)
216     MDC.Consumer.handlePrebuiltModuleDependency(PrebuiltModuleDep{I});
217 }
218 
219 ModuleID ModuleDepCollectorPP::handleTopLevelModule(const Module *M) {
220   assert(M == M->getTopLevelModule() && "Expected top level module!");
221 
222   // If this module has been handled already, just return its ID.
223   auto ModI = MDC.ModularDeps.insert({M, nullptr});
224   if (!ModI.second)
225     return ModI.first->second->ID;
226 
227   ModI.first->second = std::make_unique<ModuleDeps>();
228   ModuleDeps &MD = *ModI.first->second;
229 
230   MD.ID.ModuleName = M->getFullModuleName();
231   MD.ImportedByMainFile = DirectModularDeps.contains(M);
232   MD.ImplicitModulePCMPath = std::string(M->getASTFile()->getName());
233   MD.IsSystem = M->IsSystem;
234 
235   const FileEntry *ModuleMap = MDC.ScanInstance.getPreprocessor()
236                                    .getHeaderSearchInfo()
237                                    .getModuleMap()
238                                    .getModuleMapFileForUniquing(M);
239 
240   if (ModuleMap) {
241     StringRef Path = ModuleMap->tryGetRealPathName();
242     if (Path.empty())
243       Path = ModuleMap->getName();
244     MD.ClangModuleMapFile = std::string(Path);
245   }
246 
247   serialization::ModuleFile *MF =
248       MDC.ScanInstance.getASTReader()->getModuleManager().lookup(
249           M->getASTFile());
250   MDC.ScanInstance.getASTReader()->visitInputFiles(
251       *MF, true, true, [&](const serialization::InputFile &IF, bool isSystem) {
252         // __inferred_module.map is the result of the way in which an implicit
253         // module build handles inferred modules. It adds an overlay VFS with
254         // this file in the proper directory and relies on the rest of Clang to
255         // handle it like normal. With explicitly built modules we don't need
256         // to play VFS tricks, so replace it with the correct module map.
257         if (IF.getFile()->getName().endswith("__inferred_module.map")) {
258           MD.FileDeps.insert(ModuleMap->getName());
259           return;
260         }
261         MD.FileDeps.insert(IF.getFile()->getName());
262       });
263 
264   // We usually don't need to list the module map files of our dependencies when
265   // building a module explicitly: their semantics will be deserialized from PCM
266   // files.
267   //
268   // However, some module maps loaded implicitly during the dependency scan can
269   // describe anti-dependencies. That happens when this module, let's call it
270   // M1, is marked as '[no_undeclared_includes]' and tries to access a header
271   // "M2/M2.h" from another module, M2, but doesn't have a 'use M2;'
272   // declaration. The explicit build needs the module map for M2 so that it
273   // knows that textually including "M2/M2.h" is not allowed.
274   // E.g., '__has_include("M2/M2.h")' should return false, but without M2's
275   // module map the explicit build would return true.
276   //
277   // An alternative approach would be to tell the explicit build what its
278   // textual dependencies are, instead of having it re-discover its
279   // anti-dependencies. For example, we could create and use an `-ivfs-overlay`
280   // with `fall-through: false` that explicitly listed the dependencies.
281   // However, that's more complicated to implement and harder to reason about.
282   if (M->NoUndeclaredIncludes) {
283     // We don't have a good way to determine which module map described the
284     // anti-dependency (let alone what's the corresponding top-level module
285     // map). We simply specify all the module maps in the order they were loaded
286     // during the implicit build during scan.
287     // TODO: Resolve this by serializing and only using Module::UndeclaredUses.
288     MDC.ScanInstance.getASTReader()->visitTopLevelModuleMaps(
289         *MF, [&](const FileEntry *FE) {
290           if (FE->getName().endswith("__inferred_module.map"))
291             return;
292           // The top-level modulemap of this module will be the input file. We
293           // don't need to specify it as a module map.
294           if (FE == ModuleMap)
295             return;
296           MD.ModuleMapFileDeps.push_back(FE->getName().str());
297         });
298   }
299 
300   // Add direct prebuilt module dependencies now, so that we can use them when
301   // creating a CompilerInvocation and computing context hash for this
302   // ModuleDeps instance.
303   llvm::DenseSet<const Module *> SeenModules;
304   addAllSubmodulePrebuiltDeps(M, MD, SeenModules);
305 
306   MD.BuildInvocation = MDC.makeInvocationForModuleBuildWithoutPaths(
307       MD, [&](CompilerInvocation &BuildInvocation) {
308         if (MDC.OptimizeArgs)
309           optimizeHeaderSearchOpts(BuildInvocation.getHeaderSearchOpts(),
310                                    *MDC.ScanInstance.getASTReader(), *MF);
311       });
312   MD.ID.ContextHash = MD.BuildInvocation.getModuleHash();
313 
314   llvm::DenseSet<const Module *> AddedModules;
315   addAllSubmoduleDeps(M, MD, AddedModules);
316 
317   return MD.ID;
318 }
319 
320 static void forEachSubmoduleSorted(const Module *M,
321                                    llvm::function_ref<void(const Module *)> F) {
322   // Submodule order depends on order of header includes for inferred submodules
323   // we don't care about the exact order, so sort so that it's consistent across
324   // TUs to improve sharing.
325   SmallVector<const Module *> Submodules(M->submodule_begin(),
326                                          M->submodule_end());
327   llvm::stable_sort(Submodules, [](const Module *A, const Module *B) {
328     return A->Name < B->Name;
329   });
330   for (const Module *SubM : Submodules)
331     F(SubM);
332 }
333 
334 void ModuleDepCollectorPP::addAllSubmodulePrebuiltDeps(
335     const Module *M, ModuleDeps &MD,
336     llvm::DenseSet<const Module *> &SeenSubmodules) {
337   addModulePrebuiltDeps(M, MD, SeenSubmodules);
338 
339   forEachSubmoduleSorted(M, [&](const Module *SubM) {
340     addAllSubmodulePrebuiltDeps(SubM, MD, SeenSubmodules);
341   });
342 }
343 
344 void ModuleDepCollectorPP::addModulePrebuiltDeps(
345     const Module *M, ModuleDeps &MD,
346     llvm::DenseSet<const Module *> &SeenSubmodules) {
347   for (const Module *Import : M->Imports)
348     if (Import->getTopLevelModule() != M->getTopLevelModule())
349       if (MDC.isPrebuiltModule(Import->getTopLevelModule()))
350         if (SeenSubmodules.insert(Import->getTopLevelModule()).second)
351           MD.PrebuiltModuleDeps.emplace_back(Import->getTopLevelModule());
352 }
353 
354 void ModuleDepCollectorPP::addAllSubmoduleDeps(
355     const Module *M, ModuleDeps &MD,
356     llvm::DenseSet<const Module *> &AddedModules) {
357   addModuleDep(M, MD, AddedModules);
358 
359   forEachSubmoduleSorted(M, [&](const Module *SubM) {
360     addAllSubmoduleDeps(SubM, MD, AddedModules);
361   });
362 }
363 
364 void ModuleDepCollectorPP::addModuleDep(
365     const Module *M, ModuleDeps &MD,
366     llvm::DenseSet<const Module *> &AddedModules) {
367   for (const Module *Import : M->Imports) {
368     if (Import->getTopLevelModule() != M->getTopLevelModule() &&
369         !MDC.isPrebuiltModule(Import)) {
370       ModuleID ImportID = handleTopLevelModule(Import->getTopLevelModule());
371       if (AddedModules.insert(Import->getTopLevelModule()).second)
372         MD.ClangModuleDeps.push_back(ImportID);
373     }
374   }
375 }
376 
377 ModuleDepCollector::ModuleDepCollector(
378     std::unique_ptr<DependencyOutputOptions> Opts,
379     CompilerInstance &ScanInstance, DependencyConsumer &C,
380     CompilerInvocation &&OriginalCI, bool OptimizeArgs)
381     : ScanInstance(ScanInstance), Consumer(C), Opts(std::move(Opts)),
382       OriginalInvocation(std::move(OriginalCI)), OptimizeArgs(OptimizeArgs) {}
383 
384 void ModuleDepCollector::attachToPreprocessor(Preprocessor &PP) {
385   PP.addPPCallbacks(std::make_unique<ModuleDepCollectorPP>(*this));
386 }
387 
388 void ModuleDepCollector::attachToASTReader(ASTReader &R) {}
389 
390 bool ModuleDepCollector::isPrebuiltModule(const Module *M) {
391   std::string Name(M->getTopLevelModuleName());
392   const auto &PrebuiltModuleFiles =
393       ScanInstance.getHeaderSearchOpts().PrebuiltModuleFiles;
394   auto PrebuiltModuleFileIt = PrebuiltModuleFiles.find(Name);
395   if (PrebuiltModuleFileIt == PrebuiltModuleFiles.end())
396     return false;
397   assert("Prebuilt module came from the expected AST file" &&
398          PrebuiltModuleFileIt->second == M->getASTFile()->getName());
399   return true;
400 }
401