blob: 2793816235b9c08cbd0748556d81fdcd7e2bbc0e [file] [log] [blame]
Sean Callanan65dafa82010-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
Daniel Malead891f9b2012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Sean Callanan65dafa82010-08-27 01:01:44 +000012#include "lldb/Expression/ClangExpressionParser.h"
13
14#include "lldb/Core/ArchSpec.h"
15#include "lldb/Core/DataBufferHeap.h"
Sean Callanan97c924e2011-01-27 01:07:04 +000016#include "lldb/Core/Debugger.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000017#include "lldb/Core/Disassembler.h"
18#include "lldb/Core/Stream.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000019#include "lldb/Core/StreamString.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000020#include "lldb/Expression/ClangASTSource.h"
21#include "lldb/Expression/ClangExpression.h"
Sean Callananfb3058e2011-05-12 23:54:16 +000022#include "lldb/Expression/ClangExpressionDeclMap.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000023#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000024#include "lldb/Expression/RecordingMemoryManager.h"
25#include "lldb/Target/ExecutionContext.h"
Sean Callananc7674af2011-01-17 23:42:46 +000026#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000027#include "lldb/Target/Process.h"
28#include "lldb/Target/Target.h"
29
30#include "clang/AST/ASTContext.h"
31#include "clang/AST/ExternalASTSource.h"
32#include "clang/Basic/FileManager.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/Version.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000035#include "clang/CodeGen/CodeGenAction.h"
36#include "clang/CodeGen/ModuleBuilder.h"
37#include "clang/Driver/CC1Options.h"
38#include "clang/Driver/OptTable.h"
39#include "clang/Frontend/CompilerInstance.h"
40#include "clang/Frontend/CompilerInvocation.h"
41#include "clang/Frontend/FrontendActions.h"
42#include "clang/Frontend/FrontendDiagnostic.h"
43#include "clang/Frontend/FrontendPluginRegistry.h"
44#include "clang/Frontend/TextDiagnosticBuffer.h"
45#include "clang/Frontend/TextDiagnosticPrinter.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000046#include "clang/Lex/Preprocessor.h"
Sean Callanan47a5c4c2010-09-23 03:01:22 +000047#include "clang/Parse/ParseAST.h"
Sean Callanan06dc17f2012-09-24 22:25:51 +000048#include "clang/Rewrite/Frontend/FrontendActions.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000049#include "clang/Sema/SemaConsumer.h"
Sean Callanan279584c2011-03-15 00:17:19 +000050#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000051
52#include "llvm/ADT/StringRef.h"
53#include "llvm/ExecutionEngine/ExecutionEngine.h"
Sean Callanan06dc17f2012-09-24 22:25:51 +000054#include "llvm/Support/Debug.h"
Sean Callananc1535182011-10-07 23:18:13 +000055#include "llvm/Support/TargetSelect.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000056
Greg Clayton4af38352012-10-30 17:11:34 +000057#if defined(__FreeBSD__)
Peter Collingbournec3f55732011-06-03 20:40:12 +000058#define USE_STANDARD_JIT
59#endif
60
Greg Clayton2f085c62011-05-15 01:25:55 +000061#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +000062#include "llvm/ExecutionEngine/JIT.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000063#else
64#include "llvm/ExecutionEngine/MCJIT.h"
65#endif
Sean Callanan65dafa82010-08-27 01:01:44 +000066#include "llvm/LLVMContext.h"
Sean Callanan279584c2011-03-15 00:17:19 +000067#include "llvm/Module.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000068#include "llvm/Support/ErrorHandling.h"
69#include "llvm/Support/MemoryBuffer.h"
Greg Clayton22defe82010-12-02 23:20:03 +000070#include "llvm/Support/DynamicLibrary.h"
71#include "llvm/Support/Host.h"
72#include "llvm/Support/Signals.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000073
74using namespace clang;
75using namespace llvm;
76using namespace lldb_private;
77
78//===----------------------------------------------------------------------===//
79// Utility Methods for Clang
80//===----------------------------------------------------------------------===//
81
82std::string GetBuiltinIncludePath(const char *Argv0) {
83 llvm::sys::Path P =
84 llvm::sys::Path::GetMainExecutable(Argv0,
85 (void*)(intptr_t) GetBuiltinIncludePath);
86
87 if (!P.isEmpty()) {
88 P.eraseComponent(); // Remove /clang from foo/bin/clang
89 P.eraseComponent(); // Remove /bin from foo/bin
90
91 // Get foo/lib/clang/<version>/include
92 P.appendComponent("lib");
93 P.appendComponent("clang");
94 P.appendComponent(CLANG_VERSION_STRING);
95 P.appendComponent("include");
96 }
97
98 return P.str();
99}
100
101
102//===----------------------------------------------------------------------===//
103// Main driver for Clang
104//===----------------------------------------------------------------------===//
105
106static void LLVMErrorHandler(void *UserData, const std::string &Message) {
Sean Callananc1535182011-10-07 23:18:13 +0000107 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
Sean Callanan65dafa82010-08-27 01:01:44 +0000108
109 Diags.Report(diag::err_fe_error_backend) << Message;
110
111 // We cannot recover from llvm errors.
Sean Callananc1535182011-10-07 23:18:13 +0000112 assert(0);
Sean Callanan65dafa82010-08-27 01:01:44 +0000113}
114
115static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
116 using namespace clang::frontend;
117
118 switch (CI.getFrontendOpts().ProgramAction) {
119 default:
120 llvm_unreachable("Invalid program action!");
121
122 case ASTDump: return new ASTDumpAction();
123 case ASTPrint: return new ASTPrintAction();
Sean Callanan279584c2011-03-15 00:17:19 +0000124 case ASTDumpXML: return new ASTDumpXMLAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000125 case ASTView: return new ASTViewAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000126 case DumpRawTokens: return new DumpRawTokensAction();
127 case DumpTokens: return new DumpTokensAction();
128 case EmitAssembly: return new EmitAssemblyAction();
129 case EmitBC: return new EmitBCAction();
130 case EmitHTML: return new HTMLPrintAction();
131 case EmitLLVM: return new EmitLLVMAction();
132 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
133 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
134 case EmitObj: return new EmitObjAction();
135 case FixIt: return new FixItAction();
Sean Callanan05230832011-12-01 04:31:46 +0000136 case GeneratePCH: return new GeneratePCHAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000137 case GeneratePTH: return new GeneratePTHAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000138 case InitOnly: return new InitOnlyAction();
139 case ParseSyntaxOnly: return new SyntaxOnlyAction();
140
141 case PluginAction: {
142 for (FrontendPluginRegistry::iterator it =
143 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
144 it != ie; ++it) {
145 if (it->getName() == CI.getFrontendOpts().ActionName) {
146 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
147 if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
148 return 0;
149 return P.take();
150 }
151 }
152
153 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
154 << CI.getFrontendOpts().ActionName;
155 return 0;
156 }
157
158 case PrintDeclContext: return new DeclContextPrintAction();
159 case PrintPreamble: return new PrintPreambleAction();
160 case PrintPreprocessedInput: return new PrintPreprocessedAction();
161 case RewriteMacros: return new RewriteMacrosAction();
162 case RewriteObjC: return new RewriteObjCAction();
163 case RewriteTest: return new RewriteTestAction();
Sean Callananad293092011-01-18 23:32:05 +0000164 //case RunAnalysis: return new AnalysisAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000165 case RunPreprocessorOnly: return new PreprocessOnlyAction();
166 }
167}
168
169static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
170 // Create the underlying action.
171 FrontendAction *Act = CreateFrontendBaseAction(CI);
172 if (!Act)
173 return 0;
174
175 // If there are any AST files to merge, create a frontend action
176 // adaptor to perform the merge.
177 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
Sean Callanan8f2e3922012-02-04 08:49:35 +0000178 Act = new ASTMergeAction(Act, CI.getFrontendOpts().ASTMergeFiles);
Sean Callanan65dafa82010-08-27 01:01:44 +0000179
180 return Act;
181}
182
183//===----------------------------------------------------------------------===//
184// Implementation of ClangExpressionParser
185//===----------------------------------------------------------------------===//
186
Greg Clayton395fc332011-02-15 21:59:32 +0000187ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
188 ClangExpression &expr) :
189 m_expr (expr),
Sean Callanan65dafa82010-08-27 01:01:44 +0000190 m_compiler (),
191 m_code_generator (NULL),
Sean Callanan65dafa82010-08-27 01:01:44 +0000192 m_jitted_functions ()
193{
194 // Initialize targets first, so that --version shows registered targets.
195 static struct InitializeLLVM {
196 InitializeLLVM() {
197 llvm::InitializeAllTargets();
198 llvm::InitializeAllAsmPrinters();
Sean Callanan9b6898f2011-07-30 02:42:06 +0000199 llvm::InitializeAllTargetMCs();
Sean Callanan05230832011-12-01 04:31:46 +0000200 llvm::InitializeAllDisassemblers();
Sean Callanan877e57b2012-09-06 01:39:02 +0000201
202 llvm::DisablePrettyStackTrace = true;
Sean Callanan65dafa82010-08-27 01:01:44 +0000203 }
204 } InitializeLLVM;
Sean Callanan06dc17f2012-09-24 22:25:51 +0000205
Sean Callanan65dafa82010-08-27 01:01:44 +0000206 // 1. Create a new compiler instance.
207 m_compiler.reset(new CompilerInstance());
Sean Callanan65dafa82010-08-27 01:01:44 +0000208
Sean Callanan06dc17f2012-09-24 22:25:51 +0000209 // 2. Install the target.
210
211 lldb::TargetSP target_sp;
212 if (exe_scope)
213 target_sp = exe_scope->CalculateTarget();
214
215 // TODO: figure out what to really do when we don't have a valid target.
216 // Sometimes this will be ok to just use the host target triple (when we
217 // evaluate say "2+3", but other expressions like breakpoint conditions
218 // and other things that _are_ target specific really shouldn't just be
219 // using the host triple. This needs to be fixed in a better way.
220 if (target_sp && target_sp->GetArchitecture().IsValid())
221 {
222 std::string triple = target_sp->GetArchitecture().GetTriple().str();
223
224 int dash_count = 0;
225 for (size_t i = 0; i < triple.size(); ++i)
226 {
227 if (triple[i] == '-')
228 dash_count++;
229 if (dash_count == 3)
230 {
231 triple.resize(i);
232 break;
233 }
234 }
235
236 m_compiler->getTargetOpts().Triple = triple;
237 }
238 else
239 {
240 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
241 }
242
243 if (m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos)
244 m_compiler->getTargetOpts().ABI = "apcs-gnu";
245
246 m_compiler->createDiagnostics(0, 0);
247
248 // Create the target instance.
249 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
Greg Claytonb4fadde2012-11-16 21:35:22 +0000250 &m_compiler->getTargetOpts()));
Sean Callanan06dc17f2012-09-24 22:25:51 +0000251
252 assert (m_compiler->hasTarget());
253
254 // 3. Set options.
Sean Callanan65dafa82010-08-27 01:01:44 +0000255
Sean Callanan5b658cc2011-11-07 23:35:40 +0000256 lldb::LanguageType language = expr.Language();
Greg Claytonf51ed302011-01-15 01:32:14 +0000257
Sean Callanan5b658cc2011-11-07 23:35:40 +0000258 switch (language)
259 {
260 case lldb::eLanguageTypeC:
261 break;
262 case lldb::eLanguageTypeObjC:
263 m_compiler->getLangOpts().ObjC1 = true;
264 m_compiler->getLangOpts().ObjC2 = true;
265 break;
266 case lldb::eLanguageTypeC_plus_plus:
267 m_compiler->getLangOpts().CPlusPlus = true;
Sean Callananf0613182012-05-16 21:03:38 +0000268 m_compiler->getLangOpts().CPlusPlus0x = true;
Sean Callanan5b658cc2011-11-07 23:35:40 +0000269 break;
270 case lldb::eLanguageTypeObjC_plus_plus:
271 default:
272 m_compiler->getLangOpts().ObjC1 = true;
273 m_compiler->getLangOpts().ObjC2 = true;
274 m_compiler->getLangOpts().CPlusPlus = true;
Sean Callananf0613182012-05-16 21:03:38 +0000275 m_compiler->getLangOpts().CPlusPlus0x = true;
Sean Callanan5b658cc2011-11-07 23:35:40 +0000276 break;
277 }
Sean Callananc7674af2011-01-17 23:42:46 +0000278
Sean Callanan683a97c2012-10-17 22:09:59 +0000279 m_compiler->getLangOpts().Bool = true;
280 m_compiler->getLangOpts().WChar = true;
Sean Callanan6e12c7a2012-03-08 02:39:03 +0000281 m_compiler->getLangOpts().DebuggerSupport = true; // Features specifically for debugger clients
282 if (expr.DesiredResultType() == ClangExpression::eResultTypeId)
283 m_compiler->getLangOpts().DebuggerCastResultToId = true;
284
Sean Callanan6c797dc2012-04-17 00:49:48 +0000285 // Spell checking is a nice feature, but it ends up completing a
286 // lot of types that we didn't strictly speaking need to complete.
287 // As a result, we spend a long time parsing and importing debug
288 // information.
289 m_compiler->getLangOpts().SpellChecking = false;
290
Greg Clayton289afcb2012-02-18 05:35:26 +0000291 lldb::ProcessSP process_sp;
Greg Clayton395fc332011-02-15 21:59:32 +0000292 if (exe_scope)
Greg Clayton289afcb2012-02-18 05:35:26 +0000293 process_sp = exe_scope->CalculateProcess();
Greg Clayton395fc332011-02-15 21:59:32 +0000294
Greg Clayton289afcb2012-02-18 05:35:26 +0000295 if (process_sp && m_compiler->getLangOpts().ObjC1)
Sean Callananc7674af2011-01-17 23:42:46 +0000296 {
Greg Clayton289afcb2012-02-18 05:35:26 +0000297 if (process_sp->GetObjCLanguageRuntime())
Sean Callananc7674af2011-01-17 23:42:46 +0000298 {
Greg Clayton289afcb2012-02-18 05:35:26 +0000299 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() == eAppleObjC_V2)
Sean Callanan06dc17f2012-09-24 22:25:51 +0000300 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
301 else
302 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX, VersionTuple(10, 7));
Sean Callanan6e12c7a2012-03-08 02:39:03 +0000303
304 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
Sean Callanan6e12c7a2012-03-08 02:39:03 +0000305 m_compiler->getLangOpts().DebuggerObjCLiteral = true;
Sean Callananc7674af2011-01-17 23:42:46 +0000306 }
307 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000308
Sean Callanan65dafa82010-08-27 01:01:44 +0000309 m_compiler->getLangOpts().ThreadsafeStatics = false;
310 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
311 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
Sean Callanandaa6efe2011-12-21 22:22:58 +0000312
Sean Callanan65dafa82010-08-27 01:01:44 +0000313 // Set CodeGen options
314 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
315 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
316
317 // Disable some warnings.
318 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
319
Sean Callanan65dafa82010-08-27 01:01:44 +0000320 // Inform the target of the language options
321 //
322 // FIXME: We shouldn't need to do this, the target should be immutable once
323 // created. This complexity should be lifted elsewhere.
324 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
325
326 // 4. Set up the diagnostic buffer for reporting errors
327
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000328 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000329
330 // 5. Set up the source management objects inside the compiler
331
Greg Clayton22defe82010-12-02 23:20:03 +0000332 clang::FileSystemOptions file_system_options;
333 m_file_manager.reset(new clang::FileManager(file_system_options));
Sean Callanan8a3b0a82010-11-18 02:56:27 +0000334
Sean Callanan65dafa82010-08-27 01:01:44 +0000335 if (!m_compiler->hasSourceManager())
Greg Clayton22defe82010-12-02 23:20:03 +0000336 m_compiler->createSourceManager(*m_file_manager.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000337
338 m_compiler->createFileManager();
339 m_compiler->createPreprocessor();
340
341 // 6. Most of this we get from the CompilerInstance, but we
342 // also want to give the context an ExternalASTSource.
Sean Callananee8fc722010-11-19 20:20:02 +0000343 m_selector_table.reset(new SelectorTable());
Sean Callananc1535182011-10-07 23:18:13 +0000344 m_builtin_context.reset(new Builtin::Context());
Sean Callanan65dafa82010-08-27 01:01:44 +0000345
346 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
347 m_compiler->getSourceManager(),
Sean Callananc1535182011-10-07 23:18:13 +0000348 &m_compiler->getTarget(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000349 m_compiler->getPreprocessor().getIdentifierTable(),
Sean Callananee8fc722010-11-19 20:20:02 +0000350 *m_selector_table.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000351 *m_builtin_context.get(),
352 0));
353
354 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
355
356 if (decl_map)
357 {
Sean Callananf76afff2011-10-28 23:38:38 +0000358 llvm::OwningPtr<clang::ExternalASTSource> ast_source(decl_map->CreateProxy());
359 decl_map->InstallASTContext(ast_context.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000360 ast_context->setExternalSource(ast_source);
361 }
362
363 m_compiler->setASTContext(ast_context.release());
364
Greg Clayton8de27c72010-10-15 22:48:33 +0000365 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000366
Sean Callanan279584c2011-03-15 00:17:19 +0000367 m_llvm_context.reset(new LLVMContext());
Sean Callanan65dafa82010-08-27 01:01:44 +0000368 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
369 module_name,
370 m_compiler->getCodeGenOpts(),
Sean Callanan279584c2011-03-15 00:17:19 +0000371 *m_llvm_context));
Sean Callanan65dafa82010-08-27 01:01:44 +0000372}
373
374ClangExpressionParser::~ClangExpressionParser()
375{
376}
377
378unsigned
379ClangExpressionParser::Parse (Stream &stream)
380{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000381 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
382
383 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000384
385 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
Sean Callanan142f94c2012-03-01 02:03:47 +0000386 m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000387
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000388 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000389
390 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
391
392 if (ast_transformer)
393 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
394 else
395 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
396
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000397 diag_buf->EndSourceFile();
Sean Callananfb3058e2011-05-12 23:54:16 +0000398
Sean Callanan65dafa82010-08-27 01:01:44 +0000399 TextDiagnosticBuffer::const_iterator diag_iterator;
400
401 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000402
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000403 for (diag_iterator = diag_buf->warn_begin();
404 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000405 ++diag_iterator)
406 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
407
408 num_errors = 0;
409
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000410 for (diag_iterator = diag_buf->err_begin();
411 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000412 ++diag_iterator)
413 {
414 num_errors++;
415 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
416 }
417
Sean Callanan7617c292010-11-01 20:28:09 +0000418 for (diag_iterator = diag_buf->note_begin();
419 diag_iterator != diag_buf->note_end();
420 ++diag_iterator)
421 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
422
Sean Callananfb3058e2011-05-12 23:54:16 +0000423 if (!num_errors)
424 {
425 if (m_expr.DeclMap() && !m_expr.DeclMap()->ResolveUnknownTypes())
426 {
427 stream.Printf("error: Couldn't infer the type of a variable\n");
428 num_errors++;
429 }
430 }
431
Sean Callanan65dafa82010-08-27 01:01:44 +0000432 return num_errors;
433}
434
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000435static bool FindFunctionInModule (std::string &mangled_name,
436 llvm::Module *module,
437 const char *orig_name)
438{
439 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
440 fi != fe;
441 ++fi)
442 {
443 if (fi->getName().str().find(orig_name) != std::string::npos)
444 {
445 mangled_name = fi->getName().str();
446 return true;
447 }
448 }
449
450 return false;
451}
452
Sean Callanan65dafa82010-08-27 01:01:44 +0000453Error
Sean Callanan47dc4572011-09-15 02:13:07 +0000454ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_allocation_addr,
455 lldb::addr_t &func_addr,
456 lldb::addr_t &func_end,
457 ExecutionContext &exe_ctx,
458 IRForTarget::StaticDataAllocator *data_allocator,
459 bool &evaluated_statically,
460 lldb::ClangExpressionVariableSP &const_result,
461 ExecutionPolicy execution_policy)
Sean Callanan65dafa82010-08-27 01:01:44 +0000462{
Greg Claytond0882d02011-01-19 23:00:49 +0000463 func_allocation_addr = LLDB_INVALID_ADDRESS;
464 func_addr = LLDB_INVALID_ADDRESS;
465 func_end = LLDB_INVALID_ADDRESS;
Greg Claytone005f2c2010-11-06 01:53:30 +0000466 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000467
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000468 std::auto_ptr<llvm::ExecutionEngine> execution_engine_ap;
Sean Callananddf110d2012-01-24 22:06:48 +0000469
Sean Callanan65dafa82010-08-27 01:01:44 +0000470 Error err;
471
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000472 std::auto_ptr<llvm::Module> module_ap (m_code_generator->ReleaseModule());
Sean Callanan65dafa82010-08-27 01:01:44 +0000473
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000474 if (!module_ap.get())
Sean Callanan65dafa82010-08-27 01:01:44 +0000475 {
476 err.SetErrorToGenericError();
477 err.SetErrorString("IR doesn't contain a module");
478 return err;
479 }
480
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000481 // Find the actual name of the function (it's often mangled somehow)
482
483 std::string function_name;
484
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000485 if (!FindFunctionInModule(function_name, module_ap.get(), m_expr.FunctionName()))
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000486 {
487 err.SetErrorToGenericError();
488 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
489 return err;
490 }
491 else
492 {
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000493 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000494 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
495 }
496
Sean Callanan65dafa82010-08-27 01:01:44 +0000497 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
498
499 if (decl_map)
500 {
Sean Callanan97c924e2011-01-27 01:07:04 +0000501 Stream *error_stream = NULL;
Greg Clayton567e7f32011-09-22 04:58:26 +0000502 Target *target = exe_ctx.GetTargetPtr();
503 if (target)
504 error_stream = &target->GetDebugger().GetErrorStream();
Sean Callanan97c924e2011-01-27 01:07:04 +0000505
Sean Callanan47dc4572011-09-15 02:13:07 +0000506 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000507 m_expr.NeedsVariableResolution(),
Sean Callanan47dc4572011-09-15 02:13:07 +0000508 execution_policy,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000509 const_result,
Sean Callananc0492742011-05-23 21:40:23 +0000510 data_allocator,
Sean Callanan97c924e2011-01-27 01:07:04 +0000511 error_stream,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000512 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000513
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000514 bool ir_can_run = ir_for_target.runOnModule(*module_ap);
Sean Callananf18d91c2010-09-01 00:58:00 +0000515
Sean Callananddf110d2012-01-24 22:06:48 +0000516 Error &interpreter_error(ir_for_target.getInterpreterError());
517
518 if (execution_policy != eExecutionPolicyAlways && interpreter_error.Success())
Sean Callanan696cf5f2011-05-07 01:06:41 +0000519 {
Johnny Chenc6134962012-01-06 00:35:38 +0000520 if (const_result)
521 const_result->TransferAddress();
Sean Callanan47dc4572011-09-15 02:13:07 +0000522 evaluated_statically = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000523 err.Clear();
524 return err;
525 }
526
Greg Clayton567e7f32011-09-22 04:58:26 +0000527 Process *process = exe_ctx.GetProcessPtr();
528
529 if (!process || execution_policy == eExecutionPolicyNever)
Sean Callanan47dc4572011-09-15 02:13:07 +0000530 {
531 err.SetErrorToGenericError();
Sean Callananddf110d2012-01-24 22:06:48 +0000532 if (execution_policy == eExecutionPolicyAlways)
533 err.SetErrorString("Execution needed to run in the target, but the target can't be run");
534 else
535 err.SetErrorStringWithFormat("Interpreting the expression locally failed: %s", interpreter_error.AsCString());
Sean Callanan8f2e3922012-02-04 08:49:35 +0000536
Sean Callanan47dc4572011-09-15 02:13:07 +0000537 return err;
538 }
Sean Callanan06dc17f2012-09-24 22:25:51 +0000539 else if (!ir_can_run)
540 {
541 err.SetErrorToGenericError();
542 err.SetErrorString("The expression could not be prepared to run in the target");
543
544 return err;
545 }
Sean Callanan47dc4572011-09-15 02:13:07 +0000546
Sean Callanan6cf6c472011-09-20 23:01:51 +0000547 if (execution_policy != eExecutionPolicyNever &&
548 m_expr.NeedsValidation() &&
Greg Clayton567e7f32011-09-22 04:58:26 +0000549 process)
Sean Callananf18d91c2010-09-01 00:58:00 +0000550 {
Greg Clayton567e7f32011-09-22 04:58:26 +0000551 if (!process->GetDynamicCheckers())
Sean Callanan6cf6c472011-09-20 23:01:51 +0000552 {
553 DynamicCheckerFunctions *dynamic_checkers = new DynamicCheckerFunctions();
554
555 StreamString install_errors;
556
557 if (!dynamic_checkers->Install(install_errors, exe_ctx))
558 {
559 if (install_errors.GetString().empty())
560 err.SetErrorString ("couldn't install checkers, unknown error");
561 else
562 err.SetErrorString (install_errors.GetString().c_str());
563
564 return err;
565 }
566
Greg Clayton567e7f32011-09-22 04:58:26 +0000567 process->SetDynamicCheckers(dynamic_checkers);
Sean Callanan6cf6c472011-09-20 23:01:51 +0000568
569 if (log)
570 log->Printf("== [ClangUserExpression::Evaluate] Finished installing dynamic checkers ==");
571 }
572
Greg Clayton567e7f32011-09-22 04:58:26 +0000573 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000574
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000575 if (!ir_dynamic_checks.runOnModule(*module_ap))
Sean Callanane8a59a82010-09-13 21:34:21 +0000576 {
577 err.SetErrorToGenericError();
578 err.SetErrorString("Couldn't add dynamic checks to the expression");
579 return err;
580 }
581 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000582 }
583
Greg Claytond0882d02011-01-19 23:00:49 +0000584 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
585 // below so we don't need to free it.
586 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000587
588 std::string error_string;
Sean Callanan7b8eb762011-11-01 17:33:54 +0000589
590 if (log)
591 {
592 std::string s;
593 raw_string_ostream oss(s);
594
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000595 module_ap->print(oss, NULL);
Sean Callanan7b8eb762011-11-01 17:33:54 +0000596
597 oss.flush();
598
599 log->Printf ("Module being sent to JIT: \n%s", s.c_str());
600 }
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000601 llvm::Triple triple(module_ap->getTargetTriple());
602 llvm::Function *function = module_ap->getFunction (function_name.c_str());
603 EngineBuilder builder(module_ap.release());
Greg Clayton2f085c62011-05-15 01:25:55 +0000604 builder.setEngineKind(EngineKind::JIT)
605 .setErrorStr(&error_string)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000606 .setRelocationModel(llvm::Reloc::PIC_)
Greg Clayton2f085c62011-05-15 01:25:55 +0000607 .setJITMemoryManager(jit_memory_manager)
608 .setOptLevel(CodeGenOpt::Less)
609 .setAllocateGVsWithCode(true)
610 .setCodeModel(CodeModel::Small)
Sean Callanan16b53ab2011-10-12 00:12:34 +0000611 .setUseMCJIT(true);
Sean Callanan06dc17f2012-09-24 22:25:51 +0000612
Sean Callanan06dc17f2012-09-24 22:25:51 +0000613 StringRef mArch;
614 StringRef mCPU;
615 SmallVector<std::string, 0> mAttrs;
616
617 TargetMachine *target_machine = builder.selectTarget(triple,
618 mArch,
619 mCPU,
620 mAttrs);
621
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000622 execution_engine_ap.reset(builder.create(target_machine));
Sean Callanan9ac3a962010-11-02 23:20:00 +0000623
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000624 if (!execution_engine_ap.get())
Sean Callanan65dafa82010-08-27 01:01:44 +0000625 {
626 err.SetErrorToGenericError();
627 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
628 return err;
629 }
630
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000631 execution_engine_ap->DisableLazyCompilation();
Sean Callanan65dafa82010-08-27 01:01:44 +0000632
Sean Callanan65dafa82010-08-27 01:01:44 +0000633
634 // We don't actually need the function pointer here, this just forces it to get resolved.
635
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000636 void *fun_ptr = execution_engine_ap->getPointerToFunction(function);
Sean Callananddf110d2012-01-24 22:06:48 +0000637
Sean Callanan65dafa82010-08-27 01:01:44 +0000638 // Errors usually cause failures in the JIT, but if we're lucky we get here.
639
Sean Callanan7b8eb762011-11-01 17:33:54 +0000640 if (!function)
641 {
642 err.SetErrorToGenericError();
643 err.SetErrorStringWithFormat("Couldn't find '%s' in the JITted module", function_name.c_str());
644 return err;
645 }
646
Sean Callanan65dafa82010-08-27 01:01:44 +0000647 if (!fun_ptr)
648 {
649 err.SetErrorToGenericError();
Sean Callanan7b8eb762011-11-01 17:33:54 +0000650 err.SetErrorStringWithFormat("'%s' was in the JITted module but wasn't lowered", function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000651 return err;
652 }
653
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000654 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000655
Greg Clayton567e7f32011-09-22 04:58:26 +0000656
657 Process *process = exe_ctx.GetProcessPtr();
658 if (process == NULL)
Sean Callanan65dafa82010-08-27 01:01:44 +0000659 {
660 err.SetErrorToGenericError();
661 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
662 return err;
663 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000664
Sean Callanan8f2e3922012-02-04 08:49:35 +0000665 jit_memory_manager->CommitAllocations(*process);
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000666 jit_memory_manager->ReportAllocations(*execution_engine_ap);
Sean Callanan8f2e3922012-02-04 08:49:35 +0000667 jit_memory_manager->WriteData(*process);
Sean Callanan65dafa82010-08-27 01:01:44 +0000668
669 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
670
671 for (pos = m_jitted_functions.begin(); pos != end; pos++)
672 {
Greg Claytond0882d02011-01-19 23:00:49 +0000673 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000674
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000675 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000676 {
Sean Callanan8f2e3922012-02-04 08:49:35 +0000677 RecordingMemoryManager::AddrRange func_range = jit_memory_manager->GetRemoteRangeForLocal((*pos).m_local_addr);
678 func_end = func_range.first + func_range.second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000679 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000680 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000681 }
682
Sean Callanan6dff8272010-11-08 03:49:50 +0000683 if (log)
684 {
685 log->Printf("Code can be run in the target.");
686
687 StreamString disassembly_stream;
688
Greg Claytond0882d02011-01-19 23:00:49 +0000689 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000690
691 if (!err.Success())
692 {
693 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
694 }
695 else
696 {
697 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
698 }
699 }
700
Sean Callanan65dafa82010-08-27 01:01:44 +0000701 err.Clear();
702 return err;
703}
704
705Error
Greg Claytond0882d02011-01-19 23:00:49 +0000706ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000707{
Greg Claytone005f2c2010-11-06 01:53:30 +0000708 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000709
710 const char *name = m_expr.FunctionName();
711
712 Error ret;
713
714 ret.Clear();
715
716 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
717 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
718
719 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
720
721 for (pos = m_jitted_functions.begin(); pos < end; pos++)
722 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000723 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000724 {
725 func_local_addr = pos->m_local_addr;
726 func_remote_addr = pos->m_remote_addr;
727 }
728 }
729
730 if (func_local_addr == LLDB_INVALID_ADDRESS)
731 {
732 ret.SetErrorToGenericError();
733 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
734 return ret;
735 }
736
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000737 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000738 log->Printf("Found function, has local address 0x%" PRIx64 " and remote address 0x%" PRIx64, (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000739
740 std::pair <lldb::addr_t, lldb::addr_t> func_range;
741
Greg Claytond0882d02011-01-19 23:00:49 +0000742 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000743
744 if (func_range.first == 0 && func_range.second == 0)
745 {
746 ret.SetErrorToGenericError();
747 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
748 return ret;
749 }
750
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000751 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000752 log->Printf("Function's code range is [0x%" PRIx64 "+0x%" PRIx64 "]", func_range.first, func_range.second);
Sean Callanan65dafa82010-08-27 01:01:44 +0000753
Greg Clayton567e7f32011-09-22 04:58:26 +0000754 Target *target = exe_ctx.GetTargetPtr();
755 if (!target)
Sean Callanan65dafa82010-08-27 01:01:44 +0000756 {
757 ret.SetErrorToGenericError();
758 ret.SetErrorString("Couldn't find the target");
Jim Ingham6f01c932012-10-12 17:34:26 +0000759 return ret;
Sean Callanan65dafa82010-08-27 01:01:44 +0000760 }
761
Sean Callanan8f2e3922012-02-04 08:49:35 +0000762 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0));
Sean Callanan65dafa82010-08-27 01:01:44 +0000763
Greg Clayton567e7f32011-09-22 04:58:26 +0000764 Process *process = exe_ctx.GetProcessPtr();
Sean Callanan65dafa82010-08-27 01:01:44 +0000765 Error err;
Greg Clayton567e7f32011-09-22 04:58:26 +0000766 process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
Sean Callanan65dafa82010-08-27 01:01:44 +0000767
768 if (!err.Success())
769 {
770 ret.SetErrorToGenericError();
771 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
772 return ret;
773 }
774
Greg Clayton567e7f32011-09-22 04:58:26 +0000775 ArchSpec arch(target->GetArchitecture());
Sean Callanan65dafa82010-08-27 01:01:44 +0000776
Sean Callanan4f28c312012-08-01 18:50:59 +0000777 lldb::DisassemblerSP disassembler = Disassembler::FindPlugin(arch, NULL);
Sean Callanan65dafa82010-08-27 01:01:44 +0000778
Sean Callananb386d822012-08-09 00:50:26 +0000779 if (!disassembler)
Sean Callanan65dafa82010-08-27 01:01:44 +0000780 {
781 ret.SetErrorToGenericError();
Greg Clayton940b1032011-02-23 00:35:02 +0000782 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
Sean Callanan65dafa82010-08-27 01:01:44 +0000783 return ret;
784 }
785
Greg Clayton567e7f32011-09-22 04:58:26 +0000786 if (!process)
Sean Callanan65dafa82010-08-27 01:01:44 +0000787 {
788 ret.SetErrorToGenericError();
789 ret.SetErrorString("Couldn't find the process");
790 return ret;
791 }
792
793 DataExtractor extractor(buffer_sp,
Greg Clayton567e7f32011-09-22 04:58:26 +0000794 process->GetByteOrder(),
795 target->GetArchitecture().GetAddressByteSize());
Sean Callanan65dafa82010-08-27 01:01:44 +0000796
Greg Claytone005f2c2010-11-06 01:53:30 +0000797 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000798 {
799 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000800 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000801 0,
802 extractor.GetByteSize(),
803 func_remote_addr,
804 16,
805 DataExtractor::TypeUInt8);
806 }
807
Greg Clayton3508c382012-02-24 01:59:29 +0000808 disassembler->DecodeInstructions (Address (func_remote_addr), extractor, 0, UINT32_MAX, false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000809
Greg Clayton5c4c7462010-10-06 03:09:58 +0000810 InstructionList &instruction_list = disassembler->GetInstructionList();
Greg Clayton889fbd02011-03-26 19:14:58 +0000811 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
Sean Callanan65dafa82010-08-27 01:01:44 +0000812 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
813 instruction_index < num_instructions;
814 ++instruction_index)
815 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000816 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000817 instruction->Dump (&stream,
Greg Clayton889fbd02011-03-26 19:14:58 +0000818 max_opcode_byte_size,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000819 true,
Greg Clayton149731c2011-03-25 18:03:16 +0000820 true,
Greg Clayton0fef9682012-05-10 02:52:23 +0000821 &exe_ctx);
Sean Callanan65dafa82010-08-27 01:01:44 +0000822 stream.PutChar('\n');
Sean Callanan65dafa82010-08-27 01:01:44 +0000823 }
824
825 return ret;
826}