blob: cfd5d9be1118c2cc53dfc6eb407a2bdd7caef65c [file] [log] [blame]
Sean Callanan1a8d4092010-08-27 01:01:44 +00001//===-- ClangExpressionParser.cpp -------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000010// C Includes
11// C++ Includes
12// Other libraries and framework includes
Sean Callanan1a8d4092010-08-27 01:01:44 +000013#include "clang/AST/ASTContext.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000014#include "clang/AST/ASTDiagnostic.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000015#include "clang/AST/ExternalASTSource.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000016#include "clang/Basic/DiagnosticIDs.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000017#include "clang/Basic/FileManager.h"
Jim Ingham151c0322015-09-15 21:13:50 +000018#include "clang/Basic/SourceLocation.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000019#include "clang/Basic/TargetInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000020#include "clang/Basic/Version.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000021#include "clang/CodeGen/CodeGenAction.h"
22#include "clang/CodeGen/ModuleBuilder.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000023#include "clang/Edit/Commit.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000024#include "clang/Edit/EditedSource.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000025#include "clang/Edit/EditsReceiver.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/CompilerInvocation.h"
28#include "clang/Frontend/FrontendActions.h"
29#include "clang/Frontend/FrontendDiagnostic.h"
30#include "clang/Frontend/FrontendPluginRegistry.h"
31#include "clang/Frontend/TextDiagnosticBuffer.h"
32#include "clang/Frontend/TextDiagnosticPrinter.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000033#include "clang/Lex/Preprocessor.h"
Sean Callanane2ef6e32010-09-23 03:01:22 +000034#include "clang/Parse/ParseAST.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000035#include "clang/Rewrite/Core/Rewriter.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000036#include "clang/Rewrite/Frontend/FrontendActions.h"
Raphael Isemann74829732018-08-30 17:29:37 +000037#include "clang/Sema/CodeCompleteConsumer.h"
38#include "clang/Sema/Sema.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000039#include "clang/Sema/SemaConsumer.h"
40
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ExecutionEngine/ExecutionEngine.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000043#include "llvm/Support/Debug.h"
Rafael Espindola4609ea82013-06-26 14:10:56 +000044#include "llvm/Support/FileSystem.h"
Sean Callanan880e6802011-10-07 23:18:13 +000045#include "llvm/Support/TargetSelect.h"
Greg Clayton70b57652011-05-15 01:25:55 +000046
Greg Claytonc9a078a2016-03-24 23:50:03 +000047#pragma clang diagnostic push
48#pragma clang diagnostic ignored "-Wglobal-constructors"
Ed Mastea09ed032014-03-18 18:55:06 +000049#include "llvm/ExecutionEngine/MCJIT.h"
Greg Claytonc9a078a2016-03-24 23:50:03 +000050#pragma clang diagnostic pop
51
Chandler Carruth1e157582013-01-02 12:20:07 +000052#include "llvm/IR/LLVMContext.h"
53#include "llvm/IR/Module.h"
Greg Clayton38a61402010-12-02 23:20:03 +000054#include "llvm/Support/DynamicLibrary.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000055#include "llvm/Support/ErrorHandling.h"
Greg Clayton38a61402010-12-02 23:20:03 +000056#include "llvm/Support/Host.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000057#include "llvm/Support/MemoryBuffer.h"
Greg Clayton38a61402010-12-02 23:20:03 +000058#include "llvm/Support/Signals.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000059
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000060// Project includes
Jim Inghama1e541b2016-03-25 01:57:14 +000061#include "ClangDiagnostic.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000062#include "ClangExpressionParser.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000063
64#include "ClangASTSource.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000065#include "ClangExpressionDeclMap.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000066#include "ClangExpressionHelper.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000067#include "ClangModulesDeclVendor.h"
68#include "ClangPersistentVariables.h"
69#include "IRForTarget.h"
70
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000071#include "lldb/Core/Debugger.h"
72#include "lldb/Core/Disassembler.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000073#include "lldb/Core/Module.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000074#include "lldb/Core/StreamFile.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000075#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000076#include "lldb/Expression/IRExecutionUnit.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000077#include "lldb/Expression/IRInterpreter.h"
78#include "lldb/Host/File.h"
79#include "lldb/Host/HostInfo.h"
80#include "lldb/Symbol/ClangASTContext.h"
81#include "lldb/Symbol/SymbolVendor.h"
82#include "lldb/Target/ExecutionContext.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000083#include "lldb/Target/Language.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000084#include "lldb/Target/ObjCLanguageRuntime.h"
85#include "lldb/Target/Process.h"
86#include "lldb/Target/Target.h"
Sean Callananbd4dc692016-03-21 22:23:38 +000087#include "lldb/Target/ThreadPlanCallFunction.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000088#include "lldb/Utility/DataBufferHeap.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000089#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000090#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000091#include "lldb/Utility/Stream.h"
92#include "lldb/Utility/StreamString.h"
Zachary Turner573ab902017-03-21 18:25:04 +000093#include "lldb/Utility/StringList.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000094
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());
254 lldb::LanguageType frame_lang =
255 expr.Language(); // defaults to lldb::eLanguageTypeUnknown
256 bool overridden_target_opts = false;
257 lldb_private::LanguageRuntime *lang_rt = nullptr;
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000258
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259 std::string abi;
260 ArchSpec target_arch;
261 target_arch = target_sp->GetArchitecture();
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000262
Kate Stoneb9c1b512016-09-06 20:57:50 +0000263 const auto target_machine = target_arch.GetMachine();
Jason Molendaa3329782014-03-29 18:54:20 +0000264
Adrian Prantl05097242018-04-30 16:49:04 +0000265 // If the expression is being evaluated in the context of an existing stack
266 // frame, we introspect to see if the language runtime is available.
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000267
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268 lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
269 lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000270
Adrian Prantl05097242018-04-30 16:49:04 +0000271 // Make sure the user hasn't provided a preferred execution language with
272 // `expression --language X -- ...`
Kate Stoneb9c1b512016-09-06 20:57:50 +0000273 if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
274 frame_lang = frame_sp->GetLanguage();
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000275
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276 if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
277 lang_rt = process_sp->GetLanguageRuntime(frame_lang);
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000278 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000279 log->Printf("Frame has language of type %s",
280 Language::GetNameForLanguageType(frame_lang));
281 }
Alp Toker5f838642014-07-06 05:36:57 +0000282
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283 // 2. Configure the compiler with a set of default options that are
Adrian Prantl05097242018-04-30 16:49:04 +0000284 // appropriate for most situations.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000285 if (target_arch.IsValid()) {
286 std::string triple = target_arch.GetTriple().str();
287 m_compiler->getTargetOpts().Triple = triple;
288 if (log)
289 log->Printf("Using %s as the target triple",
290 m_compiler->getTargetOpts().Triple.c_str());
291 } else {
292 // If we get here we don't have a valid target and just have to guess.
293 // Sometimes this will be ok to just use the host target triple (when we
Adrian Prantl05097242018-04-30 16:49:04 +0000294 // evaluate say "2+3", but other expressions like breakpoint conditions and
295 // other things that _are_ target specific really shouldn't just be using
296 // the host triple. In such a case the language runtime should expose an
297 // overridden options set (3), below.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
299 if (log)
300 log->Printf("Using default target triple of %s",
301 m_compiler->getTargetOpts().Triple.c_str());
302 }
Adrian Prantl05097242018-04-30 16:49:04 +0000303 // Now add some special fixes for known architectures: Any arm32 iOS
304 // environment, but not on arm64
Kate Stoneb9c1b512016-09-06 20:57:50 +0000305 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
306 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
307 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
308 m_compiler->getTargetOpts().ABI = "apcs-gnu";
309 }
310 // Supported subsets of x86
311 if (target_machine == llvm::Triple::x86 ||
312 target_machine == llvm::Triple::x86_64) {
313 m_compiler->getTargetOpts().Features.push_back("+sse");
314 m_compiler->getTargetOpts().Features.push_back("+sse2");
315 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000316
Adrian Prantl05097242018-04-30 16:49:04 +0000317 // Set the target CPU to generate code for. This will be empty for any CPU
318 // that doesn't really need to make a special
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319 // CPU string.
320 m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
Ewan Crawford7648dd32016-03-10 12:38:55 +0000321
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322 // Set the target ABI
323 abi = GetClangTargetABI(target_arch);
324 if (!abi.empty())
325 m_compiler->getTargetOpts().ABI = abi;
326
327 // 3. Now allow the runtime to provide custom configuration options for the
Adrian Prantl05097242018-04-30 16:49:04 +0000328 // target. In this case, a specialized language runtime is available and we
329 // can query it for extra options. For 99% of use cases, this will not be
330 // needed and should be provided when basic platform detection is not enough.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331 if (lang_rt)
332 overridden_target_opts =
333 lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
334
335 if (overridden_target_opts)
Pavel Labath6302bf62017-02-13 11:03:17 +0000336 if (log && log->GetVerbose()) {
337 LLDB_LOGV(
338 log, "Using overridden target options for the expression evaluation");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339
340 auto opts = m_compiler->getTargetOpts();
Pavel Labath6302bf62017-02-13 11:03:17 +0000341 LLDB_LOGV(log, "Triple: '{0}'", opts.Triple);
342 LLDB_LOGV(log, "CPU: '{0}'", opts.CPU);
343 LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath);
344 LLDB_LOGV(log, "ABI: '{0}'", opts.ABI);
345 LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000346 StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
347 StringList::LogDump(log, opts.Features, "Features");
Sean Callananc7b65062011-11-07 23:35:40 +0000348 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000349
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 // 4. Create and install the target on the compiler.
351 m_compiler->createDiagnostics();
352 auto target_info = TargetInfo::CreateTargetInfo(
353 m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
354 if (log) {
355 log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign());
356 log->Printf("Target datalayout string: '%s'",
357 target_info->getDataLayout().getStringRepresentation().c_str());
358 log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str());
359 log->Printf("Target vector alignment: %d",
360 target_info->getMaxVectorAlign());
361 }
362 m_compiler->setTarget(target_info);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000363
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 assert(m_compiler->hasTarget());
Tamas Berghammerdccbfaf2015-03-31 10:21:50 +0000365
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 // 5. Set language options.
367 lldb::LanguageType language = expr.Language();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000368
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 switch (language) {
370 case lldb::eLanguageTypeC:
371 case lldb::eLanguageTypeC89:
372 case lldb::eLanguageTypeC99:
373 case lldb::eLanguageTypeC11:
374 // FIXME: the following language option is a temporary workaround,
375 // to "ask for C, get C++."
Adrian Prantl05097242018-04-30 16:49:04 +0000376 // For now, the expression parser must use C++ anytime the language is a C
377 // family language, because the expression parser uses features of C++ to
378 // capture values.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 m_compiler->getLangOpts().CPlusPlus = true;
380 break;
381 case lldb::eLanguageTypeObjC:
382 m_compiler->getLangOpts().ObjC1 = true;
383 m_compiler->getLangOpts().ObjC2 = true;
384 // FIXME: the following language option is a temporary workaround,
385 // to "ask for ObjC, get ObjC++" (see comment above).
386 m_compiler->getLangOpts().CPlusPlus = true;
Davide Italiano89419f82017-12-15 00:50:43 +0000387
388 // Clang now sets as default C++14 as the default standard (with
389 // GNU extensions), so we do the same here to avoid mismatches that
Adrian Prantl05097242018-04-30 16:49:04 +0000390 // cause compiler error when evaluating expressions (e.g. nullptr not found
391 // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
392 // two lines below) so we decide to be consistent with that, but this could
393 // be re-evaluated in the future.
Davide Italiano89419f82017-12-15 00:50:43 +0000394 m_compiler->getLangOpts().CPlusPlus11 = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 break;
396 case lldb::eLanguageTypeC_plus_plus:
397 case lldb::eLanguageTypeC_plus_plus_11:
398 case lldb::eLanguageTypeC_plus_plus_14:
399 m_compiler->getLangOpts().CPlusPlus11 = true;
400 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
401 LLVM_FALLTHROUGH;
402 case lldb::eLanguageTypeC_plus_plus_03:
403 m_compiler->getLangOpts().CPlusPlus = true;
404 // FIXME: the following language option is a temporary workaround,
Adrian Prantl05097242018-04-30 16:49:04 +0000405 // to "ask for C++, get ObjC++". Apple hopes to remove this requirement on
406 // non-Apple platforms, but for now it is needed.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 m_compiler->getLangOpts().ObjC1 = true;
408 break;
409 case lldb::eLanguageTypeObjC_plus_plus:
410 case lldb::eLanguageTypeUnknown:
411 default:
412 m_compiler->getLangOpts().ObjC1 = true;
413 m_compiler->getLangOpts().ObjC2 = true;
414 m_compiler->getLangOpts().CPlusPlus = true;
415 m_compiler->getLangOpts().CPlusPlus11 = true;
416 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
417 break;
418 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000419
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420 m_compiler->getLangOpts().Bool = true;
421 m_compiler->getLangOpts().WChar = true;
422 m_compiler->getLangOpts().Blocks = true;
423 m_compiler->getLangOpts().DebuggerSupport =
424 true; // Features specifically for debugger clients
425 if (expr.DesiredResultType() == Expression::eResultTypeId)
426 m_compiler->getLangOpts().DebuggerCastResultToId = true;
427
428 m_compiler->getLangOpts().CharIsSigned =
429 ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
430 .CharIsSignedByDefault();
431
Adrian Prantl05097242018-04-30 16:49:04 +0000432 // Spell checking is a nice feature, but it ends up completing a lot of types
433 // that we didn't strictly speaking need to complete. As a result, we spend a
434 // long time parsing and importing debug information.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000435 m_compiler->getLangOpts().SpellChecking = false;
436
437 if (process_sp && m_compiler->getLangOpts().ObjC1) {
438 if (process_sp->GetObjCLanguageRuntime()) {
439 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() ==
440 ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
441 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX,
442 VersionTuple(10, 7));
443 else
444 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
445 VersionTuple(10, 7));
446
447 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
448 m_compiler->getLangOpts().DebuggerObjCLiteral = true;
Sean Callananc3a16002011-01-17 23:42:46 +0000449 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450 }
Greg Claytonf83f32d2011-01-15 01:32:14 +0000451
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452 m_compiler->getLangOpts().ThreadsafeStatics = false;
453 m_compiler->getLangOpts().AccessControl =
454 false; // Debuggers get universal access
455 m_compiler->getLangOpts().DollarIdents =
456 true; // $ indicates a persistent variable name
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000457
Kate Stoneb9c1b512016-09-06 20:57:50 +0000458 // Set CodeGen options
459 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
460 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
461 m_compiler->getCodeGenOpts().DisableFPElim = true;
462 m_compiler->getCodeGenOpts().OmitLeafFramePointer = false;
463 if (generate_debug_info)
464 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
465 else
466 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000467
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468 // Disable some warnings.
469 m_compiler->getDiagnostics().setSeverityForGroup(
470 clang::diag::Flavor::WarningOrError, "unused-value",
471 clang::diag::Severity::Ignored, SourceLocation());
472 m_compiler->getDiagnostics().setSeverityForGroup(
473 clang::diag::Flavor::WarningOrError, "odr",
474 clang::diag::Severity::Ignored, SourceLocation());
Alp Toker10933d12014-06-12 11:14:32 +0000475
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476 // Inform the target of the language options
477 //
478 // FIXME: We shouldn't need to do this, the target should be immutable once
479 // created. This complexity should be lifted elsewhere.
480 m_compiler->getTarget().adjust(m_compiler->getLangOpts());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000481
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482 // 6. Set up the diagnostic buffer for reporting errors
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000483
Kate Stoneb9c1b512016-09-06 20:57:50 +0000484 m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000485
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486 // 7. Set up the source management objects inside the compiler
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000487
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 clang::FileSystemOptions file_system_options;
489 m_file_manager.reset(new clang::FileManager(file_system_options));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000490
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491 if (!m_compiler->hasSourceManager())
492 m_compiler->createSourceManager(*m_file_manager.get());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000493
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 m_compiler->createFileManager();
495 m_compiler->createPreprocessor(TU_Complete);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000496
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497 if (ClangModulesDeclVendor *decl_vendor =
498 target_sp->GetClangModulesDeclVendor()) {
499 ClangPersistentVariables *clang_persistent_vars =
500 llvm::cast<ClangPersistentVariables>(
501 target_sp->GetPersistentExpressionStateForLanguage(
502 lldb::eLanguageTypeC));
503 std::unique_ptr<PPCallbacks> pp_callbacks(
504 new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars));
505 m_pp_callbacks =
506 static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
507 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
508 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000509
Adrian Prantl05097242018-04-30 16:49:04 +0000510 // 8. Most of this we get from the CompilerInstance, but we also want to give
511 // the context an ExternalASTSource.
Raphael Isemann778b3082018-08-23 20:40:45 +0000512 // We enable all builtin functions beside the builtins from libc/libm (e.g.
513 // 'fopen'). Those libc functions are already correctly handled by LLDB, and
514 // additionally enabling them as expandable builtins is breaking Clang.
515 m_compiler->getLangOpts().NoBuiltin = true;
516
517 auto &PP = m_compiler->getPreprocessor();
518 auto &builtin_context = PP.getBuiltinInfo();
519 builtin_context.initializeBuiltins(PP.getIdentifierTable(),
520 m_compiler->getLangOpts());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000521
Raphael Isemann596709d2018-08-27 15:18:33 +0000522 m_compiler->createASTContext();
523 clang::ASTContext &ast_context = m_compiler->getASTContext();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000524
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 ClangExpressionHelper *type_system_helper =
526 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
527 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
Sean Callanan1a8d4092010-08-27 01:01:44 +0000528
Kate Stoneb9c1b512016-09-06 20:57:50 +0000529 if (decl_map) {
530 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source(
531 decl_map->CreateProxy());
Raphael Isemann596709d2018-08-27 15:18:33 +0000532 decl_map->InstallASTContext(ast_context, m_compiler->getFileManager());
533 ast_context.setExternalSource(ast_source);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534 }
535
536 m_ast_context.reset(
537 new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str()));
Raphael Isemann596709d2018-08-27 15:18:33 +0000538 m_ast_context->setASTContext(&ast_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539
540 std::string module_name("$__lldb_module");
541
542 m_llvm_context.reset(new LLVMContext());
543 m_code_generator.reset(CreateLLVMCodeGen(
544 m_compiler->getDiagnostics(), module_name,
545 m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(),
546 m_compiler->getCodeGenOpts(), *m_llvm_context));
Sean Callanan1a8d4092010-08-27 01:01:44 +0000547}
548
Kate Stoneb9c1b512016-09-06 20:57:50 +0000549ClangExpressionParser::~ClangExpressionParser() {}
Sean Callanan1a8d4092010-08-27 01:01:44 +0000550
Raphael Isemann74829732018-08-30 17:29:37 +0000551namespace {
552
553//----------------------------------------------------------------------
554/// @class CodeComplete
555///
556/// A code completion consumer for the clang Sema that is responsible for
557/// creating the completion suggestions when a user requests completion
558/// of an incomplete `expr` invocation.
559//----------------------------------------------------------------------
560class CodeComplete : public CodeCompleteConsumer {
561 CodeCompletionTUInfo CCTUInfo;
562
563 std::string expr;
564 unsigned position = 0;
565 StringList &matches;
566
567 /// Returns true if the given character can be used in an identifier.
568 /// This also returns true for numbers because for completion we usually
569 /// just iterate backwards over iterators.
570 ///
571 /// Note: lldb uses '$' in its internal identifiers, so we also allow this.
572 static bool IsIdChar(char c) {
573 return c == '_' || std::isalnum(c) || c == '$';
574 }
575
576 /// Returns true if the given character is used to separate arguments
577 /// in the command line of lldb.
578 static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
579
580 /// Drops all tokens in front of the expression that are unrelated for
581 /// the completion of the cmd line. 'unrelated' means here that the token
582 /// is not interested for the lldb completion API result.
583 StringRef dropUnrelatedFrontTokens(StringRef cmd) {
584 if (cmd.empty())
585 return cmd;
586
587 // If we are at the start of a word, then all tokens are unrelated to
588 // the current completion logic.
589 if (IsTokenSeparator(cmd.back()))
590 return StringRef();
591
592 // Remove all previous tokens from the string as they are unrelated
593 // to completing the current token.
594 StringRef to_remove = cmd;
595 while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {
596 to_remove = to_remove.drop_back();
597 }
598 cmd = cmd.drop_front(to_remove.size());
599
600 return cmd;
601 }
602
603 /// Removes the last identifier token from the given cmd line.
604 StringRef removeLastToken(StringRef cmd) {
605 while (!cmd.empty() && IsIdChar(cmd.back())) {
606 cmd = cmd.drop_back();
607 }
608 return cmd;
609 }
610
611 /// Attemps to merge the given completion from the given position into the
612 /// existing command. Returns the completion string that can be returned to
613 /// the lldb completion API.
614 std::string mergeCompletion(StringRef existing, unsigned pos,
615 StringRef completion) {
616 StringRef existing_command = existing.substr(0, pos);
617 // We rewrite the last token with the completion, so let's drop that
618 // token from the command.
619 existing_command = removeLastToken(existing_command);
620 // We also should remove all previous tokens from the command as they
621 // would otherwise be added to the completion that already has the
622 // completion.
623 existing_command = dropUnrelatedFrontTokens(existing_command);
624 return existing_command.str() + completion.str();
625 }
626
627public:
628 /// Constructs a CodeComplete consumer that can be attached to a Sema.
629 /// @param[out] matches
630 /// The list of matches that the lldb completion API expects as a result.
631 /// This may already contain matches, so it's only allowed to append
632 /// to this variable.
633 /// @param[out] expr
634 /// The whole expression string that we are currently parsing. This
635 /// string needs to be equal to the input the user typed, and NOT the
636 /// final code that Clang is parsing.
637 /// @param[out] position
638 /// The character position of the user cursor in the `expr` parameter.
639 ///
640 CodeComplete(StringList &matches, std::string expr, unsigned position)
641 : CodeCompleteConsumer(CodeCompleteOptions(), false),
642 CCTUInfo(std::make_shared<GlobalCodeCompletionAllocator>()), expr(expr),
643 position(position), matches(matches) {}
644
645 /// Deregisters and destroys this code-completion consumer.
646 virtual ~CodeComplete() {}
647
648 /// \name Code-completion filtering
649 /// Check if the result should be filtered out.
650 bool isResultFilteredOut(StringRef Filter,
651 CodeCompletionResult Result) override {
652 // This code is mostly copied from CodeCompleteConsumer.
653 switch (Result.Kind) {
654 case CodeCompletionResult::RK_Declaration:
655 return !(
656 Result.Declaration->getIdentifier() &&
657 Result.Declaration->getIdentifier()->getName().startswith(Filter));
658 case CodeCompletionResult::RK_Keyword:
659 return !StringRef(Result.Keyword).startswith(Filter);
660 case CodeCompletionResult::RK_Macro:
661 return !Result.Macro->getName().startswith(Filter);
662 case CodeCompletionResult::RK_Pattern:
663 return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
664 }
665 // If we trigger this assert or the above switch yields a warning, then
666 // CodeCompletionResult has been enhanced with more kinds of completion
667 // results. Expand the switch above in this case.
668 assert(false && "Unknown completion result type?");
669 // If we reach this, then we should just ignore whatever kind of unknown
670 // result we got back. We probably can't turn it into any kind of useful
671 // completion suggestion with the existing code.
672 return true;
673 }
674
675 /// \name Code-completion callbacks
676 /// Process the finalized code-completion results.
677 void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,
678 CodeCompletionResult *Results,
679 unsigned NumResults) override {
680
681 // The Sema put the incomplete token we try to complete in here during
682 // lexing, so we need to retrieve it here to know what we are completing.
683 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
684
685 // Iterate over all the results. Filter out results we don't want and
686 // process the rest.
687 for (unsigned I = 0; I != NumResults; ++I) {
688 // Filter the results with the information from the Sema.
689 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
690 continue;
691
692 CodeCompletionResult &R = Results[I];
693 std::string ToInsert;
694 // Handle the different completion kinds that come from the Sema.
695 switch (R.Kind) {
696 case CodeCompletionResult::RK_Declaration: {
697 const NamedDecl *D = R.Declaration;
698 ToInsert = R.Declaration->getNameAsString();
699 // If we have a function decl that has no arguments we want to
700 // complete the empty parantheses for the user. If the function has
701 // arguments, we at least complete the opening bracket.
702 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) {
703 if (F->getNumParams() == 0)
704 ToInsert += "()";
705 else
706 ToInsert += "(";
707 }
708 // If we try to complete a namespace, then we directly can append
709 // the '::'.
710 if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) {
711 if (!N->isAnonymousNamespace())
712 ToInsert += "::";
713 }
714 break;
715 }
716 case CodeCompletionResult::RK_Keyword:
717 ToInsert = R.Keyword;
718 break;
719 case CodeCompletionResult::RK_Macro:
720 // It's not clear if we want to complete any macros in the
721 ToInsert = R.Macro->getName().str();
722 break;
723 case CodeCompletionResult::RK_Pattern:
724 ToInsert = R.Pattern->getTypedText();
725 break;
726 }
727 // At this point all information is in the ToInsert string.
728
729 // We also filter some internal lldb identifiers here. The user
730 // shouldn't see these.
731 if (StringRef(ToInsert).startswith("$__lldb_"))
732 continue;
733 if (!ToInsert.empty()) {
734 // Merge the suggested Token into the existing command line to comply
735 // with the kind of result the lldb API expects.
736 std::string CompletionSuggestion =
737 mergeCompletion(expr, position, ToInsert);
738 matches.AppendString(CompletionSuggestion);
739 }
740 }
741 }
742
743 /// \param S the semantic-analyzer object for which code-completion is being
744 /// done.
745 ///
746 /// \param CurrentArg the index of the current argument.
747 ///
748 /// \param Candidates an array of overload candidates.
749 ///
750 /// \param NumCandidates the number of overload candidates
751 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
752 OverloadCandidate *Candidates,
753 unsigned NumCandidates,
754 SourceLocation OpenParLoc) override {
755 // At the moment we don't filter out any overloaded candidates.
756 }
757
758 CodeCompletionAllocator &getAllocator() override {
759 return CCTUInfo.getAllocator();
760 }
761
762 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
763};
764} // namespace
765
766bool ClangExpressionParser::Complete(StringList &matches, unsigned line,
767 unsigned pos, unsigned typed_pos) {
768 DiagnosticManager mgr;
769 // We need the raw user expression here because that's what the CodeComplete
770 // class uses to provide completion suggestions.
771 // However, the `Text` method only gives us the transformed expression here.
772 // To actually get the raw user input here, we have to cast our expression to
773 // the LLVMUserExpression which exposes the right API. This should never fail
774 // as we always have a ClangUserExpression whenever we call this.
775 LLVMUserExpression &llvm_expr = *static_cast<LLVMUserExpression *>(&m_expr);
776 CodeComplete CC(matches, llvm_expr.GetUserText(), typed_pos);
777 // We don't need a code generator for parsing.
778 m_code_generator.reset();
779 // Start parsing the expression with our custom code completion consumer.
780 ParseInternal(mgr, &CC, line, pos);
781 return true;
782}
783
Kate Stoneb9c1b512016-09-06 20:57:50 +0000784unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
Raphael Isemann74829732018-08-30 17:29:37 +0000785 return ParseInternal(diagnostic_manager);
786}
787
788unsigned
789ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager,
790 CodeCompleteConsumer *completion_consumer,
791 unsigned completion_line,
792 unsigned completion_column) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000793 ClangDiagnosticManagerAdapter *adapter =
794 static_cast<ClangDiagnosticManagerAdapter *>(
795 m_compiler->getDiagnostics().getClient());
796 clang::TextDiagnosticBuffer *diag_buf = adapter->GetPassthrough();
797 diag_buf->FlushDiagnostics(m_compiler->getDiagnostics());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000798
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799 adapter->ResetManager(&diagnostic_manager);
Sean Callanan579e70c2016-03-19 00:03:59 +0000800
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801 const char *expr_text = m_expr.Text();
Rafael Espindola9cb97b62014-05-21 15:08:27 +0000802
Kate Stoneb9c1b512016-09-06 20:57:50 +0000803 clang::SourceManager &source_mgr = m_compiler->getSourceManager();
804 bool created_main_file = false;
Raphael Isemann74829732018-08-30 17:29:37 +0000805
806 // Clang wants to do completion on a real file known by Clang's file manager,
807 // so we have to create one to make this work.
808 // TODO: We probably could also simulate to Clang's file manager that there
809 // is a real file that contains our code.
810 bool should_create_file = completion_consumer != nullptr;
811
812 // We also want a real file on disk if we generate full debug info.
813 should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==
814 codegenoptions::FullDebugInfo;
815
816 if (should_create_file) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000817 int temp_fd = -1;
818 llvm::SmallString<PATH_MAX> result_path;
Pavel Labath60f028f2018-06-19 15:09:07 +0000819 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000820 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
821 std::string temp_source_path = tmpdir_file_spec.GetPath();
822 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
823 } else {
824 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
825 }
826
827 if (temp_fd != -1) {
828 lldb_private::File file(temp_fd, true);
829 const size_t expr_text_len = strlen(expr_text);
830 size_t bytes_written = expr_text_len;
831 if (file.Write(expr_text, bytes_written).Success()) {
832 if (bytes_written == expr_text_len) {
833 file.Close();
834 source_mgr.setMainFileID(
835 source_mgr.createFileID(m_file_manager->getFile(result_path),
836 SourceLocation(), SrcMgr::C_User));
837 created_main_file = true;
Greg Clayton23f8c952014-03-24 23:10:19 +0000838 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 }
Greg Clayton23f8c952014-03-24 23:10:19 +0000840 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000842
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843 if (!created_main_file) {
844 std::unique_ptr<MemoryBuffer> memory_buffer =
845 MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
846 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
847 }
848
849 diag_buf->BeginSourceFile(m_compiler->getLangOpts(),
850 &m_compiler->getPreprocessor());
851
852 ClangExpressionHelper *type_system_helper =
853 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
854
855 ASTConsumer *ast_transformer =
856 type_system_helper->ASTTransformer(m_code_generator.get());
857
858 if (ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap())
859 decl_map->InstallCodeGenerator(m_code_generator.get());
860
Raphael Isemann74829732018-08-30 17:29:37 +0000861 // If we want to parse for code completion, we need to attach our code
862 // completion consumer to the Sema and specify a completion position.
863 // While parsing the Sema will call this consumer with the provided
864 // completion suggestions.
865 if (completion_consumer) {
866 auto main_file = source_mgr.getFileEntryForID(source_mgr.getMainFileID());
867 auto &PP = m_compiler->getPreprocessor();
868 // Lines and columns start at 1 in Clang, but code completion positions are
869 // indexed from 0, so we need to add 1 to the line and column here.
870 ++completion_line;
871 ++completion_column;
872 PP.SetCodeCompletionPoint(main_file, completion_line, completion_column);
873 }
874
Kate Stoneb9c1b512016-09-06 20:57:50 +0000875 if (ast_transformer) {
876 ast_transformer->Initialize(m_compiler->getASTContext());
877 ParseAST(m_compiler->getPreprocessor(), ast_transformer,
Raphael Isemann74829732018-08-30 17:29:37 +0000878 m_compiler->getASTContext(), false, TU_Complete,
879 completion_consumer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 } else {
881 m_code_generator->Initialize(m_compiler->getASTContext());
882 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(),
Raphael Isemann74829732018-08-30 17:29:37 +0000883 m_compiler->getASTContext(), false, TU_Complete,
884 completion_consumer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885 }
886
887 diag_buf->EndSourceFile();
888
889 unsigned num_errors = diag_buf->getNumErrors();
890
891 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
892 num_errors++;
Zachary Turnere2411fa2016-11-12 19:12:56 +0000893 diagnostic_manager.PutString(eDiagnosticSeverityError,
894 "while importing modules:");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000895 diagnostic_manager.AppendMessageToDiagnostic(
Zachary Turnerc1564272016-11-16 21:15:24 +0000896 m_pp_callbacks->getErrorString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000897 }
898
899 if (!num_errors) {
900 if (type_system_helper->DeclMap() &&
901 !type_system_helper->DeclMap()->ResolveUnknownTypes()) {
902 diagnostic_manager.Printf(eDiagnosticSeverityError,
903 "Couldn't infer the type of a variable");
904 num_errors++;
Greg Clayton23f8c952014-03-24 23:10:19 +0000905 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000906 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000907
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908 if (!num_errors) {
909 type_system_helper->CommitPersistentDecls();
910 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000911
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912 adapter->ResetManager();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000913
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914 return num_errors;
Sean Callanan1a8d4092010-08-27 01:01:44 +0000915}
916
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000917std::string
Kate Stoneb9c1b512016-09-06 20:57:50 +0000918ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {
919 std::string abi;
920
921 if (target_arch.IsMIPS()) {
922 switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
923 case ArchSpec::eMIPSABI_N64:
924 abi = "n64";
925 break;
926 case ArchSpec::eMIPSABI_N32:
927 abi = "n32";
928 break;
929 case ArchSpec::eMIPSABI_O32:
930 abi = "o32";
931 break;
932 default:
933 break;
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000934 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000935 }
936 return abi;
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000937}
938
Kate Stoneb9c1b512016-09-06 20:57:50 +0000939bool ClangExpressionParser::RewriteExpression(
940 DiagnosticManager &diagnostic_manager) {
941 clang::SourceManager &source_manager = m_compiler->getSourceManager();
942 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
943 nullptr);
944 clang::edit::Commit commit(editor);
945 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
Jim Inghama1e541b2016-03-25 01:57:14 +0000946
Kate Stoneb9c1b512016-09-06 20:57:50 +0000947 class RewritesReceiver : public edit::EditsReceiver {
948 Rewriter &rewrite;
Jim Inghama1e541b2016-03-25 01:57:14 +0000949
Kate Stoneb9c1b512016-09-06 20:57:50 +0000950 public:
951 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
952
953 void insert(SourceLocation loc, StringRef text) override {
954 rewrite.InsertText(loc, text);
Jim Inghama1e541b2016-03-25 01:57:14 +0000955 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000956 void replace(CharSourceRange range, StringRef text) override {
957 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
Sean Callananfc55f5d2010-09-21 00:44:12 +0000958 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000959 };
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000960
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961 RewritesReceiver rewrites_receiver(rewriter);
962
963 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
964 size_t num_diags = diagnostics.size();
965 if (num_diags == 0)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000966 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000967
968 for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) {
969 const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag);
970 if (diagnostic && diagnostic->HasFixIts()) {
971 for (const FixItHint &fixit : diagnostic->FixIts()) {
972 // This is cobbed from clang::Rewrite::FixItRewriter.
973 if (fixit.CodeToInsert.empty()) {
974 if (fixit.InsertFromRange.isValid()) {
975 commit.insertFromRange(fixit.RemoveRange.getBegin(),
976 fixit.InsertFromRange, /*afterToken=*/false,
977 fixit.BeforePreviousInsertions);
978 } else
979 commit.remove(fixit.RemoveRange);
980 } else {
981 if (fixit.RemoveRange.isTokenRange() ||
982 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd())
983 commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
984 else
985 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
986 /*afterToken=*/false, fixit.BeforePreviousInsertions);
987 }
988 }
989 }
990 }
991
992 // FIXME - do we want to try to propagate specific errors here?
993 if (!commit.isCommitable())
994 return false;
995 else if (!editor.commit(commit))
996 return false;
997
998 // Now play all the edits, and stash the result in the diagnostic manager.
999 editor.applyRewrites(rewrites_receiver);
1000 RewriteBuffer &main_file_buffer =
1001 rewriter.getEditBuffer(source_manager.getMainFileID());
1002
1003 std::string fixed_expression;
1004 llvm::raw_string_ostream out_stream(fixed_expression);
1005
1006 main_file_buffer.write(out_stream);
1007 out_stream.flush();
1008 diagnostic_manager.SetFixedExpression(fixed_expression);
1009
1010 return true;
Sean Callananfc55f5d2010-09-21 00:44:12 +00001011}
1012
Kate Stoneb9c1b512016-09-06 20:57:50 +00001013static bool FindFunctionInModule(ConstString &mangled_name,
1014 llvm::Module *module, const char *orig_name) {
1015 for (const auto &func : module->getFunctionList()) {
1016 const StringRef &name = func.getName();
1017 if (name.find(orig_name) != StringRef::npos) {
1018 mangled_name.SetString(name);
1019 return true;
Sean Callanan1a8d4092010-08-27 01:01:44 +00001020 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001022
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023 return false;
Sean Callanan1a8d4092010-08-27 01:01:44 +00001024}
Sean Callananbd4dc692016-03-21 22:23:38 +00001025
Zachary Turner97206d52017-05-12 04:51:55 +00001026lldb_private::Status ClangExpressionParser::PrepareForExecution(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027 lldb::addr_t &func_addr, lldb::addr_t &func_end,
1028 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
1029 bool &can_interpret, ExecutionPolicy execution_policy) {
1030 func_addr = LLDB_INVALID_ADDRESS;
1031 func_end = LLDB_INVALID_ADDRESS;
1032 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1033
Zachary Turner97206d52017-05-12 04:51:55 +00001034 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035
1036 std::unique_ptr<llvm::Module> llvm_module_ap(
1037 m_code_generator->ReleaseModule());
1038
1039 if (!llvm_module_ap.get()) {
1040 err.SetErrorToGenericError();
1041 err.SetErrorString("IR doesn't contain a module");
Sean Callananbd4dc692016-03-21 22:23:38 +00001042 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001043 }
1044
1045 ConstString function_name;
1046
1047 if (execution_policy != eExecutionPolicyTopLevel) {
1048 // Find the actual name of the function (it's often mangled somehow)
1049
1050 if (!FindFunctionInModule(function_name, llvm_module_ap.get(),
1051 m_expr.FunctionName())) {
1052 err.SetErrorToGenericError();
1053 err.SetErrorStringWithFormat("Couldn't find %s() in the module",
1054 m_expr.FunctionName());
1055 return err;
1056 } else {
1057 if (log)
1058 log->Printf("Found function %s for %s", function_name.AsCString(),
1059 m_expr.FunctionName());
1060 }
1061 }
1062
1063 SymbolContext sc;
1064
1065 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
1066 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
1067 } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
1068 sc.target_sp = target_sp;
1069 }
1070
1071 LLVMUserExpression::IRPasses custom_passes;
1072 {
1073 auto lang = m_expr.Language();
1074 if (log)
Bruce Mitchener4ebdee02018-05-29 09:10:46 +00001075 log->Printf("%s - Current expression language is %s\n", __FUNCTION__,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076 Language::GetNameForLanguageType(lang));
Jim Ingham22562152016-11-03 23:42:09 +00001077 lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
1078 if (process_sp && lang != lldb::eLanguageTypeUnknown) {
1079 auto runtime = process_sp->GetLanguageRuntime(lang);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 if (runtime)
1081 runtime->GetIRPasses(custom_passes);
1082 }
1083 }
1084
1085 if (custom_passes.EarlyPasses) {
1086 if (log)
1087 log->Printf("%s - Running Early IR Passes from LanguageRuntime on "
1088 "expression module '%s'",
1089 __FUNCTION__, m_expr.FunctionName());
1090
1091 custom_passes.EarlyPasses->run(*llvm_module_ap);
1092 }
1093
1094 execution_unit_sp.reset(
1095 new IRExecutionUnit(m_llvm_context, // handed off here
1096 llvm_module_ap, // handed off here
1097 function_name, exe_ctx.GetTargetSP(), sc,
1098 m_compiler->getTargetOpts().Features));
1099
1100 ClangExpressionHelper *type_system_helper =
1101 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1102 ClangExpressionDeclMap *decl_map =
1103 type_system_helper->DeclMap(); // result can be NULL
1104
1105 if (decl_map) {
1106 Stream *error_stream = NULL;
1107 Target *target = exe_ctx.GetTargetPtr();
1108 error_stream = target->GetDebugger().GetErrorFile().get();
1109
1110 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
1111 *execution_unit_sp, *error_stream,
1112 function_name.AsCString());
1113
1114 bool ir_can_run =
1115 ir_for_target.runOnModule(*execution_unit_sp->GetModule());
1116
1117 if (!ir_can_run) {
1118 err.SetErrorString(
1119 "The expression could not be prepared to run in the target");
1120 return err;
1121 }
1122
1123 Process *process = exe_ctx.GetProcessPtr();
1124
1125 if (execution_policy != eExecutionPolicyAlways &&
1126 execution_policy != eExecutionPolicyTopLevel) {
Zachary Turner97206d52017-05-12 04:51:55 +00001127 lldb_private::Status interpret_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128
1129 bool interpret_function_calls =
1130 !process ? false : process->CanInterpretFunctionCalls();
1131 can_interpret = IRInterpreter::CanInterpret(
1132 *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
1133 interpret_error, interpret_function_calls);
1134
1135 if (!can_interpret && execution_policy == eExecutionPolicyNever) {
1136 err.SetErrorStringWithFormat("Can't run the expression locally: %s",
1137 interpret_error.AsCString());
1138 return err;
1139 }
1140 }
1141
1142 if (!process && execution_policy == eExecutionPolicyAlways) {
1143 err.SetErrorString("Expression needed to run in the target, but the "
1144 "target can't be run");
1145 return err;
1146 }
1147
1148 if (!process && execution_policy == eExecutionPolicyTopLevel) {
1149 err.SetErrorString("Top-level code needs to be inserted into a runnable "
1150 "target, but the target can't be run");
1151 return err;
1152 }
1153
1154 if (execution_policy == eExecutionPolicyAlways ||
1155 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
1156 if (m_expr.NeedsValidation() && process) {
1157 if (!process->GetDynamicCheckers()) {
1158 DynamicCheckerFunctions *dynamic_checkers =
1159 new DynamicCheckerFunctions();
1160
1161 DiagnosticManager install_diagnostics;
1162
1163 if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) {
1164 if (install_diagnostics.Diagnostics().size())
1165 err.SetErrorString("couldn't install checkers, unknown error");
1166 else
1167 err.SetErrorString(install_diagnostics.GetString().c_str());
1168
1169 return err;
1170 }
1171
1172 process->SetDynamicCheckers(dynamic_checkers);
1173
1174 if (log)
1175 log->Printf("== [ClangUserExpression::Evaluate] Finished "
1176 "installing dynamic checkers ==");
1177 }
1178
1179 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(),
1180 function_name.AsCString());
1181
1182 llvm::Module *module = execution_unit_sp->GetModule();
1183 if (!module || !ir_dynamic_checks.runOnModule(*module)) {
1184 err.SetErrorToGenericError();
1185 err.SetErrorString("Couldn't add dynamic checks to the expression");
1186 return err;
1187 }
1188
1189 if (custom_passes.LatePasses) {
1190 if (log)
1191 log->Printf("%s - Running Late IR Passes from LanguageRuntime on "
1192 "expression module '%s'",
1193 __FUNCTION__, m_expr.FunctionName());
1194
1195 custom_passes.LatePasses->run(*module);
1196 }
1197 }
1198 }
1199
1200 if (execution_policy == eExecutionPolicyAlways ||
1201 execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
1202 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1203 }
1204 } else {
1205 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1206 }
1207
1208 return err;
1209}
1210
Zachary Turner97206d52017-05-12 04:51:55 +00001211lldb_private::Status ClangExpressionParser::RunStaticInitializers(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001212 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) {
Zachary Turner97206d52017-05-12 04:51:55 +00001213 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214
1215 lldbassert(execution_unit_sp.get());
1216 lldbassert(exe_ctx.HasThreadScope());
1217
1218 if (!execution_unit_sp.get()) {
1219 err.SetErrorString(
1220 "can't run static initializers for a NULL execution unit");
1221 return err;
1222 }
1223
1224 if (!exe_ctx.HasThreadScope()) {
1225 err.SetErrorString("can't run static initializers without a thread");
1226 return err;
1227 }
1228
1229 std::vector<lldb::addr_t> static_initializers;
1230
1231 execution_unit_sp->GetStaticInitializers(static_initializers);
1232
1233 for (lldb::addr_t static_initializer : static_initializers) {
1234 EvaluateExpressionOptions options;
1235
1236 lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(
1237 exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(),
1238 llvm::ArrayRef<lldb::addr_t>(), options));
1239
1240 DiagnosticManager execution_errors;
1241 lldb::ExpressionResults results =
1242 exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(
1243 exe_ctx, call_static_initializer, options, execution_errors);
1244
1245 if (results != lldb::eExpressionCompleted) {
1246 err.SetErrorStringWithFormat("couldn't run static initializer: %s",
1247 execution_errors.GetString().c_str());
1248 return err;
1249 }
1250 }
1251
1252 return err;
Sean Callananbd4dc692016-03-21 22:23:38 +00001253}