blob: 27985d02dfd97dbb19f13ae7583b2b959581ec6d [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
Jonas Devlieghere672d2c12018-11-11 23:16:43 +00009#include <cctype>
Sean Callanan1a8d4092010-08-27 01:01:44 +000010#include "clang/AST/ASTContext.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000011#include "clang/AST/ASTDiagnostic.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000012#include "clang/AST/ExternalASTSource.h"
Raphael Isemann9dd34c82018-09-17 12:06:07 +000013#include "clang/AST/PrettyPrinter.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000014#include "clang/Basic/DiagnosticIDs.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000015#include "clang/Basic/FileManager.h"
Jim Ingham151c0322015-09-15 21:13:50 +000016#include "clang/Basic/SourceLocation.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000017#include "clang/Basic/TargetInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000018#include "clang/Basic/Version.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000019#include "clang/CodeGen/CodeGenAction.h"
20#include "clang/CodeGen/ModuleBuilder.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000021#include "clang/Edit/Commit.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000022#include "clang/Edit/EditedSource.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000023#include "clang/Edit/EditsReceiver.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/CompilerInvocation.h"
26#include "clang/Frontend/FrontendActions.h"
27#include "clang/Frontend/FrontendDiagnostic.h"
28#include "clang/Frontend/FrontendPluginRegistry.h"
29#include "clang/Frontend/TextDiagnosticBuffer.h"
30#include "clang/Frontend/TextDiagnosticPrinter.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000031#include "clang/Lex/Preprocessor.h"
Sean Callanane2ef6e32010-09-23 03:01:22 +000032#include "clang/Parse/ParseAST.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000033#include "clang/Rewrite/Core/Rewriter.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000034#include "clang/Rewrite/Frontend/FrontendActions.h"
Raphael Isemann74829732018-08-30 17:29:37 +000035#include "clang/Sema/CodeCompleteConsumer.h"
36#include "clang/Sema/Sema.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000037#include "clang/Sema/SemaConsumer.h"
38
39#include "llvm/ADT/StringRef.h"
40#include "llvm/ExecutionEngine/ExecutionEngine.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000041#include "llvm/Support/Debug.h"
Rafael Espindola4609ea82013-06-26 14:10:56 +000042#include "llvm/Support/FileSystem.h"
Sean Callanan880e6802011-10-07 23:18:13 +000043#include "llvm/Support/TargetSelect.h"
Greg Clayton70b57652011-05-15 01:25:55 +000044
Greg Claytonc9a078a2016-03-24 23:50:03 +000045#pragma clang diagnostic push
46#pragma clang diagnostic ignored "-Wglobal-constructors"
Ed Mastea09ed032014-03-18 18:55:06 +000047#include "llvm/ExecutionEngine/MCJIT.h"
Greg Claytonc9a078a2016-03-24 23:50:03 +000048#pragma clang diagnostic pop
49
Chandler Carruth1e157582013-01-02 12:20:07 +000050#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Module.h"
Greg Clayton38a61402010-12-02 23:20:03 +000052#include "llvm/Support/DynamicLibrary.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000053#include "llvm/Support/ErrorHandling.h"
Greg Clayton38a61402010-12-02 23:20:03 +000054#include "llvm/Support/Host.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000055#include "llvm/Support/MemoryBuffer.h"
Greg Clayton38a61402010-12-02 23:20:03 +000056#include "llvm/Support/Signals.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000057
Jim Inghama1e541b2016-03-25 01:57:14 +000058#include "ClangDiagnostic.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000059#include "ClangExpressionParser.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000060
61#include "ClangASTSource.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000062#include "ClangExpressionDeclMap.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000063#include "ClangExpressionHelper.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000064#include "ClangModulesDeclVendor.h"
65#include "ClangPersistentVariables.h"
66#include "IRForTarget.h"
67
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000068#include "lldb/Core/Debugger.h"
69#include "lldb/Core/Disassembler.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000070#include "lldb/Core/Module.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000071#include "lldb/Core/StreamFile.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000072#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000073#include "lldb/Expression/IRExecutionUnit.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000074#include "lldb/Expression/IRInterpreter.h"
75#include "lldb/Host/File.h"
76#include "lldb/Host/HostInfo.h"
77#include "lldb/Symbol/ClangASTContext.h"
78#include "lldb/Symbol/SymbolVendor.h"
79#include "lldb/Target/ExecutionContext.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000080#include "lldb/Target/Language.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000081#include "lldb/Target/ObjCLanguageRuntime.h"
82#include "lldb/Target/Process.h"
83#include "lldb/Target/Target.h"
Sean Callananbd4dc692016-03-21 22:23:38 +000084#include "lldb/Target/ThreadPlanCallFunction.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000085#include "lldb/Utility/DataBufferHeap.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000086#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000087#include "lldb/Utility/Log.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
Sean Callanan1a8d4092010-08-27 01:01:44 +000092using namespace clang;
93using namespace llvm;
94using namespace lldb_private;
95
96//===----------------------------------------------------------------------===//
97// Utility Methods for Clang
98//===----------------------------------------------------------------------===//
99
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
101 ClangModulesDeclVendor &m_decl_vendor;
102 ClangPersistentVariables &m_persistent_vars;
103 StreamString m_error_stream;
104 bool m_has_errors = false;
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +0000105
Sean Callananc8278af2014-12-05 01:27:35 +0000106public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107 LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
108 ClangPersistentVariables &persistent_vars)
109 : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars) {}
110
111 void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
112 const clang::Module * /*null*/) override {
113 std::vector<ConstString> string_path;
114
115 for (const std::pair<IdentifierInfo *, SourceLocation> &component : path) {
116 string_path.push_back(ConstString(component.first->getName()));
Sean Callananc8278af2014-12-05 01:27:35 +0000117 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118
119 StreamString error_stream;
120
121 ClangModulesDeclVendor::ModuleVector exported_modules;
122
123 if (!m_decl_vendor.AddModule(string_path, &exported_modules,
124 m_error_stream)) {
125 m_has_errors = true;
Sean Callananc8278af2014-12-05 01:27:35 +0000126 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127
128 for (ClangModulesDeclVendor::ModuleID module : exported_modules) {
129 m_persistent_vars.AddHandLoadedClangModule(module);
Sean Callananc8278af2014-12-05 01:27:35 +0000130 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 }
132
133 bool hasErrors() { return m_has_errors; }
134
Zachary Turnerc1564272016-11-16 21:15:24 +0000135 llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
Sean Callananc8278af2014-12-05 01:27:35 +0000136};
137
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
Sean Callanan579e70c2016-03-19 00:03:59 +0000139public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140 ClangDiagnosticManagerAdapter()
141 : m_passthrough(new clang::TextDiagnosticBuffer) {}
Sean Callanan579e70c2016-03-19 00:03:59 +0000142
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 ClangDiagnosticManagerAdapter(
144 const std::shared_ptr<clang::TextDiagnosticBuffer> &passthrough)
145 : m_passthrough(passthrough) {}
Sean Callanan579e70c2016-03-19 00:03:59 +0000146
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147 void ResetManager(DiagnosticManager *manager = nullptr) {
148 m_manager = manager;
149 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000150
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
152 const clang::Diagnostic &Info) {
153 if (m_manager) {
154 llvm::SmallVector<char, 32> diag_str;
155 Info.FormatDiagnostic(diag_str);
156 diag_str.push_back('\0');
157 const char *data = diag_str.data();
Sean Callanan579e70c2016-03-19 00:03:59 +0000158
Kate Stoneb9c1b512016-09-06 20:57:50 +0000159 lldb_private::DiagnosticSeverity severity;
160 bool make_new_diagnostic = true;
161
162 switch (DiagLevel) {
163 case DiagnosticsEngine::Level::Fatal:
164 case DiagnosticsEngine::Level::Error:
165 severity = eDiagnosticSeverityError;
166 break;
167 case DiagnosticsEngine::Level::Warning:
168 severity = eDiagnosticSeverityWarning;
169 break;
170 case DiagnosticsEngine::Level::Remark:
171 case DiagnosticsEngine::Level::Ignored:
172 severity = eDiagnosticSeverityRemark;
173 break;
174 case DiagnosticsEngine::Level::Note:
175 m_manager->AppendMessageToDiagnostic(data);
176 make_new_diagnostic = false;
177 }
178 if (make_new_diagnostic) {
179 ClangDiagnostic *new_diagnostic =
180 new ClangDiagnostic(data, severity, Info.getID());
181 m_manager->AddDiagnostic(new_diagnostic);
182
183 // Don't store away warning fixits, since the compiler doesn't have
Adrian Prantl05097242018-04-30 16:49:04 +0000184 // enough context in an expression for the warning to be useful.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000185 // FIXME: Should we try to filter out FixIts that apply to our generated
186 // code, and not the user's expression?
187 if (severity == eDiagnosticSeverityError) {
188 size_t num_fixit_hints = Info.getNumFixItHints();
189 for (size_t i = 0; i < num_fixit_hints; i++) {
190 const clang::FixItHint &fixit = Info.getFixItHint(i);
191 if (!fixit.isNull())
192 new_diagnostic->AddFixitHint(fixit);
193 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000194 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000196 }
197
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198 m_passthrough->HandleDiagnostic(DiagLevel, Info);
199 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000200
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201 void FlushDiagnostics(DiagnosticsEngine &Diags) {
202 m_passthrough->FlushDiagnostics(Diags);
203 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000204
Kate Stoneb9c1b512016-09-06 20:57:50 +0000205 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
206 return new ClangDiagnosticManagerAdapter(m_passthrough);
207 }
208
209 clang::TextDiagnosticBuffer *GetPassthrough() { return m_passthrough.get(); }
Sean Callanan579e70c2016-03-19 00:03:59 +0000210
211private:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000212 DiagnosticManager *m_manager = nullptr;
213 std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough;
Sean Callanan579e70c2016-03-19 00:03:59 +0000214};
215
Sean Callanan1a8d4092010-08-27 01:01:44 +0000216//===----------------------------------------------------------------------===//
217// Implementation of ClangExpressionParser
218//===----------------------------------------------------------------------===//
219
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220ClangExpressionParser::ClangExpressionParser(ExecutionContextScope *exe_scope,
221 Expression &expr,
222 bool generate_debug_info)
223 : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
Adrian Prantl2305c042018-08-30 15:39:08 +0000224 m_pp_callbacks(nullptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000226
Adrian Prantl05097242018-04-30 16:49:04 +0000227 // We can't compile expressions without a target. So if the exe_scope is
228 // null or doesn't have a target, then we just need to get out of here. I'll
229 // lldb_assert and not make any of the compiler objects since
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230 // I can't return errors directly from the constructor. Further calls will
231 // check if the compiler was made and
232 // bag out if it wasn't.
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000233
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234 if (!exe_scope) {
235 lldb_assert(exe_scope, "Can't make an expression parser with a null scope.",
236 __FUNCTION__, __FILE__, __LINE__);
237 return;
238 }
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000239
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240 lldb::TargetSP target_sp;
241 target_sp = exe_scope->CalculateTarget();
242 if (!target_sp) {
243 lldb_assert(target_sp.get(),
244 "Can't make an expression parser with a null target.",
245 __FUNCTION__, __FILE__, __LINE__);
246 return;
247 }
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000248
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 // 1. Create a new compiler instance.
250 m_compiler.reset(new CompilerInstance());
251 lldb::LanguageType frame_lang =
252 expr.Language(); // defaults to lldb::eLanguageTypeUnknown
253 bool overridden_target_opts = false;
254 lldb_private::LanguageRuntime *lang_rt = nullptr;
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000255
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 std::string abi;
257 ArchSpec target_arch;
258 target_arch = target_sp->GetArchitecture();
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000259
Kate Stoneb9c1b512016-09-06 20:57:50 +0000260 const auto target_machine = target_arch.GetMachine();
Jason Molendaa3329782014-03-29 18:54:20 +0000261
Adrian Prantl05097242018-04-30 16:49:04 +0000262 // If the expression is being evaluated in the context of an existing stack
263 // frame, we introspect to see if the language runtime is available.
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000264
Kate Stoneb9c1b512016-09-06 20:57:50 +0000265 lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
266 lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000267
Adrian Prantl05097242018-04-30 16:49:04 +0000268 // Make sure the user hasn't provided a preferred execution language with
269 // `expression --language X -- ...`
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270 if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
271 frame_lang = frame_sp->GetLanguage();
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000272
Kate Stoneb9c1b512016-09-06 20:57:50 +0000273 if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
274 lang_rt = process_sp->GetLanguageRuntime(frame_lang);
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000275 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276 log->Printf("Frame has language of type %s",
277 Language::GetNameForLanguageType(frame_lang));
278 }
Alp Toker5f838642014-07-06 05:36:57 +0000279
Kate Stoneb9c1b512016-09-06 20:57:50 +0000280 // 2. Configure the compiler with a set of default options that are
Adrian Prantl05097242018-04-30 16:49:04 +0000281 // appropriate for most situations.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282 if (target_arch.IsValid()) {
283 std::string triple = target_arch.GetTriple().str();
284 m_compiler->getTargetOpts().Triple = triple;
285 if (log)
286 log->Printf("Using %s as the target triple",
287 m_compiler->getTargetOpts().Triple.c_str());
288 } else {
289 // If we get here we don't have a valid target and just have to guess.
290 // Sometimes this will be ok to just use the host target triple (when we
Adrian Prantl05097242018-04-30 16:49:04 +0000291 // evaluate say "2+3", but other expressions like breakpoint conditions and
292 // other things that _are_ target specific really shouldn't just be using
293 // the host triple. In such a case the language runtime should expose an
294 // overridden options set (3), below.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000295 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
296 if (log)
297 log->Printf("Using default target triple of %s",
298 m_compiler->getTargetOpts().Triple.c_str());
299 }
Adrian Prantl05097242018-04-30 16:49:04 +0000300 // Now add some special fixes for known architectures: Any arm32 iOS
301 // environment, but not on arm64
Kate Stoneb9c1b512016-09-06 20:57:50 +0000302 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
303 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
304 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
305 m_compiler->getTargetOpts().ABI = "apcs-gnu";
306 }
307 // Supported subsets of x86
308 if (target_machine == llvm::Triple::x86 ||
309 target_machine == llvm::Triple::x86_64) {
310 m_compiler->getTargetOpts().Features.push_back("+sse");
311 m_compiler->getTargetOpts().Features.push_back("+sse2");
312 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000313
Adrian Prantl05097242018-04-30 16:49:04 +0000314 // Set the target CPU to generate code for. This will be empty for any CPU
315 // that doesn't really need to make a special
Kate Stoneb9c1b512016-09-06 20:57:50 +0000316 // CPU string.
317 m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
Ewan Crawford7648dd32016-03-10 12:38:55 +0000318
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319 // Set the target ABI
320 abi = GetClangTargetABI(target_arch);
321 if (!abi.empty())
322 m_compiler->getTargetOpts().ABI = abi;
323
324 // 3. Now allow the runtime to provide custom configuration options for the
Adrian Prantl05097242018-04-30 16:49:04 +0000325 // target. In this case, a specialized language runtime is available and we
326 // can query it for extra options. For 99% of use cases, this will not be
327 // needed and should be provided when basic platform detection is not enough.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 if (lang_rt)
329 overridden_target_opts =
330 lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
331
332 if (overridden_target_opts)
Pavel Labath6302bf62017-02-13 11:03:17 +0000333 if (log && log->GetVerbose()) {
334 LLDB_LOGV(
335 log, "Using overridden target options for the expression evaluation");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336
337 auto opts = m_compiler->getTargetOpts();
Pavel Labath6302bf62017-02-13 11:03:17 +0000338 LLDB_LOGV(log, "Triple: '{0}'", opts.Triple);
339 LLDB_LOGV(log, "CPU: '{0}'", opts.CPU);
340 LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath);
341 LLDB_LOGV(log, "ABI: '{0}'", opts.ABI);
342 LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343 StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
344 StringList::LogDump(log, opts.Features, "Features");
Sean Callananc7b65062011-11-07 23:35:40 +0000345 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000346
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347 // 4. Create and install the target on the compiler.
348 m_compiler->createDiagnostics();
349 auto target_info = TargetInfo::CreateTargetInfo(
350 m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
351 if (log) {
352 log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign());
353 log->Printf("Target datalayout string: '%s'",
354 target_info->getDataLayout().getStringRepresentation().c_str());
355 log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str());
356 log->Printf("Target vector alignment: %d",
357 target_info->getMaxVectorAlign());
358 }
359 m_compiler->setTarget(target_info);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000360
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 assert(m_compiler->hasTarget());
Tamas Berghammerdccbfaf2015-03-31 10:21:50 +0000362
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363 // 5. Set language options.
364 lldb::LanguageType language = expr.Language();
Raphael Isemann0d649c62019-01-25 22:41:31 +0000365 LangOptions &lang_opts = m_compiler->getLangOpts();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000366
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 switch (language) {
368 case lldb::eLanguageTypeC:
369 case lldb::eLanguageTypeC89:
370 case lldb::eLanguageTypeC99:
371 case lldb::eLanguageTypeC11:
372 // FIXME: the following language option is a temporary workaround,
373 // to "ask for C, get C++."
Adrian Prantl05097242018-04-30 16:49:04 +0000374 // For now, the expression parser must use C++ anytime the language is a C
375 // family language, because the expression parser uses features of C++ to
376 // capture values.
Raphael Isemann0d649c62019-01-25 22:41:31 +0000377 lang_opts.CPlusPlus = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378 break;
379 case lldb::eLanguageTypeObjC:
Raphael Isemann0d649c62019-01-25 22:41:31 +0000380 lang_opts.ObjC = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 // FIXME: the following language option is a temporary workaround,
382 // to "ask for ObjC, get ObjC++" (see comment above).
Raphael Isemann0d649c62019-01-25 22:41:31 +0000383 lang_opts.CPlusPlus = true;
Davide Italiano89419f82017-12-15 00:50:43 +0000384
385 // Clang now sets as default C++14 as the default standard (with
386 // GNU extensions), so we do the same here to avoid mismatches that
Adrian Prantl05097242018-04-30 16:49:04 +0000387 // cause compiler error when evaluating expressions (e.g. nullptr not found
388 // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
389 // two lines below) so we decide to be consistent with that, but this could
390 // be re-evaluated in the future.
Raphael Isemann0d649c62019-01-25 22:41:31 +0000391 lang_opts.CPlusPlus11 = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 break;
393 case lldb::eLanguageTypeC_plus_plus:
394 case lldb::eLanguageTypeC_plus_plus_11:
395 case lldb::eLanguageTypeC_plus_plus_14:
Raphael Isemann0d649c62019-01-25 22:41:31 +0000396 lang_opts.CPlusPlus11 = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
398 LLVM_FALLTHROUGH;
399 case lldb::eLanguageTypeC_plus_plus_03:
Raphael Isemann0d649c62019-01-25 22:41:31 +0000400 lang_opts.CPlusPlus = true;
Aleksandr Urakovf3351882018-12-04 09:51:29 +0000401 if (process_sp)
Raphael Isemann0d649c62019-01-25 22:41:31 +0000402 lang_opts.ObjC =
Aleksandr Urakovf3351882018-12-04 09:51:29 +0000403 process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 break;
405 case lldb::eLanguageTypeObjC_plus_plus:
406 case lldb::eLanguageTypeUnknown:
407 default:
Raphael Isemann0d649c62019-01-25 22:41:31 +0000408 lang_opts.ObjC = true;
409 lang_opts.CPlusPlus = true;
410 lang_opts.CPlusPlus11 = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
412 break;
413 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000414
Raphael Isemann0d649c62019-01-25 22:41:31 +0000415 lang_opts.Bool = true;
416 lang_opts.WChar = true;
417 lang_opts.Blocks = true;
418 lang_opts.DebuggerSupport =
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 true; // Features specifically for debugger clients
420 if (expr.DesiredResultType() == Expression::eResultTypeId)
Raphael Isemann0d649c62019-01-25 22:41:31 +0000421 lang_opts.DebuggerCastResultToId = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422
Raphael Isemann0d649c62019-01-25 22:41:31 +0000423 lang_opts.CharIsSigned = ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
424 .CharIsSignedByDefault();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425
Adrian Prantl05097242018-04-30 16:49:04 +0000426 // Spell checking is a nice feature, but it ends up completing a lot of types
427 // that we didn't strictly speaking need to complete. As a result, we spend a
428 // long time parsing and importing debug information.
Raphael Isemann0d649c62019-01-25 22:41:31 +0000429 lang_opts.SpellChecking = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430
Raphael Isemann0d649c62019-01-25 22:41:31 +0000431 if (process_sp && lang_opts.ObjC) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000432 if (process_sp->GetObjCLanguageRuntime()) {
433 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() ==
434 ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
Raphael Isemann0d649c62019-01-25 22:41:31 +0000435 lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 else
Raphael Isemann0d649c62019-01-25 22:41:31 +0000437 lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
438 VersionTuple(10, 7));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439
440 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
Raphael Isemann0d649c62019-01-25 22:41:31 +0000441 lang_opts.DebuggerObjCLiteral = true;
Sean Callananc3a16002011-01-17 23:42:46 +0000442 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443 }
Greg Claytonf83f32d2011-01-15 01:32:14 +0000444
Raphael Isemann0d649c62019-01-25 22:41:31 +0000445 lang_opts.ThreadsafeStatics = false;
446 lang_opts.AccessControl = false; // Debuggers get universal access
447 lang_opts.DollarIdents = true; // $ indicates a persistent variable name
Raphael Isemannd424c2a2018-08-30 20:56:58 +0000448 // We enable all builtin functions beside the builtins from libc/libm (e.g.
449 // 'fopen'). Those libc functions are already correctly handled by LLDB, and
450 // additionally enabling them as expandable builtins is breaking Clang.
Raphael Isemann0d649c62019-01-25 22:41:31 +0000451 lang_opts.NoBuiltin = true;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000452
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453 // Set CodeGen options
454 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
455 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
456 m_compiler->getCodeGenOpts().DisableFPElim = true;
457 m_compiler->getCodeGenOpts().OmitLeafFramePointer = false;
458 if (generate_debug_info)
459 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
460 else
461 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000462
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463 // Disable some warnings.
464 m_compiler->getDiagnostics().setSeverityForGroup(
465 clang::diag::Flavor::WarningOrError, "unused-value",
466 clang::diag::Severity::Ignored, SourceLocation());
467 m_compiler->getDiagnostics().setSeverityForGroup(
468 clang::diag::Flavor::WarningOrError, "odr",
469 clang::diag::Severity::Ignored, SourceLocation());
Alp Toker10933d12014-06-12 11:14:32 +0000470
Kate Stoneb9c1b512016-09-06 20:57:50 +0000471 // Inform the target of the language options
472 //
473 // FIXME: We shouldn't need to do this, the target should be immutable once
474 // created. This complexity should be lifted elsewhere.
475 m_compiler->getTarget().adjust(m_compiler->getLangOpts());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000476
Kate Stoneb9c1b512016-09-06 20:57:50 +0000477 // 6. Set up the diagnostic buffer for reporting errors
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000478
Kate Stoneb9c1b512016-09-06 20:57:50 +0000479 m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000480
Kate Stoneb9c1b512016-09-06 20:57:50 +0000481 // 7. Set up the source management objects inside the compiler
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000482
Kate Stoneb9c1b512016-09-06 20:57:50 +0000483 clang::FileSystemOptions file_system_options;
484 m_file_manager.reset(new clang::FileManager(file_system_options));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000485
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486 if (!m_compiler->hasSourceManager())
487 m_compiler->createSourceManager(*m_file_manager.get());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000488
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 m_compiler->createFileManager();
490 m_compiler->createPreprocessor(TU_Complete);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000491
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492 if (ClangModulesDeclVendor *decl_vendor =
493 target_sp->GetClangModulesDeclVendor()) {
494 ClangPersistentVariables *clang_persistent_vars =
495 llvm::cast<ClangPersistentVariables>(
496 target_sp->GetPersistentExpressionStateForLanguage(
497 lldb::eLanguageTypeC));
498 std::unique_ptr<PPCallbacks> pp_callbacks(
499 new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars));
500 m_pp_callbacks =
501 static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
502 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
503 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000504
Adrian Prantl05097242018-04-30 16:49:04 +0000505 // 8. Most of this we get from the CompilerInstance, but we also want to give
506 // the context an ExternalASTSource.
Raphael Isemann778b3082018-08-23 20:40:45 +0000507
508 auto &PP = m_compiler->getPreprocessor();
509 auto &builtin_context = PP.getBuiltinInfo();
510 builtin_context.initializeBuiltins(PP.getIdentifierTable(),
511 m_compiler->getLangOpts());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000512
Raphael Isemann596709d2018-08-27 15:18:33 +0000513 m_compiler->createASTContext();
514 clang::ASTContext &ast_context = m_compiler->getASTContext();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000515
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516 ClangExpressionHelper *type_system_helper =
517 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
518 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
Sean Callanan1a8d4092010-08-27 01:01:44 +0000519
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 if (decl_map) {
521 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source(
522 decl_map->CreateProxy());
Raphael Isemann596709d2018-08-27 15:18:33 +0000523 decl_map->InstallASTContext(ast_context, m_compiler->getFileManager());
524 ast_context.setExternalSource(ast_source);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 }
526
527 m_ast_context.reset(
528 new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str()));
Raphael Isemann596709d2018-08-27 15:18:33 +0000529 m_ast_context->setASTContext(&ast_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530
531 std::string module_name("$__lldb_module");
532
533 m_llvm_context.reset(new LLVMContext());
534 m_code_generator.reset(CreateLLVMCodeGen(
535 m_compiler->getDiagnostics(), module_name,
536 m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(),
537 m_compiler->getCodeGenOpts(), *m_llvm_context));
Sean Callanan1a8d4092010-08-27 01:01:44 +0000538}
539
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540ClangExpressionParser::~ClangExpressionParser() {}
Sean Callanan1a8d4092010-08-27 01:01:44 +0000541
Raphael Isemann74829732018-08-30 17:29:37 +0000542namespace {
543
544//----------------------------------------------------------------------
545/// @class CodeComplete
546///
547/// A code completion consumer for the clang Sema that is responsible for
548/// creating the completion suggestions when a user requests completion
549/// of an incomplete `expr` invocation.
550//----------------------------------------------------------------------
551class CodeComplete : public CodeCompleteConsumer {
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000552 CodeCompletionTUInfo m_info;
Raphael Isemann74829732018-08-30 17:29:37 +0000553
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000554 std::string m_expr;
555 unsigned m_position = 0;
Raphael Isemannc11a7802018-08-30 21:26:32 +0000556 CompletionRequest &m_request;
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000557 /// The printing policy we use when printing declarations for our completion
558 /// descriptions.
559 clang::PrintingPolicy m_desc_policy;
Raphael Isemann74829732018-08-30 17:29:37 +0000560
561 /// Returns true if the given character can be used in an identifier.
562 /// This also returns true for numbers because for completion we usually
563 /// just iterate backwards over iterators.
564 ///
565 /// Note: lldb uses '$' in its internal identifiers, so we also allow this.
566 static bool IsIdChar(char c) {
567 return c == '_' || std::isalnum(c) || c == '$';
568 }
569
570 /// Returns true if the given character is used to separate arguments
571 /// in the command line of lldb.
572 static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
573
574 /// Drops all tokens in front of the expression that are unrelated for
575 /// the completion of the cmd line. 'unrelated' means here that the token
576 /// is not interested for the lldb completion API result.
577 StringRef dropUnrelatedFrontTokens(StringRef cmd) {
578 if (cmd.empty())
579 return cmd;
580
581 // If we are at the start of a word, then all tokens are unrelated to
582 // the current completion logic.
583 if (IsTokenSeparator(cmd.back()))
584 return StringRef();
585
586 // Remove all previous tokens from the string as they are unrelated
587 // to completing the current token.
588 StringRef to_remove = cmd;
589 while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {
590 to_remove = to_remove.drop_back();
591 }
592 cmd = cmd.drop_front(to_remove.size());
593
594 return cmd;
595 }
596
597 /// Removes the last identifier token from the given cmd line.
598 StringRef removeLastToken(StringRef cmd) {
599 while (!cmd.empty() && IsIdChar(cmd.back())) {
600 cmd = cmd.drop_back();
601 }
602 return cmd;
603 }
604
605 /// Attemps to merge the given completion from the given position into the
606 /// existing command. Returns the completion string that can be returned to
607 /// the lldb completion API.
608 std::string mergeCompletion(StringRef existing, unsigned pos,
609 StringRef completion) {
610 StringRef existing_command = existing.substr(0, pos);
611 // We rewrite the last token with the completion, so let's drop that
612 // token from the command.
613 existing_command = removeLastToken(existing_command);
614 // We also should remove all previous tokens from the command as they
615 // would otherwise be added to the completion that already has the
616 // completion.
617 existing_command = dropUnrelatedFrontTokens(existing_command);
618 return existing_command.str() + completion.str();
619 }
620
621public:
622 /// Constructs a CodeComplete consumer that can be attached to a Sema.
623 /// @param[out] matches
624 /// The list of matches that the lldb completion API expects as a result.
625 /// This may already contain matches, so it's only allowed to append
626 /// to this variable.
627 /// @param[out] expr
628 /// The whole expression string that we are currently parsing. This
629 /// string needs to be equal to the input the user typed, and NOT the
630 /// final code that Clang is parsing.
631 /// @param[out] position
632 /// The character position of the user cursor in the `expr` parameter.
633 ///
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000634 CodeComplete(CompletionRequest &request, clang::LangOptions ops,
635 std::string expr, unsigned position)
Raphael Isemann74829732018-08-30 17:29:37 +0000636 : CodeCompleteConsumer(CodeCompleteOptions(), false),
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000637 m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000638 m_position(position), m_request(request), m_desc_policy(ops) {
639
640 // Ensure that the printing policy is producing a description that is as
641 // short as possible.
642 m_desc_policy.SuppressScope = true;
643 m_desc_policy.SuppressTagKeyword = true;
644 m_desc_policy.FullyQualifiedName = false;
645 m_desc_policy.TerseOutput = true;
646 m_desc_policy.IncludeNewlines = false;
647 m_desc_policy.UseVoidForZeroParams = false;
648 m_desc_policy.Bool = true;
649 }
Raphael Isemann74829732018-08-30 17:29:37 +0000650
651 /// Deregisters and destroys this code-completion consumer.
652 virtual ~CodeComplete() {}
653
654 /// \name Code-completion filtering
655 /// Check if the result should be filtered out.
656 bool isResultFilteredOut(StringRef Filter,
657 CodeCompletionResult Result) override {
658 // This code is mostly copied from CodeCompleteConsumer.
659 switch (Result.Kind) {
660 case CodeCompletionResult::RK_Declaration:
661 return !(
662 Result.Declaration->getIdentifier() &&
663 Result.Declaration->getIdentifier()->getName().startswith(Filter));
664 case CodeCompletionResult::RK_Keyword:
665 return !StringRef(Result.Keyword).startswith(Filter);
666 case CodeCompletionResult::RK_Macro:
667 return !Result.Macro->getName().startswith(Filter);
668 case CodeCompletionResult::RK_Pattern:
669 return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
670 }
671 // If we trigger this assert or the above switch yields a warning, then
672 // CodeCompletionResult has been enhanced with more kinds of completion
673 // results. Expand the switch above in this case.
674 assert(false && "Unknown completion result type?");
675 // If we reach this, then we should just ignore whatever kind of unknown
676 // result we got back. We probably can't turn it into any kind of useful
677 // completion suggestion with the existing code.
678 return true;
679 }
680
681 /// \name Code-completion callbacks
682 /// Process the finalized code-completion results.
683 void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,
684 CodeCompletionResult *Results,
685 unsigned NumResults) override {
686
687 // The Sema put the incomplete token we try to complete in here during
688 // lexing, so we need to retrieve it here to know what we are completing.
689 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
690
691 // Iterate over all the results. Filter out results we don't want and
692 // process the rest.
693 for (unsigned I = 0; I != NumResults; ++I) {
694 // Filter the results with the information from the Sema.
695 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
696 continue;
697
698 CodeCompletionResult &R = Results[I];
699 std::string ToInsert;
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000700 std::string Description;
Raphael Isemann74829732018-08-30 17:29:37 +0000701 // Handle the different completion kinds that come from the Sema.
702 switch (R.Kind) {
703 case CodeCompletionResult::RK_Declaration: {
704 const NamedDecl *D = R.Declaration;
705 ToInsert = R.Declaration->getNameAsString();
706 // If we have a function decl that has no arguments we want to
707 // complete the empty parantheses for the user. If the function has
708 // arguments, we at least complete the opening bracket.
709 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) {
710 if (F->getNumParams() == 0)
711 ToInsert += "()";
712 else
713 ToInsert += "(";
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000714 raw_string_ostream OS(Description);
715 F->print(OS, m_desc_policy, false);
716 OS.flush();
717 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
718 Description = V->getType().getAsString(m_desc_policy);
719 } else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) {
720 Description = F->getType().getAsString(m_desc_policy);
721 } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) {
722 // If we try to complete a namespace, then we can directly append
723 // the '::'.
Raphael Isemann74829732018-08-30 17:29:37 +0000724 if (!N->isAnonymousNamespace())
725 ToInsert += "::";
726 }
727 break;
728 }
729 case CodeCompletionResult::RK_Keyword:
730 ToInsert = R.Keyword;
731 break;
732 case CodeCompletionResult::RK_Macro:
Raphael Isemann74829732018-08-30 17:29:37 +0000733 ToInsert = R.Macro->getName().str();
734 break;
735 case CodeCompletionResult::RK_Pattern:
736 ToInsert = R.Pattern->getTypedText();
737 break;
738 }
739 // At this point all information is in the ToInsert string.
740
741 // We also filter some internal lldb identifiers here. The user
742 // shouldn't see these.
743 if (StringRef(ToInsert).startswith("$__lldb_"))
744 continue;
745 if (!ToInsert.empty()) {
746 // Merge the suggested Token into the existing command line to comply
747 // with the kind of result the lldb API expects.
748 std::string CompletionSuggestion =
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000749 mergeCompletion(m_expr, m_position, ToInsert);
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000750 m_request.AddCompletion(CompletionSuggestion, Description);
Raphael Isemann74829732018-08-30 17:29:37 +0000751 }
752 }
753 }
754
755 /// \param S the semantic-analyzer object for which code-completion is being
756 /// done.
757 ///
758 /// \param CurrentArg the index of the current argument.
759 ///
760 /// \param Candidates an array of overload candidates.
761 ///
762 /// \param NumCandidates the number of overload candidates
763 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
764 OverloadCandidate *Candidates,
765 unsigned NumCandidates,
766 SourceLocation OpenParLoc) override {
767 // At the moment we don't filter out any overloaded candidates.
768 }
769
770 CodeCompletionAllocator &getAllocator() override {
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000771 return m_info.getAllocator();
Raphael Isemann74829732018-08-30 17:29:37 +0000772 }
773
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000774 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; }
Raphael Isemann74829732018-08-30 17:29:37 +0000775};
776} // namespace
777
Raphael Isemannc11a7802018-08-30 21:26:32 +0000778bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line,
Raphael Isemann74829732018-08-30 17:29:37 +0000779 unsigned pos, unsigned typed_pos) {
780 DiagnosticManager mgr;
781 // We need the raw user expression here because that's what the CodeComplete
782 // class uses to provide completion suggestions.
783 // However, the `Text` method only gives us the transformed expression here.
784 // To actually get the raw user input here, we have to cast our expression to
785 // the LLVMUserExpression which exposes the right API. This should never fail
786 // as we always have a ClangUserExpression whenever we call this.
787 LLVMUserExpression &llvm_expr = *static_cast<LLVMUserExpression *>(&m_expr);
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000788 CodeComplete CC(request, m_compiler->getLangOpts(), llvm_expr.GetUserText(),
789 typed_pos);
Raphael Isemann74829732018-08-30 17:29:37 +0000790 // We don't need a code generator for parsing.
791 m_code_generator.reset();
792 // Start parsing the expression with our custom code completion consumer.
793 ParseInternal(mgr, &CC, line, pos);
794 return true;
795}
796
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
Raphael Isemann74829732018-08-30 17:29:37 +0000798 return ParseInternal(diagnostic_manager);
799}
800
801unsigned
802ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager,
803 CodeCompleteConsumer *completion_consumer,
804 unsigned completion_line,
805 unsigned completion_column) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000806 ClangDiagnosticManagerAdapter *adapter =
807 static_cast<ClangDiagnosticManagerAdapter *>(
808 m_compiler->getDiagnostics().getClient());
809 clang::TextDiagnosticBuffer *diag_buf = adapter->GetPassthrough();
810 diag_buf->FlushDiagnostics(m_compiler->getDiagnostics());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000811
Kate Stoneb9c1b512016-09-06 20:57:50 +0000812 adapter->ResetManager(&diagnostic_manager);
Sean Callanan579e70c2016-03-19 00:03:59 +0000813
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 const char *expr_text = m_expr.Text();
Rafael Espindola9cb97b62014-05-21 15:08:27 +0000815
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816 clang::SourceManager &source_mgr = m_compiler->getSourceManager();
817 bool created_main_file = false;
Raphael Isemann74829732018-08-30 17:29:37 +0000818
819 // Clang wants to do completion on a real file known by Clang's file manager,
820 // so we have to create one to make this work.
821 // TODO: We probably could also simulate to Clang's file manager that there
822 // is a real file that contains our code.
823 bool should_create_file = completion_consumer != nullptr;
824
825 // We also want a real file on disk if we generate full debug info.
826 should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==
827 codegenoptions::FullDebugInfo;
828
829 if (should_create_file) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830 int temp_fd = -1;
Stella Stamenovab3f44ad2018-12-10 17:23:28 +0000831 llvm::SmallString<128> result_path;
Pavel Labath60f028f2018-06-19 15:09:07 +0000832 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000833 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
834 std::string temp_source_path = tmpdir_file_spec.GetPath();
835 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
836 } else {
837 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
838 }
839
840 if (temp_fd != -1) {
841 lldb_private::File file(temp_fd, true);
842 const size_t expr_text_len = strlen(expr_text);
843 size_t bytes_written = expr_text_len;
844 if (file.Write(expr_text, bytes_written).Success()) {
845 if (bytes_written == expr_text_len) {
846 file.Close();
847 source_mgr.setMainFileID(
848 source_mgr.createFileID(m_file_manager->getFile(result_path),
849 SourceLocation(), SrcMgr::C_User));
850 created_main_file = true;
Greg Clayton23f8c952014-03-24 23:10:19 +0000851 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852 }
Greg Clayton23f8c952014-03-24 23:10:19 +0000853 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000855
Kate Stoneb9c1b512016-09-06 20:57:50 +0000856 if (!created_main_file) {
857 std::unique_ptr<MemoryBuffer> memory_buffer =
858 MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
859 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
860 }
861
862 diag_buf->BeginSourceFile(m_compiler->getLangOpts(),
863 &m_compiler->getPreprocessor());
864
865 ClangExpressionHelper *type_system_helper =
866 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
867
868 ASTConsumer *ast_transformer =
869 type_system_helper->ASTTransformer(m_code_generator.get());
870
871 if (ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap())
872 decl_map->InstallCodeGenerator(m_code_generator.get());
873
Raphael Isemann74829732018-08-30 17:29:37 +0000874 // If we want to parse for code completion, we need to attach our code
875 // completion consumer to the Sema and specify a completion position.
876 // While parsing the Sema will call this consumer with the provided
877 // completion suggestions.
878 if (completion_consumer) {
879 auto main_file = source_mgr.getFileEntryForID(source_mgr.getMainFileID());
880 auto &PP = m_compiler->getPreprocessor();
881 // Lines and columns start at 1 in Clang, but code completion positions are
882 // indexed from 0, so we need to add 1 to the line and column here.
883 ++completion_line;
884 ++completion_column;
885 PP.SetCodeCompletionPoint(main_file, completion_line, completion_column);
886 }
887
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 if (ast_transformer) {
889 ast_transformer->Initialize(m_compiler->getASTContext());
890 ParseAST(m_compiler->getPreprocessor(), ast_transformer,
Raphael Isemann74829732018-08-30 17:29:37 +0000891 m_compiler->getASTContext(), false, TU_Complete,
892 completion_consumer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893 } else {
894 m_code_generator->Initialize(m_compiler->getASTContext());
895 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(),
Raphael Isemann74829732018-08-30 17:29:37 +0000896 m_compiler->getASTContext(), false, TU_Complete,
897 completion_consumer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000898 }
899
900 diag_buf->EndSourceFile();
901
902 unsigned num_errors = diag_buf->getNumErrors();
903
904 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
905 num_errors++;
Zachary Turnere2411fa2016-11-12 19:12:56 +0000906 diagnostic_manager.PutString(eDiagnosticSeverityError,
907 "while importing modules:");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908 diagnostic_manager.AppendMessageToDiagnostic(
Zachary Turnerc1564272016-11-16 21:15:24 +0000909 m_pp_callbacks->getErrorString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910 }
911
912 if (!num_errors) {
913 if (type_system_helper->DeclMap() &&
914 !type_system_helper->DeclMap()->ResolveUnknownTypes()) {
915 diagnostic_manager.Printf(eDiagnosticSeverityError,
916 "Couldn't infer the type of a variable");
917 num_errors++;
Greg Clayton23f8c952014-03-24 23:10:19 +0000918 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000919 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000920
Kate Stoneb9c1b512016-09-06 20:57:50 +0000921 if (!num_errors) {
922 type_system_helper->CommitPersistentDecls();
923 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000924
Kate Stoneb9c1b512016-09-06 20:57:50 +0000925 adapter->ResetManager();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000926
Kate Stoneb9c1b512016-09-06 20:57:50 +0000927 return num_errors;
Sean Callanan1a8d4092010-08-27 01:01:44 +0000928}
929
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000930std::string
Kate Stoneb9c1b512016-09-06 20:57:50 +0000931ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {
932 std::string abi;
933
934 if (target_arch.IsMIPS()) {
935 switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
936 case ArchSpec::eMIPSABI_N64:
937 abi = "n64";
938 break;
939 case ArchSpec::eMIPSABI_N32:
940 abi = "n32";
941 break;
942 case ArchSpec::eMIPSABI_O32:
943 abi = "o32";
944 break;
945 default:
946 break;
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000947 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948 }
949 return abi;
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000950}
951
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952bool ClangExpressionParser::RewriteExpression(
953 DiagnosticManager &diagnostic_manager) {
954 clang::SourceManager &source_manager = m_compiler->getSourceManager();
955 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
956 nullptr);
957 clang::edit::Commit commit(editor);
958 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
Jim Inghama1e541b2016-03-25 01:57:14 +0000959
Kate Stoneb9c1b512016-09-06 20:57:50 +0000960 class RewritesReceiver : public edit::EditsReceiver {
961 Rewriter &rewrite;
Jim Inghama1e541b2016-03-25 01:57:14 +0000962
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963 public:
964 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
965
966 void insert(SourceLocation loc, StringRef text) override {
967 rewrite.InsertText(loc, text);
Jim Inghama1e541b2016-03-25 01:57:14 +0000968 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 void replace(CharSourceRange range, StringRef text) override {
970 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
Sean Callananfc55f5d2010-09-21 00:44:12 +0000971 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000972 };
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000973
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 RewritesReceiver rewrites_receiver(rewriter);
975
976 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
977 size_t num_diags = diagnostics.size();
978 if (num_diags == 0)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000979 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980
981 for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) {
982 const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag);
983 if (diagnostic && diagnostic->HasFixIts()) {
984 for (const FixItHint &fixit : diagnostic->FixIts()) {
985 // This is cobbed from clang::Rewrite::FixItRewriter.
986 if (fixit.CodeToInsert.empty()) {
987 if (fixit.InsertFromRange.isValid()) {
988 commit.insertFromRange(fixit.RemoveRange.getBegin(),
989 fixit.InsertFromRange, /*afterToken=*/false,
990 fixit.BeforePreviousInsertions);
991 } else
992 commit.remove(fixit.RemoveRange);
993 } else {
994 if (fixit.RemoveRange.isTokenRange() ||
995 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd())
996 commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
997 else
998 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
999 /*afterToken=*/false, fixit.BeforePreviousInsertions);
1000 }
1001 }
1002 }
1003 }
1004
1005 // FIXME - do we want to try to propagate specific errors here?
1006 if (!commit.isCommitable())
1007 return false;
1008 else if (!editor.commit(commit))
1009 return false;
1010
1011 // Now play all the edits, and stash the result in the diagnostic manager.
1012 editor.applyRewrites(rewrites_receiver);
1013 RewriteBuffer &main_file_buffer =
1014 rewriter.getEditBuffer(source_manager.getMainFileID());
1015
1016 std::string fixed_expression;
1017 llvm::raw_string_ostream out_stream(fixed_expression);
1018
1019 main_file_buffer.write(out_stream);
1020 out_stream.flush();
1021 diagnostic_manager.SetFixedExpression(fixed_expression);
1022
1023 return true;
Sean Callananfc55f5d2010-09-21 00:44:12 +00001024}
1025
Kate Stoneb9c1b512016-09-06 20:57:50 +00001026static bool FindFunctionInModule(ConstString &mangled_name,
1027 llvm::Module *module, const char *orig_name) {
1028 for (const auto &func : module->getFunctionList()) {
1029 const StringRef &name = func.getName();
1030 if (name.find(orig_name) != StringRef::npos) {
1031 mangled_name.SetString(name);
1032 return true;
Sean Callanan1a8d4092010-08-27 01:01:44 +00001033 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001034 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001035
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 return false;
Sean Callanan1a8d4092010-08-27 01:01:44 +00001037}
Sean Callananbd4dc692016-03-21 22:23:38 +00001038
Zachary Turner97206d52017-05-12 04:51:55 +00001039lldb_private::Status ClangExpressionParser::PrepareForExecution(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001040 lldb::addr_t &func_addr, lldb::addr_t &func_end,
1041 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
1042 bool &can_interpret, ExecutionPolicy execution_policy) {
1043 func_addr = LLDB_INVALID_ADDRESS;
1044 func_end = LLDB_INVALID_ADDRESS;
1045 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1046
Zachary Turner97206d52017-05-12 04:51:55 +00001047 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001048
1049 std::unique_ptr<llvm::Module> llvm_module_ap(
1050 m_code_generator->ReleaseModule());
1051
1052 if (!llvm_module_ap.get()) {
1053 err.SetErrorToGenericError();
1054 err.SetErrorString("IR doesn't contain a module");
Sean Callananbd4dc692016-03-21 22:23:38 +00001055 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001056 }
1057
1058 ConstString function_name;
1059
1060 if (execution_policy != eExecutionPolicyTopLevel) {
1061 // Find the actual name of the function (it's often mangled somehow)
1062
1063 if (!FindFunctionInModule(function_name, llvm_module_ap.get(),
1064 m_expr.FunctionName())) {
1065 err.SetErrorToGenericError();
1066 err.SetErrorStringWithFormat("Couldn't find %s() in the module",
1067 m_expr.FunctionName());
1068 return err;
1069 } else {
1070 if (log)
1071 log->Printf("Found function %s for %s", function_name.AsCString(),
1072 m_expr.FunctionName());
1073 }
1074 }
1075
1076 SymbolContext sc;
1077
1078 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
1079 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
1080 } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
1081 sc.target_sp = target_sp;
1082 }
1083
1084 LLVMUserExpression::IRPasses custom_passes;
1085 {
1086 auto lang = m_expr.Language();
1087 if (log)
Bruce Mitchener4ebdee02018-05-29 09:10:46 +00001088 log->Printf("%s - Current expression language is %s\n", __FUNCTION__,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001089 Language::GetNameForLanguageType(lang));
Jim Ingham22562152016-11-03 23:42:09 +00001090 lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
1091 if (process_sp && lang != lldb::eLanguageTypeUnknown) {
1092 auto runtime = process_sp->GetLanguageRuntime(lang);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 if (runtime)
1094 runtime->GetIRPasses(custom_passes);
1095 }
1096 }
1097
1098 if (custom_passes.EarlyPasses) {
1099 if (log)
1100 log->Printf("%s - Running Early IR Passes from LanguageRuntime on "
1101 "expression module '%s'",
1102 __FUNCTION__, m_expr.FunctionName());
1103
1104 custom_passes.EarlyPasses->run(*llvm_module_ap);
1105 }
1106
1107 execution_unit_sp.reset(
1108 new IRExecutionUnit(m_llvm_context, // handed off here
1109 llvm_module_ap, // handed off here
1110 function_name, exe_ctx.GetTargetSP(), sc,
1111 m_compiler->getTargetOpts().Features));
1112
1113 ClangExpressionHelper *type_system_helper =
1114 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1115 ClangExpressionDeclMap *decl_map =
1116 type_system_helper->DeclMap(); // result can be NULL
1117
1118 if (decl_map) {
1119 Stream *error_stream = NULL;
1120 Target *target = exe_ctx.GetTargetPtr();
1121 error_stream = target->GetDebugger().GetErrorFile().get();
1122
1123 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
1124 *execution_unit_sp, *error_stream,
1125 function_name.AsCString());
1126
1127 bool ir_can_run =
1128 ir_for_target.runOnModule(*execution_unit_sp->GetModule());
1129
1130 if (!ir_can_run) {
1131 err.SetErrorString(
1132 "The expression could not be prepared to run in the target");
1133 return err;
1134 }
1135
1136 Process *process = exe_ctx.GetProcessPtr();
1137
1138 if (execution_policy != eExecutionPolicyAlways &&
1139 execution_policy != eExecutionPolicyTopLevel) {
Zachary Turner97206d52017-05-12 04:51:55 +00001140 lldb_private::Status interpret_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001141
1142 bool interpret_function_calls =
1143 !process ? false : process->CanInterpretFunctionCalls();
1144 can_interpret = IRInterpreter::CanInterpret(
1145 *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
1146 interpret_error, interpret_function_calls);
1147
1148 if (!can_interpret && execution_policy == eExecutionPolicyNever) {
1149 err.SetErrorStringWithFormat("Can't run the expression locally: %s",
1150 interpret_error.AsCString());
1151 return err;
1152 }
1153 }
1154
1155 if (!process && execution_policy == eExecutionPolicyAlways) {
1156 err.SetErrorString("Expression needed to run in the target, but the "
1157 "target can't be run");
1158 return err;
1159 }
1160
1161 if (!process && execution_policy == eExecutionPolicyTopLevel) {
1162 err.SetErrorString("Top-level code needs to be inserted into a runnable "
1163 "target, but the target can't be run");
1164 return err;
1165 }
1166
1167 if (execution_policy == eExecutionPolicyAlways ||
1168 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
1169 if (m_expr.NeedsValidation() && process) {
1170 if (!process->GetDynamicCheckers()) {
1171 DynamicCheckerFunctions *dynamic_checkers =
1172 new DynamicCheckerFunctions();
1173
1174 DiagnosticManager install_diagnostics;
1175
1176 if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) {
1177 if (install_diagnostics.Diagnostics().size())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001178 err.SetErrorString(install_diagnostics.GetString().c_str());
Raphael Isemann262dd8c2018-09-11 13:59:47 +00001179 else
1180 err.SetErrorString("couldn't install checkers, unknown error");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001181
1182 return err;
1183 }
1184
1185 process->SetDynamicCheckers(dynamic_checkers);
1186
1187 if (log)
Raphael Isemannf75a9dc2019-02-11 21:45:33 +00001188 log->Printf("== [ClangExpressionParser::PrepareForExecution] "
1189 "Finished installing dynamic checkers ==");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190 }
1191
1192 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(),
1193 function_name.AsCString());
1194
1195 llvm::Module *module = execution_unit_sp->GetModule();
1196 if (!module || !ir_dynamic_checks.runOnModule(*module)) {
1197 err.SetErrorToGenericError();
1198 err.SetErrorString("Couldn't add dynamic checks to the expression");
1199 return err;
1200 }
1201
1202 if (custom_passes.LatePasses) {
1203 if (log)
1204 log->Printf("%s - Running Late IR Passes from LanguageRuntime on "
1205 "expression module '%s'",
1206 __FUNCTION__, m_expr.FunctionName());
1207
1208 custom_passes.LatePasses->run(*module);
1209 }
1210 }
1211 }
1212
1213 if (execution_policy == eExecutionPolicyAlways ||
1214 execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
1215 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1216 }
1217 } else {
1218 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1219 }
1220
1221 return err;
1222}
1223
Zachary Turner97206d52017-05-12 04:51:55 +00001224lldb_private::Status ClangExpressionParser::RunStaticInitializers(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001225 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) {
Zachary Turner97206d52017-05-12 04:51:55 +00001226 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001227
1228 lldbassert(execution_unit_sp.get());
1229 lldbassert(exe_ctx.HasThreadScope());
1230
1231 if (!execution_unit_sp.get()) {
1232 err.SetErrorString(
1233 "can't run static initializers for a NULL execution unit");
1234 return err;
1235 }
1236
1237 if (!exe_ctx.HasThreadScope()) {
1238 err.SetErrorString("can't run static initializers without a thread");
1239 return err;
1240 }
1241
1242 std::vector<lldb::addr_t> static_initializers;
1243
1244 execution_unit_sp->GetStaticInitializers(static_initializers);
1245
1246 for (lldb::addr_t static_initializer : static_initializers) {
1247 EvaluateExpressionOptions options;
1248
1249 lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(
1250 exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(),
1251 llvm::ArrayRef<lldb::addr_t>(), options));
1252
1253 DiagnosticManager execution_errors;
1254 lldb::ExpressionResults results =
1255 exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(
1256 exe_ctx, call_static_initializer, options, execution_errors);
1257
1258 if (results != lldb::eExpressionCompleted) {
1259 err.SetErrorStringWithFormat("couldn't run static initializer: %s",
1260 execution_errors.GetString().c_str());
1261 return err;
1262 }
1263 }
1264
1265 return err;
Sean Callananbd4dc692016-03-21 22:23:38 +00001266}