LLDB mainline
ClangModulesDeclVendor.cpp
Go to the documentation of this file.
1//===-- ClangModulesDeclVendor.cpp ----------------------------------------===//
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/Basic/Diagnostic.h"
10#include "clang/Basic/DiagnosticFrontend.h"
11#include "clang/Basic/IdentifierTable.h"
12#include "clang/Basic/TargetInfo.h"
13#include "clang/Frontend/CompilerInstance.h"
14#include "clang/Frontend/FrontendActions.h"
15#include "clang/Frontend/TextDiagnosticPrinter.h"
16#include "clang/Lex/Preprocessor.h"
17#include "clang/Lex/PreprocessorOptions.h"
18#include "clang/Parse/Parser.h"
19#include "clang/Sema/Lookup.h"
20#include "clang/Serialization/ASTReader.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/Support/Path.h"
23#include "llvm/Support/Threading.h"
24
25#include "ClangHost.h"
27
30#include "lldb/Core/Progress.h"
33#include "lldb/Target/Target.h"
37#include "lldb/Utility/Log.h"
38
39#include <memory>
40
41using namespace lldb_private;
42
43namespace {
44/// Any Clang compiler requires a consumer for diagnostics. This one stores
45/// them as strings so we can provide them to the user in case a module failed
46/// to load.
47class StoringDiagnosticConsumer : public clang::DiagnosticConsumer {
48public:
49 StoringDiagnosticConsumer();
50
51 void HandleDiagnostic(clang::DiagnosticsEngine::Level DiagLevel,
52 const clang::Diagnostic &info) override;
53
54 void ClearDiagnostics();
55
56 void DumpDiagnostics(Stream &error_stream);
57
58 void BeginSourceFile(const clang::LangOptions &LangOpts,
59 const clang::Preprocessor *PP = nullptr) override;
60 void EndSourceFile() override;
61
62private:
63 bool HandleModuleRemark(const clang::Diagnostic &info);
64 void SetCurrentModuleProgress(std::string module_name);
65
66 typedef std::pair<clang::DiagnosticsEngine::Level, std::string>
67 IDAndDiagnostic;
68 std::vector<IDAndDiagnostic> m_diagnostics;
69 std::unique_ptr<clang::DiagnosticOptions> m_diag_opts;
70 /// The DiagnosticPrinter used for creating the full diagnostic messages
71 /// that are stored in m_diagnostics.
72 std::unique_ptr<clang::TextDiagnosticPrinter> m_diag_printer;
73 /// Output stream of m_diag_printer.
74 std::unique_ptr<llvm::raw_string_ostream> m_os;
75 /// Output string filled by m_os. Will be reused for different diagnostics.
76 std::string m_output;
77 /// A Progress with explicitly managed lifetime.
78 std::unique_ptr<Progress> m_current_progress_up;
79 std::vector<std::string> m_module_build_stack;
80};
81
82/// The private implementation of our ClangModulesDeclVendor. Contains all the
83/// Clang state required to load modules.
84class ClangModulesDeclVendorImpl : public ClangModulesDeclVendor {
85public:
86 ClangModulesDeclVendorImpl(
87 std::unique_ptr<clang::DiagnosticOptions> diagnostic_options,
88 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine,
89 std::shared_ptr<clang::CompilerInvocation> compiler_invocation,
90 std::unique_ptr<clang::CompilerInstance> compiler_instance,
91 std::unique_ptr<clang::Parser> parser);
92
93 ~ClangModulesDeclVendorImpl() override = default;
94
95 llvm::Error AddModule(const SourceModule &module,
96 ModuleVector *exported_modules) override;
97
98 llvm::Error AddModulesForCompileUnit(CompileUnit &cu,
99 ModuleVector &exported_modules) override;
100
101 uint32_t FindDecls(ConstString name, bool append, uint32_t max_matches,
102 std::vector<CompilerDecl> &decls) override;
103
104 void ForEachMacro(
105 const ModuleVector &modules,
106 std::function<bool(llvm::StringRef, llvm::StringRef)> handler) override;
107
108private:
109 typedef llvm::DenseSet<ModuleID> ExportedModuleSet;
110 void ReportModuleExportsHelper(ExportedModuleSet &exports,
111 clang::Module *module);
112
113 void ReportModuleExports(ModuleVector &exports, clang::Module *module);
114
115 clang::ModuleLoadResult DoGetModule(clang::ModuleIdPath path,
116 bool make_visible);
117
118 bool m_enabled = false;
119
120 std::unique_ptr<clang::DiagnosticOptions> m_diagnostic_options;
121 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> m_diagnostics_engine;
122 std::shared_ptr<clang::CompilerInvocation> m_compiler_invocation;
123 std::unique_ptr<clang::CompilerInstance> m_compiler_instance;
124 std::unique_ptr<clang::Parser> m_parser;
125 size_t m_source_location_index =
126 0; // used to give name components fake SourceLocations
127
128 typedef std::vector<ConstString> ImportedModule;
129 typedef std::map<ImportedModule, clang::Module *> ImportedModuleMap;
130 typedef llvm::DenseSet<ModuleID> ImportedModuleSet;
131 ImportedModuleMap m_imported_modules;
132 ImportedModuleSet m_user_imported_modules;
133 // We assume that every ASTContext has an TypeSystemClang, so we also store
134 // a custom TypeSystemClang for our internal ASTContext.
135 std::shared_ptr<TypeSystemClang> m_ast_context;
136};
137} // anonymous namespace
138
139StoringDiagnosticConsumer::StoringDiagnosticConsumer() {
140 m_diag_opts = std::make_unique<clang::DiagnosticOptions>();
141 m_os = std::make_unique<llvm::raw_string_ostream>(m_output);
142 m_diag_printer =
143 std::make_unique<clang::TextDiagnosticPrinter>(*m_os, *m_diag_opts);
144}
145
146void StoringDiagnosticConsumer::HandleDiagnostic(
147 clang::DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &info) {
148 if (HandleModuleRemark(info))
149 return;
150
151 // Print the diagnostic to m_output.
152 m_output.clear();
153 m_diag_printer->HandleDiagnostic(DiagLevel, info);
154
155 // Store the diagnostic for later.
156 m_diagnostics.push_back(IDAndDiagnostic(DiagLevel, m_output));
157}
158
159void StoringDiagnosticConsumer::ClearDiagnostics() { m_diagnostics.clear(); }
160
161void StoringDiagnosticConsumer::DumpDiagnostics(Stream &error_stream) {
162 for (IDAndDiagnostic &diag : m_diagnostics) {
163 switch (diag.first) {
164 default:
165 error_stream.PutCString(diag.second);
166 error_stream.PutChar('\n');
167 break;
168 case clang::DiagnosticsEngine::Level::Ignored:
169 break;
170 }
171 }
172}
173
174void StoringDiagnosticConsumer::BeginSourceFile(
175 const clang::LangOptions &LangOpts, const clang::Preprocessor *PP) {
176 m_diag_printer->BeginSourceFile(LangOpts, PP);
177}
178
179void StoringDiagnosticConsumer::EndSourceFile() {
180 m_current_progress_up = nullptr;
181 m_diag_printer->EndSourceFile();
182}
183
184bool StoringDiagnosticConsumer::HandleModuleRemark(
185 const clang::Diagnostic &info) {
186 Log *log = GetLog(LLDBLog::Types | LLDBLog::Expressions);
187 switch (info.getID()) {
188 case clang::diag::remark_module_build: {
189 const auto &module_name = info.getArgStdStr(0);
190 SetCurrentModuleProgress(module_name);
191 m_module_build_stack.push_back(module_name);
192
193 const auto &module_path = info.getArgStdStr(1);
194 LLDB_LOG(log, "Building Clang module {0} as {1}", module_name, module_path);
195 return true;
196 }
197 case clang::diag::remark_module_build_done: {
198 // The current module is done.
199 m_module_build_stack.pop_back();
200 if (m_module_build_stack.empty()) {
201 m_current_progress_up = nullptr;
202 } else {
203 // When the just completed module began building, a module that depends on
204 // it ("module A") was effectively paused. Update the progress to re-show
205 // "module A" as continuing to be built.
206 const auto &resumed_module_name = m_module_build_stack.back();
207 SetCurrentModuleProgress(resumed_module_name);
208 }
209
210 const auto &module_name = info.getArgStdStr(0);
211 LLDB_LOG(log, "Finished building Clang module {0}", module_name);
212 return true;
213 }
214 default:
215 return false;
216 }
217}
218
219void StoringDiagnosticConsumer::SetCurrentModuleProgress(
220 std::string module_name) {
221 if (!m_current_progress_up)
222 m_current_progress_up =
223 std::make_unique<Progress>("Building Clang modules");
224
225 m_current_progress_up->Increment(1, std::move(module_name));
226}
227
230
232
233ClangModulesDeclVendorImpl::ClangModulesDeclVendorImpl(
234 std::unique_ptr<clang::DiagnosticOptions> diagnostic_options,
235 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine,
236 std::shared_ptr<clang::CompilerInvocation> compiler_invocation,
237 std::unique_ptr<clang::CompilerInstance> compiler_instance,
238 std::unique_ptr<clang::Parser> parser)
239 : m_diagnostic_options(std::move(diagnostic_options)),
240 m_diagnostics_engine(std::move(diagnostics_engine)),
241 m_compiler_invocation(std::move(compiler_invocation)),
242 m_compiler_instance(std::move(compiler_instance)),
243 m_parser(std::move(parser)) {
244
245 // Initialize our TypeSystemClang.
246 m_ast_context =
247 std::make_shared<TypeSystemClang>("ClangModulesDeclVendor ASTContext",
248 m_compiler_instance->getASTContext());
249}
250
251void ClangModulesDeclVendorImpl::ReportModuleExportsHelper(
252 ExportedModuleSet &exports, clang::Module *module) {
253 if (exports.count(reinterpret_cast<ClangModulesDeclVendor::ModuleID>(module)))
254 return;
255
256 exports.insert(reinterpret_cast<ClangModulesDeclVendor::ModuleID>(module));
257
258 llvm::SmallVector<clang::Module *, 2> sub_exports;
259
260 module->getExportedModules(sub_exports);
261
262 for (clang::Module *module : sub_exports)
263 ReportModuleExportsHelper(exports, module);
264}
265
266void ClangModulesDeclVendorImpl::ReportModuleExports(
267 ClangModulesDeclVendor::ModuleVector &exports, clang::Module *module) {
268 ExportedModuleSet exports_set;
269
270 ReportModuleExportsHelper(exports_set, module);
271
272 for (ModuleID module : exports_set)
273 exports.push_back(module);
274}
275
276llvm::Error
277ClangModulesDeclVendorImpl::AddModule(const SourceModule &module,
278 ModuleVector *exported_modules) {
279 // Fail early.
280
281 if (m_compiler_instance->hadModuleLoaderFatalFailure())
282 return llvm::createStringError(
283 "couldn't load a module because the module loader is in a fatal state");
284
285 // Check if we've already imported this module.
286
287 std::vector<ConstString> imported_module;
288
289 for (ConstString path_component : module.path)
290 imported_module.push_back(path_component);
291
292 {
293 ImportedModuleMap::iterator mi = m_imported_modules.find(imported_module);
294
295 if (mi != m_imported_modules.end()) {
296 if (exported_modules)
297 ReportModuleExports(*exported_modules, mi->second);
298 return llvm::Error::success();
299 }
300 }
301
302 clang::HeaderSearch &HS =
303 m_compiler_instance->getPreprocessor().getHeaderSearchInfo();
304
305 if (module.search_path) {
306 auto path_begin = llvm::sys::path::begin(module.search_path.GetStringRef());
307 auto path_end = llvm::sys::path::end(module.search_path.GetStringRef());
308 auto sysroot_begin = llvm::sys::path::begin(module.sysroot.GetStringRef());
309 auto sysroot_end = llvm::sys::path::end(module.sysroot.GetStringRef());
310 // FIXME: Use C++14 std::equal(it, it, it, it) variant once it's available.
311 bool is_system_module = (std::distance(path_begin, path_end) >=
312 std::distance(sysroot_begin, sysroot_end)) &&
313 std::equal(sysroot_begin, sysroot_end, path_begin);
314 // No need to inject search paths to modules in the sysroot.
315 if (!is_system_module) {
316 bool is_system = true;
317 bool is_framework = false;
318 auto dir = HS.getFileMgr().getOptionalDirectoryRef(
319 module.search_path.GetStringRef());
320 if (!dir)
321 return llvm::createStringError(
322 "couldn't find module search path directory %s",
323 module.search_path.GetCString());
324
325 auto file = HS.lookupModuleMapFile(*dir, is_framework);
326 if (!file)
327 return llvm::createStringError("couldn't find modulemap file in %s",
328 module.search_path.GetCString());
329
330 if (HS.parseAndLoadModuleMapFile(*file, is_system))
331 return llvm::createStringError(
332 "failed to parse and load modulemap file in %s",
333 module.search_path.GetCString());
334 }
335 }
336
337 if (!HS.lookupModule(module.path.front().GetStringRef()))
338 return llvm::createStringError("header search couldn't locate module '%s'",
339 module.path.front().AsCString());
340
341 llvm::SmallVector<clang::IdentifierLoc, 4> clang_path;
342
343 {
344 clang::SourceManager &source_manager =
345 m_compiler_instance->getASTContext().getSourceManager();
346
347 for (ConstString path_component : module.path) {
348 clang_path.emplace_back(
349 source_manager.getLocForStartOfFile(source_manager.getMainFileID())
350 .getLocWithOffset(m_source_location_index++),
351 &m_compiler_instance->getASTContext().Idents.get(
352 path_component.GetStringRef()));
353 }
354 }
355
356 StoringDiagnosticConsumer *diagnostic_consumer =
357 static_cast<StoringDiagnosticConsumer *>(
358 m_compiler_instance->getDiagnostics().getClient());
359
360 diagnostic_consumer->ClearDiagnostics();
361
362 clang::Module *top_level_module = DoGetModule(clang_path.front(), false);
363
364 if (!top_level_module) {
365 lldb_private::StreamString error_stream;
366 diagnostic_consumer->DumpDiagnostics(error_stream);
367
368 return llvm::createStringError(llvm::formatv(
369 "couldn't load top-level module {0}:\n{1}",
370 module.path.front().GetStringRef(), error_stream.GetString()));
371 }
372
373 clang::Module *submodule = top_level_module;
374
375 for (auto &component : llvm::ArrayRef<ConstString>(module.path).drop_front()) {
376 clang::Module *found = submodule->findSubmodule(component.GetStringRef());
377 if (!found) {
378 lldb_private::StreamString error_stream;
379 diagnostic_consumer->DumpDiagnostics(error_stream);
380
381 return llvm::createStringError(llvm::formatv(
382 "couldn't load submodule '{0}' of module '{1}':\n{2}",
383 component.GetStringRef(), submodule->getFullModuleName(),
384 error_stream.GetString()));
385 }
386
387 submodule = found;
388 }
389
390 // If we didn't make the submodule visible here, Clang wouldn't allow LLDB to
391 // pick any of the decls in the submodules during C++ name lookup.
392 if (submodule)
393 m_compiler_instance->makeModuleVisible(
394 submodule, clang::Module::NameVisibilityKind::AllVisible,
395 /*ImportLoc=*/{});
396
397 clang::Module *requested_module = DoGetModule(clang_path, true);
398
399 if (requested_module != nullptr) {
400 if (exported_modules)
401 ReportModuleExports(*exported_modules, requested_module);
402
403 m_imported_modules[imported_module] = requested_module;
404
405 m_enabled = true;
406
407 return llvm::Error::success();
408 }
409
410 return llvm::createStringError(
411 llvm::formatv("unknown error while loading module {0}\n",
412 module.path.front().GetStringRef()));
413}
414
433
434llvm::Error ClangModulesDeclVendorImpl::AddModulesForCompileUnit(
435 CompileUnit &cu, ClangModulesDeclVendor::ModuleVector &exported_modules) {
436 if (!LanguageSupportsClangModules(cu.GetLanguage()))
437 return llvm::Error::success();
438
439 llvm::Error errors = llvm::Error::success();
440
441 for (auto &imported_module : cu.GetImportedModules())
442 if (auto err = AddModule(imported_module, &exported_modules))
443 errors = llvm::joinErrors(std::move(errors), std::move(err));
444
445 return errors;
446}
447
448// ClangImporter::lookupValue
449
450uint32_t
451ClangModulesDeclVendorImpl::FindDecls(ConstString name, bool append,
452 uint32_t max_matches,
453 std::vector<CompilerDecl> &decls) {
454 if (!m_enabled)
455 return 0;
456
457 if (!append)
458 decls.clear();
459
460 clang::IdentifierInfo &ident =
461 m_compiler_instance->getASTContext().Idents.get(name.GetStringRef());
462
463 clang::LookupResult lookup_result(
464 m_compiler_instance->getSema(), clang::DeclarationName(&ident),
465 clang::SourceLocation(), clang::Sema::LookupOrdinaryName);
466
467 m_compiler_instance->getSema().LookupName(
468 lookup_result,
469 m_compiler_instance->getSema().getScopeForContext(
470 m_compiler_instance->getASTContext().getTranslationUnitDecl()));
471
472 uint32_t num_matches = 0;
473
474 for (clang::NamedDecl *named_decl : lookup_result) {
475 if (num_matches >= max_matches)
476 return num_matches;
477
478 decls.push_back(m_ast_context->GetCompilerDecl(named_decl));
479 ++num_matches;
480 }
481
482 return num_matches;
483}
484
485void ClangModulesDeclVendorImpl::ForEachMacro(
487 std::function<bool(llvm::StringRef, llvm::StringRef)> handler) {
488 if (!m_enabled)
489 return;
490
491 typedef std::map<ModuleID, ssize_t> ModulePriorityMap;
492 ModulePriorityMap module_priorities;
493
494 ssize_t priority = 0;
495
496 for (ModuleID module : modules)
497 module_priorities[module] = priority++;
498
499 if (m_compiler_instance->getPreprocessor().getExternalSource()) {
500 m_compiler_instance->getPreprocessor()
501 .getExternalSource()
502 ->ReadDefinedMacros();
503 }
504
505 for (clang::Preprocessor::macro_iterator
506 mi = m_compiler_instance->getPreprocessor().macro_begin(),
507 me = m_compiler_instance->getPreprocessor().macro_end();
508 mi != me; ++mi) {
509 const clang::IdentifierInfo *ii = nullptr;
510
511 {
512 if (clang::IdentifierInfoLookup *lookup =
513 m_compiler_instance->getPreprocessor()
514 .getIdentifierTable()
515 .getExternalIdentifierLookup()) {
516 lookup->get(mi->first->getName());
517 }
518 if (!ii)
519 ii = mi->first;
520 }
521
522 ssize_t found_priority = -1;
523 clang::MacroInfo *macro_info = nullptr;
524
525 for (clang::ModuleMacro *module_macro :
526 m_compiler_instance->getPreprocessor().getLeafModuleMacros(ii)) {
527 clang::Module *module = module_macro->getOwningModule();
528
529 {
530 ModulePriorityMap::iterator pi =
531 module_priorities.find(reinterpret_cast<ModuleID>(module));
532
533 if (pi != module_priorities.end() && pi->second > found_priority) {
534 macro_info = module_macro->getMacroInfo();
535 found_priority = pi->second;
536 }
537 }
538
539 clang::Module *top_level_module = module->getTopLevelModule();
540
541 if (top_level_module != module) {
542 ModulePriorityMap::iterator pi = module_priorities.find(
543 reinterpret_cast<ModuleID>(top_level_module));
544
545 if ((pi != module_priorities.end()) && pi->second > found_priority) {
546 macro_info = module_macro->getMacroInfo();
547 found_priority = pi->second;
548 }
549 }
550 }
551
552 if (macro_info) {
553 std::string macro_expansion = "#define ";
554 llvm::StringRef macro_identifier = mi->first->getName();
555 macro_expansion.append(macro_identifier.str());
556
557 {
558 if (macro_info->isFunctionLike()) {
559 macro_expansion.append("(");
560
561 bool first_arg = true;
562
563 for (auto pi = macro_info->param_begin(),
564 pe = macro_info->param_end();
565 pi != pe; ++pi) {
566 if (!first_arg)
567 macro_expansion.append(", ");
568 else
569 first_arg = false;
570
571 macro_expansion.append((*pi)->getName().str());
572 }
573
574 if (macro_info->isC99Varargs()) {
575 if (first_arg)
576 macro_expansion.append("...");
577 else
578 macro_expansion.append(", ...");
579 } else if (macro_info->isGNUVarargs())
580 macro_expansion.append("...");
581
582 macro_expansion.append(")");
583 }
584
585 macro_expansion.append(" ");
586
587 bool first_token = true;
588
589 for (clang::MacroInfo::const_tokens_iterator
590 ti = macro_info->tokens_begin(),
591 te = macro_info->tokens_end();
592 ti != te; ++ti) {
593 if (!first_token)
594 macro_expansion.append(" ");
595 else
596 first_token = false;
597
598 if (ti->isLiteral()) {
599 if (const char *literal_data = ti->getLiteralData()) {
600 std::string token_str(literal_data, ti->getLength());
601 macro_expansion.append(token_str);
602 } else {
603 bool invalid = false;
604 const char *literal_source =
605 m_compiler_instance->getSourceManager().getCharacterData(
606 ti->getLocation(), &invalid);
607
608 if (invalid) {
609 lldbassert(0 && "Unhandled token kind");
610 macro_expansion.append("<unknown literal value>");
611 } else {
612 macro_expansion.append(
613 std::string(literal_source, ti->getLength()));
614 }
615 }
616 } else if (const char *punctuator_spelling =
617 clang::tok::getPunctuatorSpelling(ti->getKind())) {
618 macro_expansion.append(punctuator_spelling);
619 } else if (const char *keyword_spelling =
620 clang::tok::getKeywordSpelling(ti->getKind())) {
621 macro_expansion.append(keyword_spelling);
622 } else {
623 switch (ti->getKind()) {
624 case clang::tok::TokenKind::identifier:
625 macro_expansion.append(ti->getIdentifierInfo()->getName().str());
626 break;
627 case clang::tok::TokenKind::raw_identifier:
628 macro_expansion.append(ti->getRawIdentifier().str());
629 break;
630 default:
631 macro_expansion.append(ti->getName());
632 break;
633 }
634 }
635 }
636
637 if (handler(macro_identifier, macro_expansion)) {
638 return;
639 }
640 }
641 }
642 }
643}
644
645clang::ModuleLoadResult
646ClangModulesDeclVendorImpl::DoGetModule(clang::ModuleIdPath path,
647 bool make_visible) {
648 clang::Module::NameVisibilityKind visibility =
649 make_visible ? clang::Module::AllVisible : clang::Module::Hidden;
650
651 const bool is_inclusion_directive = false;
652
653 return m_compiler_instance->loadModule(path.front().getLoc(), path,
654 visibility, is_inclusion_directive);
655}
656
657static const char *ModuleImportBufferName = "LLDBModulesMemoryBuffer";
658
661 // FIXME we should insure programmatically that the expression parser's
662 // compiler and the modules runtime's
663 // compiler are both initialized in the same way – preferably by the same
664 // code.
665
666 if (!target.GetPlatform()->SupportsModules())
667 return nullptr;
668
669 const ArchSpec &arch = target.GetArchitecture();
670
671 std::vector<std::string> compiler_invocation_arguments = {
672 "clang",
673 "-fmodules",
674 "-fimplicit-module-maps",
675 "-fcxx-modules",
676 "-fsyntax-only",
677 "-femit-all-decls",
678 "-target",
679 arch.GetTriple().str(),
680 "-fmodules-validate-system-headers",
681 "-Werror=non-modular-include-in-framework-module",
682 "-Xclang=-fincremental-extensions",
683 "-Rmodule-build"};
684
685 target.GetPlatform()->AddClangModuleCompilationOptions(
686 &target, compiler_invocation_arguments);
687
688 compiler_invocation_arguments.push_back(ModuleImportBufferName);
689
690 // Add additional search paths with { "-I", path } or { "-F", path } here.
691
692 {
693 llvm::SmallString<128> path;
694 const auto &props = ModuleList::GetGlobalModuleListProperties();
695 props.GetClangModulesCachePath().GetPath(path);
696 std::string module_cache_argument("-fmodules-cache-path=");
697 module_cache_argument.append(std::string(path.str()));
698 compiler_invocation_arguments.push_back(module_cache_argument);
699 }
700
701 FileSpecList module_search_paths = target.GetClangModuleSearchPaths();
702
703 for (size_t spi = 0, spe = module_search_paths.GetSize(); spi < spe; ++spi) {
704 const FileSpec &search_path = module_search_paths.GetFileSpecAtIndex(spi);
705
706 std::string search_path_argument = "-I";
707 search_path_argument.append(search_path.GetPath());
708
709 compiler_invocation_arguments.push_back(search_path_argument);
710 }
711
712 {
713 FileSpec clang_resource_dir = GetClangResourceDir();
714
715 if (FileSystem::Instance().IsDirectory(clang_resource_dir.GetPath())) {
716 compiler_invocation_arguments.push_back("-resource-dir");
717 compiler_invocation_arguments.push_back(clang_resource_dir.GetPath());
718 }
719 }
720
721 std::vector<const char *> compiler_invocation_argument_cstrs;
722 compiler_invocation_argument_cstrs.reserve(
723 compiler_invocation_arguments.size());
724 for (const std::string &arg : compiler_invocation_arguments)
725 compiler_invocation_argument_cstrs.push_back(arg.c_str());
726
727 auto diag_options_up =
728 clang::CreateAndPopulateDiagOpts(compiler_invocation_argument_cstrs);
729 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine =
730 clang::CompilerInstance::createDiagnostics(
731 *FileSystem::Instance().GetVirtualFileSystem(), *diag_options_up,
732 new StoringDiagnosticConsumer);
733
735 LLDB_LOG(log, "ClangModulesDeclVendor's compiler flags {0:$[ ]}",
736 llvm::make_range(compiler_invocation_arguments.begin(),
737 compiler_invocation_arguments.end()));
738
739 clang::CreateInvocationOptions CIOpts;
740 CIOpts.Diags = diagnostics_engine;
741 std::shared_ptr<clang::CompilerInvocation> invocation =
742 clang::createInvocation(compiler_invocation_argument_cstrs,
743 std::move(CIOpts));
744
745 if (!invocation)
746 return nullptr;
747
748 std::unique_ptr<llvm::MemoryBuffer> source_buffer =
749 llvm::MemoryBuffer::getMemBuffer(
750 "extern int __lldb __attribute__((unavailable));",
752
753 invocation->getPreprocessorOpts().addRemappedFile(ModuleImportBufferName,
754 source_buffer.release());
755
756 auto instance = std::make_unique<clang::CompilerInstance>(invocation);
757
758 // Make sure clang uses the same VFS as LLDB.
759 instance->setVirtualFileSystem(FileSystem::Instance().GetVirtualFileSystem());
760 instance->createFileManager();
761 instance->setDiagnostics(diagnostics_engine);
762
763 std::unique_ptr<clang::FrontendAction> action(new clang::SyntaxOnlyAction);
764
765 instance->setTarget(clang::TargetInfo::CreateTargetInfo(
766 *diagnostics_engine, instance->getInvocation().getTargetOpts()));
767
768 if (!instance->hasTarget())
769 return nullptr;
770
771 instance->getTarget().adjust(*diagnostics_engine, instance->getLangOpts(),
772 /*AuxTarget=*/nullptr);
773
774 if (!action->BeginSourceFile(*instance,
775 instance->getFrontendOpts().Inputs[0]))
776 return nullptr;
777
778 instance->createASTReader();
779
780 instance->createSema(action->getTranslationUnitKind(), nullptr);
781
782 const bool skipFunctionBodies = false;
783 std::unique_ptr<clang::Parser> parser(new clang::Parser(
784 instance->getPreprocessor(), instance->getSema(), skipFunctionBodies));
785
786 instance->getPreprocessor().EnterMainSourceFile();
787 parser->Initialize();
788
789 clang::Parser::DeclGroupPtrTy parsed;
790 auto ImportState = clang::Sema::ModuleImportState::NotACXX20Module;
791 while (!parser->ParseTopLevelDecl(parsed, ImportState))
792 ;
793
794 return new ClangModulesDeclVendorImpl(
795 std::move(diag_options_up), std::move(diagnostics_engine),
796 std::move(invocation), std::move(instance), std::move(parser));
797}
static const char * ModuleImportBufferName
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:369
static void DumpDiagnostics(void *cookie)
An architecture specification class.
Definition ArchSpec.h:31
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:468
static ClangModulesDeclVendor * Create(Target &target)
static bool LanguageSupportsClangModules(lldb::LanguageType language)
Query whether Clang supports modules for a particular language.
A class that describes a compilation unit.
Definition CompileUnit.h:43
const std::vector< SourceModule > & GetImportedModules()
Get the compile unit's imported module list.
lldb::LanguageType GetLanguage()
A uniqued constant string class.
Definition ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const char * GetCString() const
Get the string value as a C string.
DeclVendor(DeclVendorKind kind)
Definition DeclVendor.h:28
A file collection class.
const FileSpec & GetFileSpecAtIndex(size_t idx) const
Get file at index.
size_t GetSize() const
Get the number of files in the file list.
A file utility class.
Definition FileSpec.h:57
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
static FileSystem & Instance()
static ModuleListProperties & GetGlobalModuleListProperties()
llvm::StringRef GetString() const
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:65
size_t PutChar(char ch)
Definition Stream.cpp:131
FileSpecList GetClangModuleSearchPaths()
Definition Target.cpp:4850
lldb::PlatformSP GetPlatform()
Definition Target.h:1593
const ArchSpec & GetArchitecture() const
Definition Target.h:1098
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.
Definition Log.h:332
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".