blob: 266b1e229634325734735277f061e282ea3a3e0e [file] [log] [blame]
Sean Callanan1a8d4092010-08-27 01:01:44 +00001//===-- ClangExpressionParser.cpp -------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Sean Callanan1a8d4092010-08-27 01:01:44 +00006//
7//===----------------------------------------------------------------------===//
8
Sean Callanan1a8d4092010-08-27 01:01:44 +00009#include "clang/AST/ASTContext.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000010#include "clang/AST/ASTDiagnostic.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000011#include "clang/AST/ExternalASTSource.h"
Raphael Isemann9dd34c82018-09-17 12:06:07 +000012#include "clang/AST/PrettyPrinter.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000013#include "clang/Basic/DiagnosticIDs.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000014#include "clang/Basic/FileManager.h"
Jim Ingham151c0322015-09-15 21:13:50 +000015#include "clang/Basic/SourceLocation.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000016#include "clang/Basic/TargetInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000017#include "clang/Basic/Version.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000018#include "clang/CodeGen/CodeGenAction.h"
19#include "clang/CodeGen/ModuleBuilder.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000020#include "clang/Edit/Commit.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000021#include "clang/Edit/EditedSource.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000022#include "clang/Edit/EditsReceiver.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000023#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"
Sean Callanan1a8d4092010-08-27 01:01:44 +000030#include "clang/Lex/Preprocessor.h"
Sean Callanane2ef6e32010-09-23 03:01:22 +000031#include "clang/Parse/ParseAST.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000032#include "clang/Rewrite/Core/Rewriter.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000033#include "clang/Rewrite/Frontend/FrontendActions.h"
Raphael Isemann74829732018-08-30 17:29:37 +000034#include "clang/Sema/CodeCompleteConsumer.h"
35#include "clang/Sema/Sema.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000036#include "clang/Sema/SemaConsumer.h"
37
38#include "llvm/ADT/StringRef.h"
39#include "llvm/ExecutionEngine/ExecutionEngine.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000040#include "llvm/Support/Debug.h"
Rafael Espindola4609ea82013-06-26 14:10:56 +000041#include "llvm/Support/FileSystem.h"
Sean Callanan880e6802011-10-07 23:18:13 +000042#include "llvm/Support/TargetSelect.h"
Greg Clayton70b57652011-05-15 01:25:55 +000043
Greg Claytonc9a078a2016-03-24 23:50:03 +000044#pragma clang diagnostic push
45#pragma clang diagnostic ignored "-Wglobal-constructors"
Ed Mastea09ed032014-03-18 18:55:06 +000046#include "llvm/ExecutionEngine/MCJIT.h"
Greg Claytonc9a078a2016-03-24 23:50:03 +000047#pragma clang diagnostic pop
48
Chandler Carruth1e157582013-01-02 12:20:07 +000049#include "llvm/IR/LLVMContext.h"
50#include "llvm/IR/Module.h"
Greg Clayton38a61402010-12-02 23:20:03 +000051#include "llvm/Support/DynamicLibrary.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000052#include "llvm/Support/ErrorHandling.h"
Greg Clayton38a61402010-12-02 23:20:03 +000053#include "llvm/Support/Host.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000054#include "llvm/Support/MemoryBuffer.h"
Greg Clayton38a61402010-12-02 23:20:03 +000055#include "llvm/Support/Signals.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000056
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000057#include "ClangASTSource.h"
Jonas Devlieghere63e2e592019-02-13 01:30:41 +000058#include "ClangDiagnostic.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000059#include "ClangExpressionDeclMap.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000060#include "ClangExpressionHelper.h"
Jonas Devlieghere63e2e592019-02-13 01:30:41 +000061#include "ClangExpressionParser.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000062#include "ClangModulesDeclVendor.h"
63#include "ClangPersistentVariables.h"
64#include "IRForTarget.h"
Jonas Devlieghere63e2e592019-02-13 01:30:41 +000065#include "ModuleDependencyCollector.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000066
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000067#include "lldb/Core/Debugger.h"
68#include "lldb/Core/Disassembler.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000069#include "lldb/Core/Module.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000070#include "lldb/Core/StreamFile.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000071#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000072#include "lldb/Expression/IRExecutionUnit.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000073#include "lldb/Expression/IRInterpreter.h"
74#include "lldb/Host/File.h"
75#include "lldb/Host/HostInfo.h"
76#include "lldb/Symbol/ClangASTContext.h"
77#include "lldb/Symbol/SymbolVendor.h"
78#include "lldb/Target/ExecutionContext.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000079#include "lldb/Target/Language.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000080#include "lldb/Target/ObjCLanguageRuntime.h"
81#include "lldb/Target/Process.h"
82#include "lldb/Target/Target.h"
Sean Callananbd4dc692016-03-21 22:23:38 +000083#include "lldb/Target/ThreadPlanCallFunction.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000084#include "lldb/Utility/DataBufferHeap.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000085#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000086#include "lldb/Utility/Log.h"
Jonas Devlieghere63e2e592019-02-13 01:30:41 +000087#include "lldb/Utility/Reproducer.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000088#include "lldb/Utility/Stream.h"
89#include "lldb/Utility/StreamString.h"
Zachary Turner573ab902017-03-21 18:25:04 +000090#include "lldb/Utility/StringList.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000091
Jonas Devlieghere796ac802019-02-11 23:13:08 +000092#include <cctype>
93#include <memory>
94
Sean Callanan1a8d4092010-08-27 01:01:44 +000095using namespace clang;
96using namespace llvm;
97using namespace lldb_private;
98
99//===----------------------------------------------------------------------===//
100// Utility Methods for Clang
101//===----------------------------------------------------------------------===//
102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
104 ClangModulesDeclVendor &m_decl_vendor;
105 ClangPersistentVariables &m_persistent_vars;
106 StreamString m_error_stream;
107 bool m_has_errors = false;
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +0000108
Sean Callananc8278af2014-12-05 01:27:35 +0000109public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110 LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
111 ClangPersistentVariables &persistent_vars)
112 : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars) {}
113
114 void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
115 const clang::Module * /*null*/) override {
116 std::vector<ConstString> string_path;
117
118 for (const std::pair<IdentifierInfo *, SourceLocation> &component : path) {
119 string_path.push_back(ConstString(component.first->getName()));
Sean Callananc8278af2014-12-05 01:27:35 +0000120 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121
122 StreamString error_stream;
123
124 ClangModulesDeclVendor::ModuleVector exported_modules;
125
126 if (!m_decl_vendor.AddModule(string_path, &exported_modules,
127 m_error_stream)) {
128 m_has_errors = true;
Sean Callananc8278af2014-12-05 01:27:35 +0000129 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000130
131 for (ClangModulesDeclVendor::ModuleID module : exported_modules) {
132 m_persistent_vars.AddHandLoadedClangModule(module);
Sean Callananc8278af2014-12-05 01:27:35 +0000133 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000134 }
135
136 bool hasErrors() { return m_has_errors; }
137
Zachary Turnerc1564272016-11-16 21:15:24 +0000138 llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
Sean Callananc8278af2014-12-05 01:27:35 +0000139};
140
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
Sean Callanan579e70c2016-03-19 00:03:59 +0000142public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 ClangDiagnosticManagerAdapter()
144 : m_passthrough(new clang::TextDiagnosticBuffer) {}
Sean Callanan579e70c2016-03-19 00:03:59 +0000145
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146 ClangDiagnosticManagerAdapter(
147 const std::shared_ptr<clang::TextDiagnosticBuffer> &passthrough)
148 : m_passthrough(passthrough) {}
Sean Callanan579e70c2016-03-19 00:03:59 +0000149
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150 void ResetManager(DiagnosticManager *manager = nullptr) {
151 m_manager = manager;
152 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000153
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
155 const clang::Diagnostic &Info) {
156 if (m_manager) {
157 llvm::SmallVector<char, 32> diag_str;
158 Info.FormatDiagnostic(diag_str);
159 diag_str.push_back('\0');
160 const char *data = diag_str.data();
Sean Callanan579e70c2016-03-19 00:03:59 +0000161
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162 lldb_private::DiagnosticSeverity severity;
163 bool make_new_diagnostic = true;
164
165 switch (DiagLevel) {
166 case DiagnosticsEngine::Level::Fatal:
167 case DiagnosticsEngine::Level::Error:
168 severity = eDiagnosticSeverityError;
169 break;
170 case DiagnosticsEngine::Level::Warning:
171 severity = eDiagnosticSeverityWarning;
172 break;
173 case DiagnosticsEngine::Level::Remark:
174 case DiagnosticsEngine::Level::Ignored:
175 severity = eDiagnosticSeverityRemark;
176 break;
177 case DiagnosticsEngine::Level::Note:
178 m_manager->AppendMessageToDiagnostic(data);
179 make_new_diagnostic = false;
180 }
181 if (make_new_diagnostic) {
182 ClangDiagnostic *new_diagnostic =
183 new ClangDiagnostic(data, severity, Info.getID());
184 m_manager->AddDiagnostic(new_diagnostic);
185
186 // Don't store away warning fixits, since the compiler doesn't have
Adrian Prantl05097242018-04-30 16:49:04 +0000187 // enough context in an expression for the warning to be useful.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188 // FIXME: Should we try to filter out FixIts that apply to our generated
189 // code, and not the user's expression?
190 if (severity == eDiagnosticSeverityError) {
191 size_t num_fixit_hints = Info.getNumFixItHints();
192 for (size_t i = 0; i < num_fixit_hints; i++) {
193 const clang::FixItHint &fixit = Info.getFixItHint(i);
194 if (!fixit.isNull())
195 new_diagnostic->AddFixitHint(fixit);
196 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000197 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000199 }
200
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201 m_passthrough->HandleDiagnostic(DiagLevel, Info);
202 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000203
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204 void FlushDiagnostics(DiagnosticsEngine &Diags) {
205 m_passthrough->FlushDiagnostics(Diags);
206 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000207
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
209 return new ClangDiagnosticManagerAdapter(m_passthrough);
210 }
211
212 clang::TextDiagnosticBuffer *GetPassthrough() { return m_passthrough.get(); }
Sean Callanan579e70c2016-03-19 00:03:59 +0000213
214private:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000215 DiagnosticManager *m_manager = nullptr;
216 std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough;
Sean Callanan579e70c2016-03-19 00:03:59 +0000217};
218
Sean Callanan1a8d4092010-08-27 01:01:44 +0000219//===----------------------------------------------------------------------===//
220// Implementation of ClangExpressionParser
221//===----------------------------------------------------------------------===//
222
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223ClangExpressionParser::ClangExpressionParser(ExecutionContextScope *exe_scope,
224 Expression &expr,
225 bool generate_debug_info)
226 : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
Adrian Prantl2305c042018-08-30 15:39:08 +0000227 m_pp_callbacks(nullptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000229
Adrian Prantl05097242018-04-30 16:49:04 +0000230 // We can't compile expressions without a target. So if the exe_scope is
231 // null or doesn't have a target, then we just need to get out of here. I'll
232 // lldb_assert and not make any of the compiler objects since
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 // I can't return errors directly from the constructor. Further calls will
234 // check if the compiler was made and
235 // bag out if it wasn't.
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000236
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237 if (!exe_scope) {
238 lldb_assert(exe_scope, "Can't make an expression parser with a null scope.",
239 __FUNCTION__, __FILE__, __LINE__);
240 return;
241 }
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000242
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243 lldb::TargetSP target_sp;
244 target_sp = exe_scope->CalculateTarget();
245 if (!target_sp) {
246 lldb_assert(target_sp.get(),
247 "Can't make an expression parser with a null target.",
248 __FUNCTION__, __FILE__, __LINE__);
249 return;
250 }
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000251
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252 // 1. Create a new compiler instance.
253 m_compiler.reset(new CompilerInstance());
Jonas Devlieghere63e2e592019-02-13 01:30:41 +0000254
255 // When capturing a reproducer, hook up the file collector with clang to
256 // collector modules and headers.
257 if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
258 repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>();
259 m_compiler->setModuleDepCollector(
260 std::make_shared<ModuleDependencyCollectorAdaptor>(
261 fp.GetFileCollector()));
262 DependencyOutputOptions &opts = m_compiler->getDependencyOutputOpts();
263 opts.IncludeSystemHeaders = true;
264 opts.IncludeModuleFiles = true;
265 }
266
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267 lldb::LanguageType frame_lang =
268 expr.Language(); // defaults to lldb::eLanguageTypeUnknown
269 bool overridden_target_opts = false;
270 lldb_private::LanguageRuntime *lang_rt = nullptr;
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000271
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272 std::string abi;
273 ArchSpec target_arch;
274 target_arch = target_sp->GetArchitecture();
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000275
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276 const auto target_machine = target_arch.GetMachine();
Jason Molendaa3329782014-03-29 18:54:20 +0000277
Adrian Prantl05097242018-04-30 16:49:04 +0000278 // If the expression is being evaluated in the context of an existing stack
279 // frame, we introspect to see if the language runtime is available.
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000280
Kate Stoneb9c1b512016-09-06 20:57:50 +0000281 lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
282 lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000283
Adrian Prantl05097242018-04-30 16:49:04 +0000284 // Make sure the user hasn't provided a preferred execution language with
285 // `expression --language X -- ...`
Kate Stoneb9c1b512016-09-06 20:57:50 +0000286 if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
287 frame_lang = frame_sp->GetLanguage();
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000288
Kate Stoneb9c1b512016-09-06 20:57:50 +0000289 if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
290 lang_rt = process_sp->GetLanguageRuntime(frame_lang);
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000291 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000292 log->Printf("Frame has language of type %s",
293 Language::GetNameForLanguageType(frame_lang));
294 }
Alp Toker5f838642014-07-06 05:36:57 +0000295
Kate Stoneb9c1b512016-09-06 20:57:50 +0000296 // 2. Configure the compiler with a set of default options that are
Adrian Prantl05097242018-04-30 16:49:04 +0000297 // appropriate for most situations.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298 if (target_arch.IsValid()) {
299 std::string triple = target_arch.GetTriple().str();
300 m_compiler->getTargetOpts().Triple = triple;
301 if (log)
302 log->Printf("Using %s as the target triple",
303 m_compiler->getTargetOpts().Triple.c_str());
304 } else {
305 // If we get here we don't have a valid target and just have to guess.
306 // Sometimes this will be ok to just use the host target triple (when we
Adrian Prantl05097242018-04-30 16:49:04 +0000307 // evaluate say "2+3", but other expressions like breakpoint conditions and
308 // other things that _are_ target specific really shouldn't just be using
309 // the host triple. In such a case the language runtime should expose an
310 // overridden options set (3), below.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000311 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
312 if (log)
313 log->Printf("Using default target triple of %s",
314 m_compiler->getTargetOpts().Triple.c_str());
315 }
Adrian Prantl05097242018-04-30 16:49:04 +0000316 // Now add some special fixes for known architectures: Any arm32 iOS
317 // environment, but not on arm64
Kate Stoneb9c1b512016-09-06 20:57:50 +0000318 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
319 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
320 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
321 m_compiler->getTargetOpts().ABI = "apcs-gnu";
322 }
323 // Supported subsets of x86
324 if (target_machine == llvm::Triple::x86 ||
325 target_machine == llvm::Triple::x86_64) {
326 m_compiler->getTargetOpts().Features.push_back("+sse");
327 m_compiler->getTargetOpts().Features.push_back("+sse2");
328 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000329
Adrian Prantl05097242018-04-30 16:49:04 +0000330 // Set the target CPU to generate code for. This will be empty for any CPU
331 // that doesn't really need to make a special
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332 // CPU string.
333 m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
Ewan Crawford7648dd32016-03-10 12:38:55 +0000334
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 // Set the target ABI
336 abi = GetClangTargetABI(target_arch);
337 if (!abi.empty())
338 m_compiler->getTargetOpts().ABI = abi;
339
340 // 3. Now allow the runtime to provide custom configuration options for the
Adrian Prantl05097242018-04-30 16:49:04 +0000341 // target. In this case, a specialized language runtime is available and we
342 // can query it for extra options. For 99% of use cases, this will not be
343 // needed and should be provided when basic platform detection is not enough.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 if (lang_rt)
345 overridden_target_opts =
346 lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
347
348 if (overridden_target_opts)
Pavel Labath6302bf62017-02-13 11:03:17 +0000349 if (log && log->GetVerbose()) {
350 LLDB_LOGV(
351 log, "Using overridden target options for the expression evaluation");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352
353 auto opts = m_compiler->getTargetOpts();
Pavel Labath6302bf62017-02-13 11:03:17 +0000354 LLDB_LOGV(log, "Triple: '{0}'", opts.Triple);
355 LLDB_LOGV(log, "CPU: '{0}'", opts.CPU);
356 LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath);
357 LLDB_LOGV(log, "ABI: '{0}'", opts.ABI);
358 LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
360 StringList::LogDump(log, opts.Features, "Features");
Sean Callananc7b65062011-11-07 23:35:40 +0000361 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000362
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363 // 4. Create and install the target on the compiler.
364 m_compiler->createDiagnostics();
365 auto target_info = TargetInfo::CreateTargetInfo(
366 m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
367 if (log) {
368 log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign());
369 log->Printf("Target datalayout string: '%s'",
370 target_info->getDataLayout().getStringRepresentation().c_str());
371 log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str());
372 log->Printf("Target vector alignment: %d",
373 target_info->getMaxVectorAlign());
374 }
375 m_compiler->setTarget(target_info);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000376
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 assert(m_compiler->hasTarget());
Tamas Berghammerdccbfaf2015-03-31 10:21:50 +0000378
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 // 5. Set language options.
380 lldb::LanguageType language = expr.Language();
Raphael Isemann0d649c62019-01-25 22:41:31 +0000381 LangOptions &lang_opts = m_compiler->getLangOpts();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000382
Kate Stoneb9c1b512016-09-06 20:57:50 +0000383 switch (language) {
384 case lldb::eLanguageTypeC:
385 case lldb::eLanguageTypeC89:
386 case lldb::eLanguageTypeC99:
387 case lldb::eLanguageTypeC11:
388 // FIXME: the following language option is a temporary workaround,
389 // to "ask for C, get C++."
Adrian Prantl05097242018-04-30 16:49:04 +0000390 // For now, the expression parser must use C++ anytime the language is a C
391 // family language, because the expression parser uses features of C++ to
392 // capture values.
Raphael Isemann0d649c62019-01-25 22:41:31 +0000393 lang_opts.CPlusPlus = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 break;
395 case lldb::eLanguageTypeObjC:
Raphael Isemann0d649c62019-01-25 22:41:31 +0000396 lang_opts.ObjC = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 // FIXME: the following language option is a temporary workaround,
398 // to "ask for ObjC, get ObjC++" (see comment above).
Raphael Isemann0d649c62019-01-25 22:41:31 +0000399 lang_opts.CPlusPlus = true;
Davide Italiano89419f82017-12-15 00:50:43 +0000400
401 // Clang now sets as default C++14 as the default standard (with
402 // GNU extensions), so we do the same here to avoid mismatches that
Adrian Prantl05097242018-04-30 16:49:04 +0000403 // cause compiler error when evaluating expressions (e.g. nullptr not found
404 // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
405 // two lines below) so we decide to be consistent with that, but this could
406 // be re-evaluated in the future.
Raphael Isemann0d649c62019-01-25 22:41:31 +0000407 lang_opts.CPlusPlus11 = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 break;
409 case lldb::eLanguageTypeC_plus_plus:
410 case lldb::eLanguageTypeC_plus_plus_11:
411 case lldb::eLanguageTypeC_plus_plus_14:
Raphael Isemann0d649c62019-01-25 22:41:31 +0000412 lang_opts.CPlusPlus11 = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
414 LLVM_FALLTHROUGH;
415 case lldb::eLanguageTypeC_plus_plus_03:
Raphael Isemann0d649c62019-01-25 22:41:31 +0000416 lang_opts.CPlusPlus = true;
Aleksandr Urakovf3351882018-12-04 09:51:29 +0000417 if (process_sp)
Raphael Isemann0d649c62019-01-25 22:41:31 +0000418 lang_opts.ObjC =
Aleksandr Urakovf3351882018-12-04 09:51:29 +0000419 process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420 break;
421 case lldb::eLanguageTypeObjC_plus_plus:
422 case lldb::eLanguageTypeUnknown:
423 default:
Raphael Isemann0d649c62019-01-25 22:41:31 +0000424 lang_opts.ObjC = true;
425 lang_opts.CPlusPlus = true;
426 lang_opts.CPlusPlus11 = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
428 break;
429 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000430
Raphael Isemann0d649c62019-01-25 22:41:31 +0000431 lang_opts.Bool = true;
432 lang_opts.WChar = true;
433 lang_opts.Blocks = true;
434 lang_opts.DebuggerSupport =
Kate Stoneb9c1b512016-09-06 20:57:50 +0000435 true; // Features specifically for debugger clients
436 if (expr.DesiredResultType() == Expression::eResultTypeId)
Raphael Isemann0d649c62019-01-25 22:41:31 +0000437 lang_opts.DebuggerCastResultToId = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438
Raphael Isemann0d649c62019-01-25 22:41:31 +0000439 lang_opts.CharIsSigned = ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
440 .CharIsSignedByDefault();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441
Adrian Prantl05097242018-04-30 16:49:04 +0000442 // Spell checking is a nice feature, but it ends up completing a lot of types
443 // that we didn't strictly speaking need to complete. As a result, we spend a
444 // long time parsing and importing debug information.
Raphael Isemann0d649c62019-01-25 22:41:31 +0000445 lang_opts.SpellChecking = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446
Raphael Isemann0d649c62019-01-25 22:41:31 +0000447 if (process_sp && lang_opts.ObjC) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448 if (process_sp->GetObjCLanguageRuntime()) {
449 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() ==
450 ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
Raphael Isemann0d649c62019-01-25 22:41:31 +0000451 lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452 else
Raphael Isemann0d649c62019-01-25 22:41:31 +0000453 lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
454 VersionTuple(10, 7));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455
456 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
Raphael Isemann0d649c62019-01-25 22:41:31 +0000457 lang_opts.DebuggerObjCLiteral = true;
Sean Callananc3a16002011-01-17 23:42:46 +0000458 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459 }
Greg Claytonf83f32d2011-01-15 01:32:14 +0000460
Raphael Isemann0d649c62019-01-25 22:41:31 +0000461 lang_opts.ThreadsafeStatics = false;
462 lang_opts.AccessControl = false; // Debuggers get universal access
463 lang_opts.DollarIdents = true; // $ indicates a persistent variable name
Raphael Isemannd424c2a2018-08-30 20:56:58 +0000464 // We enable all builtin functions beside the builtins from libc/libm (e.g.
465 // 'fopen'). Those libc functions are already correctly handled by LLDB, and
466 // additionally enabling them as expandable builtins is breaking Clang.
Raphael Isemann0d649c62019-01-25 22:41:31 +0000467 lang_opts.NoBuiltin = true;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000468
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 // Set CodeGen options
470 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
471 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
472 m_compiler->getCodeGenOpts().DisableFPElim = true;
473 m_compiler->getCodeGenOpts().OmitLeafFramePointer = false;
474 if (generate_debug_info)
475 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
476 else
477 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000478
Kate Stoneb9c1b512016-09-06 20:57:50 +0000479 // Disable some warnings.
480 m_compiler->getDiagnostics().setSeverityForGroup(
481 clang::diag::Flavor::WarningOrError, "unused-value",
482 clang::diag::Severity::Ignored, SourceLocation());
483 m_compiler->getDiagnostics().setSeverityForGroup(
484 clang::diag::Flavor::WarningOrError, "odr",
485 clang::diag::Severity::Ignored, SourceLocation());
Alp Toker10933d12014-06-12 11:14:32 +0000486
Kate Stoneb9c1b512016-09-06 20:57:50 +0000487 // Inform the target of the language options
488 //
489 // FIXME: We shouldn't need to do this, the target should be immutable once
490 // created. This complexity should be lifted elsewhere.
491 m_compiler->getTarget().adjust(m_compiler->getLangOpts());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000492
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493 // 6. Set up the diagnostic buffer for reporting errors
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000494
Kate Stoneb9c1b512016-09-06 20:57:50 +0000495 m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000496
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497 // 7. Set up the source management objects inside the compiler
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000498
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499 clang::FileSystemOptions file_system_options;
500 m_file_manager.reset(new clang::FileManager(file_system_options));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000501
Kate Stoneb9c1b512016-09-06 20:57:50 +0000502 if (!m_compiler->hasSourceManager())
Jonas Devlieghere70355ac2019-02-12 03:47:39 +0000503 m_compiler->createSourceManager(*m_file_manager);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000504
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505 m_compiler->createFileManager();
506 m_compiler->createPreprocessor(TU_Complete);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000507
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508 if (ClangModulesDeclVendor *decl_vendor =
509 target_sp->GetClangModulesDeclVendor()) {
510 ClangPersistentVariables *clang_persistent_vars =
511 llvm::cast<ClangPersistentVariables>(
512 target_sp->GetPersistentExpressionStateForLanguage(
513 lldb::eLanguageTypeC));
514 std::unique_ptr<PPCallbacks> pp_callbacks(
515 new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars));
516 m_pp_callbacks =
517 static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
518 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
519 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000520
Adrian Prantl05097242018-04-30 16:49:04 +0000521 // 8. Most of this we get from the CompilerInstance, but we also want to give
522 // the context an ExternalASTSource.
Raphael Isemann778b3082018-08-23 20:40:45 +0000523
524 auto &PP = m_compiler->getPreprocessor();
525 auto &builtin_context = PP.getBuiltinInfo();
526 builtin_context.initializeBuiltins(PP.getIdentifierTable(),
527 m_compiler->getLangOpts());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000528
Raphael Isemann596709d2018-08-27 15:18:33 +0000529 m_compiler->createASTContext();
530 clang::ASTContext &ast_context = m_compiler->getASTContext();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000531
Kate Stoneb9c1b512016-09-06 20:57:50 +0000532 ClangExpressionHelper *type_system_helper =
533 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
534 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
Sean Callanan1a8d4092010-08-27 01:01:44 +0000535
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536 if (decl_map) {
537 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source(
538 decl_map->CreateProxy());
Raphael Isemann596709d2018-08-27 15:18:33 +0000539 decl_map->InstallASTContext(ast_context, m_compiler->getFileManager());
540 ast_context.setExternalSource(ast_source);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 }
542
543 m_ast_context.reset(
544 new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str()));
Raphael Isemann596709d2018-08-27 15:18:33 +0000545 m_ast_context->setASTContext(&ast_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546
547 std::string module_name("$__lldb_module");
548
549 m_llvm_context.reset(new LLVMContext());
550 m_code_generator.reset(CreateLLVMCodeGen(
551 m_compiler->getDiagnostics(), module_name,
552 m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(),
553 m_compiler->getCodeGenOpts(), *m_llvm_context));
Sean Callanan1a8d4092010-08-27 01:01:44 +0000554}
555
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556ClangExpressionParser::~ClangExpressionParser() {}
Sean Callanan1a8d4092010-08-27 01:01:44 +0000557
Raphael Isemann74829732018-08-30 17:29:37 +0000558namespace {
559
560//----------------------------------------------------------------------
561/// @class CodeComplete
562///
563/// A code completion consumer for the clang Sema that is responsible for
564/// creating the completion suggestions when a user requests completion
565/// of an incomplete `expr` invocation.
566//----------------------------------------------------------------------
567class CodeComplete : public CodeCompleteConsumer {
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000568 CodeCompletionTUInfo m_info;
Raphael Isemann74829732018-08-30 17:29:37 +0000569
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000570 std::string m_expr;
571 unsigned m_position = 0;
Raphael Isemannc11a7802018-08-30 21:26:32 +0000572 CompletionRequest &m_request;
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000573 /// The printing policy we use when printing declarations for our completion
574 /// descriptions.
575 clang::PrintingPolicy m_desc_policy;
Raphael Isemann74829732018-08-30 17:29:37 +0000576
577 /// Returns true if the given character can be used in an identifier.
578 /// This also returns true for numbers because for completion we usually
579 /// just iterate backwards over iterators.
580 ///
581 /// Note: lldb uses '$' in its internal identifiers, so we also allow this.
582 static bool IsIdChar(char c) {
583 return c == '_' || std::isalnum(c) || c == '$';
584 }
585
586 /// Returns true if the given character is used to separate arguments
587 /// in the command line of lldb.
588 static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
589
590 /// Drops all tokens in front of the expression that are unrelated for
591 /// the completion of the cmd line. 'unrelated' means here that the token
592 /// is not interested for the lldb completion API result.
593 StringRef dropUnrelatedFrontTokens(StringRef cmd) {
594 if (cmd.empty())
595 return cmd;
596
597 // If we are at the start of a word, then all tokens are unrelated to
598 // the current completion logic.
599 if (IsTokenSeparator(cmd.back()))
600 return StringRef();
601
602 // Remove all previous tokens from the string as they are unrelated
603 // to completing the current token.
604 StringRef to_remove = cmd;
605 while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {
606 to_remove = to_remove.drop_back();
607 }
608 cmd = cmd.drop_front(to_remove.size());
609
610 return cmd;
611 }
612
613 /// Removes the last identifier token from the given cmd line.
614 StringRef removeLastToken(StringRef cmd) {
615 while (!cmd.empty() && IsIdChar(cmd.back())) {
616 cmd = cmd.drop_back();
617 }
618 return cmd;
619 }
620
621 /// Attemps to merge the given completion from the given position into the
622 /// existing command. Returns the completion string that can be returned to
623 /// the lldb completion API.
624 std::string mergeCompletion(StringRef existing, unsigned pos,
625 StringRef completion) {
626 StringRef existing_command = existing.substr(0, pos);
627 // We rewrite the last token with the completion, so let's drop that
628 // token from the command.
629 existing_command = removeLastToken(existing_command);
630 // We also should remove all previous tokens from the command as they
631 // would otherwise be added to the completion that already has the
632 // completion.
633 existing_command = dropUnrelatedFrontTokens(existing_command);
634 return existing_command.str() + completion.str();
635 }
636
637public:
638 /// Constructs a CodeComplete consumer that can be attached to a Sema.
639 /// @param[out] matches
640 /// The list of matches that the lldb completion API expects as a result.
641 /// This may already contain matches, so it's only allowed to append
642 /// to this variable.
643 /// @param[out] expr
644 /// The whole expression string that we are currently parsing. This
645 /// string needs to be equal to the input the user typed, and NOT the
646 /// final code that Clang is parsing.
647 /// @param[out] position
648 /// The character position of the user cursor in the `expr` parameter.
649 ///
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000650 CodeComplete(CompletionRequest &request, clang::LangOptions ops,
651 std::string expr, unsigned position)
Raphael Isemann74829732018-08-30 17:29:37 +0000652 : CodeCompleteConsumer(CodeCompleteOptions(), false),
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000653 m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000654 m_position(position), m_request(request), m_desc_policy(ops) {
655
656 // Ensure that the printing policy is producing a description that is as
657 // short as possible.
658 m_desc_policy.SuppressScope = true;
659 m_desc_policy.SuppressTagKeyword = true;
660 m_desc_policy.FullyQualifiedName = false;
661 m_desc_policy.TerseOutput = true;
662 m_desc_policy.IncludeNewlines = false;
663 m_desc_policy.UseVoidForZeroParams = false;
664 m_desc_policy.Bool = true;
665 }
Raphael Isemann74829732018-08-30 17:29:37 +0000666
667 /// Deregisters and destroys this code-completion consumer.
668 virtual ~CodeComplete() {}
669
670 /// \name Code-completion filtering
671 /// Check if the result should be filtered out.
672 bool isResultFilteredOut(StringRef Filter,
673 CodeCompletionResult Result) override {
674 // This code is mostly copied from CodeCompleteConsumer.
675 switch (Result.Kind) {
676 case CodeCompletionResult::RK_Declaration:
677 return !(
678 Result.Declaration->getIdentifier() &&
679 Result.Declaration->getIdentifier()->getName().startswith(Filter));
680 case CodeCompletionResult::RK_Keyword:
681 return !StringRef(Result.Keyword).startswith(Filter);
682 case CodeCompletionResult::RK_Macro:
683 return !Result.Macro->getName().startswith(Filter);
684 case CodeCompletionResult::RK_Pattern:
685 return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
686 }
687 // If we trigger this assert or the above switch yields a warning, then
688 // CodeCompletionResult has been enhanced with more kinds of completion
689 // results. Expand the switch above in this case.
690 assert(false && "Unknown completion result type?");
691 // If we reach this, then we should just ignore whatever kind of unknown
692 // result we got back. We probably can't turn it into any kind of useful
693 // completion suggestion with the existing code.
694 return true;
695 }
696
697 /// \name Code-completion callbacks
698 /// Process the finalized code-completion results.
699 void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,
700 CodeCompletionResult *Results,
701 unsigned NumResults) override {
702
703 // The Sema put the incomplete token we try to complete in here during
704 // lexing, so we need to retrieve it here to know what we are completing.
705 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
706
707 // Iterate over all the results. Filter out results we don't want and
708 // process the rest.
709 for (unsigned I = 0; I != NumResults; ++I) {
710 // Filter the results with the information from the Sema.
711 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
712 continue;
713
714 CodeCompletionResult &R = Results[I];
715 std::string ToInsert;
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000716 std::string Description;
Raphael Isemann74829732018-08-30 17:29:37 +0000717 // Handle the different completion kinds that come from the Sema.
718 switch (R.Kind) {
719 case CodeCompletionResult::RK_Declaration: {
720 const NamedDecl *D = R.Declaration;
721 ToInsert = R.Declaration->getNameAsString();
722 // If we have a function decl that has no arguments we want to
723 // complete the empty parantheses for the user. If the function has
724 // arguments, we at least complete the opening bracket.
725 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) {
726 if (F->getNumParams() == 0)
727 ToInsert += "()";
728 else
729 ToInsert += "(";
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000730 raw_string_ostream OS(Description);
731 F->print(OS, m_desc_policy, false);
732 OS.flush();
733 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
734 Description = V->getType().getAsString(m_desc_policy);
735 } else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) {
736 Description = F->getType().getAsString(m_desc_policy);
737 } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) {
738 // If we try to complete a namespace, then we can directly append
739 // the '::'.
Raphael Isemann74829732018-08-30 17:29:37 +0000740 if (!N->isAnonymousNamespace())
741 ToInsert += "::";
742 }
743 break;
744 }
745 case CodeCompletionResult::RK_Keyword:
746 ToInsert = R.Keyword;
747 break;
748 case CodeCompletionResult::RK_Macro:
Raphael Isemann74829732018-08-30 17:29:37 +0000749 ToInsert = R.Macro->getName().str();
750 break;
751 case CodeCompletionResult::RK_Pattern:
752 ToInsert = R.Pattern->getTypedText();
753 break;
754 }
755 // At this point all information is in the ToInsert string.
756
757 // We also filter some internal lldb identifiers here. The user
758 // shouldn't see these.
759 if (StringRef(ToInsert).startswith("$__lldb_"))
760 continue;
761 if (!ToInsert.empty()) {
762 // Merge the suggested Token into the existing command line to comply
763 // with the kind of result the lldb API expects.
764 std::string CompletionSuggestion =
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000765 mergeCompletion(m_expr, m_position, ToInsert);
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000766 m_request.AddCompletion(CompletionSuggestion, Description);
Raphael Isemann74829732018-08-30 17:29:37 +0000767 }
768 }
769 }
770
771 /// \param S the semantic-analyzer object for which code-completion is being
772 /// done.
773 ///
774 /// \param CurrentArg the index of the current argument.
775 ///
776 /// \param Candidates an array of overload candidates.
777 ///
778 /// \param NumCandidates the number of overload candidates
779 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
780 OverloadCandidate *Candidates,
781 unsigned NumCandidates,
782 SourceLocation OpenParLoc) override {
783 // At the moment we don't filter out any overloaded candidates.
784 }
785
786 CodeCompletionAllocator &getAllocator() override {
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000787 return m_info.getAllocator();
Raphael Isemann74829732018-08-30 17:29:37 +0000788 }
789
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000790 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; }
Raphael Isemann74829732018-08-30 17:29:37 +0000791};
792} // namespace
793
Raphael Isemannc11a7802018-08-30 21:26:32 +0000794bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line,
Raphael Isemann74829732018-08-30 17:29:37 +0000795 unsigned pos, unsigned typed_pos) {
796 DiagnosticManager mgr;
797 // We need the raw user expression here because that's what the CodeComplete
798 // class uses to provide completion suggestions.
799 // However, the `Text` method only gives us the transformed expression here.
800 // To actually get the raw user input here, we have to cast our expression to
801 // the LLVMUserExpression which exposes the right API. This should never fail
802 // as we always have a ClangUserExpression whenever we call this.
803 LLVMUserExpression &llvm_expr = *static_cast<LLVMUserExpression *>(&m_expr);
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000804 CodeComplete CC(request, m_compiler->getLangOpts(), llvm_expr.GetUserText(),
805 typed_pos);
Raphael Isemann74829732018-08-30 17:29:37 +0000806 // We don't need a code generator for parsing.
807 m_code_generator.reset();
808 // Start parsing the expression with our custom code completion consumer.
809 ParseInternal(mgr, &CC, line, pos);
810 return true;
811}
812
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
Raphael Isemann74829732018-08-30 17:29:37 +0000814 return ParseInternal(diagnostic_manager);
815}
816
817unsigned
818ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager,
819 CodeCompleteConsumer *completion_consumer,
820 unsigned completion_line,
821 unsigned completion_column) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000822 ClangDiagnosticManagerAdapter *adapter =
823 static_cast<ClangDiagnosticManagerAdapter *>(
824 m_compiler->getDiagnostics().getClient());
825 clang::TextDiagnosticBuffer *diag_buf = adapter->GetPassthrough();
826 diag_buf->FlushDiagnostics(m_compiler->getDiagnostics());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000827
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828 adapter->ResetManager(&diagnostic_manager);
Sean Callanan579e70c2016-03-19 00:03:59 +0000829
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830 const char *expr_text = m_expr.Text();
Rafael Espindola9cb97b62014-05-21 15:08:27 +0000831
Kate Stoneb9c1b512016-09-06 20:57:50 +0000832 clang::SourceManager &source_mgr = m_compiler->getSourceManager();
833 bool created_main_file = false;
Raphael Isemann74829732018-08-30 17:29:37 +0000834
835 // Clang wants to do completion on a real file known by Clang's file manager,
836 // so we have to create one to make this work.
837 // TODO: We probably could also simulate to Clang's file manager that there
838 // is a real file that contains our code.
839 bool should_create_file = completion_consumer != nullptr;
840
841 // We also want a real file on disk if we generate full debug info.
842 should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==
843 codegenoptions::FullDebugInfo;
844
845 if (should_create_file) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 int temp_fd = -1;
Stella Stamenovab3f44ad2018-12-10 17:23:28 +0000847 llvm::SmallString<128> result_path;
Pavel Labath60f028f2018-06-19 15:09:07 +0000848 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
850 std::string temp_source_path = tmpdir_file_spec.GetPath();
851 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
852 } else {
853 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
854 }
855
856 if (temp_fd != -1) {
857 lldb_private::File file(temp_fd, true);
858 const size_t expr_text_len = strlen(expr_text);
859 size_t bytes_written = expr_text_len;
860 if (file.Write(expr_text, bytes_written).Success()) {
861 if (bytes_written == expr_text_len) {
862 file.Close();
863 source_mgr.setMainFileID(
864 source_mgr.createFileID(m_file_manager->getFile(result_path),
865 SourceLocation(), SrcMgr::C_User));
866 created_main_file = true;
Greg Clayton23f8c952014-03-24 23:10:19 +0000867 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868 }
Greg Clayton23f8c952014-03-24 23:10:19 +0000869 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000870 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000871
Kate Stoneb9c1b512016-09-06 20:57:50 +0000872 if (!created_main_file) {
873 std::unique_ptr<MemoryBuffer> memory_buffer =
874 MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
875 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
876 }
877
878 diag_buf->BeginSourceFile(m_compiler->getLangOpts(),
879 &m_compiler->getPreprocessor());
880
881 ClangExpressionHelper *type_system_helper =
882 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
883
884 ASTConsumer *ast_transformer =
885 type_system_helper->ASTTransformer(m_code_generator.get());
886
887 if (ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap())
888 decl_map->InstallCodeGenerator(m_code_generator.get());
889
Raphael Isemann74829732018-08-30 17:29:37 +0000890 // If we want to parse for code completion, we need to attach our code
891 // completion consumer to the Sema and specify a completion position.
892 // While parsing the Sema will call this consumer with the provided
893 // completion suggestions.
894 if (completion_consumer) {
895 auto main_file = source_mgr.getFileEntryForID(source_mgr.getMainFileID());
896 auto &PP = m_compiler->getPreprocessor();
897 // Lines and columns start at 1 in Clang, but code completion positions are
898 // indexed from 0, so we need to add 1 to the line and column here.
899 ++completion_line;
900 ++completion_column;
901 PP.SetCodeCompletionPoint(main_file, completion_line, completion_column);
902 }
903
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904 if (ast_transformer) {
905 ast_transformer->Initialize(m_compiler->getASTContext());
906 ParseAST(m_compiler->getPreprocessor(), ast_transformer,
Raphael Isemann74829732018-08-30 17:29:37 +0000907 m_compiler->getASTContext(), false, TU_Complete,
908 completion_consumer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000909 } else {
910 m_code_generator->Initialize(m_compiler->getASTContext());
911 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(),
Raphael Isemann74829732018-08-30 17:29:37 +0000912 m_compiler->getASTContext(), false, TU_Complete,
913 completion_consumer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914 }
915
916 diag_buf->EndSourceFile();
917
918 unsigned num_errors = diag_buf->getNumErrors();
919
920 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
921 num_errors++;
Zachary Turnere2411fa2016-11-12 19:12:56 +0000922 diagnostic_manager.PutString(eDiagnosticSeverityError,
923 "while importing modules:");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 diagnostic_manager.AppendMessageToDiagnostic(
Zachary Turnerc1564272016-11-16 21:15:24 +0000925 m_pp_callbacks->getErrorString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926 }
927
928 if (!num_errors) {
929 if (type_system_helper->DeclMap() &&
930 !type_system_helper->DeclMap()->ResolveUnknownTypes()) {
931 diagnostic_manager.Printf(eDiagnosticSeverityError,
932 "Couldn't infer the type of a variable");
933 num_errors++;
Greg Clayton23f8c952014-03-24 23:10:19 +0000934 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000935 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000936
Kate Stoneb9c1b512016-09-06 20:57:50 +0000937 if (!num_errors) {
938 type_system_helper->CommitPersistentDecls();
939 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000940
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941 adapter->ResetManager();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000942
Kate Stoneb9c1b512016-09-06 20:57:50 +0000943 return num_errors;
Sean Callanan1a8d4092010-08-27 01:01:44 +0000944}
945
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000946std::string
Kate Stoneb9c1b512016-09-06 20:57:50 +0000947ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {
948 std::string abi;
949
950 if (target_arch.IsMIPS()) {
951 switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
952 case ArchSpec::eMIPSABI_N64:
953 abi = "n64";
954 break;
955 case ArchSpec::eMIPSABI_N32:
956 abi = "n32";
957 break;
958 case ArchSpec::eMIPSABI_O32:
959 abi = "o32";
960 break;
961 default:
962 break;
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000963 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964 }
965 return abi;
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000966}
967
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968bool ClangExpressionParser::RewriteExpression(
969 DiagnosticManager &diagnostic_manager) {
970 clang::SourceManager &source_manager = m_compiler->getSourceManager();
971 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
972 nullptr);
973 clang::edit::Commit commit(editor);
974 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
Jim Inghama1e541b2016-03-25 01:57:14 +0000975
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 class RewritesReceiver : public edit::EditsReceiver {
977 Rewriter &rewrite;
Jim Inghama1e541b2016-03-25 01:57:14 +0000978
Kate Stoneb9c1b512016-09-06 20:57:50 +0000979 public:
980 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
981
982 void insert(SourceLocation loc, StringRef text) override {
983 rewrite.InsertText(loc, text);
Jim Inghama1e541b2016-03-25 01:57:14 +0000984 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985 void replace(CharSourceRange range, StringRef text) override {
986 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
Sean Callananfc55f5d2010-09-21 00:44:12 +0000987 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000988 };
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000989
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 RewritesReceiver rewrites_receiver(rewriter);
991
992 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
993 size_t num_diags = diagnostics.size();
994 if (num_diags == 0)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000995 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996
997 for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) {
998 const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag);
999 if (diagnostic && diagnostic->HasFixIts()) {
1000 for (const FixItHint &fixit : diagnostic->FixIts()) {
1001 // This is cobbed from clang::Rewrite::FixItRewriter.
1002 if (fixit.CodeToInsert.empty()) {
1003 if (fixit.InsertFromRange.isValid()) {
1004 commit.insertFromRange(fixit.RemoveRange.getBegin(),
1005 fixit.InsertFromRange, /*afterToken=*/false,
1006 fixit.BeforePreviousInsertions);
1007 } else
1008 commit.remove(fixit.RemoveRange);
1009 } else {
1010 if (fixit.RemoveRange.isTokenRange() ||
1011 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd())
1012 commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
1013 else
1014 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
1015 /*afterToken=*/false, fixit.BeforePreviousInsertions);
1016 }
1017 }
1018 }
1019 }
1020
1021 // FIXME - do we want to try to propagate specific errors here?
1022 if (!commit.isCommitable())
1023 return false;
1024 else if (!editor.commit(commit))
1025 return false;
1026
1027 // Now play all the edits, and stash the result in the diagnostic manager.
1028 editor.applyRewrites(rewrites_receiver);
1029 RewriteBuffer &main_file_buffer =
1030 rewriter.getEditBuffer(source_manager.getMainFileID());
1031
1032 std::string fixed_expression;
1033 llvm::raw_string_ostream out_stream(fixed_expression);
1034
1035 main_file_buffer.write(out_stream);
1036 out_stream.flush();
1037 diagnostic_manager.SetFixedExpression(fixed_expression);
1038
1039 return true;
Sean Callananfc55f5d2010-09-21 00:44:12 +00001040}
1041
Kate Stoneb9c1b512016-09-06 20:57:50 +00001042static bool FindFunctionInModule(ConstString &mangled_name,
1043 llvm::Module *module, const char *orig_name) {
1044 for (const auto &func : module->getFunctionList()) {
1045 const StringRef &name = func.getName();
1046 if (name.find(orig_name) != StringRef::npos) {
1047 mangled_name.SetString(name);
1048 return true;
Sean Callanan1a8d4092010-08-27 01:01:44 +00001049 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001050 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001051
Kate Stoneb9c1b512016-09-06 20:57:50 +00001052 return false;
Sean Callanan1a8d4092010-08-27 01:01:44 +00001053}
Sean Callananbd4dc692016-03-21 22:23:38 +00001054
Zachary Turner97206d52017-05-12 04:51:55 +00001055lldb_private::Status ClangExpressionParser::PrepareForExecution(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001056 lldb::addr_t &func_addr, lldb::addr_t &func_end,
1057 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
1058 bool &can_interpret, ExecutionPolicy execution_policy) {
1059 func_addr = LLDB_INVALID_ADDRESS;
1060 func_end = LLDB_INVALID_ADDRESS;
1061 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1062
Zachary Turner97206d52017-05-12 04:51:55 +00001063 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001064
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001065 std::unique_ptr<llvm::Module> llvm_module_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001066 m_code_generator->ReleaseModule());
1067
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001068 if (!llvm_module_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001069 err.SetErrorToGenericError();
1070 err.SetErrorString("IR doesn't contain a module");
Sean Callananbd4dc692016-03-21 22:23:38 +00001071 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001072 }
1073
1074 ConstString function_name;
1075
1076 if (execution_policy != eExecutionPolicyTopLevel) {
1077 // Find the actual name of the function (it's often mangled somehow)
1078
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001079 if (!FindFunctionInModule(function_name, llvm_module_up.get(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 m_expr.FunctionName())) {
1081 err.SetErrorToGenericError();
1082 err.SetErrorStringWithFormat("Couldn't find %s() in the module",
1083 m_expr.FunctionName());
1084 return err;
1085 } else {
1086 if (log)
1087 log->Printf("Found function %s for %s", function_name.AsCString(),
1088 m_expr.FunctionName());
1089 }
1090 }
1091
1092 SymbolContext sc;
1093
1094 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
1095 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
1096 } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
1097 sc.target_sp = target_sp;
1098 }
1099
1100 LLVMUserExpression::IRPasses custom_passes;
1101 {
1102 auto lang = m_expr.Language();
1103 if (log)
Bruce Mitchener4ebdee02018-05-29 09:10:46 +00001104 log->Printf("%s - Current expression language is %s\n", __FUNCTION__,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001105 Language::GetNameForLanguageType(lang));
Jim Ingham22562152016-11-03 23:42:09 +00001106 lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
1107 if (process_sp && lang != lldb::eLanguageTypeUnknown) {
1108 auto runtime = process_sp->GetLanguageRuntime(lang);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109 if (runtime)
1110 runtime->GetIRPasses(custom_passes);
1111 }
1112 }
1113
1114 if (custom_passes.EarlyPasses) {
1115 if (log)
1116 log->Printf("%s - Running Early IR Passes from LanguageRuntime on "
1117 "expression module '%s'",
1118 __FUNCTION__, m_expr.FunctionName());
1119
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001120 custom_passes.EarlyPasses->run(*llvm_module_up);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121 }
1122
Jonas Devlieghere796ac802019-02-11 23:13:08 +00001123 execution_unit_sp = std::make_shared<IRExecutionUnit>(
1124 m_llvm_context, // handed off here
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001125 llvm_module_up, // handed off here
1126 function_name, exe_ctx.GetTargetSP(), sc,
Jonas Devlieghere796ac802019-02-11 23:13:08 +00001127 m_compiler->getTargetOpts().Features);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128
1129 ClangExpressionHelper *type_system_helper =
1130 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1131 ClangExpressionDeclMap *decl_map =
1132 type_system_helper->DeclMap(); // result can be NULL
1133
1134 if (decl_map) {
1135 Stream *error_stream = NULL;
1136 Target *target = exe_ctx.GetTargetPtr();
1137 error_stream = target->GetDebugger().GetErrorFile().get();
1138
1139 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
1140 *execution_unit_sp, *error_stream,
1141 function_name.AsCString());
1142
1143 bool ir_can_run =
1144 ir_for_target.runOnModule(*execution_unit_sp->GetModule());
1145
1146 if (!ir_can_run) {
1147 err.SetErrorString(
1148 "The expression could not be prepared to run in the target");
1149 return err;
1150 }
1151
1152 Process *process = exe_ctx.GetProcessPtr();
1153
1154 if (execution_policy != eExecutionPolicyAlways &&
1155 execution_policy != eExecutionPolicyTopLevel) {
Zachary Turner97206d52017-05-12 04:51:55 +00001156 lldb_private::Status interpret_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001157
1158 bool interpret_function_calls =
1159 !process ? false : process->CanInterpretFunctionCalls();
1160 can_interpret = IRInterpreter::CanInterpret(
1161 *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
1162 interpret_error, interpret_function_calls);
1163
1164 if (!can_interpret && execution_policy == eExecutionPolicyNever) {
1165 err.SetErrorStringWithFormat("Can't run the expression locally: %s",
1166 interpret_error.AsCString());
1167 return err;
1168 }
1169 }
1170
1171 if (!process && execution_policy == eExecutionPolicyAlways) {
1172 err.SetErrorString("Expression needed to run in the target, but the "
1173 "target can't be run");
1174 return err;
1175 }
1176
1177 if (!process && execution_policy == eExecutionPolicyTopLevel) {
1178 err.SetErrorString("Top-level code needs to be inserted into a runnable "
1179 "target, but the target can't be run");
1180 return err;
1181 }
1182
1183 if (execution_policy == eExecutionPolicyAlways ||
1184 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
1185 if (m_expr.NeedsValidation() && process) {
1186 if (!process->GetDynamicCheckers()) {
1187 DynamicCheckerFunctions *dynamic_checkers =
1188 new DynamicCheckerFunctions();
1189
1190 DiagnosticManager install_diagnostics;
1191
1192 if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) {
1193 if (install_diagnostics.Diagnostics().size())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001194 err.SetErrorString(install_diagnostics.GetString().c_str());
Raphael Isemann262dd8c2018-09-11 13:59:47 +00001195 else
1196 err.SetErrorString("couldn't install checkers, unknown error");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197
1198 return err;
1199 }
1200
1201 process->SetDynamicCheckers(dynamic_checkers);
1202
1203 if (log)
Raphael Isemannf75a9dc2019-02-11 21:45:33 +00001204 log->Printf("== [ClangExpressionParser::PrepareForExecution] "
1205 "Finished installing dynamic checkers ==");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001206 }
1207
1208 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(),
1209 function_name.AsCString());
1210
1211 llvm::Module *module = execution_unit_sp->GetModule();
1212 if (!module || !ir_dynamic_checks.runOnModule(*module)) {
1213 err.SetErrorToGenericError();
1214 err.SetErrorString("Couldn't add dynamic checks to the expression");
1215 return err;
1216 }
1217
1218 if (custom_passes.LatePasses) {
1219 if (log)
1220 log->Printf("%s - Running Late IR Passes from LanguageRuntime on "
1221 "expression module '%s'",
1222 __FUNCTION__, m_expr.FunctionName());
1223
1224 custom_passes.LatePasses->run(*module);
1225 }
1226 }
1227 }
1228
1229 if (execution_policy == eExecutionPolicyAlways ||
1230 execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
1231 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1232 }
1233 } else {
1234 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1235 }
1236
1237 return err;
1238}
1239
Zachary Turner97206d52017-05-12 04:51:55 +00001240lldb_private::Status ClangExpressionParser::RunStaticInitializers(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) {
Zachary Turner97206d52017-05-12 04:51:55 +00001242 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001243
1244 lldbassert(execution_unit_sp.get());
1245 lldbassert(exe_ctx.HasThreadScope());
1246
1247 if (!execution_unit_sp.get()) {
1248 err.SetErrorString(
1249 "can't run static initializers for a NULL execution unit");
1250 return err;
1251 }
1252
1253 if (!exe_ctx.HasThreadScope()) {
1254 err.SetErrorString("can't run static initializers without a thread");
1255 return err;
1256 }
1257
1258 std::vector<lldb::addr_t> static_initializers;
1259
1260 execution_unit_sp->GetStaticInitializers(static_initializers);
1261
1262 for (lldb::addr_t static_initializer : static_initializers) {
1263 EvaluateExpressionOptions options;
1264
1265 lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(
1266 exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(),
1267 llvm::ArrayRef<lldb::addr_t>(), options));
1268
1269 DiagnosticManager execution_errors;
1270 lldb::ExpressionResults results =
1271 exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(
1272 exe_ctx, call_static_initializer, options, execution_errors);
1273
1274 if (results != lldb::eExpressionCompleted) {
1275 err.SetErrorStringWithFormat("couldn't run static initializer: %s",
1276 execution_errors.GetString().c_str());
1277 return err;
1278 }
1279 }
1280
1281 return err;
Sean Callananbd4dc692016-03-21 22:23:38 +00001282}