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