/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===-- ClangExpressionParser.cpp -----------------------------------------===// |
2 | | // |
3 | | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | | // See https://llvm.org/LICENSE.txt for license information. |
5 | | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | |
9 | | #include "clang/AST/ASTContext.h" |
10 | | #include "clang/AST/ASTDiagnostic.h" |
11 | | #include "clang/AST/ExternalASTSource.h" |
12 | | #include "clang/AST/PrettyPrinter.h" |
13 | | #include "clang/Basic/Builtins.h" |
14 | | #include "clang/Basic/DiagnosticIDs.h" |
15 | | #include "clang/Basic/SourceLocation.h" |
16 | | #include "clang/Basic/TargetInfo.h" |
17 | | #include "clang/Basic/Version.h" |
18 | | #include "clang/CodeGen/CodeGenAction.h" |
19 | | #include "clang/CodeGen/ModuleBuilder.h" |
20 | | #include "clang/Edit/Commit.h" |
21 | | #include "clang/Edit/EditedSource.h" |
22 | | #include "clang/Edit/EditsReceiver.h" |
23 | | #include "clang/Frontend/CompilerInstance.h" |
24 | | #include "clang/Frontend/CompilerInvocation.h" |
25 | | #include "clang/Frontend/FrontendActions.h" |
26 | | #include "clang/Frontend/FrontendDiagnostic.h" |
27 | | #include "clang/Frontend/FrontendPluginRegistry.h" |
28 | | #include "clang/Frontend/TextDiagnosticBuffer.h" |
29 | | #include "clang/Frontend/TextDiagnosticPrinter.h" |
30 | | #include "clang/Lex/Preprocessor.h" |
31 | | #include "clang/Parse/ParseAST.h" |
32 | | #include "clang/Rewrite/Core/Rewriter.h" |
33 | | #include "clang/Rewrite/Frontend/FrontendActions.h" |
34 | | #include "clang/Sema/CodeCompleteConsumer.h" |
35 | | #include "clang/Sema/Sema.h" |
36 | | #include "clang/Sema/SemaConsumer.h" |
37 | | |
38 | | #include "llvm/ADT/StringRef.h" |
39 | | #include "llvm/ExecutionEngine/ExecutionEngine.h" |
40 | | #include "llvm/Support/CrashRecoveryContext.h" |
41 | | #include "llvm/Support/Debug.h" |
42 | | #include "llvm/Support/FileSystem.h" |
43 | | #include "llvm/Support/TargetSelect.h" |
44 | | |
45 | | #include "llvm/IR/LLVMContext.h" |
46 | | #include "llvm/IR/Module.h" |
47 | | #include "llvm/Support/DynamicLibrary.h" |
48 | | #include "llvm/Support/ErrorHandling.h" |
49 | | #include "llvm/Support/MemoryBuffer.h" |
50 | | #include "llvm/Support/Signals.h" |
51 | | #include "llvm/TargetParser/Host.h" |
52 | | |
53 | | #include "ClangDiagnostic.h" |
54 | | #include "ClangExpressionParser.h" |
55 | | #include "ClangUserExpression.h" |
56 | | |
57 | | #include "ASTUtils.h" |
58 | | #include "ClangASTSource.h" |
59 | | #include "ClangDiagnostic.h" |
60 | | #include "ClangExpressionDeclMap.h" |
61 | | #include "ClangExpressionHelper.h" |
62 | | #include "ClangExpressionParser.h" |
63 | | #include "ClangHost.h" |
64 | | #include "ClangModulesDeclVendor.h" |
65 | | #include "ClangPersistentVariables.h" |
66 | | #include "IRDynamicChecks.h" |
67 | | #include "IRForTarget.h" |
68 | | #include "ModuleDependencyCollector.h" |
69 | | |
70 | | #include "Plugins/TypeSystem/Clang/TypeSystemClang.h" |
71 | | #include "lldb/Core/Debugger.h" |
72 | | #include "lldb/Core/Disassembler.h" |
73 | | #include "lldb/Core/Module.h" |
74 | | #include "lldb/Expression/IRExecutionUnit.h" |
75 | | #include "lldb/Expression/IRInterpreter.h" |
76 | | #include "lldb/Host/File.h" |
77 | | #include "lldb/Host/HostInfo.h" |
78 | | #include "lldb/Symbol/SymbolVendor.h" |
79 | | #include "lldb/Target/ExecutionContext.h" |
80 | | #include "lldb/Target/Language.h" |
81 | | #include "lldb/Target/Process.h" |
82 | | #include "lldb/Target/Target.h" |
83 | | #include "lldb/Target/ThreadPlanCallFunction.h" |
84 | | #include "lldb/Utility/DataBufferHeap.h" |
85 | | #include "lldb/Utility/LLDBAssert.h" |
86 | | #include "lldb/Utility/LLDBLog.h" |
87 | | #include "lldb/Utility/Log.h" |
88 | | #include "lldb/Utility/Stream.h" |
89 | | #include "lldb/Utility/StreamString.h" |
90 | | #include "lldb/Utility/StringList.h" |
91 | | |
92 | | #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" |
93 | | |
94 | | #include <cctype> |
95 | | #include <memory> |
96 | | #include <optional> |
97 | | |
98 | | using namespace clang; |
99 | | using namespace llvm; |
100 | | using namespace lldb_private; |
101 | | |
102 | | //===----------------------------------------------------------------------===// |
103 | | // Utility Methods for Clang |
104 | | //===----------------------------------------------------------------------===// |
105 | | |
106 | | class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks { |
107 | | ClangModulesDeclVendor &m_decl_vendor; |
108 | | ClangPersistentVariables &m_persistent_vars; |
109 | | clang::SourceManager &m_source_mgr; |
110 | | StreamString m_error_stream; |
111 | | bool m_has_errors = false; |
112 | | |
113 | | public: |
114 | | LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor, |
115 | | ClangPersistentVariables &persistent_vars, |
116 | | clang::SourceManager &source_mgr) |
117 | 11.9k | : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars), |
118 | 11.9k | m_source_mgr(source_mgr) {} |
119 | | |
120 | | void moduleImport(SourceLocation import_location, clang::ModuleIdPath path, |
121 | 380 | const clang::Module * /*null*/) override { |
122 | | // Ignore modules that are imported in the wrapper code as these are not |
123 | | // loaded by the user. |
124 | 380 | llvm::StringRef filename = |
125 | 380 | m_source_mgr.getPresumedLoc(import_location).getFilename(); |
126 | 380 | if (filename == ClangExpressionSourceCode::g_prefix_file_name) |
127 | 354 | return; |
128 | | |
129 | 26 | SourceModule module; |
130 | | |
131 | 26 | for (const std::pair<IdentifierInfo *, SourceLocation> &component : path) |
132 | 26 | module.path.push_back(ConstString(component.first->getName())); |
133 | | |
134 | 26 | StreamString error_stream; |
135 | | |
136 | 26 | ClangModulesDeclVendor::ModuleVector exported_modules; |
137 | 26 | if (!m_decl_vendor.AddModule(module, &exported_modules, m_error_stream)) |
138 | 6 | m_has_errors = true; |
139 | | |
140 | 26 | for (ClangModulesDeclVendor::ModuleID module : exported_modules) |
141 | 7.29k | m_persistent_vars.AddHandLoadedClangModule(module); |
142 | 26 | } |
143 | | |
144 | 11.9k | bool hasErrors() { return m_has_errors; } |
145 | | |
146 | 6 | llvm::StringRef getErrorString() { return m_error_stream.GetString(); } |
147 | | }; |
148 | | |
149 | 424 | static void AddAllFixIts(ClangDiagnostic *diag, const clang::Diagnostic &Info) { |
150 | 424 | for (auto &fix_it : Info.getFixItHints()) { |
151 | 30 | if (fix_it.isNull()) |
152 | 0 | continue; |
153 | 30 | diag->AddFixitHint(fix_it); |
154 | 30 | } |
155 | 424 | } |
156 | | |
157 | | class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer { |
158 | | public: |
159 | 11.9k | ClangDiagnosticManagerAdapter(DiagnosticOptions &opts) { |
160 | 11.9k | DiagnosticOptions *options = new DiagnosticOptions(opts); |
161 | 11.9k | options->ShowPresumedLoc = true; |
162 | 11.9k | options->ShowLevel = false; |
163 | 11.9k | m_os = std::make_shared<llvm::raw_string_ostream>(m_output); |
164 | 11.9k | m_passthrough = |
165 | 11.9k | std::make_shared<clang::TextDiagnosticPrinter>(*m_os, options); |
166 | 11.9k | } |
167 | | |
168 | 23.8k | void ResetManager(DiagnosticManager *manager = nullptr) { |
169 | 23.8k | m_manager = manager; |
170 | 23.8k | } |
171 | | |
172 | | /// Returns the last ClangDiagnostic message that the DiagnosticManager |
173 | | /// received or a nullptr if the DiagnosticMangager hasn't seen any |
174 | | /// Clang diagnostics yet. |
175 | 74 | ClangDiagnostic *MaybeGetLastClangDiag() const { |
176 | 74 | if (m_manager->Diagnostics().empty()) |
177 | 0 | return nullptr; |
178 | 74 | lldb_private::Diagnostic *diag = m_manager->Diagnostics().back().get(); |
179 | 74 | ClangDiagnostic *clang_diag = dyn_cast<ClangDiagnostic>(diag); |
180 | 74 | return clang_diag; |
181 | 74 | } |
182 | | |
183 | | void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, |
184 | 50.6k | const clang::Diagnostic &Info) override { |
185 | 50.6k | if (!m_manager) { |
186 | | // We have no DiagnosticManager before/after parsing but we still could |
187 | | // receive diagnostics (e.g., by the ASTImporter failing to copy decls |
188 | | // when we move the expression result ot the ScratchASTContext). Let's at |
189 | | // least log these diagnostics until we find a way to properly render |
190 | | // them and display them to the user. |
191 | 50.0k | Log *log = GetLog(LLDBLog::Expressions); |
192 | 50.0k | if (log) { |
193 | 0 | llvm::SmallVector<char, 32> diag_str; |
194 | 0 | Info.FormatDiagnostic(diag_str); |
195 | 0 | diag_str.push_back('\0'); |
196 | 0 | const char *plain_diag = diag_str.data(); |
197 | 0 | LLDB_LOG(log, "Received diagnostic outside parsing: {0}", plain_diag); |
198 | 0 | } |
199 | 50.0k | return; |
200 | 50.0k | } |
201 | | |
202 | | // Update error/warning counters. |
203 | 545 | DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info); |
204 | | |
205 | | // Render diagnostic message to m_output. |
206 | 545 | m_output.clear(); |
207 | 545 | m_passthrough->HandleDiagnostic(DiagLevel, Info); |
208 | 545 | m_os->flush(); |
209 | | |
210 | 545 | lldb_private::DiagnosticSeverity severity; |
211 | 545 | bool make_new_diagnostic = true; |
212 | | |
213 | 545 | switch (DiagLevel) { |
214 | 8 | case DiagnosticsEngine::Level::Fatal: |
215 | 368 | case DiagnosticsEngine::Level::Error: |
216 | 368 | severity = eDiagnosticSeverityError; |
217 | 368 | break; |
218 | 103 | case DiagnosticsEngine::Level::Warning: |
219 | 103 | severity = eDiagnosticSeverityWarning; |
220 | 103 | break; |
221 | 0 | case DiagnosticsEngine::Level::Remark: |
222 | 0 | case DiagnosticsEngine::Level::Ignored: |
223 | 0 | severity = eDiagnosticSeverityRemark; |
224 | 0 | break; |
225 | 74 | case DiagnosticsEngine::Level::Note: |
226 | 74 | m_manager->AppendMessageToDiagnostic(m_output); |
227 | 74 | make_new_diagnostic = false; |
228 | | |
229 | | // 'note:' diagnostics for errors and warnings can also contain Fix-Its. |
230 | | // We add these Fix-Its to the last error diagnostic to make sure |
231 | | // that we later have all Fix-Its related to an 'error' diagnostic when |
232 | | // we apply them to the user expression. |
233 | 74 | auto *clang_diag = MaybeGetLastClangDiag(); |
234 | | // If we don't have a previous diagnostic there is nothing to do. |
235 | | // If the previous diagnostic already has its own Fix-Its, assume that |
236 | | // the 'note:' Fix-It is just an alternative way to solve the issue and |
237 | | // ignore these Fix-Its. |
238 | 74 | if (!clang_diag || clang_diag->HasFixIts()) |
239 | 4 | break; |
240 | | // Ignore all Fix-Its that are not associated with an error. |
241 | 70 | if (clang_diag->GetSeverity() != eDiagnosticSeverityError) |
242 | 14 | break; |
243 | 56 | AddAllFixIts(clang_diag, Info); |
244 | 56 | break; |
245 | 545 | } |
246 | 545 | if (make_new_diagnostic) { |
247 | | // ClangDiagnostic messages are expected to have no whitespace/newlines |
248 | | // around them. |
249 | 471 | std::string stripped_output = |
250 | 471 | std::string(llvm::StringRef(m_output).trim()); |
251 | | |
252 | 471 | auto new_diagnostic = std::make_unique<ClangDiagnostic>( |
253 | 471 | stripped_output, severity, Info.getID()); |
254 | | |
255 | | // Don't store away warning fixits, since the compiler doesn't have |
256 | | // enough context in an expression for the warning to be useful. |
257 | | // FIXME: Should we try to filter out FixIts that apply to our generated |
258 | | // code, and not the user's expression? |
259 | 471 | if (severity == eDiagnosticSeverityError) |
260 | 368 | AddAllFixIts(new_diagnostic.get(), Info); |
261 | | |
262 | 471 | m_manager->AddDiagnostic(std::move(new_diagnostic)); |
263 | 471 | } |
264 | 545 | } |
265 | | |
266 | 11.9k | void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override { |
267 | 11.9k | m_passthrough->BeginSourceFile(LO, PP); |
268 | 11.9k | } |
269 | | |
270 | 11.9k | void EndSourceFile() override { m_passthrough->EndSourceFile(); } |
271 | | |
272 | | private: |
273 | | DiagnosticManager *m_manager = nullptr; |
274 | | std::shared_ptr<clang::TextDiagnosticPrinter> m_passthrough; |
275 | | /// Output stream of m_passthrough. |
276 | | std::shared_ptr<llvm::raw_string_ostream> m_os; |
277 | | /// Output string filled by m_os. |
278 | | std::string m_output; |
279 | | }; |
280 | | |
281 | | static void SetupModuleHeaderPaths(CompilerInstance *compiler, |
282 | | std::vector<std::string> include_directories, |
283 | 354 | lldb::TargetSP target_sp) { |
284 | 354 | Log *log = GetLog(LLDBLog::Expressions); |
285 | | |
286 | 354 | HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts(); |
287 | | |
288 | 1.41k | for (const std::string &dir : include_directories) { |
289 | 1.41k | search_opts.AddPath(dir, frontend::System, false, true); |
290 | 1.41k | LLDB_LOG(log, "Added user include dir: {0}", dir); |
291 | 1.41k | } |
292 | | |
293 | 354 | llvm::SmallString<128> module_cache; |
294 | 354 | const auto &props = ModuleList::GetGlobalModuleListProperties(); |
295 | 354 | props.GetClangModulesCachePath().GetPath(module_cache); |
296 | 354 | search_opts.ModuleCachePath = std::string(module_cache.str()); |
297 | 354 | LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str()); |
298 | | |
299 | 354 | search_opts.ResourceDir = GetClangResourceDir().GetPath(); |
300 | | |
301 | 354 | search_opts.ImplicitModuleMaps = true; |
302 | 354 | } |
303 | | |
304 | | /// Iff the given identifier is a C++ keyword, remove it from the |
305 | | /// identifier table (i.e., make the token a normal identifier). |
306 | 369k | static void RemoveCppKeyword(IdentifierTable &idents, llvm::StringRef token) { |
307 | | // FIXME: 'using' is used by LLDB for local variables, so we can't remove |
308 | | // this keyword without breaking this functionality. |
309 | 369k | if (token == "using") |
310 | 1.16k | return; |
311 | | // GCC's '__null' is used by LLDB to define NULL/Nil/nil. |
312 | 367k | if (token == "__null") |
313 | 1.16k | return; |
314 | | |
315 | 366k | LangOptions cpp_lang_opts; |
316 | 366k | cpp_lang_opts.CPlusPlus = true; |
317 | 366k | cpp_lang_opts.CPlusPlus11 = true; |
318 | 366k | cpp_lang_opts.CPlusPlus20 = true; |
319 | | |
320 | 366k | clang::IdentifierInfo &ii = idents.get(token); |
321 | | // The identifier has to be a C++-exclusive keyword. if not, then there is |
322 | | // nothing to do. |
323 | 366k | if (!ii.isCPlusPlusKeyword(cpp_lang_opts)) |
324 | 230k | return; |
325 | | // If the token is already an identifier, then there is nothing to do. |
326 | 136k | if (ii.getTokenID() == clang::tok::identifier) |
327 | 0 | return; |
328 | | // Otherwise the token is a C++ keyword, so turn it back into a normal |
329 | | // identifier. |
330 | 136k | ii.revertTokenIDToIdentifier(); |
331 | 136k | } |
332 | | |
333 | | /// Remove all C++ keywords from the given identifier table. |
334 | 1.16k | static void RemoveAllCppKeywords(IdentifierTable &idents) { |
335 | 369k | #define KEYWORD(NAME, FLAGS) RemoveCppKeyword(idents, llvm::StringRef(#NAME)); |
336 | 1.16k | #include "clang/Basic/TokenKinds.def" |
337 | 1.16k | } |
338 | | |
339 | | /// Configures Clang diagnostics for the expression parser. |
340 | 11.9k | static void SetupDefaultClangDiagnostics(CompilerInstance &compiler) { |
341 | | // List of Clang warning groups that are not useful when parsing expressions. |
342 | 11.9k | const std::vector<const char *> groupsToIgnore = { |
343 | 11.9k | "unused-value", |
344 | 11.9k | "odr", |
345 | 11.9k | "unused-getter-return-value", |
346 | 11.9k | }; |
347 | 35.8k | for (const char *group : groupsToIgnore) { |
348 | 35.8k | compiler.getDiagnostics().setSeverityForGroup( |
349 | 35.8k | clang::diag::Flavor::WarningOrError, group, |
350 | 35.8k | clang::diag::Severity::Ignored, SourceLocation()); |
351 | 35.8k | } |
352 | 11.9k | } |
353 | | |
354 | | //===----------------------------------------------------------------------===// |
355 | | // Implementation of ClangExpressionParser |
356 | | //===----------------------------------------------------------------------===// |
357 | | |
358 | | ClangExpressionParser::ClangExpressionParser( |
359 | | ExecutionContextScope *exe_scope, Expression &expr, |
360 | | bool generate_debug_info, std::vector<std::string> include_directories, |
361 | | std::string filename) |
362 | 11.9k | : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(), |
363 | 11.9k | m_pp_callbacks(nullptr), |
364 | 11.9k | m_include_directories(std::move(include_directories)), |
365 | 11.9k | m_filename(std::move(filename)) { |
366 | 11.9k | Log *log = GetLog(LLDBLog::Expressions); |
367 | | |
368 | | // We can't compile expressions without a target. So if the exe_scope is |
369 | | // null or doesn't have a target, then we just need to get out of here. I'll |
370 | | // lldbassert and not make any of the compiler objects since |
371 | | // I can't return errors directly from the constructor. Further calls will |
372 | | // check if the compiler was made and |
373 | | // bag out if it wasn't. |
374 | | |
375 | 11.9k | if (!exe_scope) { |
376 | 0 | lldbassert(exe_scope && |
377 | 0 | "Can't make an expression parser with a null scope."); |
378 | 0 | return; |
379 | 0 | } |
380 | | |
381 | 11.9k | lldb::TargetSP target_sp; |
382 | 11.9k | target_sp = exe_scope->CalculateTarget(); |
383 | 11.9k | if (!target_sp) { |
384 | 0 | lldbassert(target_sp.get() && |
385 | 0 | "Can't make an expression parser with a null target."); |
386 | 0 | return; |
387 | 0 | } |
388 | | |
389 | | // 1. Create a new compiler instance. |
390 | 11.9k | m_compiler = std::make_unique<CompilerInstance>(); |
391 | | |
392 | | // Make sure clang uses the same VFS as LLDB. |
393 | 11.9k | m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem()); |
394 | | |
395 | 11.9k | lldb::LanguageType frame_lang = |
396 | 11.9k | expr.Language(); // defaults to lldb::eLanguageTypeUnknown |
397 | | |
398 | 11.9k | std::string abi; |
399 | 11.9k | ArchSpec target_arch; |
400 | 11.9k | target_arch = target_sp->GetArchitecture(); |
401 | | |
402 | 11.9k | const auto target_machine = target_arch.GetMachine(); |
403 | | |
404 | | // If the expression is being evaluated in the context of an existing stack |
405 | | // frame, we introspect to see if the language runtime is available. |
406 | | |
407 | 11.9k | lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame(); |
408 | 11.9k | lldb::ProcessSP process_sp = exe_scope->CalculateProcess(); |
409 | | |
410 | | // Make sure the user hasn't provided a preferred execution language with |
411 | | // `expression --language X -- ...` |
412 | 11.9k | if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown740 ) |
413 | 740 | frame_lang = frame_sp->GetLanguage(); |
414 | | |
415 | 11.9k | if (process_sp && frame_lang != lldb::eLanguageTypeUnknown11.6k ) { |
416 | 7.65k | LLDB_LOGF(log, "Frame has language of type %s", |
417 | 7.65k | Language::GetNameForLanguageType(frame_lang)); |
418 | 7.65k | } |
419 | | |
420 | | // 2. Configure the compiler with a set of default options that are |
421 | | // appropriate for most situations. |
422 | 11.9k | if (target_arch.IsValid()) { |
423 | 11.9k | std::string triple = target_arch.GetTriple().str(); |
424 | 11.9k | m_compiler->getTargetOpts().Triple = triple; |
425 | 11.9k | LLDB_LOGF(log, "Using %s as the target triple", |
426 | 11.9k | m_compiler->getTargetOpts().Triple.c_str()); |
427 | 11.9k | } else { |
428 | | // If we get here we don't have a valid target and just have to guess. |
429 | | // Sometimes this will be ok to just use the host target triple (when we |
430 | | // evaluate say "2+3", but other expressions like breakpoint conditions and |
431 | | // other things that _are_ target specific really shouldn't just be using |
432 | | // the host triple. In such a case the language runtime should expose an |
433 | | // overridden options set (3), below. |
434 | 0 | m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple(); |
435 | 0 | LLDB_LOGF(log, "Using default target triple of %s", |
436 | 0 | m_compiler->getTargetOpts().Triple.c_str()); |
437 | 0 | } |
438 | | // Now add some special fixes for known architectures: Any arm32 iOS |
439 | | // environment, but not on arm64 |
440 | 11.9k | if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos && |
441 | 11.9k | m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos && |
442 | 11.9k | m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos0 ) { |
443 | 0 | m_compiler->getTargetOpts().ABI = "apcs-gnu"; |
444 | 0 | } |
445 | | // Supported subsets of x86 |
446 | 11.9k | if (target_machine == llvm::Triple::x86 || |
447 | 11.9k | target_machine == llvm::Triple::x86_64) { |
448 | 11.9k | m_compiler->getTargetOpts().Features.push_back("+sse"); |
449 | 11.9k | m_compiler->getTargetOpts().Features.push_back("+sse2"); |
450 | 11.9k | } |
451 | | |
452 | | // Set the target CPU to generate code for. This will be empty for any CPU |
453 | | // that doesn't really need to make a special |
454 | | // CPU string. |
455 | 11.9k | m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU(); |
456 | | |
457 | | // Set the target ABI |
458 | 11.9k | abi = GetClangTargetABI(target_arch); |
459 | 11.9k | if (!abi.empty()) |
460 | 0 | m_compiler->getTargetOpts().ABI = abi; |
461 | | |
462 | | // 3. Create and install the target on the compiler. |
463 | 11.9k | m_compiler->createDiagnostics(); |
464 | | // Limit the number of error diagnostics we emit. |
465 | | // A value of 0 means no limit for both LLDB and Clang. |
466 | 11.9k | m_compiler->getDiagnostics().setErrorLimit(target_sp->GetExprErrorLimit()); |
467 | | |
468 | 11.9k | auto target_info = TargetInfo::CreateTargetInfo( |
469 | 11.9k | m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts); |
470 | 11.9k | if (log) { |
471 | 28 | LLDB_LOGF(log, "Target datalayout string: '%s'", |
472 | 28 | target_info->getDataLayoutString()); |
473 | 28 | LLDB_LOGF(log, "Target ABI: '%s'", target_info->getABI().str().c_str()); |
474 | 28 | LLDB_LOGF(log, "Target vector alignment: %d", |
475 | 28 | target_info->getMaxVectorAlign()); |
476 | 28 | } |
477 | 11.9k | m_compiler->setTarget(target_info); |
478 | | |
479 | 11.9k | assert(m_compiler->hasTarget()); |
480 | | |
481 | | // 4. Set language options. |
482 | 11.9k | lldb::LanguageType language = expr.Language(); |
483 | 11.9k | LangOptions &lang_opts = m_compiler->getLangOpts(); |
484 | | |
485 | 11.9k | switch (language) { |
486 | 5 | case lldb::eLanguageTypeC: |
487 | 5 | case lldb::eLanguageTypeC89: |
488 | 65 | case lldb::eLanguageTypeC99: |
489 | 698 | case lldb::eLanguageTypeC11: |
490 | | // FIXME: the following language option is a temporary workaround, |
491 | | // to "ask for C, get C++." |
492 | | // For now, the expression parser must use C++ anytime the language is a C |
493 | | // family language, because the expression parser uses features of C++ to |
494 | | // capture values. |
495 | 698 | lang_opts.CPlusPlus = true; |
496 | 698 | break; |
497 | 470 | case lldb::eLanguageTypeObjC: |
498 | 470 | lang_opts.ObjC = true; |
499 | | // FIXME: the following language option is a temporary workaround, |
500 | | // to "ask for ObjC, get ObjC++" (see comment above). |
501 | 470 | lang_opts.CPlusPlus = true; |
502 | | |
503 | | // Clang now sets as default C++14 as the default standard (with |
504 | | // GNU extensions), so we do the same here to avoid mismatches that |
505 | | // cause compiler error when evaluating expressions (e.g. nullptr not found |
506 | | // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see |
507 | | // two lines below) so we decide to be consistent with that, but this could |
508 | | // be re-evaluated in the future. |
509 | 470 | lang_opts.CPlusPlus11 = true; |
510 | 470 | break; |
511 | 2 | case lldb::eLanguageTypeC_plus_plus_20: |
512 | 2 | lang_opts.CPlusPlus20 = true; |
513 | 2 | [[fallthrough]]; |
514 | 2 | case lldb::eLanguageTypeC_plus_plus_17: |
515 | | // FIXME: add a separate case for CPlusPlus14. Currently folded into C++17 |
516 | | // because C++14 is the default standard for Clang but enabling CPlusPlus14 |
517 | | // expression evaluatino doesn't pass the test-suite cleanly. |
518 | 2 | lang_opts.CPlusPlus14 = true; |
519 | 2 | lang_opts.CPlusPlus17 = true; |
520 | 2 | [[fallthrough]]; |
521 | 62 | case lldb::eLanguageTypeC_plus_plus: |
522 | 5.46k | case lldb::eLanguageTypeC_plus_plus_11: |
523 | 5.70k | case lldb::eLanguageTypeC_plus_plus_14: |
524 | 5.70k | lang_opts.CPlusPlus11 = true; |
525 | 5.70k | m_compiler->getHeaderSearchOpts().UseLibcxx = true; |
526 | 5.70k | [[fallthrough]]; |
527 | 5.70k | case lldb::eLanguageTypeC_plus_plus_03: |
528 | 5.70k | lang_opts.CPlusPlus = true; |
529 | 5.70k | if (process_sp) |
530 | 5.69k | lang_opts.ObjC = |
531 | 5.69k | process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr; |
532 | 5.70k | break; |
533 | 59 | case lldb::eLanguageTypeObjC_plus_plus: |
534 | 5.07k | case lldb::eLanguageTypeUnknown: |
535 | 5.07k | default: |
536 | 5.07k | lang_opts.ObjC = true; |
537 | 5.07k | lang_opts.CPlusPlus = true; |
538 | 5.07k | lang_opts.CPlusPlus11 = true; |
539 | 5.07k | m_compiler->getHeaderSearchOpts().UseLibcxx = true; |
540 | 5.07k | break; |
541 | 11.9k | } |
542 | | |
543 | 11.9k | lang_opts.Bool = true; |
544 | 11.9k | lang_opts.WChar = true; |
545 | 11.9k | lang_opts.Blocks = true; |
546 | 11.9k | lang_opts.DebuggerSupport = |
547 | 11.9k | true; // Features specifically for debugger clients |
548 | 11.9k | if (expr.DesiredResultType() == Expression::eResultTypeId) |
549 | 77 | lang_opts.DebuggerCastResultToId = true; |
550 | | |
551 | 11.9k | lang_opts.CharIsSigned = ArchSpec(m_compiler->getTargetOpts().Triple.c_str()) |
552 | 11.9k | .CharIsSignedByDefault(); |
553 | | |
554 | | // Spell checking is a nice feature, but it ends up completing a lot of types |
555 | | // that we didn't strictly speaking need to complete. As a result, we spend a |
556 | | // long time parsing and importing debug information. |
557 | 11.9k | lang_opts.SpellChecking = false; |
558 | | |
559 | 11.9k | auto *clang_expr = dyn_cast<ClangUserExpression>(&m_expr); |
560 | 11.9k | if (clang_expr && clang_expr->DidImportCxxModules()7.27k ) { |
561 | 354 | LLDB_LOG(log, "Adding lang options for importing C++ modules"); |
562 | | |
563 | 354 | lang_opts.Modules = true; |
564 | | // We want to implicitly build modules. |
565 | 354 | lang_opts.ImplicitModules = true; |
566 | | // To automatically import all submodules when we import 'std'. |
567 | 354 | lang_opts.ModulesLocalVisibility = false; |
568 | | |
569 | | // We use the @import statements, so we need this: |
570 | | // FIXME: We could use the modules-ts, but that currently doesn't work. |
571 | 354 | lang_opts.ObjC = true; |
572 | | |
573 | | // Options we need to parse libc++ code successfully. |
574 | | // FIXME: We should ask the driver for the appropriate default flags. |
575 | 354 | lang_opts.GNUMode = true; |
576 | 354 | lang_opts.GNUKeywords = true; |
577 | 354 | lang_opts.CPlusPlus11 = true; |
578 | 354 | lang_opts.BuiltinHeadersInSystemModules = true; |
579 | | |
580 | | // The Darwin libc expects this macro to be set. |
581 | 354 | lang_opts.GNUCVersion = 40201; |
582 | | |
583 | 354 | SetupModuleHeaderPaths(m_compiler.get(), m_include_directories, |
584 | 354 | target_sp); |
585 | 354 | } |
586 | | |
587 | 11.9k | if (process_sp && lang_opts.ObjC11.6k ) { |
588 | 10.9k | if (auto *runtime = ObjCLanguageRuntime::Get(*process_sp)) { |
589 | 10.9k | switch (runtime->GetRuntimeVersion()) { |
590 | 10.9k | case ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2: |
591 | 10.9k | lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7)); |
592 | 10.9k | break; |
593 | 0 | case ObjCLanguageRuntime::ObjCRuntimeVersions::eObjC_VersionUnknown: |
594 | 0 | case ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V1: |
595 | 0 | lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX, |
596 | 0 | VersionTuple(10, 7)); |
597 | 0 | break; |
598 | 0 | case ObjCLanguageRuntime::ObjCRuntimeVersions::eGNUstep_libobjc2: |
599 | 0 | lang_opts.ObjCRuntime.set(ObjCRuntime::GNUstep, VersionTuple(2, 0)); |
600 | 0 | break; |
601 | 10.9k | } |
602 | | |
603 | 10.9k | if (runtime->HasNewLiteralsAndIndexing()) |
604 | 1.53k | lang_opts.DebuggerObjCLiteral = true; |
605 | 10.9k | } |
606 | 10.9k | } |
607 | | |
608 | 11.9k | lang_opts.ThreadsafeStatics = false; |
609 | 11.9k | lang_opts.AccessControl = false; // Debuggers get universal access |
610 | 11.9k | lang_opts.DollarIdents = true; // $ indicates a persistent variable name |
611 | | // We enable all builtin functions beside the builtins from libc/libm (e.g. |
612 | | // 'fopen'). Those libc functions are already correctly handled by LLDB, and |
613 | | // additionally enabling them as expandable builtins is breaking Clang. |
614 | 11.9k | lang_opts.NoBuiltin = true; |
615 | | |
616 | | // Set CodeGen options |
617 | 11.9k | m_compiler->getCodeGenOpts().EmitDeclMetadata = true; |
618 | 11.9k | m_compiler->getCodeGenOpts().InstrumentFunctions = false; |
619 | 11.9k | m_compiler->getCodeGenOpts().setFramePointer( |
620 | 11.9k | CodeGenOptions::FramePointerKind::All); |
621 | 11.9k | if (generate_debug_info) |
622 | 4.67k | m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo); |
623 | 7.27k | else |
624 | 7.27k | m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo); |
625 | | |
626 | | // Disable some warnings. |
627 | 11.9k | SetupDefaultClangDiagnostics(*m_compiler); |
628 | | |
629 | | // Inform the target of the language options |
630 | | // |
631 | | // FIXME: We shouldn't need to do this, the target should be immutable once |
632 | | // created. This complexity should be lifted elsewhere. |
633 | 11.9k | m_compiler->getTarget().adjust(m_compiler->getDiagnostics(), |
634 | 11.9k | m_compiler->getLangOpts()); |
635 | | |
636 | | // 5. Set up the diagnostic buffer for reporting errors |
637 | | |
638 | 11.9k | auto diag_mgr = new ClangDiagnosticManagerAdapter( |
639 | 11.9k | m_compiler->getDiagnostics().getDiagnosticOptions()); |
640 | 11.9k | m_compiler->getDiagnostics().setClient(diag_mgr); |
641 | | |
642 | | // 6. Set up the source management objects inside the compiler |
643 | 11.9k | m_compiler->createFileManager(); |
644 | 11.9k | if (!m_compiler->hasSourceManager()) |
645 | 11.9k | m_compiler->createSourceManager(m_compiler->getFileManager()); |
646 | 11.9k | m_compiler->createPreprocessor(TU_Complete); |
647 | | |
648 | 11.9k | switch (language) { |
649 | 5 | case lldb::eLanguageTypeC: |
650 | 5 | case lldb::eLanguageTypeC89: |
651 | 65 | case lldb::eLanguageTypeC99: |
652 | 698 | case lldb::eLanguageTypeC11: |
653 | 1.16k | case lldb::eLanguageTypeObjC: |
654 | | // This is not a C++ expression but we enabled C++ as explained above. |
655 | | // Remove all C++ keywords from the PP so that the user can still use |
656 | | // variables that have C++ keywords as names (e.g. 'int template;'). |
657 | 1.16k | RemoveAllCppKeywords(m_compiler->getPreprocessor().getIdentifierTable()); |
658 | 1.16k | break; |
659 | 10.7k | default: |
660 | 10.7k | break; |
661 | 11.9k | } |
662 | | |
663 | 11.9k | if (auto *clang_persistent_vars = llvm::cast<ClangPersistentVariables>( |
664 | 11.9k | target_sp->GetPersistentExpressionStateForLanguage( |
665 | 11.9k | lldb::eLanguageTypeC))) { |
666 | 11.9k | if (std::shared_ptr<ClangModulesDeclVendor> decl_vendor = |
667 | 11.9k | clang_persistent_vars->GetClangModulesDeclVendor()) { |
668 | 11.9k | std::unique_ptr<PPCallbacks> pp_callbacks( |
669 | 11.9k | new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars, |
670 | 11.9k | m_compiler->getSourceManager())); |
671 | 11.9k | m_pp_callbacks = |
672 | 11.9k | static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get()); |
673 | 11.9k | m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks)); |
674 | 11.9k | } |
675 | 11.9k | } |
676 | | |
677 | | // 7. Most of this we get from the CompilerInstance, but we also want to give |
678 | | // the context an ExternalASTSource. |
679 | | |
680 | 11.9k | auto &PP = m_compiler->getPreprocessor(); |
681 | 11.9k | auto &builtin_context = PP.getBuiltinInfo(); |
682 | 11.9k | builtin_context.initializeBuiltins(PP.getIdentifierTable(), |
683 | 11.9k | m_compiler->getLangOpts()); |
684 | | |
685 | 11.9k | m_compiler->createASTContext(); |
686 | 11.9k | clang::ASTContext &ast_context = m_compiler->getASTContext(); |
687 | | |
688 | 11.9k | m_ast_context = std::make_shared<TypeSystemClang>( |
689 | 11.9k | "Expression ASTContext for '" + m_filename + "'", ast_context); |
690 | | |
691 | 11.9k | std::string module_name("$__lldb_module"); |
692 | | |
693 | 11.9k | m_llvm_context = std::make_unique<LLVMContext>(); |
694 | 11.9k | m_code_generator.reset(CreateLLVMCodeGen( |
695 | 11.9k | m_compiler->getDiagnostics(), module_name, |
696 | 11.9k | &m_compiler->getVirtualFileSystem(), m_compiler->getHeaderSearchOpts(), |
697 | 11.9k | m_compiler->getPreprocessorOpts(), m_compiler->getCodeGenOpts(), |
698 | 11.9k | *m_llvm_context)); |
699 | 11.9k | } |
700 | | |
701 | 11.9k | ClangExpressionParser::~ClangExpressionParser() = default; |
702 | | |
703 | | namespace { |
704 | | |
705 | | /// \class CodeComplete |
706 | | /// |
707 | | /// A code completion consumer for the clang Sema that is responsible for |
708 | | /// creating the completion suggestions when a user requests completion |
709 | | /// of an incomplete `expr` invocation. |
710 | | class CodeComplete : public CodeCompleteConsumer { |
711 | | CodeCompletionTUInfo m_info; |
712 | | |
713 | | std::string m_expr; |
714 | | unsigned m_position = 0; |
715 | | /// The printing policy we use when printing declarations for our completion |
716 | | /// descriptions. |
717 | | clang::PrintingPolicy m_desc_policy; |
718 | | |
719 | | struct CompletionWithPriority { |
720 | | CompletionResult::Completion completion; |
721 | | /// See CodeCompletionResult::Priority; |
722 | | unsigned Priority; |
723 | | |
724 | | /// Establishes a deterministic order in a list of CompletionWithPriority. |
725 | | /// The order returned here is the order in which the completions are |
726 | | /// displayed to the user. |
727 | 2.67k | bool operator<(const CompletionWithPriority &o) const { |
728 | | // High priority results should come first. |
729 | 2.67k | if (Priority != o.Priority) |
730 | 684 | return Priority > o.Priority; |
731 | | |
732 | | // Identical priority, so just make sure it's a deterministic order. |
733 | 1.99k | return completion.GetUniqueKey() < o.completion.GetUniqueKey(); |
734 | 2.67k | } |
735 | | }; |
736 | | |
737 | | /// The stored completions. |
738 | | /// Warning: These are in a non-deterministic order until they are sorted |
739 | | /// and returned back to the caller. |
740 | | std::vector<CompletionWithPriority> m_completions; |
741 | | |
742 | | /// Returns true if the given character can be used in an identifier. |
743 | | /// This also returns true for numbers because for completion we usually |
744 | | /// just iterate backwards over iterators. |
745 | | /// |
746 | | /// Note: lldb uses '$' in its internal identifiers, so we also allow this. |
747 | 780 | static bool IsIdChar(char c) { |
748 | 780 | return c == '_' || std::isalnum(c)775 || c == '$'253 ; |
749 | 780 | } |
750 | | |
751 | | /// Returns true if the given character is used to separate arguments |
752 | | /// in the command line of lldb. |
753 | 992 | static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'872 ; } |
754 | | |
755 | | /// Drops all tokens in front of the expression that are unrelated for |
756 | | /// the completion of the cmd line. 'unrelated' means here that the token |
757 | | /// is not interested for the lldb completion API result. |
758 | 458 | StringRef dropUnrelatedFrontTokens(StringRef cmd) const { |
759 | 458 | if (cmd.empty()) |
760 | 205 | return cmd; |
761 | | |
762 | | // If we are at the start of a word, then all tokens are unrelated to |
763 | | // the current completion logic. |
764 | 253 | if (IsTokenSeparator(cmd.back())) |
765 | 104 | return StringRef(); |
766 | | |
767 | | // Remove all previous tokens from the string as they are unrelated |
768 | | // to completing the current token. |
769 | 149 | StringRef to_remove = cmd; |
770 | 872 | while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())739 ) { |
771 | 723 | to_remove = to_remove.drop_back(); |
772 | 723 | } |
773 | 149 | cmd = cmd.drop_front(to_remove.size()); |
774 | | |
775 | 149 | return cmd; |
776 | 253 | } |
777 | | |
778 | | /// Removes the last identifier token from the given cmd line. |
779 | 458 | StringRef removeLastToken(StringRef cmd) const { |
780 | 985 | while (!cmd.empty() && IsIdChar(cmd.back())780 ) { |
781 | 527 | cmd = cmd.drop_back(); |
782 | 527 | } |
783 | 458 | return cmd; |
784 | 458 | } |
785 | | |
786 | | /// Attempts to merge the given completion from the given position into the |
787 | | /// existing command. Returns the completion string that can be returned to |
788 | | /// the lldb completion API. |
789 | | std::string mergeCompletion(StringRef existing, unsigned pos, |
790 | 458 | StringRef completion) const { |
791 | 458 | StringRef existing_command = existing.substr(0, pos); |
792 | | // We rewrite the last token with the completion, so let's drop that |
793 | | // token from the command. |
794 | 458 | existing_command = removeLastToken(existing_command); |
795 | | // We also should remove all previous tokens from the command as they |
796 | | // would otherwise be added to the completion that already has the |
797 | | // completion. |
798 | 458 | existing_command = dropUnrelatedFrontTokens(existing_command); |
799 | 458 | return existing_command.str() + completion.str(); |
800 | 458 | } |
801 | | |
802 | | public: |
803 | | /// Constructs a CodeComplete consumer that can be attached to a Sema. |
804 | | /// |
805 | | /// \param[out] expr |
806 | | /// The whole expression string that we are currently parsing. This |
807 | | /// string needs to be equal to the input the user typed, and NOT the |
808 | | /// final code that Clang is parsing. |
809 | | /// \param[out] position |
810 | | /// The character position of the user cursor in the `expr` parameter. |
811 | | /// |
812 | | CodeComplete(clang::LangOptions ops, std::string expr, unsigned position) |
813 | 53 | : CodeCompleteConsumer(CodeCompleteOptions()), |
814 | 53 | m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr), |
815 | 53 | m_position(position), m_desc_policy(ops) { |
816 | | |
817 | | // Ensure that the printing policy is producing a description that is as |
818 | | // short as possible. |
819 | 53 | m_desc_policy.SuppressScope = true; |
820 | 53 | m_desc_policy.SuppressTagKeyword = true; |
821 | 53 | m_desc_policy.FullyQualifiedName = false; |
822 | 53 | m_desc_policy.TerseOutput = true; |
823 | 53 | m_desc_policy.IncludeNewlines = false; |
824 | 53 | m_desc_policy.UseVoidForZeroParams = false; |
825 | 53 | m_desc_policy.Bool = true; |
826 | 53 | } |
827 | | |
828 | | /// \name Code-completion filtering |
829 | | /// Check if the result should be filtered out. |
830 | | bool isResultFilteredOut(StringRef Filter, |
831 | 1.57k | CodeCompletionResult Result) override { |
832 | | // This code is mostly copied from CodeCompleteConsumer. |
833 | 1.57k | switch (Result.Kind) { |
834 | 829 | case CodeCompletionResult::RK_Declaration: |
835 | 829 | return !( |
836 | 829 | Result.Declaration->getIdentifier() && |
837 | 829 | Result.Declaration->getIdentifier()->getName().startswith(Filter)733 ); |
838 | 367 | case CodeCompletionResult::RK_Keyword: |
839 | 367 | return !StringRef(Result.Keyword).startswith(Filter); |
840 | 0 | case CodeCompletionResult::RK_Macro: |
841 | 0 | return !Result.Macro->getName().startswith(Filter); |
842 | 383 | case CodeCompletionResult::RK_Pattern: |
843 | 383 | return !StringRef(Result.Pattern->getAsString()).startswith(Filter); |
844 | 1.57k | } |
845 | | // If we trigger this assert or the above switch yields a warning, then |
846 | | // CodeCompletionResult has been enhanced with more kinds of completion |
847 | | // results. Expand the switch above in this case. |
848 | 0 | assert(false && "Unknown completion result type?"); |
849 | | // If we reach this, then we should just ignore whatever kind of unknown |
850 | | // result we got back. We probably can't turn it into any kind of useful |
851 | | // completion suggestion with the existing code. |
852 | 0 | return true; |
853 | 0 | } |
854 | | |
855 | | private: |
856 | | /// Generate the completion strings for the given CodeCompletionResult. |
857 | | /// Note that this function has to process results that could come in |
858 | | /// non-deterministic order, so this function should have no side effects. |
859 | | /// To make this easier to enforce, this function and all its parameters |
860 | | /// should always be const-qualified. |
861 | | /// \return Returns std::nullopt if no completion should be provided for the |
862 | | /// given CodeCompletionResult. |
863 | | std::optional<CompletionWithPriority> |
864 | 466 | getCompletionForResult(const CodeCompletionResult &R) const { |
865 | 466 | std::string ToInsert; |
866 | 466 | std::string Description; |
867 | | // Handle the different completion kinds that come from the Sema. |
868 | 466 | switch (R.Kind) { |
869 | 225 | case CodeCompletionResult::RK_Declaration: { |
870 | 225 | const NamedDecl *D = R.Declaration; |
871 | 225 | ToInsert = R.Declaration->getNameAsString(); |
872 | | // If we have a function decl that has no arguments we want to |
873 | | // complete the empty parantheses for the user. If the function has |
874 | | // arguments, we at least complete the opening bracket. |
875 | 225 | if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) { |
876 | 61 | if (F->getNumParams() == 0) |
877 | 41 | ToInsert += "()"; |
878 | 20 | else |
879 | 20 | ToInsert += "("; |
880 | 61 | raw_string_ostream OS(Description); |
881 | 61 | F->print(OS, m_desc_policy, false); |
882 | 61 | OS.flush(); |
883 | 164 | } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) { |
884 | 68 | Description = V->getType().getAsString(m_desc_policy); |
885 | 96 | } else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) { |
886 | 5 | Description = F->getType().getAsString(m_desc_policy); |
887 | 91 | } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) { |
888 | | // If we try to complete a namespace, then we can directly append |
889 | | // the '::'. |
890 | 5 | if (!N->isAnonymousNamespace()) |
891 | 5 | ToInsert += "::"; |
892 | 5 | } |
893 | 225 | break; |
894 | 0 | } |
895 | 116 | case CodeCompletionResult::RK_Keyword: |
896 | 116 | ToInsert = R.Keyword; |
897 | 116 | break; |
898 | 0 | case CodeCompletionResult::RK_Macro: |
899 | 0 | ToInsert = R.Macro->getName().str(); |
900 | 0 | break; |
901 | 125 | case CodeCompletionResult::RK_Pattern: |
902 | 125 | ToInsert = R.Pattern->getTypedText(); |
903 | 125 | break; |
904 | 466 | } |
905 | | // We also filter some internal lldb identifiers here. The user |
906 | | // shouldn't see these. |
907 | 466 | if (llvm::StringRef(ToInsert).startswith("$__lldb_")) |
908 | 8 | return std::nullopt; |
909 | 458 | if (ToInsert.empty()) |
910 | 0 | return std::nullopt; |
911 | | // Merge the suggested Token into the existing command line to comply |
912 | | // with the kind of result the lldb API expects. |
913 | 458 | std::string CompletionSuggestion = |
914 | 458 | mergeCompletion(m_expr, m_position, ToInsert); |
915 | | |
916 | 458 | CompletionResult::Completion completion(CompletionSuggestion, Description, |
917 | 458 | CompletionMode::Normal); |
918 | 458 | return {{completion, R.Priority}}; |
919 | 458 | } |
920 | | |
921 | | public: |
922 | | /// Adds the completions to the given CompletionRequest. |
923 | 53 | void GetCompletions(CompletionRequest &request) { |
924 | | // Bring m_completions into a deterministic order and pass it on to the |
925 | | // CompletionRequest. |
926 | 53 | llvm::sort(m_completions); |
927 | | |
928 | 53 | for (const CompletionWithPriority &C : m_completions) |
929 | 458 | request.AddCompletion(C.completion.GetCompletion(), |
930 | 458 | C.completion.GetDescription(), |
931 | 458 | C.completion.GetMode()); |
932 | 53 | } |
933 | | |
934 | | /// \name Code-completion callbacks |
935 | | /// Process the finalized code-completion results. |
936 | | void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context, |
937 | | CodeCompletionResult *Results, |
938 | 53 | unsigned NumResults) override { |
939 | | |
940 | | // The Sema put the incomplete token we try to complete in here during |
941 | | // lexing, so we need to retrieve it here to know what we are completing. |
942 | 53 | StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter(); |
943 | | |
944 | | // Iterate over all the results. Filter out results we don't want and |
945 | | // process the rest. |
946 | 2.04k | for (unsigned I = 0; I != NumResults; ++I1.98k ) { |
947 | | // Filter the results with the information from the Sema. |
948 | 1.98k | if (!Filter.empty() && isResultFilteredOut(Filter, Results[I])1.57k ) |
949 | 1.52k | continue; |
950 | | |
951 | 466 | CodeCompletionResult &R = Results[I]; |
952 | 466 | std::optional<CompletionWithPriority> CompletionAndPriority = |
953 | 466 | getCompletionForResult(R); |
954 | 466 | if (!CompletionAndPriority) |
955 | 8 | continue; |
956 | 458 | m_completions.push_back(*CompletionAndPriority); |
957 | 458 | } |
958 | 53 | } |
959 | | |
960 | | /// \param S the semantic-analyzer object for which code-completion is being |
961 | | /// done. |
962 | | /// |
963 | | /// \param CurrentArg the index of the current argument. |
964 | | /// |
965 | | /// \param Candidates an array of overload candidates. |
966 | | /// |
967 | | /// \param NumCandidates the number of overload candidates |
968 | | void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, |
969 | | OverloadCandidate *Candidates, |
970 | | unsigned NumCandidates, |
971 | | SourceLocation OpenParLoc, |
972 | 3 | bool Braced) override { |
973 | | // At the moment we don't filter out any overloaded candidates. |
974 | 3 | } |
975 | | |
976 | 52 | CodeCompletionAllocator &getAllocator() override { |
977 | 52 | return m_info.getAllocator(); |
978 | 52 | } |
979 | | |
980 | 52 | CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; } |
981 | | }; |
982 | | } // namespace |
983 | | |
984 | | bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line, |
985 | 53 | unsigned pos, unsigned typed_pos) { |
986 | 53 | DiagnosticManager mgr; |
987 | | // We need the raw user expression here because that's what the CodeComplete |
988 | | // class uses to provide completion suggestions. |
989 | | // However, the `Text` method only gives us the transformed expression here. |
990 | | // To actually get the raw user input here, we have to cast our expression to |
991 | | // the LLVMUserExpression which exposes the right API. This should never fail |
992 | | // as we always have a ClangUserExpression whenever we call this. |
993 | 53 | ClangUserExpression *llvm_expr = cast<ClangUserExpression>(&m_expr); |
994 | 53 | CodeComplete CC(m_compiler->getLangOpts(), llvm_expr->GetUserText(), |
995 | 53 | typed_pos); |
996 | | // We don't need a code generator for parsing. |
997 | 53 | m_code_generator.reset(); |
998 | | // Start parsing the expression with our custom code completion consumer. |
999 | 53 | ParseInternal(mgr, &CC, line, pos); |
1000 | 53 | CC.GetCompletions(request); |
1001 | 53 | return true; |
1002 | 53 | } |
1003 | | |
1004 | 11.8k | unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) { |
1005 | 11.8k | return ParseInternal(diagnostic_manager); |
1006 | 11.8k | } |
1007 | | |
1008 | | unsigned |
1009 | | ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager, |
1010 | | CodeCompleteConsumer *completion_consumer, |
1011 | | unsigned completion_line, |
1012 | 11.9k | unsigned completion_column) { |
1013 | 11.9k | ClangDiagnosticManagerAdapter *adapter = |
1014 | 11.9k | static_cast<ClangDiagnosticManagerAdapter *>( |
1015 | 11.9k | m_compiler->getDiagnostics().getClient()); |
1016 | | |
1017 | 11.9k | adapter->ResetManager(&diagnostic_manager); |
1018 | | |
1019 | 11.9k | const char *expr_text = m_expr.Text(); |
1020 | | |
1021 | 11.9k | clang::SourceManager &source_mgr = m_compiler->getSourceManager(); |
1022 | 11.9k | bool created_main_file = false; |
1023 | | |
1024 | | // Clang wants to do completion on a real file known by Clang's file manager, |
1025 | | // so we have to create one to make this work. |
1026 | | // TODO: We probably could also simulate to Clang's file manager that there |
1027 | | // is a real file that contains our code. |
1028 | 11.9k | bool should_create_file = completion_consumer != nullptr; |
1029 | | |
1030 | | // We also want a real file on disk if we generate full debug info. |
1031 | 11.9k | should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() == |
1032 | 11.9k | codegenoptions::FullDebugInfo; |
1033 | | |
1034 | 11.9k | if (should_create_file) { |
1035 | 4.72k | int temp_fd = -1; |
1036 | 4.72k | llvm::SmallString<128> result_path; |
1037 | 4.72k | if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) { |
1038 | 4.72k | tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr"); |
1039 | 4.72k | std::string temp_source_path = tmpdir_file_spec.GetPath(); |
1040 | 4.72k | llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path); |
1041 | 4.72k | } else { |
1042 | 0 | llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path); |
1043 | 0 | } |
1044 | | |
1045 | 4.72k | if (temp_fd != -1) { |
1046 | 4.72k | lldb_private::NativeFile file(temp_fd, File::eOpenOptionWriteOnly, true); |
1047 | 4.72k | const size_t expr_text_len = strlen(expr_text); |
1048 | 4.72k | size_t bytes_written = expr_text_len; |
1049 | 4.72k | if (file.Write(expr_text, bytes_written).Success()) { |
1050 | 4.72k | if (bytes_written == expr_text_len) { |
1051 | 4.72k | file.Close(); |
1052 | 4.72k | if (auto fileEntry = m_compiler->getFileManager().getOptionalFileRef( |
1053 | 4.72k | result_path)) { |
1054 | 4.72k | source_mgr.setMainFileID(source_mgr.createFileID( |
1055 | 4.72k | *fileEntry, |
1056 | 4.72k | SourceLocation(), SrcMgr::C_User)); |
1057 | 4.72k | created_main_file = true; |
1058 | 4.72k | } |
1059 | 4.72k | } |
1060 | 4.72k | } |
1061 | 4.72k | } |
1062 | 4.72k | } |
1063 | | |
1064 | 11.9k | if (!created_main_file) { |
1065 | 7.22k | std::unique_ptr<MemoryBuffer> memory_buffer = |
1066 | 7.22k | MemoryBuffer::getMemBufferCopy(expr_text, m_filename); |
1067 | 7.22k | source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer))); |
1068 | 7.22k | } |
1069 | | |
1070 | 11.9k | adapter->BeginSourceFile(m_compiler->getLangOpts(), |
1071 | 11.9k | &m_compiler->getPreprocessor()); |
1072 | | |
1073 | 11.9k | ClangExpressionHelper *type_system_helper = |
1074 | 11.9k | dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); |
1075 | | |
1076 | | // If we want to parse for code completion, we need to attach our code |
1077 | | // completion consumer to the Sema and specify a completion position. |
1078 | | // While parsing the Sema will call this consumer with the provided |
1079 | | // completion suggestions. |
1080 | 11.9k | if (completion_consumer) { |
1081 | 53 | auto main_file = |
1082 | 53 | source_mgr.getFileEntryRefForID(source_mgr.getMainFileID()); |
1083 | 53 | auto &PP = m_compiler->getPreprocessor(); |
1084 | | // Lines and columns start at 1 in Clang, but code completion positions are |
1085 | | // indexed from 0, so we need to add 1 to the line and column here. |
1086 | 53 | ++completion_line; |
1087 | 53 | ++completion_column; |
1088 | 53 | PP.SetCodeCompletionPoint(*main_file, completion_line, completion_column); |
1089 | 53 | } |
1090 | | |
1091 | 11.9k | ASTConsumer *ast_transformer = |
1092 | 11.9k | type_system_helper->ASTTransformer(m_code_generator.get()); |
1093 | | |
1094 | 11.9k | std::unique_ptr<clang::ASTConsumer> Consumer; |
1095 | 11.9k | if (ast_transformer) { |
1096 | 9.28k | Consumer = std::make_unique<ASTConsumerForwarder>(ast_transformer); |
1097 | 9.28k | } else if (2.66k m_code_generator2.66k ) { |
1098 | 2.66k | Consumer = std::make_unique<ASTConsumerForwarder>(m_code_generator.get()); |
1099 | 2.66k | } else { |
1100 | 0 | Consumer = std::make_unique<ASTConsumer>(); |
1101 | 0 | } |
1102 | | |
1103 | 11.9k | clang::ASTContext &ast_context = m_compiler->getASTContext(); |
1104 | | |
1105 | 11.9k | m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context, |
1106 | 11.9k | *Consumer, TU_Complete, completion_consumer)); |
1107 | 11.9k | m_compiler->setASTConsumer(std::move(Consumer)); |
1108 | | |
1109 | 11.9k | if (ast_context.getLangOpts().Modules) { |
1110 | 354 | m_compiler->createASTReader(); |
1111 | 354 | m_ast_context->setSema(&m_compiler->getSema()); |
1112 | 354 | } |
1113 | | |
1114 | 11.9k | ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap(); |
1115 | 11.9k | if (decl_map) { |
1116 | 9.94k | decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer()); |
1117 | 9.94k | decl_map->InstallDiagnosticManager(diagnostic_manager); |
1118 | | |
1119 | 9.94k | clang::ExternalASTSource *ast_source = decl_map->CreateProxy(); |
1120 | | |
1121 | 9.94k | if (ast_context.getExternalSource()) { |
1122 | 354 | auto module_wrapper = |
1123 | 354 | new ExternalASTSourceWrapper(ast_context.getExternalSource()); |
1124 | | |
1125 | 354 | auto ast_source_wrapper = new ExternalASTSourceWrapper(ast_source); |
1126 | | |
1127 | 354 | auto multiplexer = |
1128 | 354 | new SemaSourceWithPriorities(*module_wrapper, *ast_source_wrapper); |
1129 | 354 | IntrusiveRefCntPtr<ExternalASTSource> Source(multiplexer); |
1130 | 354 | ast_context.setExternalSource(Source); |
1131 | 9.58k | } else { |
1132 | 9.58k | ast_context.setExternalSource(ast_source); |
1133 | 9.58k | } |
1134 | 9.94k | decl_map->InstallASTContext(*m_ast_context); |
1135 | 9.94k | } |
1136 | | |
1137 | | // Check that the ASTReader is properly attached to ASTContext and Sema. |
1138 | 11.9k | if (ast_context.getLangOpts().Modules) { |
1139 | 354 | assert(m_compiler->getASTContext().getExternalSource() && |
1140 | 354 | "ASTContext doesn't know about the ASTReader?"); |
1141 | 354 | assert(m_compiler->getSema().getExternalSource() && |
1142 | 354 | "Sema doesn't know about the ASTReader?"); |
1143 | 354 | } |
1144 | | |
1145 | 11.9k | { |
1146 | 11.9k | llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema( |
1147 | 11.9k | &m_compiler->getSema()); |
1148 | 11.9k | ParseAST(m_compiler->getSema(), false, false); |
1149 | 11.9k | } |
1150 | | |
1151 | | // Make sure we have no pointer to the Sema we are about to destroy. |
1152 | 11.9k | if (ast_context.getLangOpts().Modules) |
1153 | 354 | m_ast_context->setSema(nullptr); |
1154 | | // Destroy the Sema. This is necessary because we want to emulate the |
1155 | | // original behavior of ParseAST (which also destroys the Sema after parsing). |
1156 | 11.9k | m_compiler->setSema(nullptr); |
1157 | | |
1158 | 11.9k | adapter->EndSourceFile(); |
1159 | | |
1160 | 11.9k | unsigned num_errors = adapter->getNumErrors(); |
1161 | | |
1162 | 11.9k | if (m_pp_callbacks && m_pp_callbacks->hasErrors()11.9k ) { |
1163 | 6 | num_errors++; |
1164 | 6 | diagnostic_manager.PutString(eDiagnosticSeverityError, |
1165 | 6 | "while importing modules:"); |
1166 | 6 | diagnostic_manager.AppendMessageToDiagnostic( |
1167 | 6 | m_pp_callbacks->getErrorString()); |
1168 | 6 | } |
1169 | | |
1170 | 11.9k | if (!num_errors) { |
1171 | 11.6k | type_system_helper->CommitPersistentDecls(); |
1172 | 11.6k | } |
1173 | | |
1174 | 11.9k | adapter->ResetManager(); |
1175 | | |
1176 | 11.9k | return num_errors; |
1177 | 11.9k | } |
1178 | | |
1179 | | std::string |
1180 | 11.9k | ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) { |
1181 | 11.9k | std::string abi; |
1182 | | |
1183 | 11.9k | if (target_arch.IsMIPS()) { |
1184 | 0 | switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) { |
1185 | 0 | case ArchSpec::eMIPSABI_N64: |
1186 | 0 | abi = "n64"; |
1187 | 0 | break; |
1188 | 0 | case ArchSpec::eMIPSABI_N32: |
1189 | 0 | abi = "n32"; |
1190 | 0 | break; |
1191 | 0 | case ArchSpec::eMIPSABI_O32: |
1192 | 0 | abi = "o32"; |
1193 | 0 | break; |
1194 | 0 | default: |
1195 | 0 | break; |
1196 | 0 | } |
1197 | 0 | } |
1198 | 11.9k | return abi; |
1199 | 11.9k | } |
1200 | | |
1201 | | /// Applies the given Fix-It hint to the given commit. |
1202 | 30 | static void ApplyFixIt(const FixItHint &fixit, clang::edit::Commit &commit) { |
1203 | | // This is cobbed from clang::Rewrite::FixItRewriter. |
1204 | 30 | if (fixit.CodeToInsert.empty()) { |
1205 | 2 | if (fixit.InsertFromRange.isValid()) { |
1206 | 0 | commit.insertFromRange(fixit.RemoveRange.getBegin(), |
1207 | 0 | fixit.InsertFromRange, /*afterToken=*/false, |
1208 | 0 | fixit.BeforePreviousInsertions); |
1209 | 0 | return; |
1210 | 0 | } |
1211 | 2 | commit.remove(fixit.RemoveRange); |
1212 | 2 | return; |
1213 | 2 | } |
1214 | 28 | if (fixit.RemoveRange.isTokenRange() || |
1215 | 28 | fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd()10 ) { |
1216 | 18 | commit.replace(fixit.RemoveRange, fixit.CodeToInsert); |
1217 | 18 | return; |
1218 | 18 | } |
1219 | 10 | commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert, |
1220 | 10 | /*afterToken=*/false, fixit.BeforePreviousInsertions); |
1221 | 10 | } |
1222 | | |
1223 | | bool ClangExpressionParser::RewriteExpression( |
1224 | 24 | DiagnosticManager &diagnostic_manager) { |
1225 | 24 | clang::SourceManager &source_manager = m_compiler->getSourceManager(); |
1226 | 24 | clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(), |
1227 | 24 | nullptr); |
1228 | 24 | clang::edit::Commit commit(editor); |
1229 | 24 | clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts()); |
1230 | | |
1231 | 24 | class RewritesReceiver : public edit::EditsReceiver { |
1232 | 24 | Rewriter &rewrite; |
1233 | | |
1234 | 24 | public: |
1235 | 24 | RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {} |
1236 | | |
1237 | 24 | void insert(SourceLocation loc, StringRef text) override { |
1238 | 10 | rewrite.InsertText(loc, text); |
1239 | 10 | } |
1240 | 24 | void replace(CharSourceRange range, StringRef text) override { |
1241 | 20 | rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text); |
1242 | 20 | } |
1243 | 24 | }; |
1244 | | |
1245 | 24 | RewritesReceiver rewrites_receiver(rewriter); |
1246 | | |
1247 | 24 | const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics(); |
1248 | 24 | size_t num_diags = diagnostics.size(); |
1249 | 24 | if (num_diags == 0) |
1250 | 0 | return false; |
1251 | | |
1252 | 34 | for (const auto &diag : diagnostic_manager.Diagnostics())24 { |
1253 | 34 | const auto *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag.get()); |
1254 | 34 | if (!diagnostic) |
1255 | 0 | continue; |
1256 | 34 | if (!diagnostic->HasFixIts()) |
1257 | 6 | continue; |
1258 | 28 | for (const FixItHint &fixit : diagnostic->FixIts()) |
1259 | 30 | ApplyFixIt(fixit, commit); |
1260 | 28 | } |
1261 | | |
1262 | | // FIXME - do we want to try to propagate specific errors here? |
1263 | 24 | if (!commit.isCommitable()) |
1264 | 0 | return false; |
1265 | 24 | else if (!editor.commit(commit)) |
1266 | 0 | return false; |
1267 | | |
1268 | | // Now play all the edits, and stash the result in the diagnostic manager. |
1269 | 24 | editor.applyRewrites(rewrites_receiver); |
1270 | 24 | RewriteBuffer &main_file_buffer = |
1271 | 24 | rewriter.getEditBuffer(source_manager.getMainFileID()); |
1272 | | |
1273 | 24 | std::string fixed_expression; |
1274 | 24 | llvm::raw_string_ostream out_stream(fixed_expression); |
1275 | | |
1276 | 24 | main_file_buffer.write(out_stream); |
1277 | 24 | out_stream.flush(); |
1278 | 24 | diagnostic_manager.SetFixedExpression(fixed_expression); |
1279 | | |
1280 | 24 | return true; |
1281 | 24 | } |
1282 | | |
1283 | | static bool FindFunctionInModule(ConstString &mangled_name, |
1284 | 11.5k | llvm::Module *module, const char *orig_name) { |
1285 | 12.5k | for (const auto &func : module->getFunctionList()) { |
1286 | 12.5k | const StringRef &name = func.getName(); |
1287 | 12.5k | if (name.contains(orig_name)) { |
1288 | 11.5k | mangled_name.SetString(name); |
1289 | 11.5k | return true; |
1290 | 11.5k | } |
1291 | 12.5k | } |
1292 | | |
1293 | 0 | return false; |
1294 | 11.5k | } |
1295 | | |
1296 | | lldb_private::Status ClangExpressionParser::PrepareForExecution( |
1297 | | lldb::addr_t &func_addr, lldb::addr_t &func_end, |
1298 | | lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx, |
1299 | 11.6k | bool &can_interpret, ExecutionPolicy execution_policy) { |
1300 | 11.6k | func_addr = LLDB_INVALID_ADDRESS; |
1301 | 11.6k | func_end = LLDB_INVALID_ADDRESS; |
1302 | 11.6k | Log *log = GetLog(LLDBLog::Expressions); |
1303 | | |
1304 | 11.6k | lldb_private::Status err; |
1305 | | |
1306 | 11.6k | std::unique_ptr<llvm::Module> llvm_module_up( |
1307 | 11.6k | m_code_generator->ReleaseModule()); |
1308 | | |
1309 | 11.6k | if (!llvm_module_up) { |
1310 | 0 | err.SetErrorToGenericError(); |
1311 | 0 | err.SetErrorString("IR doesn't contain a module"); |
1312 | 0 | return err; |
1313 | 0 | } |
1314 | | |
1315 | 11.6k | ConstString function_name; |
1316 | | |
1317 | 11.6k | if (execution_policy != eExecutionPolicyTopLevel) { |
1318 | | // Find the actual name of the function (it's often mangled somehow) |
1319 | | |
1320 | 11.5k | if (!FindFunctionInModule(function_name, llvm_module_up.get(), |
1321 | 11.5k | m_expr.FunctionName())) { |
1322 | 0 | err.SetErrorToGenericError(); |
1323 | 0 | err.SetErrorStringWithFormat("Couldn't find %s() in the module", |
1324 | 0 | m_expr.FunctionName()); |
1325 | 0 | return err; |
1326 | 11.5k | } else { |
1327 | 11.5k | LLDB_LOGF(log, "Found function %s for %s", function_name.AsCString(), |
1328 | 11.5k | m_expr.FunctionName()); |
1329 | 11.5k | } |
1330 | 11.5k | } |
1331 | | |
1332 | 11.6k | SymbolContext sc; |
1333 | | |
1334 | 11.6k | if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) { |
1335 | 7.44k | sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything); |
1336 | 7.44k | } else if (lldb::TargetSP 4.17k target_sp4.17k = exe_ctx.GetTargetSP()) { |
1337 | 4.17k | sc.target_sp = target_sp; |
1338 | 4.17k | } |
1339 | | |
1340 | 11.6k | LLVMUserExpression::IRPasses custom_passes; |
1341 | 11.6k | { |
1342 | 11.6k | auto lang = m_expr.Language(); |
1343 | 11.6k | LLDB_LOGF(log, "%s - Current expression language is %s\n", __FUNCTION__, |
1344 | 11.6k | Language::GetNameForLanguageType(lang)); |
1345 | 11.6k | lldb::ProcessSP process_sp = exe_ctx.GetProcessSP(); |
1346 | 11.6k | if (process_sp && lang != lldb::eLanguageTypeUnknown11.3k ) { |
1347 | 6.61k | auto runtime = process_sp->GetLanguageRuntime(lang); |
1348 | 6.61k | if (runtime) |
1349 | 5.90k | runtime->GetIRPasses(custom_passes); |
1350 | 6.61k | } |
1351 | 11.6k | } |
1352 | | |
1353 | 11.6k | if (custom_passes.EarlyPasses) { |
1354 | 0 | LLDB_LOGF(log, |
1355 | 0 | "%s - Running Early IR Passes from LanguageRuntime on " |
1356 | 0 | "expression module '%s'", |
1357 | 0 | __FUNCTION__, m_expr.FunctionName()); |
1358 | |
|
1359 | 0 | custom_passes.EarlyPasses->run(*llvm_module_up); |
1360 | 0 | } |
1361 | | |
1362 | 11.6k | execution_unit_sp = std::make_shared<IRExecutionUnit>( |
1363 | 11.6k | m_llvm_context, // handed off here |
1364 | 11.6k | llvm_module_up, // handed off here |
1365 | 11.6k | function_name, exe_ctx.GetTargetSP(), sc, |
1366 | 11.6k | m_compiler->getTargetOpts().Features); |
1367 | | |
1368 | 11.6k | ClangExpressionHelper *type_system_helper = |
1369 | 11.6k | dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper()); |
1370 | 11.6k | ClangExpressionDeclMap *decl_map = |
1371 | 11.6k | type_system_helper->DeclMap(); // result can be NULL |
1372 | | |
1373 | 11.6k | if (decl_map) { |
1374 | 9.61k | StreamString error_stream; |
1375 | 9.61k | IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(), |
1376 | 9.61k | *execution_unit_sp, error_stream, |
1377 | 9.61k | function_name.AsCString()); |
1378 | | |
1379 | 9.61k | if (!ir_for_target.runOnModule(*execution_unit_sp->GetModule())) { |
1380 | 12 | err.SetErrorString(error_stream.GetString()); |
1381 | 12 | return err; |
1382 | 12 | } |
1383 | | |
1384 | 9.60k | Process *process = exe_ctx.GetProcessPtr(); |
1385 | | |
1386 | 9.60k | if (execution_policy != eExecutionPolicyAlways && |
1387 | 9.60k | execution_policy != eExecutionPolicyTopLevel6.93k ) { |
1388 | 6.89k | lldb_private::Status interpret_error; |
1389 | | |
1390 | 6.89k | bool interpret_function_calls = |
1391 | 6.89k | !process ? false279 : process->CanInterpretFunctionCalls()6.61k ; |
1392 | 6.89k | can_interpret = IRInterpreter::CanInterpret( |
1393 | 6.89k | *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(), |
1394 | 6.89k | interpret_error, interpret_function_calls); |
1395 | | |
1396 | 6.89k | if (!can_interpret && execution_policy == eExecutionPolicyNever1.23k ) { |
1397 | 5 | err.SetErrorStringWithFormat( |
1398 | 5 | "Can't evaluate the expression without a running target due to: %s", |
1399 | 5 | interpret_error.AsCString()); |
1400 | 5 | return err; |
1401 | 5 | } |
1402 | 6.89k | } |
1403 | | |
1404 | 9.60k | if (!process && execution_policy == eExecutionPolicyAlways290 ) { |
1405 | 0 | err.SetErrorString("Expression needed to run in the target, but the " |
1406 | 0 | "target can't be run"); |
1407 | 0 | return err; |
1408 | 0 | } |
1409 | | |
1410 | 9.60k | if (!process && execution_policy == eExecutionPolicyTopLevel290 ) { |
1411 | 11 | err.SetErrorString("Top-level code needs to be inserted into a runnable " |
1412 | 11 | "target, but the target can't be run"); |
1413 | 11 | return err; |
1414 | 11 | } |
1415 | | |
1416 | 9.59k | if (execution_policy == eExecutionPolicyAlways || |
1417 | 9.59k | (6.92k execution_policy != eExecutionPolicyTopLevel6.92k && !can_interpret6.88k )) { |
1418 | 3.89k | if (m_expr.NeedsValidation() && process1.23k ) { |
1419 | 1.23k | if (!process->GetDynamicCheckers()) { |
1420 | 370 | ClangDynamicCheckerFunctions *dynamic_checkers = |
1421 | 370 | new ClangDynamicCheckerFunctions(); |
1422 | | |
1423 | 370 | DiagnosticManager install_diags; |
1424 | 370 | if (Error Err = dynamic_checkers->Install(install_diags, exe_ctx)) { |
1425 | 0 | std::string ErrMsg = "couldn't install checkers: " + toString(std::move(Err)); |
1426 | 0 | if (install_diags.Diagnostics().size()) |
1427 | 0 | ErrMsg = ErrMsg + "\n" + install_diags.GetString().c_str(); |
1428 | 0 | err.SetErrorString(ErrMsg); |
1429 | 0 | return err; |
1430 | 0 | } |
1431 | | |
1432 | 370 | process->SetDynamicCheckers(dynamic_checkers); |
1433 | | |
1434 | 370 | LLDB_LOGF(log, "== [ClangExpressionParser::PrepareForExecution] " |
1435 | 370 | "Finished installing dynamic checkers =="); |
1436 | 370 | } |
1437 | | |
1438 | 1.23k | if (auto *checker_funcs = llvm::dyn_cast<ClangDynamicCheckerFunctions>( |
1439 | 1.23k | process->GetDynamicCheckers())) { |
1440 | 1.23k | IRDynamicChecks ir_dynamic_checks(*checker_funcs, |
1441 | 1.23k | function_name.AsCString()); |
1442 | | |
1443 | 1.23k | llvm::Module *module = execution_unit_sp->GetModule(); |
1444 | 1.23k | if (!module || !ir_dynamic_checks.runOnModule(*module)) { |
1445 | 0 | err.SetErrorToGenericError(); |
1446 | 0 | err.SetErrorString("Couldn't add dynamic checks to the expression"); |
1447 | 0 | return err; |
1448 | 0 | } |
1449 | | |
1450 | 1.23k | if (custom_passes.LatePasses) { |
1451 | 0 | LLDB_LOGF(log, |
1452 | 0 | "%s - Running Late IR Passes from LanguageRuntime on " |
1453 | 0 | "expression module '%s'", |
1454 | 0 | __FUNCTION__, m_expr.FunctionName()); |
1455 | |
|
1456 | 0 | custom_passes.LatePasses->run(*module); |
1457 | 0 | } |
1458 | 1.23k | } |
1459 | 1.23k | } |
1460 | 3.89k | } |
1461 | | |
1462 | 9.59k | if (execution_policy == eExecutionPolicyAlways || |
1463 | 9.59k | execution_policy == eExecutionPolicyTopLevel6.92k || !can_interpret6.88k ) { |
1464 | 3.92k | execution_unit_sp->GetRunnableInfo(err, func_addr, func_end); |
1465 | 3.92k | } |
1466 | 9.59k | } else { |
1467 | 2.00k | execution_unit_sp->GetRunnableInfo(err, func_addr, func_end); |
1468 | 2.00k | } |
1469 | | |
1470 | 11.5k | return err; |
1471 | 11.6k | } |
1472 | | |
1473 | | lldb_private::Status ClangExpressionParser::RunStaticInitializers( |
1474 | 34 | lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) { |
1475 | 34 | lldb_private::Status err; |
1476 | | |
1477 | 34 | lldbassert(execution_unit_sp.get()); |
1478 | 34 | lldbassert(exe_ctx.HasThreadScope()); |
1479 | | |
1480 | 34 | if (!execution_unit_sp.get()) { |
1481 | 0 | err.SetErrorString( |
1482 | 0 | "can't run static initializers for a NULL execution unit"); |
1483 | 0 | return err; |
1484 | 0 | } |
1485 | | |
1486 | 34 | if (!exe_ctx.HasThreadScope()) { |
1487 | 0 | err.SetErrorString("can't run static initializers without a thread"); |
1488 | 0 | return err; |
1489 | 0 | } |
1490 | | |
1491 | 34 | std::vector<lldb::addr_t> static_initializers; |
1492 | | |
1493 | 34 | execution_unit_sp->GetStaticInitializers(static_initializers); |
1494 | | |
1495 | 34 | for (lldb::addr_t static_initializer : static_initializers) { |
1496 | 6 | EvaluateExpressionOptions options; |
1497 | | |
1498 | 6 | lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction( |
1499 | 6 | exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(), |
1500 | 6 | llvm::ArrayRef<lldb::addr_t>(), options)); |
1501 | | |
1502 | 6 | DiagnosticManager execution_errors; |
1503 | 6 | lldb::ExpressionResults results = |
1504 | 6 | exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan( |
1505 | 6 | exe_ctx, call_static_initializer, options, execution_errors); |
1506 | | |
1507 | 6 | if (results != lldb::eExpressionCompleted) { |
1508 | 2 | err.SetErrorStringWithFormat("couldn't run static initializer: %s", |
1509 | 2 | execution_errors.GetString().c_str()); |
1510 | 2 | return err; |
1511 | 2 | } |
1512 | 6 | } |
1513 | | |
1514 | 32 | return err; |
1515 | 34 | } |