blob: 81c03f36c5231b7f12fcb09a25e5e3e66af45d5c [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
10#include "lldb/Expression/ClangExpressionParser.h"
11
12#include "lldb/Core/ArchSpec.h"
13#include "lldb/Core/DataBufferHeap.h"
Sean Callanan97c924e2011-01-27 01:07:04 +000014#include "lldb/Core/Debugger.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000015#include "lldb/Core/Disassembler.h"
16#include "lldb/Core/Stream.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000017#include "lldb/Core/StreamString.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000018#include "lldb/Expression/ClangASTSource.h"
19#include "lldb/Expression/ClangExpression.h"
Sean Callananfb3058e2011-05-12 23:54:16 +000020#include "lldb/Expression/ClangExpressionDeclMap.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000021#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000022#include "lldb/Expression/IRToDWARF.h"
23#include "lldb/Expression/RecordingMemoryManager.h"
24#include "lldb/Target/ExecutionContext.h"
Sean Callananc7674af2011-01-17 23:42:46 +000025#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000026#include "lldb/Target/Process.h"
27#include "lldb/Target/Target.h"
28
29#include "clang/AST/ASTContext.h"
30#include "clang/AST/ExternalASTSource.h"
31#include "clang/Basic/FileManager.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Basic/Version.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000034#include "clang/CodeGen/CodeGenAction.h"
35#include "clang/CodeGen/ModuleBuilder.h"
36#include "clang/Driver/CC1Options.h"
37#include "clang/Driver/OptTable.h"
38#include "clang/Frontend/CompilerInstance.h"
39#include "clang/Frontend/CompilerInvocation.h"
40#include "clang/Frontend/FrontendActions.h"
41#include "clang/Frontend/FrontendDiagnostic.h"
42#include "clang/Frontend/FrontendPluginRegistry.h"
43#include "clang/Frontend/TextDiagnosticBuffer.h"
44#include "clang/Frontend/TextDiagnosticPrinter.h"
45#include "clang/Frontend/VerifyDiagnosticsClient.h"
46#include "clang/Lex/Preprocessor.h"
Sean Callanan47a5c4c2010-09-23 03:01:22 +000047#include "clang/Parse/ParseAST.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000048#include "clang/Rewrite/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"
Greg Clayton2f085c62011-05-15 01:25:55 +000054
Peter Collingbournec3f55732011-06-03 20:40:12 +000055#if !defined(__APPLE__)
56#define USE_STANDARD_JIT
57#endif
58
Greg Clayton2f085c62011-05-15 01:25:55 +000059#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +000060#include "llvm/ExecutionEngine/JIT.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000061#else
62#include "llvm/ExecutionEngine/MCJIT.h"
63#endif
Sean Callanan65dafa82010-08-27 01:01:44 +000064#include "llvm/LLVMContext.h"
Sean Callanan279584c2011-03-15 00:17:19 +000065#include "llvm/Module.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000066#include "llvm/Support/ErrorHandling.h"
67#include "llvm/Support/MemoryBuffer.h"
Greg Clayton22defe82010-12-02 23:20:03 +000068#include "llvm/Support/DynamicLibrary.h"
69#include "llvm/Support/Host.h"
70#include "llvm/Support/Signals.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000071#include "llvm/Target/TargetRegistry.h"
72#include "llvm/Target/TargetSelect.h"
73
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) {
107 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
108
109 Diags.Report(diag::err_fe_error_backend) << Message;
110
111 // We cannot recover from llvm errors.
112 exit(1);
113}
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();
136 case GeneratePCH: return new GeneratePCHAction();
137 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())
178 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
179 CI.getFrontendOpts().ASTMergeFiles.size());
180
181 return Act;
182}
183
184//===----------------------------------------------------------------------===//
185// Implementation of ClangExpressionParser
186//===----------------------------------------------------------------------===//
187
Greg Clayton395fc332011-02-15 21:59:32 +0000188ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
189 ClangExpression &expr) :
190 m_expr (expr),
Sean Callanan65dafa82010-08-27 01:01:44 +0000191 m_compiler (),
192 m_code_generator (NULL),
193 m_execution_engine (),
194 m_jitted_functions ()
195{
196 // Initialize targets first, so that --version shows registered targets.
197 static struct InitializeLLVM {
198 InitializeLLVM() {
199 llvm::InitializeAllTargets();
200 llvm::InitializeAllAsmPrinters();
Sean Callanan9b6898f2011-07-30 02:42:06 +0000201 llvm::InitializeAllTargetMCs();
Sean Callanan65dafa82010-08-27 01:01:44 +0000202 }
203 } InitializeLLVM;
Greg Clayton395fc332011-02-15 21:59:32 +0000204
Sean Callanan65dafa82010-08-27 01:01:44 +0000205 // 1. Create a new compiler instance.
206 m_compiler.reset(new CompilerInstance());
Sean Callanan65dafa82010-08-27 01:01:44 +0000207
208 // 2. Set options.
209
210 // Parse expressions as Objective C++ regardless of context.
211 // Our hook into Clang's lookup mechanism only works in C++.
212 m_compiler->getLangOpts().CPlusPlus = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000213
214 // Setup objective C
Sean Callanan65dafa82010-08-27 01:01:44 +0000215 m_compiler->getLangOpts().ObjC1 = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000216 m_compiler->getLangOpts().ObjC2 = true;
Sean Callananc7674af2011-01-17 23:42:46 +0000217
Greg Clayton395fc332011-02-15 21:59:32 +0000218 Process *process = NULL;
219 if (exe_scope)
220 process = exe_scope->CalculateProcess();
221
Sean Callananc7674af2011-01-17 23:42:46 +0000222 if (process)
223 {
224 if (process->GetObjCLanguageRuntime())
225 {
Greg Claytonb3448432011-03-24 21:19:54 +0000226 if (process->GetObjCLanguageRuntime()->GetRuntimeVersion() == eAppleObjC_V2)
Sean Callananc7674af2011-01-17 23:42:46 +0000227 {
228 m_compiler->getLangOpts().ObjCNonFragileABI = true; // NOT i386
229 m_compiler->getLangOpts().ObjCNonFragileABI2 = true; // NOT i386
230 }
231 }
232 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000233
Sean Callanan65dafa82010-08-27 01:01:44 +0000234 m_compiler->getLangOpts().ThreadsafeStatics = false;
235 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
236 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
Sean Callanan24312442011-08-23 21:20:51 +0000237 //m_compiler->getLangOpts().DebuggerSupport = true; // Features specifically for debugger clients
Sean Callanan65dafa82010-08-27 01:01:44 +0000238
239 // Set CodeGen options
240 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
241 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
242
243 // Disable some warnings.
244 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
245
246 // Set the target triple.
Greg Clayton395fc332011-02-15 21:59:32 +0000247 Target *target = NULL;
248 if (exe_scope)
249 target = exe_scope->CalculateTarget();
250
251 // TODO: figure out what to really do when we don't have a valid target.
252 // Sometimes this will be ok to just use the host target triple (when we
253 // evaluate say "2+3", but other expressions like breakpoint conditions
254 // and other things that _are_ target specific really shouldn't just be
255 // using the host triple. This needs to be fixed in a better way.
256 if (target && target->GetArchitecture().IsValid())
Sean Callanan2a8c3382011-04-14 02:01:31 +0000257 {
258 std::string triple = target->GetArchitecture().GetTriple().str();
259
260 int dash_count = 0;
Johnny Chen2bc9eb32011-07-19 19:48:13 +0000261 for (size_t i = 0; i < triple.size(); ++i)
Sean Callanan2a8c3382011-04-14 02:01:31 +0000262 {
263 if (triple[i] == '-')
264 dash_count++;
265 if (dash_count == 3)
266 {
267 triple.resize(i);
268 break;
269 }
270 }
271
272 m_compiler->getTargetOpts().Triple = triple;
273 }
Greg Clayton395fc332011-02-15 21:59:32 +0000274 else
Sean Callanan2a8c3382011-04-14 02:01:31 +0000275 {
Greg Clayton395fc332011-02-15 21:59:32 +0000276 m_compiler->getTargetOpts().Triple = llvm::sys::getHostTriple();
Sean Callanan2a8c3382011-04-14 02:01:31 +0000277 }
278
Sean Callanan65dafa82010-08-27 01:01:44 +0000279 // 3. Set up various important bits of infrastructure.
280 m_compiler->createDiagnostics(0, 0);
281
282 // Create the target instance.
283 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
284 m_compiler->getTargetOpts()));
285
286 assert (m_compiler->hasTarget());
287
288 // Inform the target of the language options
289 //
290 // FIXME: We shouldn't need to do this, the target should be immutable once
291 // created. This complexity should be lifted elsewhere.
292 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
293
294 // 4. Set up the diagnostic buffer for reporting errors
295
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000296 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000297
298 // 5. Set up the source management objects inside the compiler
299
Greg Clayton22defe82010-12-02 23:20:03 +0000300 clang::FileSystemOptions file_system_options;
301 m_file_manager.reset(new clang::FileManager(file_system_options));
Sean Callanan8a3b0a82010-11-18 02:56:27 +0000302
Sean Callanan65dafa82010-08-27 01:01:44 +0000303 if (!m_compiler->hasSourceManager())
Greg Clayton22defe82010-12-02 23:20:03 +0000304 m_compiler->createSourceManager(*m_file_manager.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000305
306 m_compiler->createFileManager();
307 m_compiler->createPreprocessor();
308
309 // 6. Most of this we get from the CompilerInstance, but we
310 // also want to give the context an ExternalASTSource.
Sean Callananee8fc722010-11-19 20:20:02 +0000311 m_selector_table.reset(new SelectorTable());
Sean Callanan65dafa82010-08-27 01:01:44 +0000312 m_builtin_context.reset(new Builtin::Context(m_compiler->getTarget()));
313
314 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
315 m_compiler->getSourceManager(),
316 m_compiler->getTarget(),
317 m_compiler->getPreprocessor().getIdentifierTable(),
Sean Callananee8fc722010-11-19 20:20:02 +0000318 *m_selector_table.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000319 *m_builtin_context.get(),
320 0));
321
322 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
323
324 if (decl_map)
325 {
326 OwningPtr<clang::ExternalASTSource> ast_source(new ClangASTSource(*ast_context, *decl_map));
327 ast_context->setExternalSource(ast_source);
328 }
329
330 m_compiler->setASTContext(ast_context.release());
331
Greg Clayton8de27c72010-10-15 22:48:33 +0000332 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000333
Sean Callanan279584c2011-03-15 00:17:19 +0000334 m_llvm_context.reset(new LLVMContext());
Sean Callanan65dafa82010-08-27 01:01:44 +0000335 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
336 module_name,
337 m_compiler->getCodeGenOpts(),
Sean Callanan279584c2011-03-15 00:17:19 +0000338 *m_llvm_context));
Sean Callanan65dafa82010-08-27 01:01:44 +0000339}
340
341ClangExpressionParser::~ClangExpressionParser()
342{
343}
344
345unsigned
346ClangExpressionParser::Parse (Stream &stream)
347{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000348 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
349
350 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000351
352 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
353 FileID memory_buffer_file_id = m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
354
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000355 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000356
357 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
358
359 if (ast_transformer)
360 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
361 else
362 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
363
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000364 diag_buf->EndSourceFile();
Sean Callananfb3058e2011-05-12 23:54:16 +0000365
Sean Callanan65dafa82010-08-27 01:01:44 +0000366 TextDiagnosticBuffer::const_iterator diag_iterator;
367
368 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000369
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000370 for (diag_iterator = diag_buf->warn_begin();
371 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000372 ++diag_iterator)
373 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
374
375 num_errors = 0;
376
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000377 for (diag_iterator = diag_buf->err_begin();
378 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000379 ++diag_iterator)
380 {
381 num_errors++;
382 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
383 }
384
Sean Callanan7617c292010-11-01 20:28:09 +0000385 for (diag_iterator = diag_buf->note_begin();
386 diag_iterator != diag_buf->note_end();
387 ++diag_iterator)
388 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
389
Sean Callananfb3058e2011-05-12 23:54:16 +0000390 if (!num_errors)
391 {
392 if (m_expr.DeclMap() && !m_expr.DeclMap()->ResolveUnknownTypes())
393 {
394 stream.Printf("error: Couldn't infer the type of a variable\n");
395 num_errors++;
396 }
397 }
398
Sean Callanan65dafa82010-08-27 01:01:44 +0000399 return num_errors;
400}
401
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000402static bool FindFunctionInModule (std::string &mangled_name,
403 llvm::Module *module,
404 const char *orig_name)
405{
406 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
407 fi != fe;
408 ++fi)
409 {
410 if (fi->getName().str().find(orig_name) != std::string::npos)
411 {
412 mangled_name = fi->getName().str();
413 return true;
414 }
415 }
416
417 return false;
418}
419
Sean Callanan65dafa82010-08-27 01:01:44 +0000420Error
421ClangExpressionParser::MakeDWARF ()
422{
423 Error err;
424
425 llvm::Module *module = m_code_generator->GetModule();
426
427 if (!module)
428 {
429 err.SetErrorToGenericError();
430 err.SetErrorString("IR doesn't contain a module");
431 return err;
432 }
433
Greg Clayton427f2902010-12-14 02:59:59 +0000434 ClangExpressionVariableList *local_variables = m_expr.LocalVariables();
Sean Callanan65dafa82010-08-27 01:01:44 +0000435 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
436
437 if (!local_variables)
438 {
439 err.SetErrorToGenericError();
440 err.SetErrorString("Can't convert an expression without a VariableList to DWARF");
441 return err;
442 }
443
444 if (!decl_map)
445 {
446 err.SetErrorToGenericError();
447 err.SetErrorString("Can't convert an expression without a DeclMap to DWARF");
448 return err;
449 }
450
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000451 std::string function_name;
452
453 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
454 {
455 err.SetErrorToGenericError();
456 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
457 return err;
458 }
459
460 IRToDWARF ir_to_dwarf(*local_variables, decl_map, m_expr.DwarfOpcodeStream(), function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000461
462 if (!ir_to_dwarf.runOnModule(*module))
463 {
464 err.SetErrorToGenericError();
465 err.SetErrorString("Couldn't convert the expression to DWARF");
466 return err;
467 }
468
469 err.Clear();
470 return err;
471}
472
473Error
Greg Claytond0882d02011-01-19 23:00:49 +0000474ClangExpressionParser::MakeJIT (lldb::addr_t &func_allocation_addr,
475 lldb::addr_t &func_addr,
Sean Callanan830a9032010-08-27 23:31:21 +0000476 lldb::addr_t &func_end,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000477 ExecutionContext &exe_ctx,
Sean Callananc0492742011-05-23 21:40:23 +0000478 IRForTarget::StaticDataAllocator *data_allocator,
Sean Callanan696cf5f2011-05-07 01:06:41 +0000479 lldb::ClangExpressionVariableSP &const_result,
480 bool jit_only_if_needed)
Sean Callanan65dafa82010-08-27 01:01:44 +0000481{
Greg Claytond0882d02011-01-19 23:00:49 +0000482 func_allocation_addr = LLDB_INVALID_ADDRESS;
483 func_addr = LLDB_INVALID_ADDRESS;
484 func_end = LLDB_INVALID_ADDRESS;
Greg Claytone005f2c2010-11-06 01:53:30 +0000485 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000486
Sean Callanan65dafa82010-08-27 01:01:44 +0000487 Error err;
488
489 llvm::Module *module = m_code_generator->ReleaseModule();
490
491 if (!module)
492 {
493 err.SetErrorToGenericError();
494 err.SetErrorString("IR doesn't contain a module");
495 return err;
496 }
497
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000498 // Find the actual name of the function (it's often mangled somehow)
499
500 std::string function_name;
501
502 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
503 {
504 err.SetErrorToGenericError();
505 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
506 return err;
507 }
508 else
509 {
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000510 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000511 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
512 }
513
Sean Callanan65dafa82010-08-27 01:01:44 +0000514 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
515
516 if (decl_map)
517 {
Sean Callanan97c924e2011-01-27 01:07:04 +0000518 Stream *error_stream = NULL;
519
520 if (exe_ctx.target)
521 error_stream = &exe_ctx.target->GetDebugger().GetErrorStream();
522
Sean Callanane8a59a82010-09-13 21:34:21 +0000523 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000524 m_expr.NeedsVariableResolution(),
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000525 const_result,
Sean Callananc0492742011-05-23 21:40:23 +0000526 data_allocator,
Sean Callanan97c924e2011-01-27 01:07:04 +0000527 error_stream,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000528 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000529
530 if (!ir_for_target.runOnModule(*module))
531 {
532 err.SetErrorToGenericError();
533 err.SetErrorString("Couldn't convert the expression to DWARF");
534 return err;
535 }
Sean Callananf18d91c2010-09-01 00:58:00 +0000536
Sean Callanan696cf5f2011-05-07 01:06:41 +0000537 if (jit_only_if_needed && const_result.get())
538 {
539 err.Clear();
540 return err;
541 }
542
Jim Inghamd1686902010-10-14 23:45:03 +0000543 if (m_expr.NeedsValidation() && exe_ctx.process->GetDynamicCheckers())
Sean Callananf18d91c2010-09-01 00:58:00 +0000544 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000545 IRDynamicChecks ir_dynamic_checks(*exe_ctx.process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000546
547 if (!ir_dynamic_checks.runOnModule(*module))
548 {
549 err.SetErrorToGenericError();
550 err.SetErrorString("Couldn't add dynamic checks to the expression");
551 return err;
552 }
553 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000554 }
555
Greg Claytond0882d02011-01-19 23:00:49 +0000556 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
557 // below so we don't need to free it.
558 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000559
560 std::string error_string;
Sean Callanan9b6898f2011-07-30 02:42:06 +0000561
Greg Clayton2f085c62011-05-15 01:25:55 +0000562#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +0000563 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
564 &error_string,
Greg Claytond0882d02011-01-19 23:00:49 +0000565 jit_memory_manager,
Sean Callananc2c6f772010-10-26 00:31:56 +0000566 CodeGenOpt::Less,
Sean Callanan65dafa82010-08-27 01:01:44 +0000567 true,
Peter Collingbournec4d4fb52011-07-30 22:42:24 +0000568 Reloc::Default,
Sean Callanan65dafa82010-08-27 01:01:44 +0000569 CodeModel::Small));
Greg Clayton2f085c62011-05-15 01:25:55 +0000570#else
571 EngineBuilder builder(module);
572 builder.setEngineKind(EngineKind::JIT)
573 .setErrorStr(&error_string)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000574 .setRelocationModel(llvm::Reloc::PIC_)
Greg Clayton2f085c62011-05-15 01:25:55 +0000575 .setJITMemoryManager(jit_memory_manager)
576 .setOptLevel(CodeGenOpt::Less)
577 .setAllocateGVsWithCode(true)
578 .setCodeModel(CodeModel::Small)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000579 .setUseMCJIT(true);
Greg Clayton2f085c62011-05-15 01:25:55 +0000580 m_execution_engine.reset(builder.create());
581#endif
Sean Callanan9ac3a962010-11-02 23:20:00 +0000582
Sean Callanan65dafa82010-08-27 01:01:44 +0000583 if (!m_execution_engine.get())
584 {
585 err.SetErrorToGenericError();
586 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
587 return err;
588 }
589
590 m_execution_engine->DisableLazyCompilation();
591
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000592 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000593
594 // We don't actually need the function pointer here, this just forces it to get resolved.
595
596 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
597
598 // Errors usually cause failures in the JIT, but if we're lucky we get here.
599
600 if (!fun_ptr)
601 {
602 err.SetErrorToGenericError();
603 err.SetErrorString("Couldn't JIT the function");
604 return err;
605 }
606
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000607 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000608
609 ExecutionContext &exc_context(exe_ctx);
610
611 if (exc_context.process == NULL)
612 {
613 err.SetErrorToGenericError();
614 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
615 return err;
616 }
617
618 // Look over the regions allocated for the function compiled. The JIT
619 // tries to allocate the functions & stubs close together, so we should try to
620 // write them that way too...
621 // For now I only write functions with no stubs, globals, exception tables,
622 // etc. So I only need to write the functions.
623
624 size_t alloc_size = 0;
625
Greg Claytond0882d02011-01-19 23:00:49 +0000626 std::map<uint8_t *, uint8_t *>::iterator fun_pos = jit_memory_manager->m_functions.begin();
627 std::map<uint8_t *, uint8_t *>::iterator fun_end = jit_memory_manager->m_functions.end();
Greg Clayton9d2b3212011-05-15 23:56:52 +0000628
Sean Callanan65dafa82010-08-27 01:01:44 +0000629 for (; fun_pos != fun_end; ++fun_pos)
Greg Clayton9d2b3212011-05-15 23:56:52 +0000630 {
631 size_t mem_size = fun_pos->second - fun_pos->first;
632 if (log)
633 log->Printf ("JIT memory: [%p - %p) size = %zu", fun_pos->first, fun_pos->second, mem_size);
634 alloc_size += mem_size;
635 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000636
637 Error alloc_error;
Greg Claytond0882d02011-01-19 23:00:49 +0000638 func_allocation_addr = exc_context.process->AllocateMemory (alloc_size,
639 lldb::ePermissionsReadable|lldb::ePermissionsExecutable,
640 alloc_error);
Sean Callanan65dafa82010-08-27 01:01:44 +0000641
Greg Claytond0882d02011-01-19 23:00:49 +0000642 if (func_allocation_addr == LLDB_INVALID_ADDRESS)
Sean Callanan65dafa82010-08-27 01:01:44 +0000643 {
644 err.SetErrorToGenericError();
645 err.SetErrorStringWithFormat("Couldn't allocate memory for the JITted function: %s", alloc_error.AsCString("unknown error"));
646 return err;
647 }
648
Greg Claytond0882d02011-01-19 23:00:49 +0000649 lldb::addr_t cursor = func_allocation_addr;
Sean Callanan65dafa82010-08-27 01:01:44 +0000650
Greg Claytond0882d02011-01-19 23:00:49 +0000651 for (fun_pos = jit_memory_manager->m_functions.begin(); fun_pos != fun_end; fun_pos++)
Sean Callanan65dafa82010-08-27 01:01:44 +0000652 {
653 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
654 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
655 size_t size = lend - lstart;
656
657 Error write_error;
658
659 if (exc_context.process->WriteMemory(cursor, (void *) lstart, size, write_error) != size)
660 {
661 err.SetErrorToGenericError();
Greg Claytonc0fa5332011-05-22 22:46:53 +0000662 err.SetErrorStringWithFormat("Couldn't copy JIT code for function into the target: %s", write_error.AsCString("unknown error"));
Sean Callanan65dafa82010-08-27 01:01:44 +0000663 return err;
664 }
665
Greg Claytond0882d02011-01-19 23:00:49 +0000666 jit_memory_manager->AddToLocalToRemoteMap (lstart, size, cursor);
Sean Callanan65dafa82010-08-27 01:01:44 +0000667 cursor += size;
668 }
669
670 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
671
672 for (pos = m_jitted_functions.begin(); pos != end; pos++)
673 {
Greg Claytond0882d02011-01-19 23:00:49 +0000674 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000675
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000676 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000677 {
Greg Claytond0882d02011-01-19 23:00:49 +0000678 func_end = jit_memory_manager->GetRemoteRangeForLocal ((*pos).m_local_addr).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)
Sean Callanan65dafa82010-08-27 01:01:44 +0000738 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
739
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)
Sean Callanan65dafa82010-08-27 01:01:44 +0000752 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
753
754 if (!exe_ctx.target)
755 {
756 ret.SetErrorToGenericError();
757 ret.SetErrorString("Couldn't find the target");
758 }
759
760 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
761
762 Error err;
763 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
764
765 if (!err.Success())
766 {
767 ret.SetErrorToGenericError();
768 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
769 return ret;
770 }
771
772 ArchSpec arch(exe_ctx.target->GetArchitecture());
773
Greg Clayton149731c2011-03-25 18:03:16 +0000774 Disassembler *disassembler = Disassembler::FindPlugin(arch, NULL);
Sean Callanan65dafa82010-08-27 01:01:44 +0000775
776 if (disassembler == NULL)
777 {
778 ret.SetErrorToGenericError();
Greg Clayton940b1032011-02-23 00:35:02 +0000779 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
Sean Callanan65dafa82010-08-27 01:01:44 +0000780 return ret;
781 }
782
783 if (!exe_ctx.process)
784 {
785 ret.SetErrorToGenericError();
786 ret.SetErrorString("Couldn't find the process");
787 return ret;
788 }
789
790 DataExtractor extractor(buffer_sp,
791 exe_ctx.process->GetByteOrder(),
792 exe_ctx.target->GetArchitecture().GetAddressByteSize());
793
Greg Claytone005f2c2010-11-06 01:53:30 +0000794 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000795 {
796 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000797 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000798 0,
799 extractor.GetByteSize(),
800 func_remote_addr,
801 16,
802 DataExtractor::TypeUInt8);
803 }
804
Jim Inghamaa3e3e12011-03-22 01:48:42 +0000805 disassembler->DecodeInstructions (Address (NULL, func_remote_addr), extractor, 0, UINT32_MAX, false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000806
Greg Clayton5c4c7462010-10-06 03:09:58 +0000807 InstructionList &instruction_list = disassembler->GetInstructionList();
Greg Clayton889fbd02011-03-26 19:14:58 +0000808 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
Sean Callanan65dafa82010-08-27 01:01:44 +0000809 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
810 instruction_index < num_instructions;
811 ++instruction_index)
812 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000813 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000814 instruction->Dump (&stream,
Greg Clayton889fbd02011-03-26 19:14:58 +0000815 max_opcode_byte_size,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000816 true,
Greg Clayton149731c2011-03-25 18:03:16 +0000817 true,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000818 &exe_ctx,
Sean Callanan65dafa82010-08-27 01:01:44 +0000819 true);
820 stream.PutChar('\n');
Sean Callanan65dafa82010-08-27 01:01:44 +0000821 }
822
823 return ret;
824}