| 1 | //===- DependencyScanningWorker.cpp - Thread-Safe Scanning Worker ---------===// |
| 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/DependencyScanning/DependencyScanningWorker.h" |
| 10 | #include "clang/Basic/Diagnostic.h" |
| 11 | #include "clang/Basic/DiagnosticFrontend.h" |
| 12 | #include "clang/Basic/DiagnosticSerialization.h" |
| 13 | #include "clang/DependencyScanning/DependencyActionController.h" |
| 14 | #include "clang/DependencyScanning/DependencyConsumer.h" |
| 15 | #include "clang/DependencyScanning/DependencyScanningFilesystem.h" |
| 16 | #include "clang/Frontend/FrontendActions.h" |
| 17 | #include "clang/Lex/Preprocessor.h" |
| 18 | #include "clang/Sema/SemaOpenACC.h" |
| 19 | #include "clang/Serialization/ObjectFilePCHContainerReader.h" |
| 20 | #include "llvm/ADT/IntrusiveRefCntPtr.h" |
| 21 | #include "llvm/ADT/ScopeExit.h" |
| 22 | #include "llvm/Option/Option.h" |
| 23 | #include "llvm/Support/AdvisoryLock.h" |
| 24 | #include "llvm/Support/CrashRecoveryContext.h" |
| 25 | #include "llvm/Support/VirtualFileSystem.h" |
| 26 | #include "llvm/TargetParser/Host.h" |
| 27 | #include <mutex> |
| 28 | #include <thread> |
| 29 | |
| 30 | using namespace clang; |
| 31 | using namespace dependencies; |
| 32 | |
| 33 | static bool (const HeaderSearchOptions &HSOpts, |
| 34 | const HeaderSearchOptions &ExistingHSOpts, |
| 35 | DiagnosticsEngine *Diags, |
| 36 | const LangOptions &LangOpts) { |
| 37 | if (LangOpts.Modules) { |
| 38 | if (HSOpts.VFSOverlayFiles != ExistingHSOpts.VFSOverlayFiles) { |
| 39 | if (Diags) { |
| 40 | Diags->Report(DiagID: diag::warn_pch_vfsoverlay_mismatch); |
| 41 | auto VFSNote = [&](int Type, ArrayRef<std::string> VFSOverlays) { |
| 42 | if (VFSOverlays.empty()) { |
| 43 | Diags->Report(DiagID: diag::note_pch_vfsoverlay_empty) << Type; |
| 44 | } else { |
| 45 | std::string Files = llvm::join(R&: VFSOverlays, Separator: "\n" ); |
| 46 | Diags->Report(DiagID: diag::note_pch_vfsoverlay_files) << Type << Files; |
| 47 | } |
| 48 | }; |
| 49 | VFSNote(0, HSOpts.VFSOverlayFiles); |
| 50 | VFSNote(1, ExistingHSOpts.VFSOverlayFiles); |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | return false; |
| 55 | } |
| 56 | namespace { |
| 57 | using PrebuiltModuleFilesT = decltype(HeaderSearchOptions::PrebuiltModuleFiles); |
| 58 | |
| 59 | /// A listener that collects the imported modules and the input |
| 60 | /// files. While visiting, collect vfsoverlays and file inputs that determine |
| 61 | /// whether prebuilt modules fully resolve in stable directories. |
| 62 | class PrebuiltModuleListener : public ASTReaderListener { |
| 63 | public: |
| 64 | PrebuiltModuleListener(PrebuiltModuleFilesT &PrebuiltModuleFiles, |
| 65 | llvm::SmallVector<std::string> &NewModuleFiles, |
| 66 | PrebuiltModulesAttrsMap &PrebuiltModulesASTMap, |
| 67 | const HeaderSearchOptions &HSOpts, |
| 68 | const LangOptions &LangOpts, DiagnosticsEngine &Diags, |
| 69 | const ArrayRef<StringRef> StableDirs) |
| 70 | : PrebuiltModuleFiles(PrebuiltModuleFiles), |
| 71 | NewModuleFiles(NewModuleFiles), |
| 72 | PrebuiltModulesASTMap(PrebuiltModulesASTMap), ExistingHSOpts(HSOpts), |
| 73 | ExistingLangOpts(LangOpts), Diags(Diags), StableDirs(StableDirs) {} |
| 74 | |
| 75 | bool needsImportVisitation() const override { return true; } |
| 76 | bool needsInputFileVisitation() override { return true; } |
| 77 | bool needsSystemInputFileVisitation() override { return true; } |
| 78 | |
| 79 | /// Accumulate the modules are transitively depended on by the initial |
| 80 | /// prebuilt module. |
| 81 | void visitImport(StringRef ModuleName, StringRef Filename) override { |
| 82 | if (PrebuiltModuleFiles.insert(x: {ModuleName.str(), Filename.str()}).second) |
| 83 | NewModuleFiles.push_back(Elt: Filename.str()); |
| 84 | |
| 85 | auto PrebuiltMapEntry = PrebuiltModulesASTMap.try_emplace(Key: Filename); |
| 86 | PrebuiltModuleASTAttrs &PrebuiltModule = PrebuiltMapEntry.first->second; |
| 87 | if (PrebuiltMapEntry.second) |
| 88 | PrebuiltModule.setInStableDir(!StableDirs.empty()); |
| 89 | |
| 90 | if (auto It = PrebuiltModulesASTMap.find(Key: CurrentFile); |
| 91 | It != PrebuiltModulesASTMap.end() && CurrentFile != Filename) |
| 92 | PrebuiltModule.addDependent(ModuleFile: It->getKey()); |
| 93 | } |
| 94 | |
| 95 | /// For each input file discovered, check whether it's external path is in a |
| 96 | /// stable directory. Traversal is stopped if the current module is not |
| 97 | /// considered stable. |
| 98 | bool visitInputFileAsRequested(StringRef FilenameAsRequested, |
| 99 | StringRef Filename, bool isSystem, |
| 100 | bool isOverridden, time_t StoredTime, |
| 101 | bool isExplicitModule) override { |
| 102 | if (StableDirs.empty()) |
| 103 | return false; |
| 104 | auto PrebuiltEntryIt = PrebuiltModulesASTMap.find(Key: CurrentFile); |
| 105 | if ((PrebuiltEntryIt == PrebuiltModulesASTMap.end()) || |
| 106 | (!PrebuiltEntryIt->second.isInStableDir())) |
| 107 | return false; |
| 108 | |
| 109 | PrebuiltEntryIt->second.setInStableDir( |
| 110 | isPathInStableDir(Directories: StableDirs, Input: Filename)); |
| 111 | return PrebuiltEntryIt->second.isInStableDir(); |
| 112 | } |
| 113 | |
| 114 | /// Update which module that is being actively traversed. |
| 115 | void visitModuleFile(ModuleFileName Filename, serialization::ModuleKind Kind, |
| 116 | bool DirectlyImported) override { |
| 117 | // If the CurrentFile is not |
| 118 | // considered stable, update any of it's transitive dependents. |
| 119 | auto PrebuiltEntryIt = PrebuiltModulesASTMap.find(Key: CurrentFile); |
| 120 | if ((PrebuiltEntryIt != PrebuiltModulesASTMap.end()) && |
| 121 | !PrebuiltEntryIt->second.isInStableDir()) |
| 122 | PrebuiltEntryIt->second.updateDependentsNotInStableDirs( |
| 123 | PrebuiltModulesMap&: PrebuiltModulesASTMap); |
| 124 | CurrentFile = Filename.str(); |
| 125 | } |
| 126 | |
| 127 | /// Check the header search options for a given module when considering |
| 128 | /// if the module comes from stable directories. |
| 129 | bool (const HeaderSearchOptions &HSOpts, |
| 130 | StringRef ModuleFilename, StringRef ContextHash, |
| 131 | bool Complain) override { |
| 132 | |
| 133 | auto PrebuiltMapEntry = PrebuiltModulesASTMap.try_emplace(Key: CurrentFile); |
| 134 | PrebuiltModuleASTAttrs &PrebuiltModule = PrebuiltMapEntry.first->second; |
| 135 | if (PrebuiltMapEntry.second) |
| 136 | PrebuiltModule.setInStableDir(!StableDirs.empty()); |
| 137 | |
| 138 | if (PrebuiltModule.isInStableDir()) |
| 139 | PrebuiltModule.setInStableDir(areOptionsInStableDir(Directories: StableDirs, HSOpts)); |
| 140 | |
| 141 | return false; |
| 142 | } |
| 143 | |
| 144 | /// Accumulate vfsoverlays used to build these prebuilt modules. |
| 145 | bool (const HeaderSearchOptions &HSOpts, |
| 146 | bool Complain) override { |
| 147 | |
| 148 | auto PrebuiltMapEntry = PrebuiltModulesASTMap.try_emplace(Key: CurrentFile); |
| 149 | PrebuiltModuleASTAttrs &PrebuiltModule = PrebuiltMapEntry.first->second; |
| 150 | if (PrebuiltMapEntry.second) |
| 151 | PrebuiltModule.setInStableDir(!StableDirs.empty()); |
| 152 | |
| 153 | PrebuiltModule.setVFS( |
| 154 | llvm::StringSet<>(llvm::from_range, HSOpts.VFSOverlayFiles)); |
| 155 | |
| 156 | return checkHeaderSearchPaths( |
| 157 | HSOpts, ExistingHSOpts, Diags: Complain ? &Diags : nullptr, LangOpts: ExistingLangOpts); |
| 158 | } |
| 159 | |
| 160 | private: |
| 161 | PrebuiltModuleFilesT &PrebuiltModuleFiles; |
| 162 | llvm::SmallVector<std::string> &NewModuleFiles; |
| 163 | PrebuiltModulesAttrsMap &PrebuiltModulesASTMap; |
| 164 | const HeaderSearchOptions &ExistingHSOpts; |
| 165 | const LangOptions &ExistingLangOpts; |
| 166 | DiagnosticsEngine &Diags; |
| 167 | std::string CurrentFile; |
| 168 | const ArrayRef<StringRef> StableDirs; |
| 169 | }; |
| 170 | } // namespace |
| 171 | |
| 172 | /// Visit the given prebuilt module and collect all of the modules it |
| 173 | /// transitively imports and contributing input files. |
| 174 | static bool visitPrebuiltModule(StringRef PrebuiltModuleFilename, |
| 175 | CompilerInstance &CI, |
| 176 | PrebuiltModuleFilesT &ModuleFiles, |
| 177 | PrebuiltModulesAttrsMap &PrebuiltModulesASTMap, |
| 178 | DiagnosticsEngine &Diags, |
| 179 | const ArrayRef<StringRef> StableDirs) { |
| 180 | // List of module files to be processed. |
| 181 | llvm::SmallVector<std::string> Worklist; |
| 182 | |
| 183 | PrebuiltModuleListener Listener(ModuleFiles, Worklist, PrebuiltModulesASTMap, |
| 184 | CI.getHeaderSearchOpts(), CI.getLangOpts(), |
| 185 | Diags, StableDirs); |
| 186 | |
| 187 | Listener.visitModuleFile(Filename: ModuleFileName::makeExplicit(Name: PrebuiltModuleFilename), |
| 188 | Kind: serialization::MK_ExplicitModule, |
| 189 | /*DirectlyImported=*/true); |
| 190 | if (ASTReader::readASTFileControlBlock( |
| 191 | Filename: PrebuiltModuleFilename, FileMgr&: CI.getFileManager(), ModCache: CI.getModuleCache(), |
| 192 | PCHContainerRdr: CI.getPCHContainerReader(), |
| 193 | /*FindModuleFileExtensions=*/false, Listener, |
| 194 | /*ValidateDiagnosticOptions=*/false, ClientLoadCapabilities: ASTReader::ARR_OutOfDate)) |
| 195 | return true; |
| 196 | |
| 197 | while (!Worklist.empty()) { |
| 198 | // FIXME: This is assuming the PCH only refers to explicitly-built modules, |
| 199 | // which technically is not guaranteed. To remove the assumption, we'd need |
| 200 | // to also rework how the module files are handled to the scan, specifically |
| 201 | // change the values of HeaderSearchOptions::PrebuiltModuleFiles from plain |
| 202 | // paths to ModuleFileName. |
| 203 | Listener.visitModuleFile(Filename: ModuleFileName::makeExplicit(Name: Worklist.back()), |
| 204 | Kind: serialization::MK_ExplicitModule, |
| 205 | /*DirectlyImported=*/false); |
| 206 | if (ASTReader::readASTFileControlBlock( |
| 207 | Filename: Worklist.pop_back_val(), FileMgr&: CI.getFileManager(), ModCache: CI.getModuleCache(), |
| 208 | PCHContainerRdr: CI.getPCHContainerReader(), |
| 209 | /*FindModuleFileExtensions=*/false, Listener, |
| 210 | /*ValidateDiagnosticOptions=*/false)) |
| 211 | return true; |
| 212 | } |
| 213 | return false; |
| 214 | } |
| 215 | |
| 216 | /// Transform arbitrary file name into an object-like file name. |
| 217 | static std::string makeObjFileName(StringRef FileName) { |
| 218 | SmallString<128> ObjFileName(FileName); |
| 219 | llvm::sys::path::replace_extension(path&: ObjFileName, extension: "o" ); |
| 220 | return std::string(ObjFileName); |
| 221 | } |
| 222 | |
| 223 | /// Deduce the dependency target based on the output file and input files. |
| 224 | static std::string |
| 225 | deduceDepTarget(const std::string &OutputFile, |
| 226 | const SmallVectorImpl<FrontendInputFile> &InputFiles) { |
| 227 | if (OutputFile != "-" ) |
| 228 | return OutputFile; |
| 229 | |
| 230 | if (InputFiles.empty() || !InputFiles.front().isFile()) |
| 231 | return "clang-scan-deps\\ dependency" ; |
| 232 | |
| 233 | return makeObjFileName(FileName: InputFiles.front().getFile()); |
| 234 | } |
| 235 | |
| 236 | // Clang implements -D and -U by splatting text into a predefines buffer. This |
| 237 | // allows constructs such as `-DFඞ=3 "-D F\u{0D9E} 4 3 2”` to be accepted and |
| 238 | // define the same macro, or adding C++ style comments before the macro name. |
| 239 | // |
| 240 | // This function checks that the first non-space characters in the macro |
| 241 | // obviously form an identifier that can be uniqued on without lexing. Failing |
| 242 | // to do this could lead to changing the final definition of a macro. |
| 243 | // |
| 244 | // We could set up a preprocessor and actually lex the name, but that's very |
| 245 | // heavyweight for a situation that will almost never happen in practice. |
| 246 | static std::optional<StringRef> getSimpleMacroName(StringRef Macro) { |
| 247 | StringRef Name = Macro.split(Separator: "=" ).first.ltrim(Chars: " \t" ); |
| 248 | std::size_t I = 0; |
| 249 | |
| 250 | auto FinishName = [&]() -> std::optional<StringRef> { |
| 251 | StringRef SimpleName = Name.slice(Start: 0, End: I); |
| 252 | if (SimpleName.empty()) |
| 253 | return std::nullopt; |
| 254 | return SimpleName; |
| 255 | }; |
| 256 | |
| 257 | for (; I != Name.size(); ++I) { |
| 258 | switch (Name[I]) { |
| 259 | case '(': // Start of macro parameter list |
| 260 | case ' ': // End of macro name |
| 261 | case '\t': |
| 262 | return FinishName(); |
| 263 | case '_': |
| 264 | continue; |
| 265 | default: |
| 266 | if (llvm::isAlnum(C: Name[I])) |
| 267 | continue; |
| 268 | return std::nullopt; |
| 269 | } |
| 270 | } |
| 271 | return FinishName(); |
| 272 | } |
| 273 | |
| 274 | static void canonicalizeDefines(PreprocessorOptions &PPOpts) { |
| 275 | using MacroOpt = std::pair<StringRef, std::size_t>; |
| 276 | std::vector<MacroOpt> SimpleNames; |
| 277 | SimpleNames.reserve(n: PPOpts.Macros.size()); |
| 278 | std::size_t Index = 0; |
| 279 | for (const auto &M : PPOpts.Macros) { |
| 280 | auto SName = getSimpleMacroName(Macro: M.first); |
| 281 | // Skip optimizing if we can't guarantee we can preserve relative order. |
| 282 | if (!SName) |
| 283 | return; |
| 284 | SimpleNames.emplace_back(args&: *SName, args&: Index); |
| 285 | ++Index; |
| 286 | } |
| 287 | |
| 288 | llvm::stable_sort(Range&: SimpleNames, C: llvm::less_first()); |
| 289 | // Keep the last instance of each macro name by going in reverse |
| 290 | auto NewEnd = std::unique( |
| 291 | first: SimpleNames.rbegin(), last: SimpleNames.rend(), |
| 292 | binary_pred: [](const MacroOpt &A, const MacroOpt &B) { return A.first == B.first; }); |
| 293 | SimpleNames.erase(first: SimpleNames.begin(), last: NewEnd.base()); |
| 294 | |
| 295 | // Apply permutation. |
| 296 | decltype(PPOpts.Macros) NewMacros; |
| 297 | NewMacros.reserve(n: SimpleNames.size()); |
| 298 | for (std::size_t I = 0, E = SimpleNames.size(); I != E; ++I) { |
| 299 | std::size_t OriginalIndex = SimpleNames[I].second; |
| 300 | // We still emit undefines here as they may be undefining a predefined macro |
| 301 | NewMacros.push_back(x: std::move(PPOpts.Macros[OriginalIndex])); |
| 302 | } |
| 303 | std::swap(x&: PPOpts.Macros, y&: NewMacros); |
| 304 | } |
| 305 | |
| 306 | namespace { |
| 307 | class ScanningDependencyDirectivesGetter : public DependencyDirectivesGetter { |
| 308 | DependencyScanningWorkerFilesystem *DepFS; |
| 309 | |
| 310 | public: |
| 311 | ScanningDependencyDirectivesGetter(FileManager &FileMgr) : DepFS(nullptr) { |
| 312 | FileMgr.getVirtualFileSystem().visit(Callback: [&](llvm::vfs::FileSystem &FS) { |
| 313 | auto *DFS = llvm::dyn_cast<DependencyScanningWorkerFilesystem>(Val: &FS); |
| 314 | if (DFS) { |
| 315 | assert(!DepFS && "Found multiple scanning VFSs" ); |
| 316 | DepFS = DFS; |
| 317 | } |
| 318 | }); |
| 319 | assert(DepFS && "Did not find scanning VFS" ); |
| 320 | } |
| 321 | |
| 322 | std::unique_ptr<DependencyDirectivesGetter> |
| 323 | cloneFor(FileManager &FileMgr) override { |
| 324 | return std::make_unique<ScanningDependencyDirectivesGetter>(args&: FileMgr); |
| 325 | } |
| 326 | |
| 327 | std::optional<ArrayRef<dependency_directives_scan::Directive>> |
| 328 | operator()(FileEntryRef File) override { |
| 329 | return DepFS->getDirectiveTokens(Path: File.getName()); |
| 330 | } |
| 331 | }; |
| 332 | } // namespace |
| 333 | |
| 334 | /// Sanitize diagnostic options for dependency scan. |
| 335 | static void sanitizeDiagOpts(DiagnosticOptions &DiagOpts) { |
| 336 | // Don't print 'X warnings and Y errors generated'. |
| 337 | DiagOpts.ShowCarets = false; |
| 338 | // Don't write out diagnostic file. |
| 339 | DiagOpts.DiagnosticSerializationFile.clear(); |
| 340 | // Don't emit warnings except for scanning specific warnings. |
| 341 | // TODO: It would be useful to add a more principled way to ignore all |
| 342 | // warnings that come from source code. The issue is that we need to |
| 343 | // ignore warnings that could be surpressed by |
| 344 | // `#pragma clang diagnostic`, while still allowing some scanning |
| 345 | // warnings for things we're not ready to turn into errors yet. |
| 346 | // See `test/ClangScanDeps/diagnostic-pragmas.c` for an example. |
| 347 | llvm::erase_if(C&: DiagOpts.Warnings, P: [](StringRef Warning) { |
| 348 | return llvm::StringSwitch<bool>(Warning) |
| 349 | .Cases(CaseStrings: {"pch-vfs-diff" , "error=pch-vfs-diff" }, Value: false) |
| 350 | .StartsWith(S: "no-error=" , Value: false) |
| 351 | .Default(Value: true); |
| 352 | }); |
| 353 | } |
| 354 | |
| 355 | static std::unique_ptr<CompilerInvocation> |
| 356 | createCompilerInvocation(ArrayRef<std::string> CommandLine, |
| 357 | DiagnosticsEngine &Diags) { |
| 358 | llvm::opt::ArgStringList Argv; |
| 359 | for (const std::string &Str : ArrayRef(CommandLine).drop_front()) |
| 360 | Argv.push_back(Elt: Str.c_str()); |
| 361 | |
| 362 | auto Invocation = std::make_unique<CompilerInvocation>(); |
| 363 | if (!CompilerInvocation::CreateFromArgs(Res&: *Invocation, CommandLineArgs: Argv, Diags)) { |
| 364 | // FIXME: Should we just go on like cc1_main does? |
| 365 | return nullptr; |
| 366 | } |
| 367 | return Invocation; |
| 368 | } |
| 369 | |
| 370 | static void initializeScanCompilerInstance( |
| 371 | CompilerInstance &ScanInstance, |
| 372 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS, |
| 373 | DiagnosticConsumer *DiagConsumer, DependencyScanningService &Service, |
| 374 | IntrusiveRefCntPtr<DependencyScanningWorkerFilesystem> DepFS) { |
| 375 | ScanInstance.setBuildingModule(false); |
| 376 | ScanInstance.createVirtualFileSystem(BaseFS: FS, DC: DiagConsumer); |
| 377 | ScanInstance.createDiagnostics(Client: DiagConsumer, /*ShouldOwnClient=*/false); |
| 378 | if (!Service.getOpts().EmitWarnings) |
| 379 | ScanInstance.getDiagnostics().setIgnoreAllWarnings(true); |
| 380 | ScanInstance.createFileManager(); |
| 381 | ScanInstance.createSourceManager(); |
| 382 | |
| 383 | // Use DepFS for getting the dependency directives if requested to do so. |
| 384 | if (Service.getOpts().Mode == ScanningMode::DependencyDirectivesScan) |
| 385 | ScanInstance.setDependencyDirectivesGetter( |
| 386 | std::make_unique<ScanningDependencyDirectivesGetter>( |
| 387 | args&: ScanInstance.getFileManager())); |
| 388 | } |
| 389 | |
| 390 | static std::shared_ptr<CompilerInvocation> |
| 391 | createScanCompilerInvocation(const CompilerInvocation &Invocation, |
| 392 | const DependencyScanningService &Service, |
| 393 | DependencyActionController &Controller) { |
| 394 | auto ScanInvocation = std::make_shared<CompilerInvocation>(args: Invocation); |
| 395 | |
| 396 | sanitizeDiagOpts(DiagOpts&: ScanInvocation->getDiagnosticOpts()); |
| 397 | |
| 398 | ScanInvocation->getPreprocessorOpts().AllowPCHWithDifferentModulesCachePath = |
| 399 | true; |
| 400 | |
| 401 | if (ScanInvocation->getHeaderSearchOpts().ModulesValidateOncePerBuildSession) |
| 402 | ScanInvocation->getHeaderSearchOpts().BuildSessionTimestamp = |
| 403 | Service.getOpts().BuildSessionTimestamp; |
| 404 | |
| 405 | ScanInvocation->getFrontendOpts().DisableFree = false; |
| 406 | ScanInvocation->getFrontendOpts().GenerateGlobalModuleIndex = false; |
| 407 | ScanInvocation->getFrontendOpts().UseGlobalModuleIndex = false; |
| 408 | ScanInvocation->getFrontendOpts().GenReducedBMI = false; |
| 409 | ScanInvocation->getFrontendOpts().ModuleOutputPath.clear(); |
| 410 | // This will prevent us compiling individual modules asynchronously since |
| 411 | // FileManager is not thread-safe, but it does improve performance for now. |
| 412 | ScanInvocation->getFrontendOpts().ModulesShareFileManager = true; |
| 413 | ScanInvocation->getHeaderSearchOpts().ModuleFormat = "raw" ; |
| 414 | ScanInvocation->getHeaderSearchOpts().ModulesIncludeVFSUsage = |
| 415 | any(Val: Service.getOpts().OptimizeArgs & ScanningOptimizations::VFS); |
| 416 | |
| 417 | // Consider different header search and diagnostic options to create |
| 418 | // different modules. This avoids the unsound aliasing of module PCMs. |
| 419 | // |
| 420 | // TODO: Implement diagnostic bucketing to reduce the impact of strict |
| 421 | // context hashing. |
| 422 | ScanInvocation->getHeaderSearchOpts().ModulesStrictContextHash = true; |
| 423 | ScanInvocation->getHeaderSearchOpts().ModulesSerializeOnlyPreprocessor = true; |
| 424 | ScanInvocation->getHeaderSearchOpts().ModulesSkipDiagnosticOptions = true; |
| 425 | ScanInvocation->getHeaderSearchOpts().ModulesSkipHeaderSearchPaths = true; |
| 426 | ScanInvocation->getHeaderSearchOpts().ModulesSkipPragmaDiagnosticMappings = |
| 427 | true; |
| 428 | ScanInvocation->getHeaderSearchOpts().ModulesForceValidateUserHeaders = false; |
| 429 | |
| 430 | // FIXME: Do this even with PCHs by marking the option as something like |
| 431 | // "preprocessor benign" in LangOptions.def so that it passes the |
| 432 | // compatibility checks in ASTReader. |
| 433 | if (ScanInvocation->getPreprocessorOpts().ImplicitPCHInclude.empty()) { |
| 434 | // Application extension only affects the handling of availability |
| 435 | // attributes, which cannot change the dependencies. |
| 436 | ScanInvocation->getLangOpts().AppExt = false; |
| 437 | } |
| 438 | |
| 439 | // Ensure that the scanner does not create new dependency collectors, |
| 440 | // and thus won't write out the extra '.d' files to disk. |
| 441 | ScanInvocation->getDependencyOutputOpts() = {}; |
| 442 | |
| 443 | Controller.initializeScanInvocation(ScanInvocation&: *ScanInvocation); |
| 444 | |
| 445 | return ScanInvocation; |
| 446 | } |
| 447 | |
| 448 | static llvm::SmallVector<StringRef> |
| 449 | getInitialStableDirs(const CompilerInstance &ScanInstance) { |
| 450 | // Create a collection of stable directories derived from the ScanInstance |
| 451 | // for determining whether module dependencies would fully resolve from |
| 452 | // those directories. |
| 453 | llvm::SmallVector<StringRef> StableDirs; |
| 454 | const StringRef Sysroot = ScanInstance.getHeaderSearchOpts().Sysroot; |
| 455 | if (!Sysroot.empty() && (llvm::sys::path::root_directory(path: Sysroot) != Sysroot)) |
| 456 | StableDirs = {Sysroot, ScanInstance.getHeaderSearchOpts().ResourceDir}; |
| 457 | return StableDirs; |
| 458 | } |
| 459 | |
| 460 | static std::optional<PrebuiltModulesAttrsMap> |
| 461 | computePrebuiltModulesASTMap(CompilerInstance &ScanInstance, |
| 462 | llvm::SmallVector<StringRef> &StableDirs) { |
| 463 | // Store a mapping of prebuilt module files and their properties like header |
| 464 | // search options. This will prevent the implicit build to create duplicate |
| 465 | // modules and will force reuse of the existing prebuilt module files |
| 466 | // instead. |
| 467 | PrebuiltModulesAttrsMap PrebuiltModulesASTMap; |
| 468 | |
| 469 | if (!ScanInstance.getPreprocessorOpts().ImplicitPCHInclude.empty()) |
| 470 | if (visitPrebuiltModule( |
| 471 | PrebuiltModuleFilename: ScanInstance.getPreprocessorOpts().ImplicitPCHInclude, CI&: ScanInstance, |
| 472 | ModuleFiles&: ScanInstance.getHeaderSearchOpts().PrebuiltModuleFiles, |
| 473 | PrebuiltModulesASTMap, Diags&: ScanInstance.getDiagnostics(), StableDirs)) |
| 474 | return {}; |
| 475 | |
| 476 | return PrebuiltModulesASTMap; |
| 477 | } |
| 478 | |
| 479 | static std::unique_ptr<DependencyOutputOptions> |
| 480 | createDependencyOutputOptions(const CompilerInvocation &Invocation) { |
| 481 | auto Opts = std::make_unique<DependencyOutputOptions>( |
| 482 | args: Invocation.getDependencyOutputOpts()); |
| 483 | // We need at least one -MT equivalent for the generator of make dependency |
| 484 | // files to work. |
| 485 | if (Opts->Targets.empty()) |
| 486 | Opts->Targets = {deduceDepTarget(OutputFile: Invocation.getFrontendOpts().OutputFile, |
| 487 | InputFiles: Invocation.getFrontendOpts().Inputs)}; |
| 488 | Opts->IncludeSystemHeaders = true; |
| 489 | |
| 490 | return Opts; |
| 491 | } |
| 492 | |
| 493 | static std::shared_ptr<ModuleDepCollector> |
| 494 | initializeScanInstanceDependencyCollector( |
| 495 | CompilerInstance &ScanInstance, |
| 496 | std::unique_ptr<DependencyOutputOptions> DepOutputOpts, |
| 497 | DependencyScanningService &Service, CompilerInvocation &Inv, |
| 498 | DependencyActionController &Controller, |
| 499 | PrebuiltModulesAttrsMap PrebuiltModulesASTMap, |
| 500 | SmallVector<StringRef> &StableDirs) { |
| 501 | auto MDC = std::make_shared<ModuleDepCollector>( |
| 502 | args&: Service, args: std::move(DepOutputOpts), args&: ScanInstance, args&: Controller, args&: Inv, |
| 503 | args: std::move(PrebuiltModulesASTMap), args&: StableDirs); |
| 504 | ScanInstance.addDependencyCollector(Listener: MDC); |
| 505 | return MDC; |
| 506 | } |
| 507 | |
| 508 | namespace { |
| 509 | /// Manages (and terminates) the asynchronous compilation of modules. |
| 510 | class AsyncModuleCompiles { |
| 511 | std::mutex Mutex; |
| 512 | bool Stop = false; |
| 513 | // FIXME: Have the service own a thread pool and use that instead. |
| 514 | std::vector<std::thread> Compiles; |
| 515 | |
| 516 | public: |
| 517 | /// Registers the module compilation, unless this instance is about to be |
| 518 | /// destroyed. |
| 519 | void add(llvm::unique_function<void()> Compile) { |
| 520 | std::lock_guard<std::mutex> Lock(Mutex); |
| 521 | if (!Stop) |
| 522 | Compiles.emplace_back(args: std::move(Compile)); |
| 523 | } |
| 524 | |
| 525 | ~AsyncModuleCompiles() { |
| 526 | { |
| 527 | std::lock_guard<std::mutex> Lock(Mutex); |
| 528 | Stop = true; |
| 529 | } |
| 530 | for (std::thread &Compile : Compiles) |
| 531 | Compile.join(); |
| 532 | } |
| 533 | }; |
| 534 | |
| 535 | struct SingleModuleWithAsyncModuleCompiles : PreprocessOnlyAction { |
| 536 | DependencyScanningService &Service; |
| 537 | DependencyActionController &Controller; |
| 538 | AsyncModuleCompiles &Compiles; |
| 539 | |
| 540 | SingleModuleWithAsyncModuleCompiles(DependencyScanningService &Service, |
| 541 | DependencyActionController &Controller, |
| 542 | AsyncModuleCompiles &Compiles) |
| 543 | : Service(Service), Controller(Controller), Compiles(Compiles) {} |
| 544 | |
| 545 | bool BeginSourceFileAction(CompilerInstance &CI) override; |
| 546 | }; |
| 547 | |
| 548 | /// Runs the preprocessor on a TU with single-module-parse-mode and compiles |
| 549 | /// modules asynchronously without blocking or importing them. |
| 550 | struct SingleTUWithAsyncModuleCompiles : PreprocessOnlyAction { |
| 551 | DependencyScanningService &Service; |
| 552 | DependencyActionController &Controller; |
| 553 | AsyncModuleCompiles &Compiles; |
| 554 | |
| 555 | SingleTUWithAsyncModuleCompiles(DependencyScanningService &Service, |
| 556 | DependencyActionController &Controller, |
| 557 | AsyncModuleCompiles &Compiles) |
| 558 | : Service(Service), Controller(Controller), Compiles(Compiles) {} |
| 559 | |
| 560 | bool BeginSourceFileAction(CompilerInstance &CI) override; |
| 561 | }; |
| 562 | |
| 563 | /// The preprocessor callback that takes care of initiating an asynchronous |
| 564 | /// module compilation if needed. |
| 565 | struct AsyncModuleCompile : PPCallbacks { |
| 566 | CompilerInstance &CI; |
| 567 | DependencyScanningService &Service; |
| 568 | DependencyActionController &Controller; |
| 569 | AsyncModuleCompiles &Compiles; |
| 570 | |
| 571 | AsyncModuleCompile(CompilerInstance &CI, DependencyScanningService &Service, |
| 572 | DependencyActionController &Controller, |
| 573 | AsyncModuleCompiles &Compiles) |
| 574 | : CI(CI), Service(Service), Controller(Controller), Compiles(Compiles) {} |
| 575 | |
| 576 | void moduleLoadSkipped(Module *M) override { |
| 577 | M = M->getTopLevelModule(); |
| 578 | |
| 579 | HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo(); |
| 580 | ModuleCache &ModCache = CI.getModuleCache(); |
| 581 | ModuleFileName ModuleFileName = HS.getCachedModuleFileName(Module: M); |
| 582 | |
| 583 | uint64_t Timestamp = ModCache.getModuleTimestamp(ModuleFilename: ModuleFileName); |
| 584 | // Someone else already built/validated the PCM. |
| 585 | if (Timestamp > CI.getHeaderSearchOpts().BuildSessionTimestamp) |
| 586 | return; |
| 587 | |
| 588 | if (!CI.getASTReader()) |
| 589 | CI.createASTReader(); |
| 590 | SmallVector<ASTReader::ImportedModule, 0> Imported; |
| 591 | // Only calling ReadASTCore() to avoid the expensive eager deserialization |
| 592 | // of the clang::Module objects in ReadAST(). |
| 593 | // FIXME: Consider doing this in the new thread depending on how expensive |
| 594 | // the read turns out to be. |
| 595 | switch (CI.getASTReader()->ReadASTCore( |
| 596 | FileName: ModuleFileName, Type: serialization::MK_ImplicitModule, ImportLoc: SourceLocation(), |
| 597 | ImportedBy: nullptr, Loaded&: Imported, ExpectedSize: {}, ExpectedModTime: {}, ExpectedSignature: {}, |
| 598 | ClientLoadCapabilities: ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing | |
| 599 | ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate)) { |
| 600 | case ASTReader::Success: |
| 601 | // We successfully read a valid, up-to-date PCM. |
| 602 | // FIXME: This could update the timestamp. Regular calls to |
| 603 | // ASTReader::ReadAST() would do so unless they encountered corrupted |
| 604 | // AST block, corrupted extension block, or did not read the expected |
| 605 | // top-level module. |
| 606 | return; |
| 607 | case ASTReader::OutOfDate: |
| 608 | case ASTReader::Missing: |
| 609 | // The most interesting case. |
| 610 | break; |
| 611 | default: |
| 612 | // Let the regular scan diagnose this. |
| 613 | return; |
| 614 | } |
| 615 | |
| 616 | auto Lock = ModCache.getLock(ModuleFilename: ModuleFileName); |
| 617 | bool Owned; |
| 618 | llvm::Error LockErr = Lock->tryLock().moveInto(Value&: Owned); |
| 619 | // Someone else is building the PCM right now. |
| 620 | if (!LockErr && !Owned) |
| 621 | return; |
| 622 | // We should build the PCM. |
| 623 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = |
| 624 | llvm::makeIntrusiveRefCnt<DependencyScanningWorkerFilesystem>( |
| 625 | A&: Service, A: Service.getOpts().MakeVFS()); |
| 626 | VFS = createVFSFromCompilerInvocation(CI: CI.getInvocation(), |
| 627 | Diags&: CI.getDiagnostics(), BaseFS: std::move(VFS)); |
| 628 | auto DC = std::make_unique<DiagnosticConsumer>(); |
| 629 | auto MC = makeInProcessModuleCache(Entries&: Service.getModuleCacheEntries(), |
| 630 | Logger&: Service.getLogger()); |
| 631 | CompilerInstance::ThreadSafeCloneConfig CloneConfig(std::move(VFS), *DC, |
| 632 | std::move(MC)); |
| 633 | auto ModCI1 = CI.cloneForModuleCompile(ImportLoc: SourceLocation(), Module: M, ModuleFileName, |
| 634 | ThreadSafeConfig: CloneConfig); |
| 635 | auto ModCI2 = CI.cloneForModuleCompile(ImportLoc: SourceLocation(), Module: M, ModuleFileName, |
| 636 | ThreadSafeConfig: CloneConfig); |
| 637 | |
| 638 | auto ModController = Controller.clone(); |
| 639 | |
| 640 | // Note: This lock belongs to a module cache that might not outlive the |
| 641 | // thread. This works, because the in-process lock only refers to an object |
| 642 | // managed by the service, which does outlive the thread. |
| 643 | Compiles.add(Compile: [Lock = std::move(Lock), ModCI1 = std::move(ModCI1), |
| 644 | ModCI2 = std::move(ModCI2), DC = std::move(DC), |
| 645 | ModController = std::move(ModController), Service = &Service, |
| 646 | Compiles = &Compiles] { |
| 647 | llvm::CrashRecoveryContext CRC; |
| 648 | (void)CRC.RunSafely(Fn: [&] { |
| 649 | // Quickly discovers and compiles modules for the real scan below. |
| 650 | SingleModuleWithAsyncModuleCompiles Action1(*Service, *ModController, |
| 651 | *Compiles); |
| 652 | (void)ModCI1->ExecuteAction(Act&: Action1); |
| 653 | // The real scan below. |
| 654 | ModCI2->getPreprocessorOpts().SingleModuleParseMode = false; |
| 655 | GenerateModuleFromModuleMapAction Action2; |
| 656 | (void)ModCI2->ExecuteAction(Act&: Action2); |
| 657 | }); |
| 658 | }); |
| 659 | } |
| 660 | }; |
| 661 | |
| 662 | bool SingleModuleWithAsyncModuleCompiles::BeginSourceFileAction( |
| 663 | CompilerInstance &CI) { |
| 664 | CI.getInvocation().getPreprocessorOpts().SingleModuleParseMode = true; |
| 665 | CI.getPreprocessor().addPPCallbacks( |
| 666 | C: std::make_unique<AsyncModuleCompile>(args&: CI, args&: Service, args&: Controller, args&: Compiles)); |
| 667 | return true; |
| 668 | } |
| 669 | |
| 670 | bool SingleTUWithAsyncModuleCompiles::BeginSourceFileAction( |
| 671 | CompilerInstance &CI) { |
| 672 | CI.getInvocation().getPreprocessorOpts().SingleModuleParseMode = true; |
| 673 | CI.getPreprocessor().addPPCallbacks( |
| 674 | C: std::make_unique<AsyncModuleCompile>(args&: CI, args&: Service, args&: Controller, args&: Compiles)); |
| 675 | return true; |
| 676 | } |
| 677 | } // namespace |
| 678 | |
| 679 | static void runTUModulePrescan(CompilerInstance &PrescanCI, |
| 680 | DependencyScanningService &Service, |
| 681 | DependencyActionController &Controller, |
| 682 | AsyncModuleCompiles &Compiles) { |
| 683 | SingleTUWithAsyncModuleCompiles Action(Service, Controller, Compiles); |
| 684 | (void)PrescanCI.ExecuteAction(Act&: Action); |
| 685 | } |
| 686 | |
| 687 | namespace clang { |
| 688 | namespace dependencies { |
| 689 | |
| 690 | std::unique_ptr<DiagnosticOptions> |
| 691 | createScanningDiagOptions(ArrayRef<std::string> CommandLine) { |
| 692 | std::vector<const char *> CCommandLine(CommandLine.size(), nullptr); |
| 693 | llvm::transform(Range&: CommandLine, d_first: CCommandLine.begin(), |
| 694 | F: [](const std::string &Str) { return Str.c_str(); }); |
| 695 | auto DiagOpts = CreateAndPopulateDiagOpts(Argv: CCommandLine); |
| 696 | sanitizeDiagOpts(DiagOpts&: *DiagOpts); |
| 697 | return DiagOpts; |
| 698 | } |
| 699 | |
| 700 | class CompilerInstanceWithContext { |
| 701 | // Context |
| 702 | DependencyScanningWorker &Worker; |
| 703 | llvm::StringRef CWD; |
| 704 | std::vector<std::string> CommandLine; |
| 705 | |
| 706 | // Context - compiler invocation |
| 707 | std::unique_ptr<CompilerInvocation> OriginalInvocation; |
| 708 | |
| 709 | // Context - output options |
| 710 | std::unique_ptr<DependencyOutputOptions> OutputOpts; |
| 711 | |
| 712 | // Context - stable directory handling |
| 713 | llvm::SmallVector<StringRef> StableDirs; |
| 714 | PrebuiltModulesAttrsMap PrebuiltModuleASTMap; |
| 715 | |
| 716 | // Context - used by AsyncScan's prescan pass |
| 717 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> ScanFS; |
| 718 | |
| 719 | // Compiler Instance |
| 720 | std::unique_ptr<CompilerInstance> CIPtr; |
| 721 | |
| 722 | // Source location offset. |
| 723 | int32_t SrcLocOffset = 0; |
| 724 | |
| 725 | CompilerInstanceWithContext(DependencyScanningWorker &Worker, StringRef CWD, |
| 726 | ArrayRef<std::string> CMD) |
| 727 | : Worker(Worker), CWD(CWD), CommandLine(CMD.begin(), CMD.end()) {} |
| 728 | |
| 729 | bool initialize(DependencyActionController &Controller, |
| 730 | DiagnosticsEngine &DiagEngine, |
| 731 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> OverlayFS) { |
| 732 | { |
| 733 | auto LogLine = Worker.Service.getLogger().log(); |
| 734 | LogLine.logArray(Prefix: "init_compiler_instance_with_context:" , Sep: " " , |
| 735 | Arr: CommandLine); |
| 736 | } |
| 737 | |
| 738 | ScanFS = Worker.makeEffectiveVFS(WorkingDirectory: CWD, OverlayFS: std::move(OverlayFS)); |
| 739 | OriginalInvocation = createCompilerInvocation(CommandLine, Diags&: DiagEngine); |
| 740 | if (!OriginalInvocation) { |
| 741 | DiagEngine.Report(DiagID: diag::err_fe_expected_compiler_job) |
| 742 | << llvm::join(R&: CommandLine, Separator: " " ); |
| 743 | return false; |
| 744 | } |
| 745 | |
| 746 | return initializeScanInstance(Controller, DiagConsumer: DiagEngine.getClient()); |
| 747 | } |
| 748 | |
| 749 | bool initializeScanInstance(DependencyActionController &Controller, |
| 750 | DiagnosticConsumer *DiagConsumer) { |
| 751 | assert(OriginalInvocation && ScanFS && |
| 752 | "OriginalInvocation and ScanFS must be set before this call" ); |
| 753 | |
| 754 | if (any(Val: Worker.Service.getOpts().OptimizeArgs & |
| 755 | ScanningOptimizations::Macros)) |
| 756 | canonicalizeDefines(PPOpts&: OriginalInvocation->getPreprocessorOpts()); |
| 757 | |
| 758 | // Create the CompilerInstance. |
| 759 | std::shared_ptr<ModuleCache> ModCache = makeInProcessModuleCache( |
| 760 | Entries&: Worker.Service.getModuleCacheEntries(), Logger&: Worker.Service.getLogger()); |
| 761 | CIPtr = std::make_unique<CompilerInstance>( |
| 762 | args: createScanCompilerInvocation(Invocation: *OriginalInvocation, Service: Worker.Service, |
| 763 | Controller), |
| 764 | args&: Worker.PCHContainerOps, args: std::move(ModCache)); |
| 765 | auto &CI = *CIPtr; |
| 766 | |
| 767 | initializeScanCompilerInstance(ScanInstance&: CI, FS: ScanFS, DiagConsumer, Service&: Worker.Service, |
| 768 | DepFS: Worker.DepFS); |
| 769 | |
| 770 | StableDirs = getInitialStableDirs(ScanInstance: CI); |
| 771 | auto MaybePrebuiltModulesASTMap = |
| 772 | computePrebuiltModulesASTMap(ScanInstance&: CI, StableDirs); |
| 773 | if (!MaybePrebuiltModulesASTMap) |
| 774 | return false; |
| 775 | |
| 776 | PrebuiltModuleASTMap = std::move(*MaybePrebuiltModulesASTMap); |
| 777 | OutputOpts = createDependencyOutputOptions(Invocation: *OriginalInvocation); |
| 778 | |
| 779 | // We do not create the target in initializeScanCompilerInstance because |
| 780 | // setting it here is unique for by-name lookups. We create the target only |
| 781 | // once here, and the information is reused for all computeDependencies |
| 782 | // calls. We do not need to call createTarget explicitly if we go through |
| 783 | // CompilerInstance::ExecuteAction to perform scanning. |
| 784 | return CI.createTarget(); |
| 785 | } |
| 786 | |
| 787 | bool prescanModulesAsync(AsyncModuleCompiles &Compiles, |
| 788 | DependencyActionController &Controller) { |
| 789 | auto ModCache = makeInProcessModuleCache( |
| 790 | Entries&: Worker.Service.getModuleCacheEntries(), Logger&: Worker.Service.getLogger()); |
| 791 | CompilerInstance PrescanCI( |
| 792 | std::make_shared<CompilerInvocation>(args&: CIPtr->getInvocation()), |
| 793 | Worker.PCHContainerOps, std::move(ModCache)); |
| 794 | |
| 795 | DiagnosticConsumer DiagConsumer; |
| 796 | initializeScanCompilerInstance(ScanInstance&: PrescanCI, FS: ScanFS, DiagConsumer: &DiagConsumer, |
| 797 | Service&: Worker.Service, DepFS: Worker.DepFS); |
| 798 | |
| 799 | // FIXME: reuse the StableDirs/PrebuiltModuleASTMap computed in |
| 800 | // initialize(). |
| 801 | SmallVector<StringRef> PrescanStableDirs = getInitialStableDirs(ScanInstance: PrescanCI); |
| 802 | if (!computePrebuiltModulesASTMap(ScanInstance&: PrescanCI, StableDirs&: PrescanStableDirs)) |
| 803 | return false; |
| 804 | |
| 805 | if (PrescanCI.getFrontendOpts().ProgramAction == frontend::GeneratePCH) |
| 806 | PrescanCI.getLangOpts().CompilingPCH = true; |
| 807 | |
| 808 | runTUModulePrescan(PrescanCI, Service&: Worker.Service, Controller, Compiles); |
| 809 | return true; |
| 810 | } |
| 811 | |
| 812 | public: |
| 813 | static std::optional<CompilerInstanceWithContext> |
| 814 | initializeFromCC1Commandline( |
| 815 | DependencyScanningWorker &Worker, StringRef CWD, |
| 816 | ArrayRef<std::string> CC1CommandLine, DiagnosticsEngine &DiagEngine, |
| 817 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> OverlayFS, |
| 818 | DependencyActionController &Controller) { |
| 819 | CompilerInstanceWithContext CIWC(Worker, CWD, CC1CommandLine); |
| 820 | if (!CIWC.initialize(Controller, DiagEngine, OverlayFS: std::move(OverlayFS))) |
| 821 | return std::nullopt; |
| 822 | return std::move(CIWC); |
| 823 | } |
| 824 | |
| 825 | bool computeDependencies(StringRef ModuleName, DependencyConsumer &Consumer, |
| 826 | DependencyActionController &Controller) { |
| 827 | Worker.Service.getLogger().log() << "start scan_by_name: " << ModuleName; |
| 828 | llvm::scope_exit ExitLogging([&] { |
| 829 | Worker.Service.getLogger().log() << "finish scan_by_name: " << ModuleName; |
| 830 | }); |
| 831 | if (SrcLocOffset >= DependencyScanningWorker::MaxNumOfByNameQueries) |
| 832 | llvm::report_fatal_error(reason: "exceeded maximum by-name scans for worker" ); |
| 833 | |
| 834 | assert(CIPtr && "CIPtr must be initialized before calling this method" ); |
| 835 | auto &CI = *CIPtr; |
| 836 | |
| 837 | // We need to reset the diagnostics, so that the diagnostics issued |
| 838 | // during a previous computeDependencies call do not affect the current |
| 839 | // call. If we do not reset, we may inherit fatal errors from a previous |
| 840 | // call. |
| 841 | CI.getDiagnostics().Reset(); |
| 842 | |
| 843 | // We create this cleanup object because computeDependencies may exit |
| 844 | // early with errors. |
| 845 | llvm::scope_exit CleanUp([&]() { |
| 846 | CI.clearDependencyCollectors(); |
| 847 | // The preprocessor may not be created at the entry of this method, |
| 848 | // but it must have been created when this method returns, whether |
| 849 | // there are errors during scanning or not. |
| 850 | CI.getPreprocessor().removePPCallbacks(); |
| 851 | }); |
| 852 | |
| 853 | auto MDC = initializeScanInstanceDependencyCollector( |
| 854 | ScanInstance&: CI, DepOutputOpts: std::make_unique<DependencyOutputOptions>(args&: *OutputOpts), |
| 855 | Service&: Worker.Service, |
| 856 | /* The MDC's constructor makes a copy of the OriginalInvocation, so |
| 857 | we can pass it in without worrying that it might be changed across |
| 858 | invocations of computeDependencies. */ |
| 859 | Inv&: *OriginalInvocation, Controller, PrebuiltModulesASTMap: PrebuiltModuleASTMap, StableDirs); |
| 860 | |
| 861 | CompilerInvocation ModuleInvocation(*OriginalInvocation); |
| 862 | if (!Controller.initialize(ScanInstance&: CI, NewInvocation&: ModuleInvocation)) |
| 863 | return false; |
| 864 | |
| 865 | if (!SrcLocOffset) { |
| 866 | // When SrcLocOffset is zero, we are at the beginning of the fake source |
| 867 | // file. In this case, we call BeginSourceFile to initialize. |
| 868 | std::unique_ptr<FrontendAction> Action = |
| 869 | std::make_unique<PreprocessOnlyAction>(); |
| 870 | auto *InputFile = CI.getFrontendOpts().Inputs.begin(); |
| 871 | bool ActionBeginSucceeded = Action->BeginSourceFile(CI, Input: *InputFile); |
| 872 | assert(ActionBeginSucceeded && "Action BeginSourceFile must succeed" ); |
| 873 | (void)ActionBeginSucceeded; |
| 874 | } |
| 875 | |
| 876 | Preprocessor &PP = CI.getPreprocessor(); |
| 877 | SourceManager &SM = PP.getSourceManager(); |
| 878 | FileID MainFileID = SM.getMainFileID(); |
| 879 | SourceLocation FileStart = SM.getLocForStartOfFile(FID: MainFileID); |
| 880 | SourceLocation IDLocation = FileStart.getLocWithOffset(Offset: SrcLocOffset); |
| 881 | PPCallbacks *CB = nullptr; |
| 882 | if (!SrcLocOffset) { |
| 883 | // We need to call EnterSourceFile when SrcLocOffset is zero to initialize |
| 884 | // the preprocessor. |
| 885 | bool PPFailed = PP.EnterSourceFile(FID: MainFileID, Dir: nullptr, Loc: SourceLocation()); |
| 886 | assert(!PPFailed && "Preprocess must be able to enter the main file." ); |
| 887 | (void)PPFailed; |
| 888 | CB = MDC->getPPCallbacks(); |
| 889 | } else { |
| 890 | // When SrcLocOffset is non-zero, the preprocessor has already been |
| 891 | // initialized through a previous call of computeDependencies. We want to |
| 892 | // preserve the PP's state, hence we do not call EnterSourceFile again. |
| 893 | MDC->attachToPreprocessor(PP); |
| 894 | CB = MDC->getPPCallbacks(); |
| 895 | |
| 896 | FileID PrevFID; |
| 897 | SrcMgr::CharacteristicKind FileType = |
| 898 | SM.getFileCharacteristic(Loc: IDLocation); |
| 899 | CB->LexedFileChanged(FID: MainFileID, |
| 900 | Reason: PPChainedCallbacks::LexedFileChangeReason::EnterFile, |
| 901 | FileType, PrevFID, Loc: IDLocation); |
| 902 | } |
| 903 | |
| 904 | // FIXME: Scan modules asynchronously here as well. |
| 905 | |
| 906 | SrcLocOffset++; |
| 907 | SmallVector<IdentifierLoc, 2> Path; |
| 908 | IdentifierInfo *ModuleID = PP.getIdentifierInfo(Name: ModuleName); |
| 909 | Path.emplace_back(Args&: IDLocation, Args&: ModuleID); |
| 910 | auto ModResult = CI.loadModule(ImportLoc: IDLocation, Path, Visibility: Module::Hidden, IsInclusionDirective: false); |
| 911 | |
| 912 | assert(CB && "Must have PPCallbacks after module loading" ); |
| 913 | CB->moduleImport(ImportLoc: SourceLocation(), Path, Imported: ModResult); |
| 914 | |
| 915 | if (!ModResult) |
| 916 | return false; |
| 917 | |
| 918 | if (CI.getDiagnostics().hasErrorOccurred()) |
| 919 | return false; |
| 920 | |
| 921 | MDC->run(Consumer); |
| 922 | MDC->applyDiscoveredDependencies(CI&: ModuleInvocation); |
| 923 | |
| 924 | bool Success = ModuleInvocation.withCowRef<bool>( |
| 925 | Fn: [&](CowCompilerInvocation &CowModuleInvocation) { |
| 926 | return Controller.finalize(ScanInstance&: CI, NewInvocation&: CowModuleInvocation); |
| 927 | }); |
| 928 | if (!Success) |
| 929 | return false; |
| 930 | |
| 931 | Consumer.handleBuildCommand( |
| 932 | Cmd: {.Executable: CommandLine[0], .Arguments: ModuleInvocation.getCC1CommandLine()}); |
| 933 | |
| 934 | return true; |
| 935 | } |
| 936 | |
| 937 | std::shared_ptr<ModuleDepCollector> |
| 938 | scanTranslationUnit(DependencyConsumer &Consumer, |
| 939 | DependencyActionController &Controller) { |
| 940 | assert(CIPtr && "CIPtr must be initialized before calling this method" ); |
| 941 | auto &CI = *CIPtr; |
| 942 | |
| 943 | std::optional<AsyncModuleCompiles> AsyncCompiles; |
| 944 | if (Worker.Service.getOpts().AsyncScanModules) { |
| 945 | AsyncCompiles.emplace(); |
| 946 | if (!prescanModulesAsync(Compiles&: *AsyncCompiles, Controller)) |
| 947 | return nullptr; |
| 948 | } |
| 949 | |
| 950 | auto MDC = initializeScanInstanceDependencyCollector( |
| 951 | ScanInstance&: CI, DepOutputOpts: std::make_unique<DependencyOutputOptions>(args&: *OutputOpts), |
| 952 | Service&: Worker.Service, Inv&: *OriginalInvocation, Controller, PrebuiltModulesASTMap: PrebuiltModuleASTMap, |
| 953 | StableDirs); |
| 954 | |
| 955 | if (CI.getDiagnostics().hasErrorOccurred()) |
| 956 | return nullptr; |
| 957 | |
| 958 | if (!Controller.initialize(ScanInstance&: CI, NewInvocation&: *OriginalInvocation)) |
| 959 | return nullptr; |
| 960 | |
| 961 | ReadPCHAndPreprocessAction Action; |
| 962 | if (!CI.ExecuteAction(Act&: Action)) |
| 963 | return nullptr; |
| 964 | |
| 965 | MDC->run(Consumer); |
| 966 | if (!applyAndReport(MDC&: *MDC, ModuleInvocation&: *OriginalInvocation, Consumer, Controller, |
| 967 | Executable: CommandLine[0])) |
| 968 | return nullptr; |
| 969 | return MDC; |
| 970 | } |
| 971 | |
| 972 | bool applyAndReport(ModuleDepCollector &MDC, |
| 973 | CompilerInvocation &ModuleInvocation, |
| 974 | DependencyConsumer &Consumer, |
| 975 | DependencyActionController &Controller, |
| 976 | StringRef Executable) { |
| 977 | MDC.applyDiscoveredDependencies(CI&: ModuleInvocation); |
| 978 | bool Success = ModuleInvocation.withCowRef<bool>( |
| 979 | Fn: [&](CowCompilerInvocation &CowModuleInvocation) { |
| 980 | return Controller.finalize(ScanInstance&: *CIPtr, NewInvocation&: CowModuleInvocation); |
| 981 | }); |
| 982 | if (!Success) |
| 983 | return false; |
| 984 | Consumer.handleBuildCommand( |
| 985 | Cmd: {.Executable: Executable.str(), .Arguments: ModuleInvocation.getCC1CommandLine()}); |
| 986 | return true; |
| 987 | } |
| 988 | }; |
| 989 | } // namespace dependencies |
| 990 | } // namespace clang |
| 991 | |
| 992 | DependencyScanningWorker::DependencyScanningWorker( |
| 993 | DependencyScanningService &Service) |
| 994 | : Service(Service) { |
| 995 | PCHContainerOps = std::make_shared<PCHContainerOperations>(); |
| 996 | // We need to read object files from PCH built outside the scanner. |
| 997 | PCHContainerOps->registerReader( |
| 998 | Reader: std::make_unique<ObjectFilePCHContainerReader>()); |
| 999 | // The scanner itself writes only raw ast files. |
| 1000 | PCHContainerOps->registerWriter(Writer: std::make_unique<RawPCHContainerWriter>()); |
| 1001 | |
| 1002 | auto BaseFS = Service.getOpts().MakeVFS(); |
| 1003 | |
| 1004 | if (Service.getOpts().TraceVFS) { |
| 1005 | TracingFS = llvm::makeIntrusiveRefCnt<llvm::vfs::TracingFileSystem>( |
| 1006 | A: std::move(BaseFS)); |
| 1007 | BaseFS = TracingFS; |
| 1008 | } |
| 1009 | |
| 1010 | DepFS = llvm::makeIntrusiveRefCnt<DependencyScanningWorkerFilesystem>( |
| 1011 | A&: Service, A: std::move(BaseFS)); |
| 1012 | } |
| 1013 | |
| 1014 | DependencyScanningWorker::~DependencyScanningWorker() = default; |
| 1015 | |
| 1016 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> |
| 1017 | DependencyScanningWorker::makeEffectiveVFS( |
| 1018 | StringRef WorkingDirectory, |
| 1019 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> OverlayFS) const { |
| 1020 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = DepFS; |
| 1021 | if (OverlayFS) { |
| 1022 | auto NewFS = |
| 1023 | llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(A: std::move(FS)); |
| 1024 | NewFS->pushOverlay(FS: std::move(OverlayFS)); |
| 1025 | FS = std::move(NewFS); |
| 1026 | } |
| 1027 | FS->setCurrentWorkingDirectory(WorkingDirectory); |
| 1028 | return FS; |
| 1029 | } |
| 1030 | |
| 1031 | bool DependencyScanningWorker::computeDependencies( |
| 1032 | StringRef WorkingDirectory, ArrayRef<ArrayRef<std::string>> CommandLines, |
| 1033 | DependencyConsumer &DepConsumer, DependencyActionController &Controller, |
| 1034 | DiagnosticConsumer &DiagConsumer, |
| 1035 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> OverlayFS) { |
| 1036 | auto FS = makeEffectiveVFS(WorkingDirectory, OverlayFS); |
| 1037 | |
| 1038 | bool Scanned = false; |
| 1039 | std::shared_ptr<ModuleDepCollector> MDC; |
| 1040 | std::optional<CompilerInstanceWithContext> CIWC; |
| 1041 | |
| 1042 | const bool Success = llvm::all_of(Range&: CommandLines, P: [&](const auto &Cmd) { |
| 1043 | if (StringRef(Cmd[1]) != "-cc1" ) { |
| 1044 | // Non-clang command. Just pass through to the dependency consumer. |
| 1045 | DepConsumer.handleBuildCommand( |
| 1046 | Cmd: {Cmd.front(), {Cmd.begin() + 1, Cmd.end()}}); |
| 1047 | return true; |
| 1048 | } |
| 1049 | |
| 1050 | Service.getLogger().log().logArray("starting scanning command:" , " " , Cmd); |
| 1051 | llvm::scope_exit ExitLogging([&] { |
| 1052 | Service.getLogger().log().logArray("finished scanning command:" , " " , |
| 1053 | Cmd); |
| 1054 | }); |
| 1055 | |
| 1056 | auto DiagOpts = createScanningDiagOptions(Cmd); |
| 1057 | auto DiagEngine = |
| 1058 | CompilerInstance::createDiagnostics(*FS, *DiagOpts, &DiagConsumer, |
| 1059 | /*ShouldOwnClient=*/false); |
| 1060 | if (!Scanned) { |
| 1061 | // Scanning runs once for the first -cc1 invocation in a chain of driver |
| 1062 | // jobs. |
| 1063 | // For any dependent jobs, reuse the scanning result and just update the |
| 1064 | // new invocation. |
| 1065 | // FIXME: to support multi-arch builds, each arch requires a separate |
| 1066 | // scan. |
| 1067 | Scanned = true; |
| 1068 | auto Result = CompilerInstanceWithContext::initializeFromCC1Commandline( |
| 1069 | Worker&: *this, CWD: WorkingDirectory, CC1CommandLine: Cmd, DiagEngine&: *DiagEngine, OverlayFS, Controller); |
| 1070 | if (!Result) |
| 1071 | return false; |
| 1072 | CIWC.emplace(std::move(*Result)); |
| 1073 | MDC = CIWC->scanTranslationUnit(Consumer&: DepConsumer, Controller); |
| 1074 | return MDC != nullptr; |
| 1075 | } |
| 1076 | |
| 1077 | auto Invocation = createCompilerInvocation(Cmd, *DiagEngine); |
| 1078 | if (!Invocation) |
| 1079 | return false; |
| 1080 | |
| 1081 | // The first cc1 is canonicalized in initializeScanInstance; each sibling |
| 1082 | // invocation must likewise be canonicalized before its cc1 command line is |
| 1083 | // emitted. This is mostly relevant for multi-arch jobs where we currently |
| 1084 | // do not do re-scans. |
| 1085 | if (any(Val: Service.getOpts().OptimizeArgs & ScanningOptimizations::Macros)) |
| 1086 | canonicalizeDefines(Invocation->getPreprocessorOpts()); |
| 1087 | |
| 1088 | assert(CIWC && "Must have an initialized CIWC" ); |
| 1089 | return CIWC->applyAndReport(MDC&: *MDC, ModuleInvocation&: *Invocation, Consumer&: DepConsumer, Controller, |
| 1090 | Executable: Cmd.front()); |
| 1091 | }); |
| 1092 | |
| 1093 | return Success && Scanned; |
| 1094 | } |
| 1095 | |
| 1096 | bool DependencyScanningWorker::computeDependenciesByName( |
| 1097 | StringRef CWD, ArrayRef<std::string> CC1CommandLine, |
| 1098 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> OverlayFS, |
| 1099 | DiagnosticConsumer &DiagConsumer, DependencyActionController &Controller, |
| 1100 | llvm::function_ref<std::optional<std::string>()> getNextName, |
| 1101 | DependencyConsumer &DepConsumer) { |
| 1102 | auto FS = makeEffectiveVFS(WorkingDirectory: CWD, OverlayFS); |
| 1103 | auto DiagOpts = createScanningDiagOptions(CommandLine: CC1CommandLine); |
| 1104 | auto DiagEngine = |
| 1105 | CompilerInstance::createDiagnostics(VFS&: *FS, Opts&: *DiagOpts, Client: &DiagConsumer, |
| 1106 | /*ShouldOwnClient=*/false); |
| 1107 | std::optional<CompilerInstanceWithContext> CIWC = |
| 1108 | CompilerInstanceWithContext::initializeFromCC1Commandline( |
| 1109 | Worker&: *this, CWD, CC1CommandLine, DiagEngine&: *DiagEngine, OverlayFS: std::move(OverlayFS), |
| 1110 | Controller); |
| 1111 | if (!CIWC) |
| 1112 | return false; |
| 1113 | |
| 1114 | bool AllScansSucceeded = true; |
| 1115 | while (std::optional<std::string> NextName = getNextName()) { |
| 1116 | bool Success = |
| 1117 | CIWC->computeDependencies(ModuleName: *NextName, Consumer&: DepConsumer, Controller); |
| 1118 | DepConsumer.finishQuery(ModuleName: *NextName, Success); |
| 1119 | AllScansSucceeded = AllScansSucceeded && Success; |
| 1120 | } |
| 1121 | return AllScansSucceeded; |
| 1122 | } |
| 1123 | |