180814287SRaphael Isemann //===-- ClangExpressionParser.cpp -----------------------------------------===//
24dbb271fSSean Callanan //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
64dbb271fSSean Callanan //
74dbb271fSSean Callanan //===----------------------------------------------------------------------===//
84dbb271fSSean Callanan
94dbb271fSSean Callanan #include "clang/AST/ASTContext.h"
10579e70c9SSean Callanan #include "clang/AST/ASTDiagnostic.h"
114dbb271fSSean Callanan #include "clang/AST/ExternalASTSource.h"
129dd34c83SRaphael Isemann #include "clang/AST/PrettyPrinter.h"
13979da9a4SReid Kleckner #include "clang/Basic/Builtins.h"
14579e70c9SSean Callanan #include "clang/Basic/DiagnosticIDs.h"
154dbb271fSSean Callanan #include "clang/Basic/SourceLocation.h"
164dbb271fSSean Callanan #include "clang/Basic/TargetInfo.h"
174dbb271fSSean Callanan #include "clang/Basic/Version.h"
184dbb271fSSean Callanan #include "clang/CodeGen/CodeGenAction.h"
194dbb271fSSean Callanan #include "clang/CodeGen/ModuleBuilder.h"
20a1e541bfSJim Ingham #include "clang/Edit/Commit.h"
21a1e541bfSJim Ingham #include "clang/Edit/EditedSource.h"
22b9c1b51eSKate Stone #include "clang/Edit/EditsReceiver.h"
234dbb271fSSean Callanan #include "clang/Frontend/CompilerInstance.h"
244dbb271fSSean Callanan #include "clang/Frontend/CompilerInvocation.h"
254dbb271fSSean Callanan #include "clang/Frontend/FrontendActions.h"
264dbb271fSSean Callanan #include "clang/Frontend/FrontendDiagnostic.h"
274dbb271fSSean Callanan #include "clang/Frontend/FrontendPluginRegistry.h"
284dbb271fSSean Callanan #include "clang/Frontend/TextDiagnosticBuffer.h"
294dbb271fSSean Callanan #include "clang/Frontend/TextDiagnosticPrinter.h"
304dbb271fSSean Callanan #include "clang/Lex/Preprocessor.h"
314dbb271fSSean Callanan #include "clang/Parse/ParseAST.h"
32a1e541bfSJim Ingham #include "clang/Rewrite/Core/Rewriter.h"
33b9c1b51eSKate Stone #include "clang/Rewrite/Frontend/FrontendActions.h"
3474829734SRaphael Isemann #include "clang/Sema/CodeCompleteConsumer.h"
3574829734SRaphael Isemann #include "clang/Sema/Sema.h"
364dbb271fSSean Callanan #include "clang/Sema/SemaConsumer.h"
374dbb271fSSean Callanan
384dbb271fSSean Callanan #include "llvm/ADT/StringRef.h"
394dbb271fSSean Callanan #include "llvm/ExecutionEngine/ExecutionEngine.h"
406c0bbfc0SRaphael Isemann #include "llvm/Support/CrashRecoveryContext.h"
414dbb271fSSean Callanan #include "llvm/Support/Debug.h"
424dbb271fSSean Callanan #include "llvm/Support/FileSystem.h"
434dbb271fSSean Callanan #include "llvm/Support/TargetSelect.h"
444dbb271fSSean Callanan
454dbb271fSSean Callanan #include "llvm/IR/LLVMContext.h"
464dbb271fSSean Callanan #include "llvm/IR/Module.h"
474dbb271fSSean Callanan #include "llvm/Support/DynamicLibrary.h"
48b9c1b51eSKate Stone #include "llvm/Support/ErrorHandling.h"
494dbb271fSSean Callanan #include "llvm/Support/Host.h"
50b9c1b51eSKate Stone #include "llvm/Support/MemoryBuffer.h"
514dbb271fSSean Callanan #include "llvm/Support/Signals.h"
524dbb271fSSean Callanan
536c0bbfc0SRaphael Isemann #include "ClangDiagnostic.h"
546c0bbfc0SRaphael Isemann #include "ClangExpressionParser.h"
556c0bbfc0SRaphael Isemann #include "ClangUserExpression.h"
566c0bbfc0SRaphael Isemann
576c0bbfc0SRaphael Isemann #include "ASTUtils.h"
584c3f2b94SEugene Zelenko #include "ClangASTSource.h"
5963e2e59bSJonas Devlieghere #include "ClangDiagnostic.h"
604c3f2b94SEugene Zelenko #include "ClangExpressionDeclMap.h"
61b9c1b51eSKate Stone #include "ClangExpressionHelper.h"
6263e2e59bSJonas Devlieghere #include "ClangExpressionParser.h"
636c0bbfc0SRaphael Isemann #include "ClangHost.h"
644c3f2b94SEugene Zelenko #include "ClangModulesDeclVendor.h"
654c3f2b94SEugene Zelenko #include "ClangPersistentVariables.h"
66bab7e3d7SAlex Langford #include "IRDynamicChecks.h"
674c3f2b94SEugene Zelenko #include "IRForTarget.h"
6863e2e59bSJonas Devlieghere #include "ModuleDependencyCollector.h"
694c3f2b94SEugene Zelenko
708be30215SAlex Langford #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
714c3f2b94SEugene Zelenko #include "lldb/Core/Debugger.h"
724c3f2b94SEugene Zelenko #include "lldb/Core/Disassembler.h"
734c3f2b94SEugene Zelenko #include "lldb/Core/Module.h"
744c3f2b94SEugene Zelenko #include "lldb/Core/StreamFile.h"
75579e70c9SSean Callanan #include "lldb/Expression/IRExecutionUnit.h"
764c3f2b94SEugene Zelenko #include "lldb/Expression/IRInterpreter.h"
774c3f2b94SEugene Zelenko #include "lldb/Host/File.h"
784c3f2b94SEugene Zelenko #include "lldb/Host/HostInfo.h"
794c3f2b94SEugene Zelenko #include "lldb/Symbol/SymbolVendor.h"
804c3f2b94SEugene Zelenko #include "lldb/Target/ExecutionContext.h"
81579e70c9SSean Callanan #include "lldb/Target/Language.h"
824c3f2b94SEugene Zelenko #include "lldb/Target/Process.h"
834c3f2b94SEugene Zelenko #include "lldb/Target/Target.h"
84bd4dc693SSean Callanan #include "lldb/Target/ThreadPlanCallFunction.h"
85666cc0b2SZachary Turner #include "lldb/Utility/DataBufferHeap.h"
86579e70c9SSean Callanan #include "lldb/Utility/LLDBAssert.h"
87c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
886f9e6901SZachary Turner #include "lldb/Utility/Log.h"
89bb894b97SJonas Devlieghere #include "lldb/Utility/ReproducerProvider.h"
90bf9a7730SZachary Turner #include "lldb/Utility/Stream.h"
91bf9a7730SZachary Turner #include "lldb/Utility/StreamString.h"
92573ab909SZachary Turner #include "lldb/Utility/StringList.h"
934c3f2b94SEugene Zelenko
94b5701710SAlex Langford #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
952637769bSAlex Langford #include "Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.h"
96b5701710SAlex Langford
97796ac80bSJonas Devlieghere #include <cctype>
98796ac80bSJonas Devlieghere #include <memory>
99796ac80bSJonas Devlieghere
1004dbb271fSSean Callanan using namespace clang;
1014dbb271fSSean Callanan using namespace llvm;
1024dbb271fSSean Callanan using namespace lldb_private;
1034dbb271fSSean Callanan
1044dbb271fSSean Callanan //===----------------------------------------------------------------------===//
1054dbb271fSSean Callanan // Utility Methods for Clang
1064dbb271fSSean Callanan //===----------------------------------------------------------------------===//
1074dbb271fSSean Callanan
108b9c1b51eSKate Stone class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
1094dbb271fSSean Callanan ClangModulesDeclVendor &m_decl_vendor;
1104dbb271fSSean Callanan ClangPersistentVariables &m_persistent_vars;
111bd2a910aSRaphael Isemann clang::SourceManager &m_source_mgr;
1124dbb271fSSean Callanan StreamString m_error_stream;
1134dbb271fSSean Callanan bool m_has_errors = false;
1144c3f2b94SEugene Zelenko
1154dbb271fSSean Callanan public:
LLDBPreprocessorCallbacks(ClangModulesDeclVendor & decl_vendor,ClangPersistentVariables & persistent_vars,clang::SourceManager & source_mgr)1164dbb271fSSean Callanan LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
117bd2a910aSRaphael Isemann ClangPersistentVariables &persistent_vars,
118bd2a910aSRaphael Isemann clang::SourceManager &source_mgr)
119bd2a910aSRaphael Isemann : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars),
120bd2a910aSRaphael Isemann m_source_mgr(source_mgr) {}
1214dbb271fSSean Callanan
moduleImport(SourceLocation import_location,clang::ModuleIdPath path,const clang::Module *)122b9c1b51eSKate Stone void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
123b9c1b51eSKate Stone const clang::Module * /*null*/) override {
124bd2a910aSRaphael Isemann // Ignore modules that are imported in the wrapper code as these are not
125bd2a910aSRaphael Isemann // loaded by the user.
126bd2a910aSRaphael Isemann llvm::StringRef filename =
127bd2a910aSRaphael Isemann m_source_mgr.getPresumedLoc(import_location).getFilename();
128bd2a910aSRaphael Isemann if (filename == ClangExpressionSourceCode::g_prefix_file_name)
129bd2a910aSRaphael Isemann return;
130bd2a910aSRaphael Isemann
1310f30a3b6SAdrian Prantl SourceModule module;
1324dbb271fSSean Callanan
1330f30a3b6SAdrian Prantl for (const std::pair<IdentifierInfo *, SourceLocation> &component : path)
1340f30a3b6SAdrian Prantl module.path.push_back(ConstString(component.first->getName()));
1354dbb271fSSean Callanan
1364dbb271fSSean Callanan StreamString error_stream;
1374dbb271fSSean Callanan
1384dbb271fSSean Callanan ClangModulesDeclVendor::ModuleVector exported_modules;
1390f30a3b6SAdrian Prantl if (!m_decl_vendor.AddModule(module, &exported_modules, m_error_stream))
1404dbb271fSSean Callanan m_has_errors = true;
1414dbb271fSSean Callanan
1420f30a3b6SAdrian Prantl for (ClangModulesDeclVendor::ModuleID module : exported_modules)
1434dbb271fSSean Callanan m_persistent_vars.AddHandLoadedClangModule(module);
1444dbb271fSSean Callanan }
1454dbb271fSSean Callanan
hasErrors()146b9c1b51eSKate Stone bool hasErrors() { return m_has_errors; }
1474dbb271fSSean Callanan
getErrorString()148c156427dSZachary Turner llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
1494dbb271fSSean Callanan };
1504dbb271fSSean Callanan
AddAllFixIts(ClangDiagnostic * diag,const clang::Diagnostic & Info)1513c2dc28dSRaphael Isemann static void AddAllFixIts(ClangDiagnostic *diag, const clang::Diagnostic &Info) {
1523c2dc28dSRaphael Isemann for (auto &fix_it : Info.getFixItHints()) {
1533c2dc28dSRaphael Isemann if (fix_it.isNull())
1543c2dc28dSRaphael Isemann continue;
1553c2dc28dSRaphael Isemann diag->AddFixitHint(fix_it);
1563c2dc28dSRaphael Isemann }
1573c2dc28dSRaphael Isemann }
1583c2dc28dSRaphael Isemann
159b9c1b51eSKate Stone class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
160579e70c9SSean Callanan public:
ClangDiagnosticManagerAdapter(DiagnosticOptions & opts)1611442efeaSRaphael Isemann ClangDiagnosticManagerAdapter(DiagnosticOptions &opts) {
16211b1eeeaSRaphael Isemann DiagnosticOptions *options = new DiagnosticOptions(opts);
16311b1eeeaSRaphael Isemann options->ShowPresumedLoc = true;
16411b1eeeaSRaphael Isemann options->ShowLevel = false;
165827c0122SJonas Devlieghere m_os = std::make_shared<llvm::raw_string_ostream>(m_output);
166827c0122SJonas Devlieghere m_passthrough =
16711b1eeeaSRaphael Isemann std::make_shared<clang::TextDiagnosticPrinter>(*m_os, options);
1681442efeaSRaphael Isemann }
169579e70c9SSean Callanan
ResetManager(DiagnosticManager * manager=nullptr)170b9c1b51eSKate Stone void ResetManager(DiagnosticManager *manager = nullptr) {
171579e70c9SSean Callanan m_manager = manager;
172579e70c9SSean Callanan }
173579e70c9SSean Callanan
1743c2dc28dSRaphael Isemann /// Returns the last ClangDiagnostic message that the DiagnosticManager
1753c2dc28dSRaphael Isemann /// received or a nullptr if the DiagnosticMangager hasn't seen any
1763c2dc28dSRaphael Isemann /// Clang diagnostics yet.
MaybeGetLastClangDiag() const1773c2dc28dSRaphael Isemann ClangDiagnostic *MaybeGetLastClangDiag() const {
1783c2dc28dSRaphael Isemann if (m_manager->Diagnostics().empty())
1793c2dc28dSRaphael Isemann return nullptr;
1803c2dc28dSRaphael Isemann lldb_private::Diagnostic *diag = m_manager->Diagnostics().back().get();
1813c2dc28dSRaphael Isemann ClangDiagnostic *clang_diag = dyn_cast<ClangDiagnostic>(diag);
1823c2dc28dSRaphael Isemann return clang_diag;
1833c2dc28dSRaphael Isemann }
1843c2dc28dSRaphael Isemann
HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,const clang::Diagnostic & Info)185b9c1b51eSKate Stone void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1861756630dSRaphael Isemann const clang::Diagnostic &Info) override {
1874e969da3SRaphael Isemann if (!m_manager) {
1884e969da3SRaphael Isemann // We have no DiagnosticManager before/after parsing but we still could
1894e969da3SRaphael Isemann // receive diagnostics (e.g., by the ASTImporter failing to copy decls
1904e969da3SRaphael Isemann // when we move the expression result ot the ScratchASTContext). Let's at
1914e969da3SRaphael Isemann // least log these diagnostics until we find a way to properly render
1924e969da3SRaphael Isemann // them and display them to the user.
193a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Expressions);
1944e969da3SRaphael Isemann if (log) {
1954e969da3SRaphael Isemann llvm::SmallVector<char, 32> diag_str;
1964e969da3SRaphael Isemann Info.FormatDiagnostic(diag_str);
1974e969da3SRaphael Isemann diag_str.push_back('\0');
1984e969da3SRaphael Isemann const char *plain_diag = diag_str.data();
1994e969da3SRaphael Isemann LLDB_LOG(log, "Received diagnostic outside parsing: {0}", plain_diag);
2004e969da3SRaphael Isemann }
2014e969da3SRaphael Isemann return;
2024e969da3SRaphael Isemann }
2034e969da3SRaphael Isemann
20483aa58d7SRaphael Isemann // Update error/warning counters.
20583aa58d7SRaphael Isemann DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
20683aa58d7SRaphael Isemann
2071442efeaSRaphael Isemann // Render diagnostic message to m_output.
2081442efeaSRaphael Isemann m_output.clear();
2091442efeaSRaphael Isemann m_passthrough->HandleDiagnostic(DiagLevel, Info);
2101442efeaSRaphael Isemann m_os->flush();
211579e70c9SSean Callanan
21215cb0bd0SRenato Golin lldb_private::DiagnosticSeverity severity;
213a1e541bfSJim Ingham bool make_new_diagnostic = true;
214a1e541bfSJim Ingham
215b9c1b51eSKate Stone switch (DiagLevel) {
216579e70c9SSean Callanan case DiagnosticsEngine::Level::Fatal:
217579e70c9SSean Callanan case DiagnosticsEngine::Level::Error:
218a1e541bfSJim Ingham severity = eDiagnosticSeverityError;
219579e70c9SSean Callanan break;
220579e70c9SSean Callanan case DiagnosticsEngine::Level::Warning:
221a1e541bfSJim Ingham severity = eDiagnosticSeverityWarning;
222579e70c9SSean Callanan break;
223579e70c9SSean Callanan case DiagnosticsEngine::Level::Remark:
224579e70c9SSean Callanan case DiagnosticsEngine::Level::Ignored:
225a1e541bfSJim Ingham severity = eDiagnosticSeverityRemark;
226579e70c9SSean Callanan break;
227579e70c9SSean Callanan case DiagnosticsEngine::Level::Note:
2281442efeaSRaphael Isemann m_manager->AppendMessageToDiagnostic(m_output);
229a1e541bfSJim Ingham make_new_diagnostic = false;
2303c2dc28dSRaphael Isemann
2313c2dc28dSRaphael Isemann // 'note:' diagnostics for errors and warnings can also contain Fix-Its.
2323c2dc28dSRaphael Isemann // We add these Fix-Its to the last error diagnostic to make sure
2333c2dc28dSRaphael Isemann // that we later have all Fix-Its related to an 'error' diagnostic when
2343c2dc28dSRaphael Isemann // we apply them to the user expression.
2353c2dc28dSRaphael Isemann auto *clang_diag = MaybeGetLastClangDiag();
2363c2dc28dSRaphael Isemann // If we don't have a previous diagnostic there is nothing to do.
2373c2dc28dSRaphael Isemann // If the previous diagnostic already has its own Fix-Its, assume that
2383c2dc28dSRaphael Isemann // the 'note:' Fix-It is just an alternative way to solve the issue and
2393c2dc28dSRaphael Isemann // ignore these Fix-Its.
2403c2dc28dSRaphael Isemann if (!clang_diag || clang_diag->HasFixIts())
2413c2dc28dSRaphael Isemann break;
2423c2dc28dSRaphael Isemann // Ignore all Fix-Its that are not associated with an error.
2433c2dc28dSRaphael Isemann if (clang_diag->GetSeverity() != eDiagnosticSeverityError)
2443c2dc28dSRaphael Isemann break;
2453c2dc28dSRaphael Isemann AddAllFixIts(clang_diag, Info);
2463c2dc28dSRaphael Isemann break;
247a1e541bfSJim Ingham }
248b9c1b51eSKate Stone if (make_new_diagnostic) {
2491442efeaSRaphael Isemann // ClangDiagnostic messages are expected to have no whitespace/newlines
2501442efeaSRaphael Isemann // around them.
251adcd0268SBenjamin Kramer std::string stripped_output =
252adcd0268SBenjamin Kramer std::string(llvm::StringRef(m_output).trim());
2531442efeaSRaphael Isemann
2547c47b4a1SRaphael Isemann auto new_diagnostic = std::make_unique<ClangDiagnostic>(
2557c47b4a1SRaphael Isemann stripped_output, severity, Info.getID());
256a1e541bfSJim Ingham
25750f7153dSDavide Italiano // Don't store away warning fixits, since the compiler doesn't have
25850f7153dSDavide Italiano // enough context in an expression for the warning to be useful.
259a1e541bfSJim Ingham // FIXME: Should we try to filter out FixIts that apply to our generated
260a1e541bfSJim Ingham // code, and not the user's expression?
2613c2dc28dSRaphael Isemann if (severity == eDiagnosticSeverityError)
2623c2dc28dSRaphael Isemann AddAllFixIts(new_diagnostic.get(), Info);
2637c47b4a1SRaphael Isemann
2647c47b4a1SRaphael Isemann m_manager->AddDiagnostic(std::move(new_diagnostic));
265579e70c9SSean Callanan }
266579e70c9SSean Callanan }
267579e70c9SSean Callanan
BeginSourceFile(const LangOptions & LO,const Preprocessor * PP)26883aa58d7SRaphael Isemann void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override {
26983aa58d7SRaphael Isemann m_passthrough->BeginSourceFile(LO, PP);
27083aa58d7SRaphael Isemann }
27183aa58d7SRaphael Isemann
EndSourceFile()27283aa58d7SRaphael Isemann void EndSourceFile() override { m_passthrough->EndSourceFile(); }
273579e70c9SSean Callanan
274579e70c9SSean Callanan private:
275579e70c9SSean Callanan DiagnosticManager *m_manager = nullptr;
2761442efeaSRaphael Isemann std::shared_ptr<clang::TextDiagnosticPrinter> m_passthrough;
2771442efeaSRaphael Isemann /// Output stream of m_passthrough.
2781442efeaSRaphael Isemann std::shared_ptr<llvm::raw_string_ostream> m_os;
2791442efeaSRaphael Isemann /// Output string filled by m_os.
2801442efeaSRaphael Isemann std::string m_output;
281579e70c9SSean Callanan };
282579e70c9SSean Callanan
SetupModuleHeaderPaths(CompilerInstance * compiler,std::vector<std::string> include_directories,lldb::TargetSP target_sp)2833ad82787SRaphael Isemann static void SetupModuleHeaderPaths(CompilerInstance *compiler,
2843ad82787SRaphael Isemann std::vector<std::string> include_directories,
2856c0bbfc0SRaphael Isemann lldb::TargetSP target_sp) {
286a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Expressions);
2876c0bbfc0SRaphael Isemann
2886c0bbfc0SRaphael Isemann HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts();
2896c0bbfc0SRaphael Isemann
2903ad82787SRaphael Isemann for (const std::string &dir : include_directories) {
2913ad82787SRaphael Isemann search_opts.AddPath(dir, frontend::System, false, true);
2926c0bbfc0SRaphael Isemann LLDB_LOG(log, "Added user include dir: {0}", dir);
2936c0bbfc0SRaphael Isemann }
2946c0bbfc0SRaphael Isemann
2956c0bbfc0SRaphael Isemann llvm::SmallString<128> module_cache;
29627df2d9fSPavel Labath const auto &props = ModuleList::GetGlobalModuleListProperties();
2976c0bbfc0SRaphael Isemann props.GetClangModulesCachePath().GetPath(module_cache);
298adcd0268SBenjamin Kramer search_opts.ModuleCachePath = std::string(module_cache.str());
2996c0bbfc0SRaphael Isemann LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str());
3006c0bbfc0SRaphael Isemann
3019379d19fSRaphael Isemann search_opts.ResourceDir = GetClangResourceDir().GetPath();
3026c0bbfc0SRaphael Isemann
3036c0bbfc0SRaphael Isemann search_opts.ImplicitModuleMaps = true;
3046c0bbfc0SRaphael Isemann }
3056c0bbfc0SRaphael Isemann
306a8350ce7SRaphael Isemann /// Iff the given identifier is a C++ keyword, remove it from the
307a8350ce7SRaphael Isemann /// identifier table (i.e., make the token a normal identifier).
RemoveCppKeyword(IdentifierTable & idents,llvm::StringRef token)308a8350ce7SRaphael Isemann static void RemoveCppKeyword(IdentifierTable &idents, llvm::StringRef token) {
309a8350ce7SRaphael Isemann // FIXME: 'using' is used by LLDB for local variables, so we can't remove
310a8350ce7SRaphael Isemann // this keyword without breaking this functionality.
311a8350ce7SRaphael Isemann if (token == "using")
312a8350ce7SRaphael Isemann return;
313a8350ce7SRaphael Isemann // GCC's '__null' is used by LLDB to define NULL/Nil/nil.
314a8350ce7SRaphael Isemann if (token == "__null")
315a8350ce7SRaphael Isemann return;
316a8350ce7SRaphael Isemann
317a8350ce7SRaphael Isemann LangOptions cpp_lang_opts;
318a8350ce7SRaphael Isemann cpp_lang_opts.CPlusPlus = true;
319a8350ce7SRaphael Isemann cpp_lang_opts.CPlusPlus11 = true;
320a8350ce7SRaphael Isemann cpp_lang_opts.CPlusPlus20 = true;
321a8350ce7SRaphael Isemann
322a8350ce7SRaphael Isemann clang::IdentifierInfo &ii = idents.get(token);
323a8350ce7SRaphael Isemann // The identifier has to be a C++-exclusive keyword. if not, then there is
324a8350ce7SRaphael Isemann // nothing to do.
325a8350ce7SRaphael Isemann if (!ii.isCPlusPlusKeyword(cpp_lang_opts))
326a8350ce7SRaphael Isemann return;
327a8350ce7SRaphael Isemann // If the token is already an identifier, then there is nothing to do.
328a8350ce7SRaphael Isemann if (ii.getTokenID() == clang::tok::identifier)
329a8350ce7SRaphael Isemann return;
330a8350ce7SRaphael Isemann // Otherwise the token is a C++ keyword, so turn it back into a normal
331a8350ce7SRaphael Isemann // identifier.
332a8350ce7SRaphael Isemann ii.revertTokenIDToIdentifier();
333a8350ce7SRaphael Isemann }
334a8350ce7SRaphael Isemann
335a8350ce7SRaphael Isemann /// Remove all C++ keywords from the given identifier table.
RemoveAllCppKeywords(IdentifierTable & idents)336a8350ce7SRaphael Isemann static void RemoveAllCppKeywords(IdentifierTable &idents) {
337a8350ce7SRaphael Isemann #define KEYWORD(NAME, FLAGS) RemoveCppKeyword(idents, llvm::StringRef(#NAME));
338a8350ce7SRaphael Isemann #include "clang/Basic/TokenKinds.def"
339a8350ce7SRaphael Isemann }
340a8350ce7SRaphael Isemann
341b0dc54e0SRaphael Isemann /// Configures Clang diagnostics for the expression parser.
SetupDefaultClangDiagnostics(CompilerInstance & compiler)342b0dc54e0SRaphael Isemann static void SetupDefaultClangDiagnostics(CompilerInstance &compiler) {
343b0dc54e0SRaphael Isemann // List of Clang warning groups that are not useful when parsing expressions.
344b0dc54e0SRaphael Isemann const std::vector<const char *> groupsToIgnore = {
345b0dc54e0SRaphael Isemann "unused-value",
346b0dc54e0SRaphael Isemann "odr",
34719b4d3ceSRaphael Isemann "unused-getter-return-value",
348b0dc54e0SRaphael Isemann };
349b0dc54e0SRaphael Isemann for (const char *group : groupsToIgnore) {
350b0dc54e0SRaphael Isemann compiler.getDiagnostics().setSeverityForGroup(
351b0dc54e0SRaphael Isemann clang::diag::Flavor::WarningOrError, group,
352b0dc54e0SRaphael Isemann clang::diag::Severity::Ignored, SourceLocation());
353b0dc54e0SRaphael Isemann }
354b0dc54e0SRaphael Isemann }
355b0dc54e0SRaphael Isemann
3564dbb271fSSean Callanan //===----------------------------------------------------------------------===//
3574dbb271fSSean Callanan // Implementation of ClangExpressionParser
3584dbb271fSSean Callanan //===----------------------------------------------------------------------===//
3594dbb271fSSean Callanan
ClangExpressionParser(ExecutionContextScope * exe_scope,Expression & expr,bool generate_debug_info,std::vector<std::string> include_directories,std::string filename)3609379d19fSRaphael Isemann ClangExpressionParser::ClangExpressionParser(
3619379d19fSRaphael Isemann ExecutionContextScope *exe_scope, Expression &expr,
3629379d19fSRaphael Isemann bool generate_debug_info, std::vector<std::string> include_directories,
3639379d19fSRaphael Isemann std::string filename)
364b9c1b51eSKate Stone : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
3656c0bbfc0SRaphael Isemann m_pp_callbacks(nullptr),
3669379d19fSRaphael Isemann m_include_directories(std::move(include_directories)),
3679379d19fSRaphael Isemann m_filename(std::move(filename)) {
368a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Expressions);
3691b6785a1SAidan Dodds
37005097246SAdrian Prantl // We can't compile expressions without a target. So if the exe_scope is
37105097246SAdrian Prantl // null or doesn't have a target, then we just need to get out of here. I'll
3727754b652SRaphael Isemann // lldbassert and not make any of the compiler objects since
373b9c1b51eSKate Stone // I can't return errors directly from the constructor. Further calls will
374b9c1b51eSKate Stone // check if the compiler was made and
3750d6a90dfSJim Ingham // bag out if it wasn't.
3760d6a90dfSJim Ingham
377b9c1b51eSKate Stone if (!exe_scope) {
3787754b652SRaphael Isemann lldbassert(exe_scope &&
3797754b652SRaphael Isemann "Can't make an expression parser with a null scope.");
3800d6a90dfSJim Ingham return;
3810d6a90dfSJim Ingham }
3820d6a90dfSJim Ingham
3830d6a90dfSJim Ingham lldb::TargetSP target_sp;
3840d6a90dfSJim Ingham target_sp = exe_scope->CalculateTarget();
385b9c1b51eSKate Stone if (!target_sp) {
3867754b652SRaphael Isemann lldbassert(target_sp.get() &&
3877754b652SRaphael Isemann "Can't make an expression parser with a null target.");
3880d6a90dfSJim Ingham return;
3890d6a90dfSJim Ingham }
3900d6a90dfSJim Ingham
3914dbb271fSSean Callanan // 1. Create a new compiler instance.
39206412daeSJonas Devlieghere m_compiler = std::make_unique<CompilerInstance>();
39363e2e59bSJonas Devlieghere
39463e2e59bSJonas Devlieghere // When capturing a reproducer, hook up the file collector with clang to
39563e2e59bSJonas Devlieghere // collector modules and headers.
39663e2e59bSJonas Devlieghere if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
39763e2e59bSJonas Devlieghere repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>();
39863e2e59bSJonas Devlieghere m_compiler->setModuleDepCollector(
39963e2e59bSJonas Devlieghere std::make_shared<ModuleDependencyCollectorAdaptor>(
40063e2e59bSJonas Devlieghere fp.GetFileCollector()));
40163e2e59bSJonas Devlieghere DependencyOutputOptions &opts = m_compiler->getDependencyOutputOpts();
40263e2e59bSJonas Devlieghere opts.IncludeSystemHeaders = true;
40363e2e59bSJonas Devlieghere opts.IncludeModuleFiles = true;
40463e2e59bSJonas Devlieghere }
40563e2e59bSJonas Devlieghere
4069764b65cSJonas Devlieghere // Make sure clang uses the same VFS as LLDB.
4071da7eac8SDuncan P. N. Exon Smith m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem());
4089764b65cSJonas Devlieghere
409b9c1b51eSKate Stone lldb::LanguageType frame_lang =
410b9c1b51eSKate Stone expr.Language(); // defaults to lldb::eLanguageTypeUnknown
4111b6785a1SAidan Dodds bool overridden_target_opts = false;
4121b6785a1SAidan Dodds lldb_private::LanguageRuntime *lang_rt = nullptr;
4134dbb271fSSean Callanan
414adc1abe7SSagar Thakur std::string abi;
4153592a6ecSBhushan D. Attarde ArchSpec target_arch;
4163592a6ecSBhushan D. Attarde target_arch = target_sp->GetArchitecture();
4173592a6ecSBhushan D. Attarde
4183592a6ecSBhushan D. Attarde const auto target_machine = target_arch.GetMachine();
4193592a6ecSBhushan D. Attarde
42005097246SAdrian Prantl // If the expression is being evaluated in the context of an existing stack
42105097246SAdrian Prantl // frame, we introspect to see if the language runtime is available.
4220d6a90dfSJim Ingham
4230d6a90dfSJim Ingham lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
4240d6a90dfSJim Ingham lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
4251b6785a1SAidan Dodds
42605097246SAdrian Prantl // Make sure the user hasn't provided a preferred execution language with
42705097246SAdrian Prantl // `expression --language X -- ...`
4280d6a90dfSJim Ingham if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
4290d6a90dfSJim Ingham frame_lang = frame_sp->GetLanguage();
4301b6785a1SAidan Dodds
431b9c1b51eSKate Stone if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
4320d6a90dfSJim Ingham lang_rt = process_sp->GetLanguageRuntime(frame_lang);
43363e5fb76SJonas Devlieghere LLDB_LOGF(log, "Frame has language of type %s",
434b9c1b51eSKate Stone Language::GetNameForLanguageType(frame_lang));
4351b6785a1SAidan Dodds }
4361b6785a1SAidan Dodds
437b9c1b51eSKate Stone // 2. Configure the compiler with a set of default options that are
43805097246SAdrian Prantl // appropriate for most situations.
439b9c1b51eSKate Stone if (target_arch.IsValid()) {
4403592a6ecSBhushan D. Attarde std::string triple = target_arch.GetTriple().str();
4414dbb271fSSean Callanan m_compiler->getTargetOpts().Triple = triple;
44263e5fb76SJonas Devlieghere LLDB_LOGF(log, "Using %s as the target triple",
443b9c1b51eSKate Stone m_compiler->getTargetOpts().Triple.c_str());
444b9c1b51eSKate Stone } else {
4451b6785a1SAidan Dodds // If we get here we don't have a valid target and just have to guess.
446b9c1b51eSKate Stone // Sometimes this will be ok to just use the host target triple (when we
44705097246SAdrian Prantl // evaluate say "2+3", but other expressions like breakpoint conditions and
44805097246SAdrian Prantl // other things that _are_ target specific really shouldn't just be using
44905097246SAdrian Prantl // the host triple. In such a case the language runtime should expose an
45005097246SAdrian Prantl // overridden options set (3), below.
4514dbb271fSSean Callanan m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
45263e5fb76SJonas Devlieghere LLDB_LOGF(log, "Using default target triple of %s",
453b9c1b51eSKate Stone m_compiler->getTargetOpts().Triple.c_str());
4544dbb271fSSean Callanan }
45505097246SAdrian Prantl // Now add some special fixes for known architectures: Any arm32 iOS
45605097246SAdrian Prantl // environment, but not on arm64
4574dbb271fSSean Callanan if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
4584dbb271fSSean Callanan m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
459b9c1b51eSKate Stone m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
4604dbb271fSSean Callanan m_compiler->getTargetOpts().ABI = "apcs-gnu";
4614dbb271fSSean Callanan }
4621b6785a1SAidan Dodds // Supported subsets of x86
4633592a6ecSBhushan D. Attarde if (target_machine == llvm::Triple::x86 ||
464b9c1b51eSKate Stone target_machine == llvm::Triple::x86_64) {
4651b6785a1SAidan Dodds m_compiler->getTargetOpts().Features.push_back("+sse");
4661b6785a1SAidan Dodds m_compiler->getTargetOpts().Features.push_back("+sse2");
4671b6785a1SAidan Dodds }
4684dbb271fSSean Callanan
46905097246SAdrian Prantl // Set the target CPU to generate code for. This will be empty for any CPU
47005097246SAdrian Prantl // that doesn't really need to make a special
471b9c1b51eSKate Stone // CPU string.
4723592a6ecSBhushan D. Attarde m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
4733592a6ecSBhushan D. Attarde
474adc1abe7SSagar Thakur // Set the target ABI
475adc1abe7SSagar Thakur abi = GetClangTargetABI(target_arch);
476adc1abe7SSagar Thakur if (!abi.empty())
477adc1abe7SSagar Thakur m_compiler->getTargetOpts().ABI = abi;
478adc1abe7SSagar Thakur
479b9c1b51eSKate Stone // 3. Now allow the runtime to provide custom configuration options for the
48005097246SAdrian Prantl // target. In this case, a specialized language runtime is available and we
48105097246SAdrian Prantl // can query it for extra options. For 99% of use cases, this will not be
48205097246SAdrian Prantl // needed and should be provided when basic platform detection is not enough.
4832637769bSAlex Langford // FIXME: Generalize this. Only RenderScriptRuntime currently supports this
4842637769bSAlex Langford // currently. Hardcoding this isn't ideal but it's better than LanguageRuntime
4852637769bSAlex Langford // having knowledge of clang::TargetOpts.
4862637769bSAlex Langford if (auto *renderscript_rt =
4872637769bSAlex Langford llvm::dyn_cast_or_null<RenderScriptRuntime>(lang_rt))
488b9c1b51eSKate Stone overridden_target_opts =
4892637769bSAlex Langford renderscript_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
4901b6785a1SAidan Dodds
4911b6785a1SAidan Dodds if (overridden_target_opts)
4926302bf6aSPavel Labath if (log && log->GetVerbose()) {
4936302bf6aSPavel Labath LLDB_LOGV(
4946302bf6aSPavel Labath log, "Using overridden target options for the expression evaluation");
4951b6785a1SAidan Dodds
4961b6785a1SAidan Dodds auto opts = m_compiler->getTargetOpts();
4976302bf6aSPavel Labath LLDB_LOGV(log, "Triple: '{0}'", opts.Triple);
4986302bf6aSPavel Labath LLDB_LOGV(log, "CPU: '{0}'", opts.CPU);
4996302bf6aSPavel Labath LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath);
5006302bf6aSPavel Labath LLDB_LOGV(log, "ABI: '{0}'", opts.ABI);
5016302bf6aSPavel Labath LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion);
5021b6785a1SAidan Dodds StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
5031b6785a1SAidan Dodds StringList::LogDump(log, opts.Features, "Features");
5041b6785a1SAidan Dodds }
5051b6785a1SAidan Dodds
5061b6785a1SAidan Dodds // 4. Create and install the target on the compiler.
5074dbb271fSSean Callanan m_compiler->createDiagnostics();
50802114e15SRaphael Isemann // Limit the number of error diagnostics we emit.
50902114e15SRaphael Isemann // A value of 0 means no limit for both LLDB and Clang.
51002114e15SRaphael Isemann m_compiler->getDiagnostics().setErrorLimit(target_sp->GetExprErrorLimit());
51102114e15SRaphael Isemann
512b9c1b51eSKate Stone auto target_info = TargetInfo::CreateTargetInfo(
513b9c1b51eSKate Stone m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
514b9c1b51eSKate Stone if (log) {
51563e5fb76SJonas Devlieghere LLDB_LOGF(log, "Using SIMD alignment: %d",
51663e5fb76SJonas Devlieghere target_info->getSimdDefaultAlign());
51763e5fb76SJonas Devlieghere LLDB_LOGF(log, "Target datalayout string: '%s'",
51844e2247dSJordan Rupprecht target_info->getDataLayoutString());
51963e5fb76SJonas Devlieghere LLDB_LOGF(log, "Target ABI: '%s'", target_info->getABI().str().c_str());
52063e5fb76SJonas Devlieghere LLDB_LOGF(log, "Target vector alignment: %d",
521b9c1b51eSKate Stone target_info->getMaxVectorAlign());
5221b6785a1SAidan Dodds }
5231b6785a1SAidan Dodds m_compiler->setTarget(target_info);
5244dbb271fSSean Callanan
5254dbb271fSSean Callanan assert(m_compiler->hasTarget());
5264dbb271fSSean Callanan
5271b6785a1SAidan Dodds // 5. Set language options.
5287648dd37SEwan Crawford lldb::LanguageType language = expr.Language();
5290d649c65SRaphael Isemann LangOptions &lang_opts = m_compiler->getLangOpts();
5307648dd37SEwan Crawford
531b9c1b51eSKate Stone switch (language) {
5324dbb271fSSean Callanan case lldb::eLanguageTypeC:
5334dbb271fSSean Callanan case lldb::eLanguageTypeC89:
5344dbb271fSSean Callanan case lldb::eLanguageTypeC99:
5354dbb271fSSean Callanan case lldb::eLanguageTypeC11:
5364dbb271fSSean Callanan // FIXME: the following language option is a temporary workaround,
5374dbb271fSSean Callanan // to "ask for C, get C++."
53805097246SAdrian Prantl // For now, the expression parser must use C++ anytime the language is a C
53905097246SAdrian Prantl // family language, because the expression parser uses features of C++ to
54005097246SAdrian Prantl // capture values.
5410d649c65SRaphael Isemann lang_opts.CPlusPlus = true;
5424dbb271fSSean Callanan break;
5434dbb271fSSean Callanan case lldb::eLanguageTypeObjC:
5440d649c65SRaphael Isemann lang_opts.ObjC = true;
5454dbb271fSSean Callanan // FIXME: the following language option is a temporary workaround,
5464dbb271fSSean Callanan // to "ask for ObjC, get ObjC++" (see comment above).
5470d649c65SRaphael Isemann lang_opts.CPlusPlus = true;
54889419f88SDavide Italiano
54989419f88SDavide Italiano // Clang now sets as default C++14 as the default standard (with
55089419f88SDavide Italiano // GNU extensions), so we do the same here to avoid mismatches that
55105097246SAdrian Prantl // cause compiler error when evaluating expressions (e.g. nullptr not found
55205097246SAdrian Prantl // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
55305097246SAdrian Prantl // two lines below) so we decide to be consistent with that, but this could
55405097246SAdrian Prantl // be re-evaluated in the future.
5550d649c65SRaphael Isemann lang_opts.CPlusPlus11 = true;
5564dbb271fSSean Callanan break;
5574dbb271fSSean Callanan case lldb::eLanguageTypeC_plus_plus:
5584dbb271fSSean Callanan case lldb::eLanguageTypeC_plus_plus_11:
5598cb75745SRaphael Isemann case lldb::eLanguageTypeC_plus_plus_14:
5600d649c65SRaphael Isemann lang_opts.CPlusPlus11 = true;
5614dbb271fSSean Callanan m_compiler->getHeaderSearchOpts().UseLibcxx = true;
56262e0681aSJason Molenda LLVM_FALLTHROUGH;
5634dbb271fSSean Callanan case lldb::eLanguageTypeC_plus_plus_03:
5640d649c65SRaphael Isemann lang_opts.CPlusPlus = true;
565f3351889SAleksandr Urakov if (process_sp)
5660d649c65SRaphael Isemann lang_opts.ObjC =
567f3351889SAleksandr Urakov process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr;
5684dbb271fSSean Callanan break;
5694dbb271fSSean Callanan case lldb::eLanguageTypeObjC_plus_plus:
5704dbb271fSSean Callanan case lldb::eLanguageTypeUnknown:
5714dbb271fSSean Callanan default:
5720d649c65SRaphael Isemann lang_opts.ObjC = true;
5730d649c65SRaphael Isemann lang_opts.CPlusPlus = true;
5740d649c65SRaphael Isemann lang_opts.CPlusPlus11 = true;
5754dbb271fSSean Callanan m_compiler->getHeaderSearchOpts().UseLibcxx = true;
5764dbb271fSSean Callanan break;
5774dbb271fSSean Callanan }
5784dbb271fSSean Callanan
5790d649c65SRaphael Isemann lang_opts.Bool = true;
5800d649c65SRaphael Isemann lang_opts.WChar = true;
5810d649c65SRaphael Isemann lang_opts.Blocks = true;
5820d649c65SRaphael Isemann lang_opts.DebuggerSupport =
583b9c1b51eSKate Stone true; // Features specifically for debugger clients
5844dbb271fSSean Callanan if (expr.DesiredResultType() == Expression::eResultTypeId)
5850d649c65SRaphael Isemann lang_opts.DebuggerCastResultToId = true;
5864dbb271fSSean Callanan
5870d649c65SRaphael Isemann lang_opts.CharIsSigned = ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
588b9c1b51eSKate Stone .CharIsSignedByDefault();
5894dbb271fSSean Callanan
59005097246SAdrian Prantl // Spell checking is a nice feature, but it ends up completing a lot of types
59105097246SAdrian Prantl // that we didn't strictly speaking need to complete. As a result, we spend a
59205097246SAdrian Prantl // long time parsing and importing debug information.
5930d649c65SRaphael Isemann lang_opts.SpellChecking = false;
5944dbb271fSSean Callanan
5957e34d78dSAdrian Prantl auto *clang_expr = dyn_cast<ClangUserExpression>(&m_expr);
5967e34d78dSAdrian Prantl if (clang_expr && clang_expr->DidImportCxxModules()) {
5976c0bbfc0SRaphael Isemann LLDB_LOG(log, "Adding lang options for importing C++ modules");
5986c0bbfc0SRaphael Isemann
5996c0bbfc0SRaphael Isemann lang_opts.Modules = true;
6006c0bbfc0SRaphael Isemann // We want to implicitly build modules.
6016c0bbfc0SRaphael Isemann lang_opts.ImplicitModules = true;
6026c0bbfc0SRaphael Isemann // To automatically import all submodules when we import 'std'.
6036c0bbfc0SRaphael Isemann lang_opts.ModulesLocalVisibility = false;
6046c0bbfc0SRaphael Isemann
6056c0bbfc0SRaphael Isemann // We use the @import statements, so we need this:
6066c0bbfc0SRaphael Isemann // FIXME: We could use the modules-ts, but that currently doesn't work.
6076c0bbfc0SRaphael Isemann lang_opts.ObjC = true;
6086c0bbfc0SRaphael Isemann
6096c0bbfc0SRaphael Isemann // Options we need to parse libc++ code successfully.
6106c0bbfc0SRaphael Isemann // FIXME: We should ask the driver for the appropriate default flags.
6116c0bbfc0SRaphael Isemann lang_opts.GNUMode = true;
6126c0bbfc0SRaphael Isemann lang_opts.GNUKeywords = true;
6136c0bbfc0SRaphael Isemann lang_opts.DoubleSquareBracketAttributes = true;
6146c0bbfc0SRaphael Isemann lang_opts.CPlusPlus11 = true;
6156c0bbfc0SRaphael Isemann
616f30ae717SAdrian Prantl // The Darwin libc expects this macro to be set.
617f30ae717SAdrian Prantl lang_opts.GNUCVersion = 40201;
618f30ae717SAdrian Prantl
6196c0bbfc0SRaphael Isemann SetupModuleHeaderPaths(m_compiler.get(), m_include_directories,
6206c0bbfc0SRaphael Isemann target_sp);
6216c0bbfc0SRaphael Isemann }
6226c0bbfc0SRaphael Isemann
6230d649c65SRaphael Isemann if (process_sp && lang_opts.ObjC) {
624e823bbe8SAlex Langford if (auto *runtime = ObjCLanguageRuntime::Get(*process_sp)) {
625e823bbe8SAlex Langford if (runtime->GetRuntimeVersion() ==
626b9c1b51eSKate Stone ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
6270d649c65SRaphael Isemann lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
6284dbb271fSSean Callanan else
6290d649c65SRaphael Isemann lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
630b9c1b51eSKate Stone VersionTuple(10, 7));
6314dbb271fSSean Callanan
632e823bbe8SAlex Langford if (runtime->HasNewLiteralsAndIndexing())
6330d649c65SRaphael Isemann lang_opts.DebuggerObjCLiteral = true;
6344dbb271fSSean Callanan }
6354dbb271fSSean Callanan }
6364dbb271fSSean Callanan
6370d649c65SRaphael Isemann lang_opts.ThreadsafeStatics = false;
6380d649c65SRaphael Isemann lang_opts.AccessControl = false; // Debuggers get universal access
6390d649c65SRaphael Isemann lang_opts.DollarIdents = true; // $ indicates a persistent variable name
640d424c2a8SRaphael Isemann // We enable all builtin functions beside the builtins from libc/libm (e.g.
641d424c2a8SRaphael Isemann // 'fopen'). Those libc functions are already correctly handled by LLDB, and
642d424c2a8SRaphael Isemann // additionally enabling them as expandable builtins is breaking Clang.
6430d649c65SRaphael Isemann lang_opts.NoBuiltin = true;
6444dbb271fSSean Callanan
6454dbb271fSSean Callanan // Set CodeGen options
6464dbb271fSSean Callanan m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
6474dbb271fSSean Callanan m_compiler->getCodeGenOpts().InstrumentFunctions = false;
648b4e06328SYuanfang Chen m_compiler->getCodeGenOpts().setFramePointer(
649b4e06328SYuanfang Chen CodeGenOptions::FramePointerKind::All);
6504dbb271fSSean Callanan if (generate_debug_info)
651e03bd650SPavel Labath m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
6524dbb271fSSean Callanan else
653e03bd650SPavel Labath m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
6544dbb271fSSean Callanan
6554dbb271fSSean Callanan // Disable some warnings.
656b0dc54e0SRaphael Isemann SetupDefaultClangDiagnostics(*m_compiler);
6574dbb271fSSean Callanan
6584dbb271fSSean Callanan // Inform the target of the language options
6594dbb271fSSean Callanan //
6604dbb271fSSean Callanan // FIXME: We shouldn't need to do this, the target should be immutable once
6614dbb271fSSean Callanan // created. This complexity should be lifted elsewhere.
662aaba3718SMelanie Blower m_compiler->getTarget().adjust(m_compiler->getDiagnostics(),
663aaba3718SMelanie Blower m_compiler->getLangOpts());
6644dbb271fSSean Callanan
6651b6785a1SAidan Dodds // 6. Set up the diagnostic buffer for reporting errors
6664dbb271fSSean Callanan
6671442efeaSRaphael Isemann auto diag_mgr = new ClangDiagnosticManagerAdapter(
6681442efeaSRaphael Isemann m_compiler->getDiagnostics().getDiagnosticOptions());
6691442efeaSRaphael Isemann m_compiler->getDiagnostics().setClient(diag_mgr);
6704dbb271fSSean Callanan
6711b6785a1SAidan Dodds // 7. Set up the source management objects inside the compiler
6724dbb271fSSean Callanan m_compiler->createFileManager();
673ff04b3d4SJonas Devlieghere if (!m_compiler->hasSourceManager())
674ff04b3d4SJonas Devlieghere m_compiler->createSourceManager(m_compiler->getFileManager());
6754dbb271fSSean Callanan m_compiler->createPreprocessor(TU_Complete);
6764dbb271fSSean Callanan
677a8350ce7SRaphael Isemann switch (language) {
678a8350ce7SRaphael Isemann case lldb::eLanguageTypeC:
679a8350ce7SRaphael Isemann case lldb::eLanguageTypeC89:
680a8350ce7SRaphael Isemann case lldb::eLanguageTypeC99:
681a8350ce7SRaphael Isemann case lldb::eLanguageTypeC11:
682a8350ce7SRaphael Isemann case lldb::eLanguageTypeObjC:
683a8350ce7SRaphael Isemann // This is not a C++ expression but we enabled C++ as explained above.
684a8350ce7SRaphael Isemann // Remove all C++ keywords from the PP so that the user can still use
685a8350ce7SRaphael Isemann // variables that have C++ keywords as names (e.g. 'int template;').
686a8350ce7SRaphael Isemann RemoveAllCppKeywords(m_compiler->getPreprocessor().getIdentifierTable());
687a8350ce7SRaphael Isemann break;
688a8350ce7SRaphael Isemann default:
689a8350ce7SRaphael Isemann break;
690a8350ce7SRaphael Isemann }
691a8350ce7SRaphael Isemann
692e9331a56SAdrian Prantl if (auto *clang_persistent_vars = llvm::cast<ClangPersistentVariables>(
693b9c1b51eSKate Stone target_sp->GetPersistentExpressionStateForLanguage(
694e9331a56SAdrian Prantl lldb::eLanguageTypeC))) {
6954c0b0de9SAlex Langford if (std::shared_ptr<ClangModulesDeclVendor> decl_vendor =
6964c0b0de9SAlex Langford clang_persistent_vars->GetClangModulesDeclVendor()) {
697e9331a56SAdrian Prantl std::unique_ptr<PPCallbacks> pp_callbacks(
698e9331a56SAdrian Prantl new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars,
699e9331a56SAdrian Prantl m_compiler->getSourceManager()));
700b9c1b51eSKate Stone m_pp_callbacks =
701b9c1b51eSKate Stone static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
7024dbb271fSSean Callanan m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
7034dbb271fSSean Callanan }
704e9331a56SAdrian Prantl }
7054dbb271fSSean Callanan
70605097246SAdrian Prantl // 8. Most of this we get from the CompilerInstance, but we also want to give
70705097246SAdrian Prantl // the context an ExternalASTSource.
708778b308eSRaphael Isemann
709778b308eSRaphael Isemann auto &PP = m_compiler->getPreprocessor();
710778b308eSRaphael Isemann auto &builtin_context = PP.getBuiltinInfo();
711778b308eSRaphael Isemann builtin_context.initializeBuiltins(PP.getIdentifierTable(),
712778b308eSRaphael Isemann m_compiler->getLangOpts());
7134dbb271fSSean Callanan
714596709d8SRaphael Isemann m_compiler->createASTContext();
715596709d8SRaphael Isemann clang::ASTContext &ast_context = m_compiler->getASTContext();
7164dbb271fSSean Callanan
71706412daeSJonas Devlieghere m_ast_context = std::make_unique<TypeSystemClang>(
71806412daeSJonas Devlieghere "Expression ASTContext for '" + m_filename + "'", ast_context);
7194dbb271fSSean Callanan
7204dbb271fSSean Callanan std::string module_name("$__lldb_module");
7214dbb271fSSean Callanan
72206412daeSJonas Devlieghere m_llvm_context = std::make_unique<LLVMContext>();
723b9c1b51eSKate Stone m_code_generator.reset(CreateLLVMCodeGen(
724b9c1b51eSKate Stone m_compiler->getDiagnostics(), module_name,
725*c5ddacb3SArgyrios Kyrtzidis &m_compiler->getVirtualFileSystem(), m_compiler->getHeaderSearchOpts(),
726*c5ddacb3SArgyrios Kyrtzidis m_compiler->getPreprocessorOpts(), m_compiler->getCodeGenOpts(),
727*c5ddacb3SArgyrios Kyrtzidis *m_llvm_context));
7284dbb271fSSean Callanan }
7294dbb271fSSean Callanan
730fd2433e1SJonas Devlieghere ClangExpressionParser::~ClangExpressionParser() = default;
7314dbb271fSSean Callanan
73274829734SRaphael Isemann namespace {
73374829734SRaphael Isemann
734f05b42e9SAdrian Prantl /// \class CodeComplete
73574829734SRaphael Isemann ///
73674829734SRaphael Isemann /// A code completion consumer for the clang Sema that is responsible for
73774829734SRaphael Isemann /// creating the completion suggestions when a user requests completion
73874829734SRaphael Isemann /// of an incomplete `expr` invocation.
73974829734SRaphael Isemann class CodeComplete : public CodeCompleteConsumer {
74039ec6e70SRaphael Isemann CodeCompletionTUInfo m_info;
74174829734SRaphael Isemann
74239ec6e70SRaphael Isemann std::string m_expr;
74339ec6e70SRaphael Isemann unsigned m_position = 0;
7449dd34c83SRaphael Isemann /// The printing policy we use when printing declarations for our completion
7459dd34c83SRaphael Isemann /// descriptions.
7469dd34c83SRaphael Isemann clang::PrintingPolicy m_desc_policy;
74774829734SRaphael Isemann
74874a51753SRaphael Isemann struct CompletionWithPriority {
74974a51753SRaphael Isemann CompletionResult::Completion completion;
75074a51753SRaphael Isemann /// See CodeCompletionResult::Priority;
75174a51753SRaphael Isemann unsigned Priority;
75274a51753SRaphael Isemann
75374a51753SRaphael Isemann /// Establishes a deterministic order in a list of CompletionWithPriority.
75474a51753SRaphael Isemann /// The order returned here is the order in which the completions are
75574a51753SRaphael Isemann /// displayed to the user.
operator <__anon5837f7100111::CodeComplete::CompletionWithPriority75674a51753SRaphael Isemann bool operator<(const CompletionWithPriority &o) const {
75774a51753SRaphael Isemann // High priority results should come first.
75874a51753SRaphael Isemann if (Priority != o.Priority)
75974a51753SRaphael Isemann return Priority > o.Priority;
76074a51753SRaphael Isemann
76174a51753SRaphael Isemann // Identical priority, so just make sure it's a deterministic order.
76274a51753SRaphael Isemann return completion.GetUniqueKey() < o.completion.GetUniqueKey();
76374a51753SRaphael Isemann }
76474a51753SRaphael Isemann };
76574a51753SRaphael Isemann
76674a51753SRaphael Isemann /// The stored completions.
76774a51753SRaphael Isemann /// Warning: These are in a non-deterministic order until they are sorted
76874a51753SRaphael Isemann /// and returned back to the caller.
76974a51753SRaphael Isemann std::vector<CompletionWithPriority> m_completions;
77074a51753SRaphael Isemann
77174829734SRaphael Isemann /// Returns true if the given character can be used in an identifier.
77274829734SRaphael Isemann /// This also returns true for numbers because for completion we usually
77374829734SRaphael Isemann /// just iterate backwards over iterators.
77474829734SRaphael Isemann ///
77574829734SRaphael Isemann /// Note: lldb uses '$' in its internal identifiers, so we also allow this.
IsIdChar(char c)77674829734SRaphael Isemann static bool IsIdChar(char c) {
77774829734SRaphael Isemann return c == '_' || std::isalnum(c) || c == '$';
77874829734SRaphael Isemann }
77974829734SRaphael Isemann
78074829734SRaphael Isemann /// Returns true if the given character is used to separate arguments
78174829734SRaphael Isemann /// in the command line of lldb.
IsTokenSeparator(char c)78274829734SRaphael Isemann static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
78374829734SRaphael Isemann
78474829734SRaphael Isemann /// Drops all tokens in front of the expression that are unrelated for
78574829734SRaphael Isemann /// the completion of the cmd line. 'unrelated' means here that the token
78674829734SRaphael Isemann /// is not interested for the lldb completion API result.
dropUnrelatedFrontTokens(StringRef cmd) const78774a51753SRaphael Isemann StringRef dropUnrelatedFrontTokens(StringRef cmd) const {
78874829734SRaphael Isemann if (cmd.empty())
78974829734SRaphael Isemann return cmd;
79074829734SRaphael Isemann
79174829734SRaphael Isemann // If we are at the start of a word, then all tokens are unrelated to
79274829734SRaphael Isemann // the current completion logic.
79374829734SRaphael Isemann if (IsTokenSeparator(cmd.back()))
79474829734SRaphael Isemann return StringRef();
79574829734SRaphael Isemann
79674829734SRaphael Isemann // Remove all previous tokens from the string as they are unrelated
79774829734SRaphael Isemann // to completing the current token.
79874829734SRaphael Isemann StringRef to_remove = cmd;
79974829734SRaphael Isemann while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {
80074829734SRaphael Isemann to_remove = to_remove.drop_back();
80174829734SRaphael Isemann }
80274829734SRaphael Isemann cmd = cmd.drop_front(to_remove.size());
80374829734SRaphael Isemann
80474829734SRaphael Isemann return cmd;
80574829734SRaphael Isemann }
80674829734SRaphael Isemann
80774829734SRaphael Isemann /// Removes the last identifier token from the given cmd line.
removeLastToken(StringRef cmd) const80874a51753SRaphael Isemann StringRef removeLastToken(StringRef cmd) const {
80974829734SRaphael Isemann while (!cmd.empty() && IsIdChar(cmd.back())) {
81074829734SRaphael Isemann cmd = cmd.drop_back();
81174829734SRaphael Isemann }
81274829734SRaphael Isemann return cmd;
81374829734SRaphael Isemann }
81474829734SRaphael Isemann
815e9264b74SKazuaki Ishizaki /// Attempts to merge the given completion from the given position into the
81674829734SRaphael Isemann /// existing command. Returns the completion string that can be returned to
81774829734SRaphael Isemann /// the lldb completion API.
mergeCompletion(StringRef existing,unsigned pos,StringRef completion) const81874829734SRaphael Isemann std::string mergeCompletion(StringRef existing, unsigned pos,
81974a51753SRaphael Isemann StringRef completion) const {
82074829734SRaphael Isemann StringRef existing_command = existing.substr(0, pos);
82174829734SRaphael Isemann // We rewrite the last token with the completion, so let's drop that
82274829734SRaphael Isemann // token from the command.
82374829734SRaphael Isemann existing_command = removeLastToken(existing_command);
82474829734SRaphael Isemann // We also should remove all previous tokens from the command as they
82574829734SRaphael Isemann // would otherwise be added to the completion that already has the
82674829734SRaphael Isemann // completion.
82774829734SRaphael Isemann existing_command = dropUnrelatedFrontTokens(existing_command);
82874829734SRaphael Isemann return existing_command.str() + completion.str();
82974829734SRaphael Isemann }
83074829734SRaphael Isemann
83174829734SRaphael Isemann public:
83274829734SRaphael Isemann /// Constructs a CodeComplete consumer that can be attached to a Sema.
833ad882774SJonas Devlieghere ///
834f05b42e9SAdrian Prantl /// \param[out] expr
83574829734SRaphael Isemann /// The whole expression string that we are currently parsing. This
83674829734SRaphael Isemann /// string needs to be equal to the input the user typed, and NOT the
83774829734SRaphael Isemann /// final code that Clang is parsing.
838f05b42e9SAdrian Prantl /// \param[out] position
83974829734SRaphael Isemann /// The character position of the user cursor in the `expr` parameter.
84074829734SRaphael Isemann ///
CodeComplete(clang::LangOptions ops,std::string expr,unsigned position)84174a51753SRaphael Isemann CodeComplete(clang::LangOptions ops, std::string expr, unsigned position)
8423a75330fSSam McCall : CodeCompleteConsumer(CodeCompleteOptions()),
84339ec6e70SRaphael Isemann m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),
84474a51753SRaphael Isemann m_position(position), m_desc_policy(ops) {
8459dd34c83SRaphael Isemann
8469dd34c83SRaphael Isemann // Ensure that the printing policy is producing a description that is as
8479dd34c83SRaphael Isemann // short as possible.
8489dd34c83SRaphael Isemann m_desc_policy.SuppressScope = true;
8499dd34c83SRaphael Isemann m_desc_policy.SuppressTagKeyword = true;
8509dd34c83SRaphael Isemann m_desc_policy.FullyQualifiedName = false;
8519dd34c83SRaphael Isemann m_desc_policy.TerseOutput = true;
8529dd34c83SRaphael Isemann m_desc_policy.IncludeNewlines = false;
8539dd34c83SRaphael Isemann m_desc_policy.UseVoidForZeroParams = false;
8549dd34c83SRaphael Isemann m_desc_policy.Bool = true;
8559dd34c83SRaphael Isemann }
85674829734SRaphael Isemann
85774829734SRaphael Isemann /// \name Code-completion filtering
85874829734SRaphael Isemann /// Check if the result should be filtered out.
isResultFilteredOut(StringRef Filter,CodeCompletionResult Result)85974829734SRaphael Isemann bool isResultFilteredOut(StringRef Filter,
86074829734SRaphael Isemann CodeCompletionResult Result) override {
86174829734SRaphael Isemann // This code is mostly copied from CodeCompleteConsumer.
86274829734SRaphael Isemann switch (Result.Kind) {
86374829734SRaphael Isemann case CodeCompletionResult::RK_Declaration:
86474829734SRaphael Isemann return !(
86574829734SRaphael Isemann Result.Declaration->getIdentifier() &&
86674829734SRaphael Isemann Result.Declaration->getIdentifier()->getName().startswith(Filter));
86774829734SRaphael Isemann case CodeCompletionResult::RK_Keyword:
86874829734SRaphael Isemann return !StringRef(Result.Keyword).startswith(Filter);
86974829734SRaphael Isemann case CodeCompletionResult::RK_Macro:
87074829734SRaphael Isemann return !Result.Macro->getName().startswith(Filter);
87174829734SRaphael Isemann case CodeCompletionResult::RK_Pattern:
87274829734SRaphael Isemann return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
87374829734SRaphael Isemann }
87474829734SRaphael Isemann // If we trigger this assert or the above switch yields a warning, then
87574829734SRaphael Isemann // CodeCompletionResult has been enhanced with more kinds of completion
87674829734SRaphael Isemann // results. Expand the switch above in this case.
87774829734SRaphael Isemann assert(false && "Unknown completion result type?");
87874829734SRaphael Isemann // If we reach this, then we should just ignore whatever kind of unknown
87974829734SRaphael Isemann // result we got back. We probably can't turn it into any kind of useful
88074829734SRaphael Isemann // completion suggestion with the existing code.
88174829734SRaphael Isemann return true;
88274829734SRaphael Isemann }
88374829734SRaphael Isemann
88474a51753SRaphael Isemann private:
88574a51753SRaphael Isemann /// Generate the completion strings for the given CodeCompletionResult.
88674a51753SRaphael Isemann /// Note that this function has to process results that could come in
88774a51753SRaphael Isemann /// non-deterministic order, so this function should have no side effects.
88874a51753SRaphael Isemann /// To make this easier to enforce, this function and all its parameters
88974a51753SRaphael Isemann /// should always be const-qualified.
89074a51753SRaphael Isemann /// \return Returns llvm::None if no completion should be provided for the
89174a51753SRaphael Isemann /// given CodeCompletionResult.
89274a51753SRaphael Isemann llvm::Optional<CompletionWithPriority>
getCompletionForResult(const CodeCompletionResult & R) const89374a51753SRaphael Isemann getCompletionForResult(const CodeCompletionResult &R) const {
89474829734SRaphael Isemann std::string ToInsert;
8959dd34c83SRaphael Isemann std::string Description;
89674829734SRaphael Isemann // Handle the different completion kinds that come from the Sema.
89774829734SRaphael Isemann switch (R.Kind) {
89874829734SRaphael Isemann case CodeCompletionResult::RK_Declaration: {
89974829734SRaphael Isemann const NamedDecl *D = R.Declaration;
90074829734SRaphael Isemann ToInsert = R.Declaration->getNameAsString();
90174829734SRaphael Isemann // If we have a function decl that has no arguments we want to
90274829734SRaphael Isemann // complete the empty parantheses for the user. If the function has
90374829734SRaphael Isemann // arguments, we at least complete the opening bracket.
90474829734SRaphael Isemann if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) {
90574829734SRaphael Isemann if (F->getNumParams() == 0)
90674829734SRaphael Isemann ToInsert += "()";
90774829734SRaphael Isemann else
90874829734SRaphael Isemann ToInsert += "(";
9099dd34c83SRaphael Isemann raw_string_ostream OS(Description);
9109dd34c83SRaphael Isemann F->print(OS, m_desc_policy, false);
9119dd34c83SRaphael Isemann OS.flush();
9129dd34c83SRaphael Isemann } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
9139dd34c83SRaphael Isemann Description = V->getType().getAsString(m_desc_policy);
9149dd34c83SRaphael Isemann } else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) {
9159dd34c83SRaphael Isemann Description = F->getType().getAsString(m_desc_policy);
9169dd34c83SRaphael Isemann } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) {
91720892fb4SRaphael Isemann // If we try to complete a namespace, then we can directly append
91874829734SRaphael Isemann // the '::'.
91974829734SRaphael Isemann if (!N->isAnonymousNamespace())
92074829734SRaphael Isemann ToInsert += "::";
92174829734SRaphael Isemann }
92274829734SRaphael Isemann break;
92374829734SRaphael Isemann }
92474829734SRaphael Isemann case CodeCompletionResult::RK_Keyword:
92574829734SRaphael Isemann ToInsert = R.Keyword;
92674829734SRaphael Isemann break;
92774829734SRaphael Isemann case CodeCompletionResult::RK_Macro:
92874829734SRaphael Isemann ToInsert = R.Macro->getName().str();
92974829734SRaphael Isemann break;
93074829734SRaphael Isemann case CodeCompletionResult::RK_Pattern:
93174829734SRaphael Isemann ToInsert = R.Pattern->getTypedText();
93274829734SRaphael Isemann break;
93374829734SRaphael Isemann }
93474829734SRaphael Isemann // We also filter some internal lldb identifiers here. The user
93574829734SRaphael Isemann // shouldn't see these.
93674a51753SRaphael Isemann if (llvm::StringRef(ToInsert).startswith("$__lldb_"))
93774a51753SRaphael Isemann return llvm::None;
93874a51753SRaphael Isemann if (ToInsert.empty())
93974a51753SRaphael Isemann return llvm::None;
94074829734SRaphael Isemann // Merge the suggested Token into the existing command line to comply
94174829734SRaphael Isemann // with the kind of result the lldb API expects.
94274829734SRaphael Isemann std::string CompletionSuggestion =
94339ec6e70SRaphael Isemann mergeCompletion(m_expr, m_position, ToInsert);
94474a51753SRaphael Isemann
94574a51753SRaphael Isemann CompletionResult::Completion completion(CompletionSuggestion, Description,
94674a51753SRaphael Isemann CompletionMode::Normal);
94774a51753SRaphael Isemann return {{completion, R.Priority}};
94874829734SRaphael Isemann }
94974a51753SRaphael Isemann
95074a51753SRaphael Isemann public:
95174a51753SRaphael Isemann /// Adds the completions to the given CompletionRequest.
GetCompletions(CompletionRequest & request)95274a51753SRaphael Isemann void GetCompletions(CompletionRequest &request) {
95374a51753SRaphael Isemann // Bring m_completions into a deterministic order and pass it on to the
95474a51753SRaphael Isemann // CompletionRequest.
95574a51753SRaphael Isemann llvm::sort(m_completions);
95674a51753SRaphael Isemann
95774a51753SRaphael Isemann for (const CompletionWithPriority &C : m_completions)
95874a51753SRaphael Isemann request.AddCompletion(C.completion.GetCompletion(),
95974a51753SRaphael Isemann C.completion.GetDescription(),
96074a51753SRaphael Isemann C.completion.GetMode());
96174a51753SRaphael Isemann }
96274a51753SRaphael Isemann
96374a51753SRaphael Isemann /// \name Code-completion callbacks
96474a51753SRaphael Isemann /// Process the finalized code-completion results.
ProcessCodeCompleteResults(Sema & SemaRef,CodeCompletionContext Context,CodeCompletionResult * Results,unsigned NumResults)96574a51753SRaphael Isemann void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,
96674a51753SRaphael Isemann CodeCompletionResult *Results,
96774a51753SRaphael Isemann unsigned NumResults) override {
96874a51753SRaphael Isemann
96974a51753SRaphael Isemann // The Sema put the incomplete token we try to complete in here during
97074a51753SRaphael Isemann // lexing, so we need to retrieve it here to know what we are completing.
97174a51753SRaphael Isemann StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
97274a51753SRaphael Isemann
97374a51753SRaphael Isemann // Iterate over all the results. Filter out results we don't want and
97474a51753SRaphael Isemann // process the rest.
97574a51753SRaphael Isemann for (unsigned I = 0; I != NumResults; ++I) {
97674a51753SRaphael Isemann // Filter the results with the information from the Sema.
97774a51753SRaphael Isemann if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
97874a51753SRaphael Isemann continue;
97974a51753SRaphael Isemann
98074a51753SRaphael Isemann CodeCompletionResult &R = Results[I];
98174a51753SRaphael Isemann llvm::Optional<CompletionWithPriority> CompletionAndPriority =
98274a51753SRaphael Isemann getCompletionForResult(R);
98374a51753SRaphael Isemann if (!CompletionAndPriority)
98474a51753SRaphael Isemann continue;
98574a51753SRaphael Isemann m_completions.push_back(*CompletionAndPriority);
98674829734SRaphael Isemann }
98774829734SRaphael Isemann }
98874829734SRaphael Isemann
98974829734SRaphael Isemann /// \param S the semantic-analyzer object for which code-completion is being
99074829734SRaphael Isemann /// done.
99174829734SRaphael Isemann ///
99274829734SRaphael Isemann /// \param CurrentArg the index of the current argument.
99374829734SRaphael Isemann ///
99474829734SRaphael Isemann /// \param Candidates an array of overload candidates.
99574829734SRaphael Isemann ///
99674829734SRaphael Isemann /// \param NumCandidates the number of overload candidates
ProcessOverloadCandidates(Sema & S,unsigned CurrentArg,OverloadCandidate * Candidates,unsigned NumCandidates,SourceLocation OpenParLoc,bool Braced)99774829734SRaphael Isemann void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
99874829734SRaphael Isemann OverloadCandidate *Candidates,
99974829734SRaphael Isemann unsigned NumCandidates,
100092417eafSSam McCall SourceLocation OpenParLoc,
100192417eafSSam McCall bool Braced) override {
100274829734SRaphael Isemann // At the moment we don't filter out any overloaded candidates.
100374829734SRaphael Isemann }
100474829734SRaphael Isemann
getAllocator()100574829734SRaphael Isemann CodeCompletionAllocator &getAllocator() override {
100639ec6e70SRaphael Isemann return m_info.getAllocator();
100774829734SRaphael Isemann }
100874829734SRaphael Isemann
getCodeCompletionTUInfo()100939ec6e70SRaphael Isemann CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; }
101074829734SRaphael Isemann };
101174829734SRaphael Isemann } // namespace
101274829734SRaphael Isemann
Complete(CompletionRequest & request,unsigned line,unsigned pos,unsigned typed_pos)1013c11a780eSRaphael Isemann bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line,
101474829734SRaphael Isemann unsigned pos, unsigned typed_pos) {
101574829734SRaphael Isemann DiagnosticManager mgr;
101674829734SRaphael Isemann // We need the raw user expression here because that's what the CodeComplete
101774829734SRaphael Isemann // class uses to provide completion suggestions.
101874829734SRaphael Isemann // However, the `Text` method only gives us the transformed expression here.
101974829734SRaphael Isemann // To actually get the raw user input here, we have to cast our expression to
102074829734SRaphael Isemann // the LLVMUserExpression which exposes the right API. This should never fail
102174829734SRaphael Isemann // as we always have a ClangUserExpression whenever we call this.
1022d63c1dbdSRaphael Isemann ClangUserExpression *llvm_expr = cast<ClangUserExpression>(&m_expr);
102374a51753SRaphael Isemann CodeComplete CC(m_compiler->getLangOpts(), llvm_expr->GetUserText(),
10249dd34c83SRaphael Isemann typed_pos);
102574829734SRaphael Isemann // We don't need a code generator for parsing.
102674829734SRaphael Isemann m_code_generator.reset();
102774829734SRaphael Isemann // Start parsing the expression with our custom code completion consumer.
102874829734SRaphael Isemann ParseInternal(mgr, &CC, line, pos);
102974a51753SRaphael Isemann CC.GetCompletions(request);
103074829734SRaphael Isemann return true;
103174829734SRaphael Isemann }
103274829734SRaphael Isemann
Parse(DiagnosticManager & diagnostic_manager)1033b9c1b51eSKate Stone unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
103474829734SRaphael Isemann return ParseInternal(diagnostic_manager);
103574829734SRaphael Isemann }
103674829734SRaphael Isemann
103774829734SRaphael Isemann unsigned
ParseInternal(DiagnosticManager & diagnostic_manager,CodeCompleteConsumer * completion_consumer,unsigned completion_line,unsigned completion_column)103874829734SRaphael Isemann ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager,
103974829734SRaphael Isemann CodeCompleteConsumer *completion_consumer,
104074829734SRaphael Isemann unsigned completion_line,
104174829734SRaphael Isemann unsigned completion_column) {
1042579e70c9SSean Callanan ClangDiagnosticManagerAdapter *adapter =
1043b9c1b51eSKate Stone static_cast<ClangDiagnosticManagerAdapter *>(
1044b9c1b51eSKate Stone m_compiler->getDiagnostics().getClient());
10454dbb271fSSean Callanan
1046579e70c9SSean Callanan adapter->ResetManager(&diagnostic_manager);
1047579e70c9SSean Callanan
10484dbb271fSSean Callanan const char *expr_text = m_expr.Text();
10494dbb271fSSean Callanan
1050615a807eSEwan Crawford clang::SourceManager &source_mgr = m_compiler->getSourceManager();
10514dbb271fSSean Callanan bool created_main_file = false;
105274829734SRaphael Isemann
105374829734SRaphael Isemann // Clang wants to do completion on a real file known by Clang's file manager,
105474829734SRaphael Isemann // so we have to create one to make this work.
105574829734SRaphael Isemann // TODO: We probably could also simulate to Clang's file manager that there
105674829734SRaphael Isemann // is a real file that contains our code.
105774829734SRaphael Isemann bool should_create_file = completion_consumer != nullptr;
105874829734SRaphael Isemann
105974829734SRaphael Isemann // We also want a real file on disk if we generate full debug info.
106074829734SRaphael Isemann should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==
106174829734SRaphael Isemann codegenoptions::FullDebugInfo;
106274829734SRaphael Isemann
106374829734SRaphael Isemann if (should_create_file) {
10644dbb271fSSean Callanan int temp_fd = -1;
1065b3f44ad9SStella Stamenova llvm::SmallString<128> result_path;
106660f028ffSPavel Labath if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
10674dbb271fSSean Callanan tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
1068615a807eSEwan Crawford std::string temp_source_path = tmpdir_file_spec.GetPath();
10694dbb271fSSean Callanan llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
1070b9c1b51eSKate Stone } else {
10714dbb271fSSean Callanan llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
10724dbb271fSSean Callanan }
10734dbb271fSSean Callanan
1074b9c1b51eSKate Stone if (temp_fd != -1) {
107514735cabSMichał Górny lldb_private::NativeFile file(temp_fd, File::eOpenOptionWriteOnly, true);
10764dbb271fSSean Callanan const size_t expr_text_len = strlen(expr_text);
10774dbb271fSSean Callanan size_t bytes_written = expr_text_len;
1078b9c1b51eSKate Stone if (file.Write(expr_text, bytes_written).Success()) {
1079b9c1b51eSKate Stone if (bytes_written == expr_text_len) {
10804dbb271fSSean Callanan file.Close();
10818b6aedc4SDuncan P. N. Exon Smith if (auto fileEntry = m_compiler->getFileManager().getOptionalFileRef(
10828b6aedc4SDuncan P. N. Exon Smith result_path)) {
1083ff04b3d4SJonas Devlieghere source_mgr.setMainFileID(source_mgr.createFileID(
108484586c14SHarlan Haskins *fileEntry,
10854dbb271fSSean Callanan SourceLocation(), SrcMgr::C_User));
10864dbb271fSSean Callanan created_main_file = true;
10874dbb271fSSean Callanan }
10884dbb271fSSean Callanan }
10894dbb271fSSean Callanan }
10904dbb271fSSean Callanan }
109184586c14SHarlan Haskins }
10924dbb271fSSean Callanan
1093b9c1b51eSKate Stone if (!created_main_file) {
1094b9c1b51eSKate Stone std::unique_ptr<MemoryBuffer> memory_buffer =
10951442efeaSRaphael Isemann MemoryBuffer::getMemBufferCopy(expr_text, m_filename);
1096615a807eSEwan Crawford source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
10974dbb271fSSean Callanan }
10984dbb271fSSean Callanan
109983aa58d7SRaphael Isemann adapter->BeginSourceFile(m_compiler->getLangOpts(),
1100b9c1b51eSKate Stone &m_compiler->getPreprocessor());
11014dbb271fSSean Callanan
1102b9c1b51eSKate Stone ClangExpressionHelper *type_system_helper =
1103b9c1b51eSKate Stone dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
11044dbb271fSSean Callanan
110574829734SRaphael Isemann // If we want to parse for code completion, we need to attach our code
110674829734SRaphael Isemann // completion consumer to the Sema and specify a completion position.
110774829734SRaphael Isemann // While parsing the Sema will call this consumer with the provided
110874829734SRaphael Isemann // completion suggestions.
110974829734SRaphael Isemann if (completion_consumer) {
111074829734SRaphael Isemann auto main_file = source_mgr.getFileEntryForID(source_mgr.getMainFileID());
111174829734SRaphael Isemann auto &PP = m_compiler->getPreprocessor();
111274829734SRaphael Isemann // Lines and columns start at 1 in Clang, but code completion positions are
111374829734SRaphael Isemann // indexed from 0, so we need to add 1 to the line and column here.
111474829734SRaphael Isemann ++completion_line;
111574829734SRaphael Isemann ++completion_column;
111674829734SRaphael Isemann PP.SetCodeCompletionPoint(main_file, completion_line, completion_column);
111774829734SRaphael Isemann }
111874829734SRaphael Isemann
11196c0bbfc0SRaphael Isemann ASTConsumer *ast_transformer =
11206c0bbfc0SRaphael Isemann type_system_helper->ASTTransformer(m_code_generator.get());
11216c0bbfc0SRaphael Isemann
11226c0bbfc0SRaphael Isemann std::unique_ptr<clang::ASTConsumer> Consumer;
1123b9c1b51eSKate Stone if (ast_transformer) {
112406412daeSJonas Devlieghere Consumer = std::make_unique<ASTConsumerForwarder>(ast_transformer);
11256c0bbfc0SRaphael Isemann } else if (m_code_generator) {
112606412daeSJonas Devlieghere Consumer = std::make_unique<ASTConsumerForwarder>(m_code_generator.get());
1127b9c1b51eSKate Stone } else {
112806412daeSJonas Devlieghere Consumer = std::make_unique<ASTConsumer>();
11294dbb271fSSean Callanan }
11304dbb271fSSean Callanan
11316c0bbfc0SRaphael Isemann clang::ASTContext &ast_context = m_compiler->getASTContext();
11326c0bbfc0SRaphael Isemann
11336c0bbfc0SRaphael Isemann m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context,
11346c0bbfc0SRaphael Isemann *Consumer, TU_Complete, completion_consumer));
11356c0bbfc0SRaphael Isemann m_compiler->setASTConsumer(std::move(Consumer));
11366c0bbfc0SRaphael Isemann
1137f74a4c1fSRaphael Isemann if (ast_context.getLangOpts().Modules) {
11387af53d75SRaphael Isemann m_compiler->createASTReader();
1139f74a4c1fSRaphael Isemann m_ast_context->setSema(&m_compiler->getSema());
1140f74a4c1fSRaphael Isemann }
11416c0bbfc0SRaphael Isemann
11426c0bbfc0SRaphael Isemann ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
11436c0bbfc0SRaphael Isemann if (decl_map) {
11446c0bbfc0SRaphael Isemann decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer());
1145cb81e662SRaphael Isemann decl_map->InstallDiagnosticManager(diagnostic_manager);
11466c0bbfc0SRaphael Isemann
11476c0bbfc0SRaphael Isemann clang::ExternalASTSource *ast_source = decl_map->CreateProxy();
11486c0bbfc0SRaphael Isemann
11496c0bbfc0SRaphael Isemann if (ast_context.getExternalSource()) {
11506c0bbfc0SRaphael Isemann auto module_wrapper =
11516c0bbfc0SRaphael Isemann new ExternalASTSourceWrapper(ast_context.getExternalSource());
11526c0bbfc0SRaphael Isemann
11536c0bbfc0SRaphael Isemann auto ast_source_wrapper = new ExternalASTSourceWrapper(ast_source);
11546c0bbfc0SRaphael Isemann
11556c0bbfc0SRaphael Isemann auto multiplexer =
11566c0bbfc0SRaphael Isemann new SemaSourceWithPriorities(*module_wrapper, *ast_source_wrapper);
11576c0bbfc0SRaphael Isemann IntrusiveRefCntPtr<ExternalASTSource> Source(multiplexer);
11586c0bbfc0SRaphael Isemann ast_context.setExternalSource(Source);
11596c0bbfc0SRaphael Isemann } else {
11606c0bbfc0SRaphael Isemann ast_context.setExternalSource(ast_source);
11616c0bbfc0SRaphael Isemann }
116249b206f9SRaphael Isemann decl_map->InstallASTContext(*m_ast_context);
11636c0bbfc0SRaphael Isemann }
11646c0bbfc0SRaphael Isemann
11656c0bbfc0SRaphael Isemann // Check that the ASTReader is properly attached to ASTContext and Sema.
11666c0bbfc0SRaphael Isemann if (ast_context.getLangOpts().Modules) {
11676c0bbfc0SRaphael Isemann assert(m_compiler->getASTContext().getExternalSource() &&
11686c0bbfc0SRaphael Isemann "ASTContext doesn't know about the ASTReader?");
11696c0bbfc0SRaphael Isemann assert(m_compiler->getSema().getExternalSource() &&
11706c0bbfc0SRaphael Isemann "Sema doesn't know about the ASTReader?");
11716c0bbfc0SRaphael Isemann }
11726c0bbfc0SRaphael Isemann
11736c0bbfc0SRaphael Isemann {
11746c0bbfc0SRaphael Isemann llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(
11756c0bbfc0SRaphael Isemann &m_compiler->getSema());
11766c0bbfc0SRaphael Isemann ParseAST(m_compiler->getSema(), false, false);
11776c0bbfc0SRaphael Isemann }
1178f74a4c1fSRaphael Isemann
1179f74a4c1fSRaphael Isemann // Make sure we have no pointer to the Sema we are about to destroy.
1180f74a4c1fSRaphael Isemann if (ast_context.getLangOpts().Modules)
1181f74a4c1fSRaphael Isemann m_ast_context->setSema(nullptr);
11826c0bbfc0SRaphael Isemann // Destroy the Sema. This is necessary because we want to emulate the
11836c0bbfc0SRaphael Isemann // original behavior of ParseAST (which also destroys the Sema after parsing).
11846c0bbfc0SRaphael Isemann m_compiler->setSema(nullptr);
11856c0bbfc0SRaphael Isemann
118683aa58d7SRaphael Isemann adapter->EndSourceFile();
11874dbb271fSSean Callanan
118883aa58d7SRaphael Isemann unsigned num_errors = adapter->getNumErrors();
11894dbb271fSSean Callanan
1190b9c1b51eSKate Stone if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
11914dbb271fSSean Callanan num_errors++;
1192e2411fabSZachary Turner diagnostic_manager.PutString(eDiagnosticSeverityError,
1193b9c1b51eSKate Stone "while importing modules:");
1194b9c1b51eSKate Stone diagnostic_manager.AppendMessageToDiagnostic(
1195c156427dSZachary Turner m_pp_callbacks->getErrorString());
11964dbb271fSSean Callanan }
11974dbb271fSSean Callanan
1198b9c1b51eSKate Stone if (!num_errors) {
119900294b34SSean Callanan type_system_helper->CommitPersistentDecls();
120000294b34SSean Callanan }
120100294b34SSean Callanan
1202579e70c9SSean Callanan adapter->ResetManager();
1203579e70c9SSean Callanan
12044dbb271fSSean Callanan return num_errors;
12054dbb271fSSean Callanan }
12064dbb271fSSean Callanan
1207adc1abe7SSagar Thakur std::string
GetClangTargetABI(const ArchSpec & target_arch)1208b9c1b51eSKate Stone ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {
1209adc1abe7SSagar Thakur std::string abi;
1210adc1abe7SSagar Thakur
1211b9c1b51eSKate Stone if (target_arch.IsMIPS()) {
1212b9c1b51eSKate Stone switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
1213adc1abe7SSagar Thakur case ArchSpec::eMIPSABI_N64:
1214b9c1b51eSKate Stone abi = "n64";
1215b9c1b51eSKate Stone break;
1216adc1abe7SSagar Thakur case ArchSpec::eMIPSABI_N32:
1217b9c1b51eSKate Stone abi = "n32";
1218b9c1b51eSKate Stone break;
1219adc1abe7SSagar Thakur case ArchSpec::eMIPSABI_O32:
1220b9c1b51eSKate Stone abi = "o32";
1221b9c1b51eSKate Stone break;
1222adc1abe7SSagar Thakur default:
1223adc1abe7SSagar Thakur break;
1224adc1abe7SSagar Thakur }
1225adc1abe7SSagar Thakur }
1226adc1abe7SSagar Thakur return abi;
1227adc1abe7SSagar Thakur }
1228adc1abe7SSagar Thakur
1229767a97b2SRaphael Isemann /// Applies the given Fix-It hint to the given commit.
ApplyFixIt(const FixItHint & fixit,clang::edit::Commit & commit)1230767a97b2SRaphael Isemann static void ApplyFixIt(const FixItHint &fixit, clang::edit::Commit &commit) {
1231767a97b2SRaphael Isemann // This is cobbed from clang::Rewrite::FixItRewriter.
1232767a97b2SRaphael Isemann if (fixit.CodeToInsert.empty()) {
1233767a97b2SRaphael Isemann if (fixit.InsertFromRange.isValid()) {
1234767a97b2SRaphael Isemann commit.insertFromRange(fixit.RemoveRange.getBegin(),
1235767a97b2SRaphael Isemann fixit.InsertFromRange, /*afterToken=*/false,
1236767a97b2SRaphael Isemann fixit.BeforePreviousInsertions);
1237767a97b2SRaphael Isemann return;
1238767a97b2SRaphael Isemann }
1239767a97b2SRaphael Isemann commit.remove(fixit.RemoveRange);
1240767a97b2SRaphael Isemann return;
1241767a97b2SRaphael Isemann }
1242767a97b2SRaphael Isemann if (fixit.RemoveRange.isTokenRange() ||
1243767a97b2SRaphael Isemann fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd()) {
1244767a97b2SRaphael Isemann commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
1245767a97b2SRaphael Isemann return;
1246767a97b2SRaphael Isemann }
1247767a97b2SRaphael Isemann commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
1248767a97b2SRaphael Isemann /*afterToken=*/false, fixit.BeforePreviousInsertions);
1249767a97b2SRaphael Isemann }
1250767a97b2SRaphael Isemann
RewriteExpression(DiagnosticManager & diagnostic_manager)1251b9c1b51eSKate Stone bool ClangExpressionParser::RewriteExpression(
1252b9c1b51eSKate Stone DiagnosticManager &diagnostic_manager) {
1253a1e541bfSJim Ingham clang::SourceManager &source_manager = m_compiler->getSourceManager();
1254b9c1b51eSKate Stone clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
1255b9c1b51eSKate Stone nullptr);
1256a1e541bfSJim Ingham clang::edit::Commit commit(editor);
1257a1e541bfSJim Ingham clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
1258a1e541bfSJim Ingham
1259a1e541bfSJim Ingham class RewritesReceiver : public edit::EditsReceiver {
1260a1e541bfSJim Ingham Rewriter &rewrite;
1261a1e541bfSJim Ingham
1262a1e541bfSJim Ingham public:
1263a1e541bfSJim Ingham RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
1264a1e541bfSJim Ingham
1265a1e541bfSJim Ingham void insert(SourceLocation loc, StringRef text) override {
1266a1e541bfSJim Ingham rewrite.InsertText(loc, text);
1267a1e541bfSJim Ingham }
1268a1e541bfSJim Ingham void replace(CharSourceRange range, StringRef text) override {
1269a1e541bfSJim Ingham rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
1270a1e541bfSJim Ingham }
1271a1e541bfSJim Ingham };
1272a1e541bfSJim Ingham
1273a1e541bfSJim Ingham RewritesReceiver rewrites_receiver(rewriter);
1274a1e541bfSJim Ingham
1275a1e541bfSJim Ingham const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
1276a1e541bfSJim Ingham size_t num_diags = diagnostics.size();
1277a1e541bfSJim Ingham if (num_diags == 0)
1278a1e541bfSJim Ingham return false;
1279a1e541bfSJim Ingham
12807c47b4a1SRaphael Isemann for (const auto &diag : diagnostic_manager.Diagnostics()) {
12817c47b4a1SRaphael Isemann const auto *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag.get());
1282767a97b2SRaphael Isemann if (!diagnostic)
1283767a97b2SRaphael Isemann continue;
1284767a97b2SRaphael Isemann if (!diagnostic->HasFixIts())
1285767a97b2SRaphael Isemann continue;
1286767a97b2SRaphael Isemann for (const FixItHint &fixit : diagnostic->FixIts())
1287767a97b2SRaphael Isemann ApplyFixIt(fixit, commit);
1288a1e541bfSJim Ingham }
1289a1e541bfSJim Ingham
1290a1e541bfSJim Ingham // FIXME - do we want to try to propagate specific errors here?
1291a1e541bfSJim Ingham if (!commit.isCommitable())
1292a1e541bfSJim Ingham return false;
1293a1e541bfSJim Ingham else if (!editor.commit(commit))
1294a1e541bfSJim Ingham return false;
1295a1e541bfSJim Ingham
1296a1e541bfSJim Ingham // Now play all the edits, and stash the result in the diagnostic manager.
1297a1e541bfSJim Ingham editor.applyRewrites(rewrites_receiver);
1298b9c1b51eSKate Stone RewriteBuffer &main_file_buffer =
1299b9c1b51eSKate Stone rewriter.getEditBuffer(source_manager.getMainFileID());
1300a1e541bfSJim Ingham
1301a1e541bfSJim Ingham std::string fixed_expression;
1302a1e541bfSJim Ingham llvm::raw_string_ostream out_stream(fixed_expression);
1303a1e541bfSJim Ingham
1304a1e541bfSJim Ingham main_file_buffer.write(out_stream);
1305a1e541bfSJim Ingham out_stream.flush();
1306a1e541bfSJim Ingham diagnostic_manager.SetFixedExpression(fixed_expression);
1307a1e541bfSJim Ingham
1308a1e541bfSJim Ingham return true;
1309a1e541bfSJim Ingham }
1310a1e541bfSJim Ingham
FindFunctionInModule(ConstString & mangled_name,llvm::Module * module,const char * orig_name)13114dbb271fSSean Callanan static bool FindFunctionInModule(ConstString &mangled_name,
1312b9c1b51eSKate Stone llvm::Module *module, const char *orig_name) {
1313b9c1b51eSKate Stone for (const auto &func : module->getFunctionList()) {
1314b129847aSAidan Dodds const StringRef &name = func.getName();
13154ba9d9c8SKazu Hirata if (name.contains(orig_name)) {
1316b129847aSAidan Dodds mangled_name.SetString(name);
13174dbb271fSSean Callanan return true;
13184dbb271fSSean Callanan }
13194dbb271fSSean Callanan }
13204dbb271fSSean Callanan
13214dbb271fSSean Callanan return false;
13224dbb271fSSean Callanan }
13234dbb271fSSean Callanan
PrepareForExecution(lldb::addr_t & func_addr,lldb::addr_t & func_end,lldb::IRExecutionUnitSP & execution_unit_sp,ExecutionContext & exe_ctx,bool & can_interpret,ExecutionPolicy execution_policy)132497206d57SZachary Turner lldb_private::Status ClangExpressionParser::PrepareForExecution(
1325b9c1b51eSKate Stone lldb::addr_t &func_addr, lldb::addr_t &func_end,
1326b9c1b51eSKate Stone lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
1327b9c1b51eSKate Stone bool &can_interpret, ExecutionPolicy execution_policy) {
13284dbb271fSSean Callanan func_addr = LLDB_INVALID_ADDRESS;
13294dbb271fSSean Callanan func_end = LLDB_INVALID_ADDRESS;
1330a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Expressions);
13314dbb271fSSean Callanan
133297206d57SZachary Turner lldb_private::Status err;
13334dbb271fSSean Callanan
1334d5b44036SJonas Devlieghere std::unique_ptr<llvm::Module> llvm_module_up(
1335b9c1b51eSKate Stone m_code_generator->ReleaseModule());
13364dbb271fSSean Callanan
1337d5b44036SJonas Devlieghere if (!llvm_module_up) {
13384dbb271fSSean Callanan err.SetErrorToGenericError();
13394dbb271fSSean Callanan err.SetErrorString("IR doesn't contain a module");
13404dbb271fSSean Callanan return err;
13414dbb271fSSean Callanan }
13424dbb271fSSean Callanan
13434dbb271fSSean Callanan ConstString function_name;
13444dbb271fSSean Callanan
1345b9c1b51eSKate Stone if (execution_policy != eExecutionPolicyTopLevel) {
134600294b34SSean Callanan // Find the actual name of the function (it's often mangled somehow)
134700294b34SSean Callanan
1348d5b44036SJonas Devlieghere if (!FindFunctionInModule(function_name, llvm_module_up.get(),
1349b9c1b51eSKate Stone m_expr.FunctionName())) {
13504dbb271fSSean Callanan err.SetErrorToGenericError();
1351b9c1b51eSKate Stone err.SetErrorStringWithFormat("Couldn't find %s() in the module",
1352b9c1b51eSKate Stone m_expr.FunctionName());
13534dbb271fSSean Callanan return err;
1354b9c1b51eSKate Stone } else {
135563e5fb76SJonas Devlieghere LLDB_LOGF(log, "Found function %s for %s", function_name.AsCString(),
1356b9c1b51eSKate Stone m_expr.FunctionName());
13574dbb271fSSean Callanan }
135800294b34SSean Callanan }
13594dbb271fSSean Callanan
1360b2814802SSean Callanan SymbolContext sc;
1361b2814802SSean Callanan
1362b9c1b51eSKate Stone if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
1363b2814802SSean Callanan sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
1364b9c1b51eSKate Stone } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
1365b2814802SSean Callanan sc.target_sp = target_sp;
1366b2814802SSean Callanan }
1367b2814802SSean Callanan
13689d484225SLuke Drummond LLVMUserExpression::IRPasses custom_passes;
13699d484225SLuke Drummond {
13709d484225SLuke Drummond auto lang = m_expr.Language();
137163e5fb76SJonas Devlieghere LLDB_LOGF(log, "%s - Current expression language is %s\n", __FUNCTION__,
13729d484225SLuke Drummond Language::GetNameForLanguageType(lang));
137322562159SJim Ingham lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
137422562159SJim Ingham if (process_sp && lang != lldb::eLanguageTypeUnknown) {
137522562159SJim Ingham auto runtime = process_sp->GetLanguageRuntime(lang);
13769d484225SLuke Drummond if (runtime)
13779d484225SLuke Drummond runtime->GetIRPasses(custom_passes);
13789d484225SLuke Drummond }
13799d484225SLuke Drummond }
13809d484225SLuke Drummond
1381b9c1b51eSKate Stone if (custom_passes.EarlyPasses) {
138263e5fb76SJonas Devlieghere LLDB_LOGF(log,
138363e5fb76SJonas Devlieghere "%s - Running Early IR Passes from LanguageRuntime on "
1384b9c1b51eSKate Stone "expression module '%s'",
1385b9c1b51eSKate Stone __FUNCTION__, m_expr.FunctionName());
13869d484225SLuke Drummond
1387d5b44036SJonas Devlieghere custom_passes.EarlyPasses->run(*llvm_module_up);
13889d484225SLuke Drummond }
13899d484225SLuke Drummond
1390796ac80bSJonas Devlieghere execution_unit_sp = std::make_shared<IRExecutionUnit>(
1391796ac80bSJonas Devlieghere m_llvm_context, // handed off here
1392d5b44036SJonas Devlieghere llvm_module_up, // handed off here
1393b9c1b51eSKate Stone function_name, exe_ctx.GetTargetSP(), sc,
1394796ac80bSJonas Devlieghere m_compiler->getTargetOpts().Features);
13954dbb271fSSean Callanan
1396b9c1b51eSKate Stone ClangExpressionHelper *type_system_helper =
1397b9c1b51eSKate Stone dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1398b9c1b51eSKate Stone ClangExpressionDeclMap *decl_map =
1399b9c1b51eSKate Stone type_system_helper->DeclMap(); // result can be NULL
14004dbb271fSSean Callanan
1401b9c1b51eSKate Stone if (decl_map) {
140291728b91SRaphael Isemann StreamString error_stream;
1403b9c1b51eSKate Stone IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
14047ca15ba7SLawrence D'Anna *execution_unit_sp, error_stream,
14054dbb271fSSean Callanan function_name.AsCString());
14064dbb271fSSean Callanan
140791728b91SRaphael Isemann if (!ir_for_target.runOnModule(*execution_unit_sp->GetModule())) {
140891728b91SRaphael Isemann err.SetErrorString(error_stream.GetString());
14093a878af2SSean Callanan return err;
14103a878af2SSean Callanan }
14113a878af2SSean Callanan
14124dbb271fSSean Callanan Process *process = exe_ctx.GetProcessPtr();
14134dbb271fSSean Callanan
1414b9c1b51eSKate Stone if (execution_policy != eExecutionPolicyAlways &&
1415b9c1b51eSKate Stone execution_policy != eExecutionPolicyTopLevel) {
141697206d57SZachary Turner lldb_private::Status interpret_error;
141700294b34SSean Callanan
1418b9c1b51eSKate Stone bool interpret_function_calls =
1419b9c1b51eSKate Stone !process ? false : process->CanInterpretFunctionCalls();
1420b9c1b51eSKate Stone can_interpret = IRInterpreter::CanInterpret(
1421b9c1b51eSKate Stone *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
142200294b34SSean Callanan interpret_error, interpret_function_calls);
14234dbb271fSSean Callanan
1424b9c1b51eSKate Stone if (!can_interpret && execution_policy == eExecutionPolicyNever) {
1425877723b7SMed Ismail Bennani err.SetErrorStringWithFormat(
1426877723b7SMed Ismail Bennani "Can't evaluate the expression without a running target due to: %s",
1427b9c1b51eSKate Stone interpret_error.AsCString());
14284dbb271fSSean Callanan return err;
14294dbb271fSSean Callanan }
143000294b34SSean Callanan }
143100294b34SSean Callanan
1432b9c1b51eSKate Stone if (!process && execution_policy == eExecutionPolicyAlways) {
1433b9c1b51eSKate Stone err.SetErrorString("Expression needed to run in the target, but the "
1434b9c1b51eSKate Stone "target can't be run");
14354dbb271fSSean Callanan return err;
14364dbb271fSSean Callanan }
14374dbb271fSSean Callanan
1438b9c1b51eSKate Stone if (!process && execution_policy == eExecutionPolicyTopLevel) {
1439b9c1b51eSKate Stone err.SetErrorString("Top-level code needs to be inserted into a runnable "
1440b9c1b51eSKate Stone "target, but the target can't be run");
144100294b34SSean Callanan return err;
144200294b34SSean Callanan }
144300294b34SSean Callanan
144400294b34SSean Callanan if (execution_policy == eExecutionPolicyAlways ||
1445b9c1b51eSKate Stone (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
1446b9c1b51eSKate Stone if (m_expr.NeedsValidation() && process) {
1447b9c1b51eSKate Stone if (!process->GetDynamicCheckers()) {
1448bab7e3d7SAlex Langford ClangDynamicCheckerFunctions *dynamic_checkers =
1449bab7e3d7SAlex Langford new ClangDynamicCheckerFunctions();
14504dbb271fSSean Callanan
1451579e70c9SSean Callanan DiagnosticManager install_diagnostics;
14524dbb271fSSean Callanan
1453b9c1b51eSKate Stone if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) {
1454579e70c9SSean Callanan if (install_diagnostics.Diagnostics().size())
1455579e70c9SSean Callanan err.SetErrorString(install_diagnostics.GetString().c_str());
1456262dd8c9SRaphael Isemann else
1457262dd8c9SRaphael Isemann err.SetErrorString("couldn't install checkers, unknown error");
14584dbb271fSSean Callanan
14594dbb271fSSean Callanan return err;
14604dbb271fSSean Callanan }
14614dbb271fSSean Callanan
14624dbb271fSSean Callanan process->SetDynamicCheckers(dynamic_checkers);
14634dbb271fSSean Callanan
146463e5fb76SJonas Devlieghere LLDB_LOGF(log, "== [ClangExpressionParser::PrepareForExecution] "
1465f75a9dc1SRaphael Isemann "Finished installing dynamic checkers ==");
14664dbb271fSSean Callanan }
14674dbb271fSSean Callanan
1468bab7e3d7SAlex Langford if (auto *checker_funcs = llvm::dyn_cast<ClangDynamicCheckerFunctions>(
1469bab7e3d7SAlex Langford process->GetDynamicCheckers())) {
1470bab7e3d7SAlex Langford IRDynamicChecks ir_dynamic_checks(*checker_funcs,
1471b9c1b51eSKate Stone function_name.AsCString());
14724dbb271fSSean Callanan
14739d484225SLuke Drummond llvm::Module *module = execution_unit_sp->GetModule();
1474b9c1b51eSKate Stone if (!module || !ir_dynamic_checks.runOnModule(*module)) {
14754dbb271fSSean Callanan err.SetErrorToGenericError();
14764dbb271fSSean Callanan err.SetErrorString("Couldn't add dynamic checks to the expression");
14774dbb271fSSean Callanan return err;
14784dbb271fSSean Callanan }
14799d484225SLuke Drummond
1480b9c1b51eSKate Stone if (custom_passes.LatePasses) {
148163e5fb76SJonas Devlieghere LLDB_LOGF(log,
148263e5fb76SJonas Devlieghere "%s - Running Late IR Passes from LanguageRuntime on "
1483b9c1b51eSKate Stone "expression module '%s'",
14849d484225SLuke Drummond __FUNCTION__, m_expr.FunctionName());
14859d484225SLuke Drummond
14869d484225SLuke Drummond custom_passes.LatePasses->run(*module);
14879d484225SLuke Drummond }
14884dbb271fSSean Callanan }
148900294b34SSean Callanan }
1490bab7e3d7SAlex Langford }
14914dbb271fSSean Callanan
1492b9c1b51eSKate Stone if (execution_policy == eExecutionPolicyAlways ||
1493b9c1b51eSKate Stone execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
14944dbb271fSSean Callanan execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
14954dbb271fSSean Callanan }
1496b9c1b51eSKate Stone } else {
14974dbb271fSSean Callanan execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
14984dbb271fSSean Callanan }
14994dbb271fSSean Callanan
15004dbb271fSSean Callanan return err;
15014dbb271fSSean Callanan }
1502bd4dc693SSean Callanan
RunStaticInitializers(lldb::IRExecutionUnitSP & execution_unit_sp,ExecutionContext & exe_ctx)150397206d57SZachary Turner lldb_private::Status ClangExpressionParser::RunStaticInitializers(
1504b9c1b51eSKate Stone lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) {
150597206d57SZachary Turner lldb_private::Status err;
1506bd4dc693SSean Callanan
1507bd4dc693SSean Callanan lldbassert(execution_unit_sp.get());
1508bd4dc693SSean Callanan lldbassert(exe_ctx.HasThreadScope());
1509bd4dc693SSean Callanan
1510b9c1b51eSKate Stone if (!execution_unit_sp.get()) {
1511b9c1b51eSKate Stone err.SetErrorString(
1512b9c1b51eSKate Stone "can't run static initializers for a NULL execution unit");
1513bd4dc693SSean Callanan return err;
1514bd4dc693SSean Callanan }
1515bd4dc693SSean Callanan
1516b9c1b51eSKate Stone if (!exe_ctx.HasThreadScope()) {
1517bd4dc693SSean Callanan err.SetErrorString("can't run static initializers without a thread");
1518bd4dc693SSean Callanan return err;
1519bd4dc693SSean Callanan }
1520bd4dc693SSean Callanan
1521bd4dc693SSean Callanan std::vector<lldb::addr_t> static_initializers;
1522bd4dc693SSean Callanan
1523bd4dc693SSean Callanan execution_unit_sp->GetStaticInitializers(static_initializers);
1524bd4dc693SSean Callanan
1525b9c1b51eSKate Stone for (lldb::addr_t static_initializer : static_initializers) {
1526bd4dc693SSean Callanan EvaluateExpressionOptions options;
1527bd4dc693SSean Callanan
1528b9c1b51eSKate Stone lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(
1529b9c1b51eSKate Stone exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(),
1530b9c1b51eSKate Stone llvm::ArrayRef<lldb::addr_t>(), options));
1531bd4dc693SSean Callanan
1532bd4dc693SSean Callanan DiagnosticManager execution_errors;
1533b9c1b51eSKate Stone lldb::ExpressionResults results =
1534b9c1b51eSKate Stone exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(
1535b9c1b51eSKate Stone exe_ctx, call_static_initializer, options, execution_errors);
1536bd4dc693SSean Callanan
1537b9c1b51eSKate Stone if (results != lldb::eExpressionCompleted) {
1538b9c1b51eSKate Stone err.SetErrorStringWithFormat("couldn't run static initializer: %s",
1539b9c1b51eSKate Stone execution_errors.GetString().c_str());
1540bd4dc693SSean Callanan return err;
1541bd4dc693SSean Callanan }
1542bd4dc693SSean Callanan }
1543bd4dc693SSean Callanan
1544bd4dc693SSean Callanan return err;
1545bd4dc693SSean Callanan }
1546