9#include "clang/Basic/Diagnostic.h"
10#include "clang/Basic/DiagnosticFrontend.h"
11#include "clang/Basic/TargetInfo.h"
12#include "clang/Frontend/CompilerInstance.h"
13#include "clang/Frontend/FrontendActions.h"
14#include "clang/Frontend/TextDiagnosticPrinter.h"
15#include "clang/Lex/Preprocessor.h"
16#include "clang/Lex/PreprocessorOptions.h"
17#include "clang/Parse/Parser.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/Serialization/ASTReader.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/Support/Path.h"
22#include "llvm/Support/Threading.h"
46class StoringDiagnosticConsumer :
public clang::DiagnosticConsumer {
48 StoringDiagnosticConsumer();
50 void HandleDiagnostic(clang::DiagnosticsEngine::Level DiagLevel,
51 const clang::Diagnostic &info)
override;
53 void ClearDiagnostics();
57 void BeginSourceFile(
const clang::LangOptions &LangOpts,
58 const clang::Preprocessor *PP =
nullptr)
override;
59 void EndSourceFile()
override;
62 bool HandleModuleRemark(
const clang::Diagnostic &info);
63 void SetCurrentModuleProgress(std::string module_name);
65 typedef std::pair<clang::DiagnosticsEngine::Level, std::string>
67 std::vector<IDAndDiagnostic> m_diagnostics;
70 std::unique_ptr<clang::TextDiagnosticPrinter> m_diag_printer;
72 std::unique_ptr<llvm::raw_string_ostream> m_os;
76 std::unique_ptr<Progress> m_current_progress_up;
77 std::vector<std::string> m_module_build_stack;
84 ClangModulesDeclVendorImpl(
85 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine,
86 std::shared_ptr<clang::CompilerInvocation> compiler_invocation,
87 std::unique_ptr<clang::CompilerInstance> compiler_instance,
88 std::unique_ptr<clang::Parser> parser);
90 ~ClangModulesDeclVendorImpl()
override =
default;
93 Stream &error_stream)
override;
96 Stream &error_stream)
override;
99 std::vector<CompilerDecl> &decls)
override;
102 const ModuleVector &modules,
103 std::function<
bool(llvm::StringRef, llvm::StringRef)> handler)
override;
106 typedef llvm::DenseSet<ModuleID> ExportedModuleSet;
107 void ReportModuleExportsHelper(ExportedModuleSet &exports,
108 clang::Module *module);
110 void ReportModuleExports(ModuleVector &exports, clang::Module *module);
112 clang::ModuleLoadResult DoGetModule(clang::ModuleIdPath path,
115 bool m_enabled =
false;
117 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> m_diagnostics_engine;
118 std::shared_ptr<clang::CompilerInvocation> m_compiler_invocation;
119 std::unique_ptr<clang::CompilerInstance> m_compiler_instance;
120 std::unique_ptr<clang::Parser> m_parser;
121 size_t m_source_location_index =
124 typedef std::vector<ConstString> ImportedModule;
125 typedef std::map<ImportedModule, clang::Module *> ImportedModuleMap;
126 typedef llvm::DenseSet<ModuleID> ImportedModuleSet;
127 ImportedModuleMap m_imported_modules;
128 ImportedModuleSet m_user_imported_modules;
131 std::shared_ptr<TypeSystemClang> m_ast_context;
135StoringDiagnosticConsumer::StoringDiagnosticConsumer() {
136 auto *options =
new clang::DiagnosticOptions();
137 m_os = std::make_unique<llvm::raw_string_ostream>(m_output);
139 std::make_unique<clang::TextDiagnosticPrinter>(*m_os, options);
142void StoringDiagnosticConsumer::HandleDiagnostic(
143 clang::DiagnosticsEngine::Level DiagLevel,
const clang::Diagnostic &info) {
144 if (HandleModuleRemark(info))
149 m_diag_printer->HandleDiagnostic(DiagLevel, info);
152 m_diagnostics.push_back(IDAndDiagnostic(DiagLevel, m_output));
155void StoringDiagnosticConsumer::ClearDiagnostics() { m_diagnostics.clear(); }
157void StoringDiagnosticConsumer::DumpDiagnostics(
Stream &error_stream) {
158 for (IDAndDiagnostic &diag : m_diagnostics) {
159 switch (diag.first) {
164 case clang::DiagnosticsEngine::Level::Ignored:
170void StoringDiagnosticConsumer::BeginSourceFile(
171 const clang::LangOptions &LangOpts,
const clang::Preprocessor *PP) {
172 m_diag_printer->BeginSourceFile(LangOpts, PP);
175void StoringDiagnosticConsumer::EndSourceFile() {
176 m_current_progress_up =
nullptr;
177 m_diag_printer->EndSourceFile();
180bool StoringDiagnosticConsumer::HandleModuleRemark(
181 const clang::Diagnostic &info) {
182 Log *log =
GetLog(LLDBLog::Types | LLDBLog::Expressions);
183 switch (info.getID()) {
184 case clang::diag::remark_module_build: {
185 const auto &module_name = info.getArgStdStr(0);
186 SetCurrentModuleProgress(module_name);
187 m_module_build_stack.push_back(module_name);
189 const auto &module_path = info.getArgStdStr(1);
190 LLDB_LOG(log,
"Building Clang module {0} as {1}", module_name, module_path);
193 case clang::diag::remark_module_build_done: {
195 m_module_build_stack.pop_back();
196 if (m_module_build_stack.empty()) {
197 m_current_progress_up =
nullptr;
202 const auto &resumed_module_name = m_module_build_stack.back();
203 SetCurrentModuleProgress(resumed_module_name);
206 const auto &module_name = info.getArgStdStr(0);
207 LLDB_LOG(log,
"Finished building Clang module {0}", module_name);
215void StoringDiagnosticConsumer::SetCurrentModuleProgress(
216 std::string module_name) {
217 if (!m_current_progress_up)
218 m_current_progress_up =
219 std::make_unique<Progress>(
"Building Clang modules");
221 m_current_progress_up->Increment(1, std::move(module_name));
229ClangModulesDeclVendorImpl::ClangModulesDeclVendorImpl(
230 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine,
231 std::shared_ptr<clang::CompilerInvocation> compiler_invocation,
232 std::unique_ptr<clang::CompilerInstance> compiler_instance,
233 std::unique_ptr<clang::Parser> parser)
234 : m_diagnostics_engine(std::move(diagnostics_engine)),
235 m_compiler_invocation(std::move(compiler_invocation)),
236 m_compiler_instance(std::move(compiler_instance)),
237 m_parser(std::move(parser)) {
241 std::make_shared<TypeSystemClang>(
"ClangModulesDeclVendor ASTContext",
242 m_compiler_instance->getASTContext());
245void ClangModulesDeclVendorImpl::ReportModuleExportsHelper(
246 ExportedModuleSet &exports, clang::Module *module) {
252 llvm::SmallVector<clang::Module *, 2> sub_exports;
254 module->getExportedModules(sub_exports);
256 for (clang::Module *module : sub_exports)
257 ReportModuleExportsHelper(exports, module);
260void ClangModulesDeclVendorImpl::ReportModuleExports(
262 ExportedModuleSet exports_set;
264 ReportModuleExportsHelper(exports_set, module);
266 for (ModuleID module : exports_set)
267 exports.push_back(module);
270bool ClangModulesDeclVendorImpl::AddModule(
const SourceModule &module,
271 ModuleVector *exported_modules,
275 if (m_compiler_instance->hadModuleLoaderFatalFailure()) {
276 error_stream.
PutCString(
"error: Couldn't load a module because the module "
277 "loader is in a fatal state.\n");
283 std::vector<ConstString> imported_module;
286 imported_module.push_back(path_component);
289 ImportedModuleMap::iterator mi = m_imported_modules.find(imported_module);
291 if (mi != m_imported_modules.end()) {
292 if (exported_modules)
293 ReportModuleExports(*exported_modules, mi->second);
298 clang::HeaderSearch &HS =
299 m_compiler_instance->getPreprocessor().getHeaderSearchInfo();
307 bool is_system_module = (std::distance(path_begin, path_end) >=
308 std::distance(sysroot_begin, sysroot_end)) &&
309 std::equal(sysroot_begin, sysroot_end, path_begin);
311 if (!is_system_module) {
313 error_stream.
Printf(
"error: No module map file in %s\n",
318 bool is_system =
true;
319 bool is_framework =
false;
320 auto dir = HS.getFileMgr().getOptionalDirectoryRef(
324 auto file = HS.lookupModuleMapFile(*dir, is_framework);
327 if (!HS.loadModuleMapFile(*file, is_system))
331 if (!HS.lookupModule(module.
path.front().GetStringRef())) {
332 error_stream.
Printf(
"error: Header search couldn't locate module %s\n",
333 module.
path.front().AsCString());
337 llvm::SmallVector<std::pair<clang::IdentifierInfo *, clang::SourceLocation>,
342 clang::SourceManager &source_manager =
343 m_compiler_instance->getASTContext().getSourceManager();
346 clang_path.push_back(std::make_pair(
347 &m_compiler_instance->getASTContext().Idents.get(
349 source_manager.getLocForStartOfFile(source_manager.getMainFileID())
350 .getLocWithOffset(m_source_location_index++)));
354 StoringDiagnosticConsumer *diagnostic_consumer =
355 static_cast<StoringDiagnosticConsumer *
>(
356 m_compiler_instance->getDiagnostics().getClient());
358 diagnostic_consumer->ClearDiagnostics();
360 clang::Module *top_level_module = DoGetModule(clang_path.front(),
false);
362 if (!top_level_module) {
363 diagnostic_consumer->DumpDiagnostics(error_stream);
364 error_stream.
Printf(
"error: Couldn't load top-level module %s\n",
365 module.
path.front().AsCString());
369 clang::Module *submodule = top_level_module;
371 for (
auto &component : llvm::ArrayRef<ConstString>(module.
path).drop_front()) {
372 submodule = submodule->findSubmodule(component.GetStringRef());
374 diagnostic_consumer->DumpDiagnostics(error_stream);
375 error_stream.
Printf(
"error: Couldn't load submodule %s\n",
376 component.GetCString());
381 clang::Module *requested_module = DoGetModule(clang_path,
true);
383 if (requested_module !=
nullptr) {
384 if (exported_modules)
385 ReportModuleExports(*exported_modules, requested_module);
387 m_imported_modules[imported_module] = requested_module;
416bool ClangModulesDeclVendorImpl::AddModulesForCompileUnit(
419 if (LanguageSupportsClangModules(cu.
GetLanguage())) {
421 if (!AddModule(imported_module, &exported_modules, error_stream))
430ClangModulesDeclVendorImpl::FindDecls(
ConstString name,
bool append,
431 uint32_t max_matches,
432 std::vector<CompilerDecl> &decls) {
439 clang::IdentifierInfo &ident =
440 m_compiler_instance->getASTContext().Idents.get(name.
GetStringRef());
442 clang::LookupResult lookup_result(
443 m_compiler_instance->getSema(), clang::DeclarationName(&ident),
444 clang::SourceLocation(), clang::Sema::LookupOrdinaryName);
446 m_compiler_instance->getSema().LookupName(
448 m_compiler_instance->getSema().getScopeForContext(
449 m_compiler_instance->getASTContext().getTranslationUnitDecl()));
451 uint32_t num_matches = 0;
453 for (clang::NamedDecl *named_decl : lookup_result) {
454 if (num_matches >= max_matches)
457 decls.push_back(m_ast_context->GetCompilerDecl(named_decl));
464void ClangModulesDeclVendorImpl::ForEachMacro(
466 std::function<
bool(llvm::StringRef, llvm::StringRef)> handler) {
470 typedef std::map<ModuleID, ssize_t> ModulePriorityMap;
471 ModulePriorityMap module_priorities;
473 ssize_t priority = 0;
475 for (ModuleID module : modules)
476 module_priorities[module] = priority++;
478 if (m_compiler_instance->getPreprocessor().getExternalSource()) {
479 m_compiler_instance->getPreprocessor()
481 ->ReadDefinedMacros();
484 for (clang::Preprocessor::macro_iterator
485 mi = m_compiler_instance->getPreprocessor().macro_begin(),
486 me = m_compiler_instance->getPreprocessor().macro_end();
488 const clang::IdentifierInfo *ii =
nullptr;
491 if (clang::IdentifierInfoLookup *lookup =
492 m_compiler_instance->getPreprocessor()
493 .getIdentifierTable()
494 .getExternalIdentifierLookup()) {
495 lookup->get(mi->first->getName());
501 ssize_t found_priority = -1;
502 clang::MacroInfo *macro_info =
nullptr;
504 for (clang::ModuleMacro *module_macro :
505 m_compiler_instance->getPreprocessor().getLeafModuleMacros(ii)) {
506 clang::Module *module = module_macro->getOwningModule();
509 ModulePriorityMap::iterator pi =
510 module_priorities.find(
reinterpret_cast<ModuleID
>(module));
512 if (pi != module_priorities.end() && pi->second > found_priority) {
513 macro_info = module_macro->getMacroInfo();
514 found_priority = pi->second;
518 clang::Module *top_level_module = module->getTopLevelModule();
520 if (top_level_module != module) {
521 ModulePriorityMap::iterator pi = module_priorities.find(
522 reinterpret_cast<ModuleID
>(top_level_module));
524 if ((pi != module_priorities.end()) && pi->second > found_priority) {
525 macro_info = module_macro->getMacroInfo();
526 found_priority = pi->second;
532 std::string macro_expansion =
"#define ";
533 llvm::StringRef macro_identifier = mi->first->getName();
534 macro_expansion.append(macro_identifier.str());
537 if (macro_info->isFunctionLike()) {
538 macro_expansion.append(
"(");
540 bool first_arg =
true;
542 for (
auto pi = macro_info->param_begin(),
543 pe = macro_info->param_end();
546 macro_expansion.append(
", ");
550 macro_expansion.append((*pi)->getName().str());
553 if (macro_info->isC99Varargs()) {
555 macro_expansion.append(
"...");
557 macro_expansion.append(
", ...");
558 }
else if (macro_info->isGNUVarargs())
559 macro_expansion.append(
"...");
561 macro_expansion.append(
")");
564 macro_expansion.append(
" ");
566 bool first_token =
true;
568 for (clang::MacroInfo::const_tokens_iterator
569 ti = macro_info->tokens_begin(),
570 te = macro_info->tokens_end();
573 macro_expansion.append(
" ");
577 if (ti->isLiteral()) {
578 if (
const char *literal_data = ti->getLiteralData()) {
579 std::string token_str(literal_data, ti->getLength());
580 macro_expansion.append(token_str);
582 bool invalid =
false;
583 const char *literal_source =
584 m_compiler_instance->getSourceManager().getCharacterData(
585 ti->getLocation(), &invalid);
589 macro_expansion.append(
"<unknown literal value>");
591 macro_expansion.append(
592 std::string(literal_source, ti->getLength()));
595 }
else if (
const char *punctuator_spelling =
596 clang::tok::getPunctuatorSpelling(ti->getKind())) {
597 macro_expansion.append(punctuator_spelling);
598 }
else if (
const char *keyword_spelling =
599 clang::tok::getKeywordSpelling(ti->getKind())) {
600 macro_expansion.append(keyword_spelling);
602 switch (ti->getKind()) {
603 case clang::tok::TokenKind::identifier:
604 macro_expansion.append(ti->getIdentifierInfo()->getName().str());
606 case clang::tok::TokenKind::raw_identifier:
607 macro_expansion.append(ti->getRawIdentifier().str());
610 macro_expansion.append(ti->getName());
616 if (handler(macro_identifier, macro_expansion)) {
624clang::ModuleLoadResult
625ClangModulesDeclVendorImpl::DoGetModule(clang::ModuleIdPath path,
627 clang::Module::NameVisibilityKind visibility =
628 make_visible ? clang::Module::AllVisible : clang::Module::Hidden;
630 const bool is_inclusion_directive =
false;
632 return m_compiler_instance->loadModule(path.front().second, path, visibility,
633 is_inclusion_directive);
650 std::vector<std::string> compiler_invocation_arguments = {
653 "-fimplicit-module-maps",
659 "-fmodules-validate-system-headers",
660 "-Werror=non-modular-include-in-framework-module",
661 "-Xclang=-fincremental-extensions",
664 target.
GetPlatform()->AddClangModuleCompilationOptions(
665 &target, compiler_invocation_arguments);
672 llvm::SmallString<128> path;
674 props.GetClangModulesCachePath().GetPath(path);
675 std::string module_cache_argument(
"-fmodules-cache-path=");
676 module_cache_argument.append(std::string(path.str()));
677 compiler_invocation_arguments.push_back(module_cache_argument);
682 for (
size_t spi = 0, spe = module_search_paths.
GetSize(); spi < spe; ++spi) {
685 std::string search_path_argument =
"-I";
686 search_path_argument.append(search_path.
GetPath());
688 compiler_invocation_arguments.push_back(search_path_argument);
695 compiler_invocation_arguments.push_back(
"-resource-dir");
696 compiler_invocation_arguments.push_back(clang_resource_dir.
GetPath());
700 std::vector<const char *> compiler_invocation_argument_cstrs;
701 compiler_invocation_argument_cstrs.reserve(
702 compiler_invocation_arguments.size());
703 for (
const std::string &arg : compiler_invocation_arguments)
704 compiler_invocation_argument_cstrs.push_back(arg.c_str());
706 auto diag_options_up =
707 clang::CreateAndPopulateDiagOpts(compiler_invocation_argument_cstrs);
708 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine =
709 clang::CompilerInstance::createDiagnostics(
711 diag_options_up.release(),
new StoringDiagnosticConsumer);
714 LLDB_LOG(log,
"ClangModulesDeclVendor's compiler flags {0:$[ ]}",
715 llvm::make_range(compiler_invocation_arguments.begin(),
716 compiler_invocation_arguments.end()));
718 clang::CreateInvocationOptions CIOpts;
719 CIOpts.Diags = diagnostics_engine;
720 std::shared_ptr<clang::CompilerInvocation> invocation =
721 clang::createInvocation(compiler_invocation_argument_cstrs,
727 std::unique_ptr<llvm::MemoryBuffer> source_buffer =
728 llvm::MemoryBuffer::getMemBuffer(
729 "extern int __lldb __attribute__((unavailable));",
733 source_buffer.release());
735 std::unique_ptr<clang::CompilerInstance> instance(
736 new clang::CompilerInstance);
740 instance->setDiagnostics(diagnostics_engine.get());
741 instance->setInvocation(invocation);
743 std::unique_ptr<clang::FrontendAction> action(
new clang::SyntaxOnlyAction);
745 instance->setTarget(clang::TargetInfo::CreateTargetInfo(
746 *diagnostics_engine, instance->getInvocation().TargetOpts));
748 if (!instance->hasTarget())
751 instance->getTarget().adjust(*diagnostics_engine, instance->getLangOpts());
753 if (!action->BeginSourceFile(*instance,
754 instance->getFrontendOpts().Inputs[0]))
757 instance->createASTReader();
759 instance->createSema(action->getTranslationUnitKind(),
nullptr);
761 const bool skipFunctionBodies =
false;
762 std::unique_ptr<clang::Parser> parser(
new clang::Parser(
763 instance->getPreprocessor(), instance->getSema(), skipFunctionBodies));
765 instance->getPreprocessor().EnterMainSourceFile();
766 parser->Initialize();
768 clang::Parser::DeclGroupPtrTy parsed;
769 auto ImportState = clang::Sema::ModuleImportState::NotACXX20Module;
770 while (!parser->ParseTopLevelDecl(parsed, ImportState))
773 return new ClangModulesDeclVendorImpl(std::move(diagnostics_engine),
774 std::move(invocation),
775 std::move(instance), std::move(parser));
static const char * ModuleImportBufferName
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
static void DumpDiagnostics(void *cookie)
An architecture specification class.
llvm::Triple & GetTriple()
Architecture triple accessor.
uint32_t FindDecls(ConstString name, bool append, uint32_t max_matches, std::vector< clang::NamedDecl * > &decls)
static ClangModulesDeclVendor * Create(Target &target)
virtual bool AddModulesForCompileUnit(CompileUnit &cu, ModuleVector &exported_modules, Stream &error_stream)=0
Add all modules referred to in a given compilation unit to the list of modules to search.
virtual void ForEachMacro(const ModuleVector &modules, std::function< bool(llvm::StringRef, llvm::StringRef)> handler)=0
Enumerate all the macros that are defined by a given set of modules that are already imported.
std::vector< ModuleID > ModuleVector
static bool LanguageSupportsClangModules(lldb::LanguageType language)
Query whether Clang supports modules for a particular language.
virtual bool AddModule(const SourceModule &module, ModuleVector *exported_modules, Stream &error_stream)=0
Add a module to the list of modules to search.
~ClangModulesDeclVendor() override
A class that describes a compilation unit.
const std::vector< SourceModule > & GetImportedModules()
Get the compile unit's imported module list.
lldb::LanguageType GetLanguage()
A uniqued constant string class.
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const FileSpec & GetFileSpecAtIndex(size_t idx) const
Get file at index.
size_t GetSize() const
Get the number of files in the file list.
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
static FileSystem & Instance()
static ModuleListProperties & GetGlobalModuleListProperties()
A stream class that can stream formatted output to a file.
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
FileSpecList GetClangModuleSearchPaths()
lldb::PlatformSP GetPlatform()
const ArchSpec & GetArchitecture() const
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
FileSpec GetClangResourceDir()
LanguageType
Programming language type.
@ eLanguageTypeC_plus_plus_14
ISO C++:2014.
@ eLanguageTypeC11
ISO C:2011.
@ eLanguageTypeC99
ISO C:1999.
@ eLanguageTypeC_plus_plus_03
ISO C++:2003.
@ eLanguageTypeObjC_plus_plus
Objective-C++.
@ eLanguageTypeC_plus_plus_11
ISO C++:2011.
@ eLanguageTypeC89
ISO C:1989.
@ eLanguageTypeC
Non-standardized C, such as K&R.
@ eLanguageTypeObjC
Objective-C.
@ eLanguageTypeC_plus_plus
ISO C++:1998.
Information needed to import a source-language module.
std::vector< ConstString > path
Something like "Module.Submodule".