;
34using namespacetooling;
35using namespacedependencies;
42DependencyConsumerForwarder(std::unique_ptr<DependencyOutputOptions> Opts,
45Opts(
std::move(Opts)),
C(
C) {}
48 C.handleDependencyOutputOpts(*Opts);
52llvm::sys::path::remove_dots(CanonPath,
true);
53llvm::sys::fs::make_absolute(WorkingDirectory, CanonPath);
54 C.handleFileDependency(CanonPath);
59StringRef WorkingDirectory;
60std::unique_ptr<DependencyOutputOptions> Opts;
68 if(LangOpts.Modules) {
71Diags->
Report(diag::warn_pch_vfsoverlay_mismatch);
73 if(VFSOverlays.empty()) {
74Diags->
Report(diag::note_pch_vfsoverlay_empty) <<
Type;
76std::string Files = llvm::join(VFSOverlays,
"\n");
77Diags->
Report(diag::note_pch_vfsoverlay_files) <<
Type<< Files;
94PrebuiltModuleListener(PrebuiltModuleFilesT &PrebuiltModuleFiles,
99: PrebuiltModuleFiles(PrebuiltModuleFiles),
100NewModuleFiles(NewModuleFiles),
101PrebuiltModuleVFSMap(PrebuiltModuleVFSMap), ExistingHSOpts(HSOpts),
102ExistingLangOpts(LangOpts), Diags(Diags) {}
107 if(PrebuiltModuleFiles.insert({ModuleName.str(), Filename.str()}).second)
108NewModuleFiles.push_back(
Filename.str());
117 boolComplain)
override{
119PrebuiltModuleVFSMap.insert(
120{CurrentFile, llvm::StringSet<>(VFSOverlayFiles)});
121 returncheckHeaderSearchPaths(
122HSOpts, ExistingHSOpts, Complain ? &Diags :
nullptr, ExistingLangOpts);
126PrebuiltModuleFilesT &PrebuiltModuleFiles;
132std::string CurrentFile;
137static boolvisitPrebuiltModule(StringRef PrebuiltModuleFilename,
139PrebuiltModuleFilesT &ModuleFiles,
144PrebuiltModuleListener Listener(ModuleFiles, Worklist, PrebuiltModuleVFSMap,
148Listener.visitModuleFile(PrebuiltModuleFilename,
157 while(!Worklist.empty()) {
170staticstd::string makeObjFileName(StringRef
FileName) {
172llvm::sys::path::replace_extension(ObjFileName,
"o");
173 returnstd::string(ObjFileName);
178deduceDepTarget(
conststd::string &OutputFile,
180 if(OutputFile !=
"-")
183 if(InputFiles.empty() || !InputFiles.front().isFile())
184 return "clang-scan-deps\\ dependency";
186 returnmakeObjFileName(InputFiles.front().getFile());
192DiagOpts.ShowCarets =
false;
203return llvm::StringSwitch<bool>(Warning)
204.Cases(
"pch-vfs-diff",
"error=pch-vfs-diff", false)
205.StartsWith(
"no-error=", false)
220staticstd::optional<StringRef> getSimpleMacroName(StringRef Macro) {
221StringRef Name =
Macro.split(
"=").first.ltrim(
" \t");
224 autoFinishName = [&]() -> std::optional<StringRef> {
225StringRef SimpleName = Name.slice(0, I);
226 if(SimpleName.empty())
231 for(; I != Name.size(); ++I) {
240 if(llvm::isAlnum(Name[I]))
249 usingMacroOpt = std::pair<StringRef, std::size_t>;
250std::vector<MacroOpt> SimpleNames;
251SimpleNames.reserve(PPOpts.
Macros.size());
252std::size_t Index = 0;
253 for(
const auto&M : PPOpts.
Macros) {
254 autoSName = getSimpleMacroName(M.first);
258SimpleNames.emplace_back(*SName, Index);
262llvm::stable_sort(SimpleNames, llvm::less_first());
264 autoNewEnd = std::unique(
265SimpleNames.rbegin(), SimpleNames.rend(),
266[](
constMacroOpt &A,
constMacroOpt &B) { return A.first == B.first; });
267SimpleNames.erase(SimpleNames.begin(), NewEnd.base());
270 decltype(PPOpts.
Macros) NewMacros;
271NewMacros.reserve(SimpleNames.size());
272 for(std::size_t I = 0,
E= SimpleNames.size(); I !=
E; ++I) {
273std::size_t OriginalIndex = SimpleNames[I].second;
275NewMacros.push_back(std::move(PPOpts.
Macros[OriginalIndex]));
277std::swap(PPOpts.
Macros, NewMacros);
284DependencyScanningAction(
289 boolEagerLoadModules,
boolDisableFree,
290std::optional<StringRef> ModuleName = std::nullopt)
291: WorkingDirectory(WorkingDirectory), Consumer(Consumer),
292Controller(Controller), DepFS(
std::move(DepFS)), Format(Format),
293OptimizeArgs(OptimizeArgs), EagerLoadModules(EagerLoadModules),
294DisableFree(DisableFree), ModuleName(ModuleName) {}
296 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
298std::shared_ptr<PCHContainerOperations> PCHContainerOps,
303OriginalInvocation.getFrontendOpts().DisableFree = DisableFree;
304 if(
any(OptimizeArgs & ScanningOptimizations::Macros))
305canonicalizeDefines(OriginalInvocation.getPreprocessorOpts());
312setLastCC1Arguments(std::move(OriginalInvocation));
319ScanInstanceStorage.emplace(std::move(PCHContainerOps));
326DiagConsumer,
false);
331 autoDiagConsumerFinisher =
332llvm::make_scope_exit([DiagConsumer]() { DiagConsumer->
finish(); });
344 any(OptimizeArgs & ScanningOptimizations::VFS);
353StringRef ModulesCachePath =
356DepFS->resetBypassedPathPrefix();
357 if(!ModulesCachePath.empty())
358DepFS->setBypassedPathPrefix(ModulesCachePath);
363 if(llvm::ErrorOr<EntryRef> Entry =
364LocalDepFS->getOrCreateFileSystemEntry(
File.getName()))
365 if(LocalDepFS->ensureDirectiveTokensArePopulated(*Entry))
366 returnEntry->getDirectiveTokens();
380 if(visitPrebuiltModule(
394 autoOpts = std::make_unique<DependencyOutputOptions>();
398 if(Opts->Targets.empty())
402Opts->IncludeSystemHeaders =
true;
405 caseScanningOutputFormat::Make:
407std::make_shared<DependencyConsumerForwarder>(
408std::move(Opts), WorkingDirectory, Consumer));
410 caseScanningOutputFormat::P1689:
411 caseScanningOutputFormat::Full:
412MDC = std::make_shared<ModuleDepCollector>(
413std::move(Opts), ScanInstance, Consumer, Controller,
414OriginalInvocation, std::move(PrebuiltModuleVFSMap), OptimizeArgs,
415EagerLoadModules, Format == ScanningOutputFormat::P1689);
435std::unique_ptr<FrontendAction> Action;
437 if(Format == ScanningOutputFormat::P1689)
438Action = std::make_unique<PreprocessOnlyAction>();
440Action = std::make_unique<GetDependenciesByModuleNameAction>(*ModuleName);
442Action = std::make_unique<ReadPCHAndPreprocessAction>();
448DiagConsumerFinisher.release();
452setLastCC1Arguments(std::move(OriginalInvocation));
460 boolhasScanned()
const{
returnScanned; }
465std::vector<std::string> takeLastCC1Arguments() {
466std::vector<std::string>
Result;
467std::swap(Result, LastCC1Arguments);
474MDC->applyDiscoveredDependencies(CI);
475LastCC1Arguments = CI.getCC1CommandLine();
479StringRef WorkingDirectory;
485 boolEagerLoadModules;
487std::optional<StringRef> ModuleName;
488std::optional<CompilerInstance> ScanInstanceStorage;
489std::shared_ptr<ModuleDepCollector> MDC;
490std::vector<std::string> LastCC1Arguments;
491 boolScanned =
false;
499: Format(Service.getFormat()), OptimizeArgs(Service.getOptimizeArgs()),
500EagerLoadModules(Service.shouldEagerLoadModules()) {
501PCHContainerOps = std::make_shared<PCHContainerOperations>();
503PCHContainerOps->registerReader(
504std::make_unique<ObjectFilePCHContainerReader>());
506PCHContainerOps->registerWriter(std::make_unique<RawPCHContainerWriter>());
509FS = llvm::makeIntrusiveRefCnt<llvm::vfs::TracingFileSystem>(std::move(FS));
525StringRef WorkingDirectory,
conststd::vector<std::string> &CommandLine,
527std::optional<StringRef> ModuleName) {
528std::vector<const char *> CLI;
529 for(
conststd::string &Arg : CommandLine)
530CLI.push_back(Arg.c_str());
532sanitizeDiagOpts(*DiagOpts);
536std::string DiagnosticOutput;
537llvm::raw_string_ostream DiagnosticsOS(DiagnosticOutput);
541DiagPrinter, ModuleName))
542 returnllvm::Error::success();
543 returnllvm::make_error<llvm::StringError>(DiagnosticsOS.str(),
544llvm::inconvertibleErrorCode());
551Argv.reserve(ArgStrs.size());
552 for(
conststd::string &Arg : ArgStrs)
553Argv.push_back(Arg.c_str());
557std::unique_ptr<driver::Driver> Driver = std::make_unique<driver::Driver>(
558Argv[0], llvm::sys::getDefaultTargetTriple(), Diags,
559 "clang LLVM compiler", FS);
560Driver->setTitle(
"clang_based_tool");
562llvm::BumpPtrAllocator Alloc;
567Diags.
Report(diag::err_drv_expand_response_file)
568<< llvm::toString(std::move(
E));
572 conststd::unique_ptr<driver::Compilation> Compilation(
577 if(Compilation->containsError())
588std::vector<std::string> CommandLine, DependencyScanningAction &Action,
590std::shared_ptr<clang::PCHContainerOperations> &PCHContainerOps,
594std::string Executable = CommandLine[0];
599 if(!Invocation.
run())
602std::vector<std::string> Args = Action.takeLastCC1Arguments();
608StringRef WorkingDirectory,
conststd::vector<std::string> &CommandLine,
612BaseFS->setCurrentWorkingDirectory(WorkingDirectory);
614std::optional<std::vector<std::string>> ModifiedCommandLine;
622llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(BaseFS);
624llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
625InMemoryFS->setCurrentWorkingDirectory(WorkingDirectory);
626OverlayFS->pushOverlay(InMemoryFS);
627ModifiedFS = OverlayFS;
631llvm::sys::fs::createUniquePath(*ModuleName +
"-%%%%%%%%.input",
634InMemoryFS->addFile(FakeInputPath, 0, llvm::MemoryBuffer::getMemBuffer(
""));
636ModifiedCommandLine = CommandLine;
637ModifiedCommandLine->emplace_back(FakeInputPath);
640 conststd::vector<std::string> &FinalCommandLine =
641ModifiedCommandLine ? *ModifiedCommandLine : CommandLine;
642 auto&FinalFS = ModifiedFS ? ModifiedFS : BaseFS;
647std::vector<const char *> FinalCCommandLine(FinalCommandLine.size(),
nullptr);
648llvm::transform(FinalCommandLine, FinalCCommandLine.begin(),
649[](
conststd::string &Str) { return Str.c_str(); });
652sanitizeDiagOpts(*DiagOpts);
660Diags->setSourceManager(&SrcMgr);
664 boolDisableFree =
true;
665DependencyScanningAction Action(WorkingDirectory, Consumer, Controller, DepFS,
666Format, OptimizeArgs, EagerLoadModules,
667DisableFree, ModuleName);
670 if(FinalCommandLine[1] ==
"-cc1") {
672PCHContainerOps, *Diags, Consumer);
676 if(StringRef(
Cmd.getCreator().getName()) !=
"clang") {
679Consumer.handleBuildCommand(
680{Cmd.getExecutable(),
681{Cmd.getArguments().begin(), Cmd.getArguments().end()}});
686std::vector<std::string> Argv;
687Argv.push_back(
Cmd.getExecutable());
688Argv.insert(Argv.end(),
Cmd.getArguments().begin(),
689 Cmd.getArguments().end());
696PCHContainerOps, *Diags, Consumer);
700 if(
Success&& !Action.hasScanned())
701Diags->
Report(diag::err_fe_expected_compiler_job)
702<< llvm::join(FinalCommandLine,
" ");
703 return Success&& Action.hasScanned();
static bool forEachDriverJob(ArrayRef< std::string > ArgStrs, DiagnosticsEngine &Diags, FileManager &FM, llvm::function_ref< bool(const driver::Command &Cmd)> Callback)
static bool createAndRunToolInvocation(std::vector< std::string > CommandLine, DependencyScanningAction &Action, FileManager &FM, std::shared_ptr< clang::PCHContainerOperations > &PCHContainerOps, DiagnosticsEngine &Diags, DependencyConsumer &Consumer)
Abstract interface for callback invocations by the ASTReader.
virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, bool Complain)
Receives the header search paths.
virtual void visitImport(StringRef ModuleName, StringRef Filename)
If needsImportVisitation returns true, this is called for each AST file imported by this AST file.
virtual void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind)
This is called for each AST file loaded.
virtual bool needsImportVisitation() const
Returns true if this ASTReaderListener wants to receive the imports of the AST file via visitImport,...
@ ARR_OutOfDate
The client can handle an AST file that cannot load because it is out-of-date relative to its input fi...
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const InMemoryModuleCache &ModuleCache, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions, unsigned ClientLoadCapabilities=ARR_ConfigurationMismatch|ARR_OutOfDate)
Read the control block for the named AST file.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
void createSourceManager(FileManager &FileMgr)
Create the source manager and replace any existing one with it.
FileManager * createFileManager(IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
Create the file manager and replace any existing one with it.
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
void createDiagnostics(llvm::vfs::FileSystem &VFS, DiagnosticConsumer *Client=nullptr, bool ShouldOwnClient=true)
Create the diagnostics engine using the invocation's diagnostic options and replace any existing one ...
void setInvocation(std::shared_ptr< CompilerInvocation > Value)
setInvocation - Replace the current invocation.
FileManager & getFileManager() const
Return the current file manager to the caller.
InMemoryModuleCache & getModuleCache() const
void addDependencyCollector(std::shared_ptr< DependencyCollector > Listener)
FrontendOptions & getFrontendOpts()
bool hasDiagnostics() const
HeaderSearchOptions & getHeaderSearchOpts()
CompilerInvocation & getInvocation()
PreprocessorOptions & getPreprocessorOpts()
bool ExecuteAction(FrontendAction &Act)
ExecuteAction - Execute the provided action against the compiler's CompilerInvocation object.
DiagnosticOptions & getDiagnosticOpts()
LangOptions & getLangOpts()
Helper class for holding the data necessary to invoke the compiler.
DependencyOutputOptions & getDependencyOutputOpts()
ArrayRef< std::string > getDependencies() const
Builds a dependency file when attached to a Preprocessor (for includes) and ASTReader (for module imp...
void finishedMainFile(DiagnosticsEngine &Diags) override
Called when the end of the main file is reached.
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
virtual void finish()
Callback to inform the diagnostic client that processing of all source files has ended.
Options for controlling the compiler diagnostics engine.
std::vector< std::string > Warnings
The list of -W... options used to alter the diagnostic mappings, with the prefixes removed.
std::string DiagnosticSerializationFile
The file to serialize diagnostics to (non-appending).
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
bool hasErrorOccurred() const
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
DiagnosticConsumer * getClient()
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Implements support for file system lookup, file system caching, and directory search management.
void AddStats(const FileManager &Other)
Import statistics from a child FileManager and add them to this current FileManager.
llvm::vfs::FileSystem & getVirtualFileSystem() const
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
Keeps track of options that affect how file operations are performed.
unsigned ModulesShareFileManager
Whether to share the FileManager when building modules.
std::string OutputFile
The output file, if any.
unsigned GenerateGlobalModuleIndex
Whether we can generate the global module index if needed.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
unsigned UseGlobalModuleIndex
Whether we can use the global module index if available.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
bool ModulesCheckRelocated
Perform extra checks when loading PCM files for mutable file systems.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
bool AllowPCHWithDifferentModulesCachePath
When true, a PCH with modules cache path different to the current compilation will not be rejected.
std::vector< std::pair< std::string, bool > > Macros
std::function< std::optional< ArrayRef< dependency_directives_scan::Directive > >(FileEntryRef)> DependencyDirectivesForFile
Function for getting the dependency preprocessor directives of a file.
This class handles loading and caching of source files into memory.
The base class of the type hierarchy.
Command - An executable path/name and argument vector to execute.
llvm::StringRef getDriverMode(StringRef ProgName, ArrayRef< const char * > Args)
Returns the driver mode option's value, i.e.
llvm::Error expandResponseFiles(SmallVectorImpl< const char * > &Args, bool ClangCLMode, llvm::BumpPtrAllocator &Alloc, llvm::vfs::FileSystem *FS=nullptr)
Expand response files from a clang driver or cc1 invocation.
bool IsClangCL(StringRef DriverMode)
Checks whether the value produced by getDriverMode is for CL mode.
ModuleKind
Specifies the kind of module that has been loaded.
@ MK_ExplicitModule
File is an explicitly-loaded module.
The JSON file list parser is used to communicate input to InstallAPI.
std::unique_ptr< DiagnosticOptions > CreateAndPopulateDiagOpts(ArrayRef< const char * > Argv)
@ Result
The result type of a method or function.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
@ Success
Template argument deduction was successful.
int __ovld __cnfn any(char)
Returns 1 if the most significant bit in any component of x is set; otherwise returns 0.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4