#include "clang/Tooling/DependencyScanning/ModuleDepCollector.h"
#include "clang/Basic/MakeSupport.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Tooling/DependencyScanning/DependencyScanningWorker.h"
#include "llvm/Support/StringSaver.h"
using namespace clang;
using namespace tooling;
using namespace dependencies;
static void optimizeHeaderSearchOpts(HeaderSearchOptions &Opts,
ASTReader &Reader,
const serialization::ModuleFile &MF) {
std::vector<HeaderSearchOptions::Entry> Entries = Opts.UserEntries;
Opts.UserEntries.clear();
llvm::BitVector SearchPathUsage(Entries.size());
llvm::DenseSet<const serialization::ModuleFile *> Visited;
std::function<void(const serialization::ModuleFile *)> VisitMF =
[&](const serialization::ModuleFile *MF) {
SearchPathUsage |= MF->SearchPathUsage;
Visited.insert(MF);
for (const serialization::ModuleFile *Import : MF->Imports)
if (!Visited.contains(Import))
VisitMF(Import);
};
VisitMF(&MF);
for (auto Idx : SearchPathUsage.set_bits())
Opts.UserEntries.push_back(Entries[Idx]);
}
CompilerInvocation ModuleDepCollector::makeInvocationForModuleBuildWithoutPaths(
const ModuleDeps &Deps,
llvm::function_ref<void(CompilerInvocation &)> Optimize) const {
CompilerInvocation CI(OriginalInvocation);
CI.getLangOpts()->resetNonModularOptions();
CI.getPreprocessorOpts().resetNonModularOptions();
CI.getFrontendOpts().Inputs.clear();
CI.getFrontendOpts().OutputFile.clear();
CI.getCodeGenOpts().MainFileName.clear();
CI.getCodeGenOpts().DwarfDebugFlags.clear();
CI.getDiagnosticOpts().DiagnosticSerializationFile.clear();
CI.getDependencyOutputOpts().OutputFile.clear();
CI.getDependencyOutputOpts().Targets.clear();
CI.getFrontendOpts().ProgramAction = frontend::GenerateModule;
CI.getLangOpts()->ModuleName = Deps.ID.ModuleName;
CI.getFrontendOpts().IsSystemModule = Deps.IsSystem;
CI.getLangOpts()->ImplicitModules = false;
CI.getHeaderSearchOpts().ImplicitModuleMaps = false;
CI.getHeaderSearchOpts().ModuleCachePath.clear();
CI.getHeaderSearchOpts().ModulesValidateOncePerBuildSession = false;
CI.getHeaderSearchOpts().BuildSessionTimestamp = 0;
CI.getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60;
CI.getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60;
for (const auto &PrebuiltModule : Deps.PrebuiltModuleDeps)
CI.getFrontendOpts().ModuleFiles.push_back(PrebuiltModule.PCMFile);
CI.getFrontendOpts().ModuleMapFiles = Deps.ModuleMapFileDeps;
Optimize(CI);
CI.getHeaderSearchOpts().ModulesStrictContextHash = true;
return CI;
}
static std::vector<std::string>
serializeCompilerInvocation(const CompilerInvocation &CI) {
llvm::BumpPtrAllocator Alloc;
llvm::StringSaver Strings(Alloc);
auto SA = [&Strings](const Twine &Arg) { return Strings.save(Arg).data(); };
SmallVector<const char *, 32> Args{"-cc1"};
CI.generateCC1CommandLine(Args, SA);
return std::vector<std::string>{Args.begin(), Args.end()};
}
static std::vector<std::string> splitString(std::string S, char Separator) {
SmallVector<StringRef> Segments;
StringRef(S).split(Segments, Separator, -1, false);
std::vector<std::string> Result;
Result.reserve(Segments.size());
for (StringRef Segment : Segments)
Result.push_back(Segment.str());
return Result;
}
std::vector<std::string> ModuleDeps::getCanonicalCommandLine(
llvm::function_ref<std::string(const ModuleID &, ModuleOutputKind)>
LookupModuleOutput) const {
CompilerInvocation CI(BuildInvocation);
FrontendOptions &FrontendOpts = CI.getFrontendOpts();
InputKind ModuleMapInputKind(FrontendOpts.DashX.getLanguage(),
InputKind::Format::ModuleMap);
FrontendOpts.Inputs.emplace_back(ClangModuleMapFile, ModuleMapInputKind);
FrontendOpts.OutputFile =
LookupModuleOutput(ID, ModuleOutputKind::ModuleFile);
if (HadSerializedDiagnostics)
CI.getDiagnosticOpts().DiagnosticSerializationFile =
LookupModuleOutput(ID, ModuleOutputKind::DiagnosticSerializationFile);
if (HadDependencyFile) {
DependencyOutputOptions &DepOpts = CI.getDependencyOutputOpts();
DepOpts.OutputFile =
LookupModuleOutput(ID, ModuleOutputKind::DependencyFile);
DepOpts.Targets = splitString(
LookupModuleOutput(ID, ModuleOutputKind::DependencyTargets), '\0');
if (!DepOpts.OutputFile.empty() && DepOpts.Targets.empty()) {
SmallString<128> Target;
quoteMakeTarget(FrontendOpts.OutputFile, Target);
DepOpts.Targets.push_back(std::string(Target));
}
}
for (ModuleID MID : ClangModuleDeps)
FrontendOpts.ModuleFiles.push_back(
LookupModuleOutput(MID, ModuleOutputKind::ModuleFile));
return serializeCompilerInvocation(CI);
}
std::vector<std::string>
ModuleDeps::getCanonicalCommandLineWithoutModulePaths() const {
return serializeCompilerInvocation(BuildInvocation);
}
void ModuleDepCollectorPP::FileChanged(SourceLocation Loc,
FileChangeReason Reason,
SrcMgr::CharacteristicKind FileType,
FileID PrevFID) {
if (Reason != PPCallbacks::EnterFile)
return;
if (MDC.ContextHash.empty()) {
MDC.ContextHash = MDC.ScanInstance.getInvocation().getModuleHash();
MDC.Consumer.handleContextHash(MDC.ContextHash);
}
SourceManager &SM = MDC.ScanInstance.getSourceManager();
if (Optional<StringRef> Filename =
SM.getNonBuiltinFilenameForID(SM.getFileID(SM.getExpansionLoc(Loc))))
MDC.FileDeps.push_back(
std::string(llvm::sys::path::remove_leading_dotslash(*Filename)));
}
void ModuleDepCollectorPP::InclusionDirective(
SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName,
bool IsAngled, CharSourceRange FilenameRange, Optional<FileEntryRef> File,
StringRef SearchPath, StringRef RelativePath, const Module *Imported,
SrcMgr::CharacteristicKind FileType) {
if (!File && !Imported) {
MDC.FileDeps.push_back(std::string(FileName));
}
handleImport(Imported);
}
void ModuleDepCollectorPP::moduleImport(SourceLocation ImportLoc,
ModuleIdPath Path,
const Module *Imported) {
handleImport(Imported);
}
void ModuleDepCollectorPP::handleImport(const Module *Imported) {
if (!Imported)
return;
const Module *TopLevelModule = Imported->getTopLevelModule();
if (MDC.isPrebuiltModule(TopLevelModule))
DirectPrebuiltModularDeps.insert(TopLevelModule);
else
DirectModularDeps.insert(TopLevelModule);
}
void ModuleDepCollectorPP::EndOfMainFile() {
FileID MainFileID = MDC.ScanInstance.getSourceManager().getMainFileID();
MDC.MainFile = std::string(MDC.ScanInstance.getSourceManager()
.getFileEntryForID(MainFileID)
->getName());
if (!MDC.ScanInstance.getPreprocessorOpts().ImplicitPCHInclude.empty())
MDC.FileDeps.push_back(
MDC.ScanInstance.getPreprocessorOpts().ImplicitPCHInclude);
for (const Module *M : DirectModularDeps) {
if (!M->getASTFile())
continue;
handleTopLevelModule(M);
}
MDC.Consumer.handleDependencyOutputOpts(*MDC.Opts);
for (auto &&I : MDC.ModularDeps)
MDC.Consumer.handleModuleDependency(*I.second);
for (auto &&I : MDC.FileDeps)
MDC.Consumer.handleFileDependency(I);
for (auto &&I : DirectPrebuiltModularDeps)
MDC.Consumer.handlePrebuiltModuleDependency(PrebuiltModuleDep{I});
}
ModuleID ModuleDepCollectorPP::handleTopLevelModule(const Module *M) {
assert(M == M->getTopLevelModule() && "Expected top level module!");
auto ModI = MDC.ModularDeps.insert({M, nullptr});
if (!ModI.second)
return ModI.first->second->ID;
ModI.first->second = std::make_unique<ModuleDeps>();
ModuleDeps &MD = *ModI.first->second;
MD.ID.ModuleName = M->getFullModuleName();
MD.ImportedByMainFile = DirectModularDeps.contains(M);
MD.ImplicitModulePCMPath = std::string(M->getASTFile()->getName());
MD.IsSystem = M->IsSystem;
const FileEntry *ModuleMap = MDC.ScanInstance.getPreprocessor()
.getHeaderSearchInfo()
.getModuleMap()
.getModuleMapFileForUniquing(M);
if (ModuleMap) {
StringRef Path = ModuleMap->tryGetRealPathName();
if (Path.empty())
Path = ModuleMap->getName();
MD.ClangModuleMapFile = std::string(Path);
}
serialization::ModuleFile *MF =
MDC.ScanInstance.getASTReader()->getModuleManager().lookup(
M->getASTFile());
MDC.ScanInstance.getASTReader()->visitInputFiles(
*MF, true, true, [&](const serialization::InputFile &IF, bool isSystem) {
if (IF.getFile()->getName().endswith("__inferred_module.map")) {
MD.FileDeps.insert(ModuleMap->getName());
return;
}
MD.FileDeps.insert(IF.getFile()->getName());
});
if (M->NoUndeclaredIncludes) {
MDC.ScanInstance.getASTReader()->visitTopLevelModuleMaps(
*MF, [&](const FileEntry *FE) {
if (FE->getName().endswith("__inferred_module.map"))
return;
if (FE == ModuleMap)
return;
MD.ModuleMapFileDeps.push_back(FE->getName().str());
});
}
llvm::DenseSet<const Module *> SeenModules;
addAllSubmodulePrebuiltDeps(M, MD, SeenModules);
MD.BuildInvocation = MDC.makeInvocationForModuleBuildWithoutPaths(
MD, [&](CompilerInvocation &BuildInvocation) {
if (MDC.OptimizeArgs)
optimizeHeaderSearchOpts(BuildInvocation.getHeaderSearchOpts(),
*MDC.ScanInstance.getASTReader(), *MF);
});
MD.HadSerializedDiagnostics = !MDC.OriginalInvocation.getDiagnosticOpts()
.DiagnosticSerializationFile.empty();
MD.HadDependencyFile =
!MDC.OriginalInvocation.getDependencyOutputOpts().OutputFile.empty();
MD.ID.ContextHash = MD.BuildInvocation.getModuleHash();
llvm::DenseSet<const Module *> AddedModules;
addAllSubmoduleDeps(M, MD, AddedModules);
return MD.ID;
}
static void forEachSubmoduleSorted(const Module *M,
llvm::function_ref<void(const Module *)> F) {
SmallVector<const Module *> Submodules(M->submodule_begin(),
M->submodule_end());
llvm::stable_sort(Submodules, [](const Module *A, const Module *B) {
return A->Name < B->Name;
});
for (const Module *SubM : Submodules)
F(SubM);
}
void ModuleDepCollectorPP::addAllSubmodulePrebuiltDeps(
const Module *M, ModuleDeps &MD,
llvm::DenseSet<const Module *> &SeenSubmodules) {
addModulePrebuiltDeps(M, MD, SeenSubmodules);
forEachSubmoduleSorted(M, [&](const Module *SubM) {
addAllSubmodulePrebuiltDeps(SubM, MD, SeenSubmodules);
});
}
void ModuleDepCollectorPP::addModulePrebuiltDeps(
const Module *M, ModuleDeps &MD,
llvm::DenseSet<const Module *> &SeenSubmodules) {
for (const Module *Import : M->Imports)
if (Import->getTopLevelModule() != M->getTopLevelModule())
if (MDC.isPrebuiltModule(Import->getTopLevelModule()))
if (SeenSubmodules.insert(Import->getTopLevelModule()).second)
MD.PrebuiltModuleDeps.emplace_back(Import->getTopLevelModule());
}
void ModuleDepCollectorPP::addAllSubmoduleDeps(
const Module *M, ModuleDeps &MD,
llvm::DenseSet<const Module *> &AddedModules) {
addModuleDep(M, MD, AddedModules);
forEachSubmoduleSorted(M, [&](const Module *SubM) {
addAllSubmoduleDeps(SubM, MD, AddedModules);
});
}
void ModuleDepCollectorPP::addModuleDep(
const Module *M, ModuleDeps &MD,
llvm::DenseSet<const Module *> &AddedModules) {
for (const Module *Import : M->Imports) {
if (Import->getTopLevelModule() != M->getTopLevelModule() &&
!MDC.isPrebuiltModule(Import)) {
ModuleID ImportID = handleTopLevelModule(Import->getTopLevelModule());
if (AddedModules.insert(Import->getTopLevelModule()).second)
MD.ClangModuleDeps.push_back(ImportID);
}
}
}
ModuleDepCollector::ModuleDepCollector(
std::unique_ptr<DependencyOutputOptions> Opts,
CompilerInstance &ScanInstance, DependencyConsumer &C,
CompilerInvocation &&OriginalCI, bool OptimizeArgs)
: ScanInstance(ScanInstance), Consumer(C), Opts(std::move(Opts)),
OriginalInvocation(std::move(OriginalCI)), OptimizeArgs(OptimizeArgs) {}
void ModuleDepCollector::attachToPreprocessor(Preprocessor &PP) {
PP.addPPCallbacks(std::make_unique<ModuleDepCollectorPP>(*this));
}
void ModuleDepCollector::attachToASTReader(ASTReader &R) {}
bool ModuleDepCollector::isPrebuiltModule(const Module *M) {
std::string Name(M->getTopLevelModuleName());
const auto &PrebuiltModuleFiles =
ScanInstance.getHeaderSearchOpts().PrebuiltModuleFiles;
auto PrebuiltModuleFileIt = PrebuiltModuleFiles.find(Name);
if (PrebuiltModuleFileIt == PrebuiltModuleFiles.end())
return false;
assert("Prebuilt module came from the expected AST file" &&
PrebuiltModuleFileIt->second == M->getASTFile()->getName());
return true;
}