blob: ecf0547e745ed8d8280d0db6b9acb633d88deaf4 [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/RecordingMemoryManager.h"
23#include "lldb/Target/ExecutionContext.h"
Sean Callananc7674af2011-01-17 23:42:46 +000024#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000025#include "lldb/Target/Process.h"
26#include "lldb/Target/Target.h"
27
28#include "clang/AST/ASTContext.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/Basic/FileManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/Version.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000033#include "clang/CodeGen/CodeGenAction.h"
34#include "clang/CodeGen/ModuleBuilder.h"
35#include "clang/Driver/CC1Options.h"
36#include "clang/Driver/OptTable.h"
37#include "clang/Frontend/CompilerInstance.h"
38#include "clang/Frontend/CompilerInvocation.h"
39#include "clang/Frontend/FrontendActions.h"
40#include "clang/Frontend/FrontendDiagnostic.h"
41#include "clang/Frontend/FrontendPluginRegistry.h"
42#include "clang/Frontend/TextDiagnosticBuffer.h"
43#include "clang/Frontend/TextDiagnosticPrinter.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000044#include "clang/Lex/Preprocessor.h"
Sean Callanan47a5c4c2010-09-23 03:01:22 +000045#include "clang/Parse/ParseAST.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000046#include "clang/Rewrite/FrontendActions.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000047#include "clang/Sema/SemaConsumer.h"
Sean Callanan279584c2011-03-15 00:17:19 +000048#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000049
50#include "llvm/ADT/StringRef.h"
51#include "llvm/ExecutionEngine/ExecutionEngine.h"
Sean Callananc1535182011-10-07 23:18:13 +000052#include "llvm/Support/TargetSelect.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000053
Peter Collingbournec3f55732011-06-03 20:40:12 +000054#if !defined(__APPLE__)
55#define USE_STANDARD_JIT
56#endif
57
Greg Clayton2f085c62011-05-15 01:25:55 +000058#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +000059#include "llvm/ExecutionEngine/JIT.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000060#else
61#include "llvm/ExecutionEngine/MCJIT.h"
62#endif
Sean Callanan65dafa82010-08-27 01:01:44 +000063#include "llvm/LLVMContext.h"
Sean Callanan279584c2011-03-15 00:17:19 +000064#include "llvm/Module.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000065#include "llvm/Support/ErrorHandling.h"
66#include "llvm/Support/MemoryBuffer.h"
Greg Clayton22defe82010-12-02 23:20:03 +000067#include "llvm/Support/DynamicLibrary.h"
68#include "llvm/Support/Host.h"
69#include "llvm/Support/Signals.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000070
71using namespace clang;
72using namespace llvm;
73using namespace lldb_private;
74
75//===----------------------------------------------------------------------===//
76// Utility Methods for Clang
77//===----------------------------------------------------------------------===//
78
79std::string GetBuiltinIncludePath(const char *Argv0) {
80 llvm::sys::Path P =
81 llvm::sys::Path::GetMainExecutable(Argv0,
82 (void*)(intptr_t) GetBuiltinIncludePath);
83
84 if (!P.isEmpty()) {
85 P.eraseComponent(); // Remove /clang from foo/bin/clang
86 P.eraseComponent(); // Remove /bin from foo/bin
87
88 // Get foo/lib/clang/<version>/include
89 P.appendComponent("lib");
90 P.appendComponent("clang");
91 P.appendComponent(CLANG_VERSION_STRING);
92 P.appendComponent("include");
93 }
94
95 return P.str();
96}
97
98
99//===----------------------------------------------------------------------===//
100// Main driver for Clang
101//===----------------------------------------------------------------------===//
102
103static void LLVMErrorHandler(void *UserData, const std::string &Message) {
Sean Callananc1535182011-10-07 23:18:13 +0000104 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
Sean Callanan65dafa82010-08-27 01:01:44 +0000105
106 Diags.Report(diag::err_fe_error_backend) << Message;
107
108 // We cannot recover from llvm errors.
Sean Callananc1535182011-10-07 23:18:13 +0000109 assert(0);
Sean Callanan65dafa82010-08-27 01:01:44 +0000110}
111
112static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
113 using namespace clang::frontend;
114
115 switch (CI.getFrontendOpts().ProgramAction) {
116 default:
117 llvm_unreachable("Invalid program action!");
118
119 case ASTDump: return new ASTDumpAction();
120 case ASTPrint: return new ASTPrintAction();
Sean Callanan279584c2011-03-15 00:17:19 +0000121 case ASTDumpXML: return new ASTDumpXMLAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000122 case ASTView: return new ASTViewAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000123 case DumpRawTokens: return new DumpRawTokensAction();
124 case DumpTokens: return new DumpTokensAction();
125 case EmitAssembly: return new EmitAssemblyAction();
126 case EmitBC: return new EmitBCAction();
127 case EmitHTML: return new HTMLPrintAction();
128 case EmitLLVM: return new EmitLLVMAction();
129 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
130 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
131 case EmitObj: return new EmitObjAction();
132 case FixIt: return new FixItAction();
Sean Callanan05230832011-12-01 04:31:46 +0000133 case GeneratePCH: return new GeneratePCHAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000134 case GeneratePTH: return new GeneratePTHAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000135 case InitOnly: return new InitOnlyAction();
136 case ParseSyntaxOnly: return new SyntaxOnlyAction();
137
138 case PluginAction: {
139 for (FrontendPluginRegistry::iterator it =
140 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
141 it != ie; ++it) {
142 if (it->getName() == CI.getFrontendOpts().ActionName) {
143 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
144 if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
145 return 0;
146 return P.take();
147 }
148 }
149
150 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
151 << CI.getFrontendOpts().ActionName;
152 return 0;
153 }
154
155 case PrintDeclContext: return new DeclContextPrintAction();
156 case PrintPreamble: return new PrintPreambleAction();
157 case PrintPreprocessedInput: return new PrintPreprocessedAction();
158 case RewriteMacros: return new RewriteMacrosAction();
159 case RewriteObjC: return new RewriteObjCAction();
160 case RewriteTest: return new RewriteTestAction();
Sean Callananad293092011-01-18 23:32:05 +0000161 //case RunAnalysis: return new AnalysisAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000162 case RunPreprocessorOnly: return new PreprocessOnlyAction();
163 }
164}
165
166static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
167 // Create the underlying action.
168 FrontendAction *Act = CreateFrontendBaseAction(CI);
169 if (!Act)
170 return 0;
171
172 // If there are any AST files to merge, create a frontend action
173 // adaptor to perform the merge.
174 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
Sean Callanan8f2e3922012-02-04 08:49:35 +0000175 Act = new ASTMergeAction(Act, CI.getFrontendOpts().ASTMergeFiles);
Sean Callanan65dafa82010-08-27 01:01:44 +0000176
177 return Act;
178}
179
180//===----------------------------------------------------------------------===//
181// Implementation of ClangExpressionParser
182//===----------------------------------------------------------------------===//
183
Greg Clayton395fc332011-02-15 21:59:32 +0000184ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
185 ClangExpression &expr) :
186 m_expr (expr),
Sean Callanan65dafa82010-08-27 01:01:44 +0000187 m_compiler (),
188 m_code_generator (NULL),
Sean Callanan65dafa82010-08-27 01:01:44 +0000189 m_jitted_functions ()
190{
191 // Initialize targets first, so that --version shows registered targets.
192 static struct InitializeLLVM {
193 InitializeLLVM() {
194 llvm::InitializeAllTargets();
195 llvm::InitializeAllAsmPrinters();
Sean Callanan9b6898f2011-07-30 02:42:06 +0000196 llvm::InitializeAllTargetMCs();
Sean Callanan05230832011-12-01 04:31:46 +0000197 llvm::InitializeAllDisassemblers();
Sean Callanan65dafa82010-08-27 01:01:44 +0000198 }
199 } InitializeLLVM;
Greg Clayton395fc332011-02-15 21:59:32 +0000200
Sean Callanan65dafa82010-08-27 01:01:44 +0000201 // 1. Create a new compiler instance.
202 m_compiler.reset(new CompilerInstance());
Sean Callanan65dafa82010-08-27 01:01:44 +0000203
204 // 2. Set options.
205
Sean Callanan5b658cc2011-11-07 23:35:40 +0000206 lldb::LanguageType language = expr.Language();
Greg Claytonf51ed302011-01-15 01:32:14 +0000207
Sean Callanan5b658cc2011-11-07 23:35:40 +0000208 switch (language)
209 {
210 case lldb::eLanguageTypeC:
211 break;
212 case lldb::eLanguageTypeObjC:
213 m_compiler->getLangOpts().ObjC1 = true;
214 m_compiler->getLangOpts().ObjC2 = true;
215 break;
216 case lldb::eLanguageTypeC_plus_plus:
217 m_compiler->getLangOpts().CPlusPlus = true;
Sean Callananf0613182012-05-16 21:03:38 +0000218 m_compiler->getLangOpts().CPlusPlus0x = true;
Sean Callanan5b658cc2011-11-07 23:35:40 +0000219 break;
220 case lldb::eLanguageTypeObjC_plus_plus:
221 default:
222 m_compiler->getLangOpts().ObjC1 = true;
223 m_compiler->getLangOpts().ObjC2 = true;
224 m_compiler->getLangOpts().CPlusPlus = true;
Sean Callananf0613182012-05-16 21:03:38 +0000225 m_compiler->getLangOpts().CPlusPlus0x = true;
Sean Callanan5b658cc2011-11-07 23:35:40 +0000226 break;
227 }
Sean Callananc7674af2011-01-17 23:42:46 +0000228
Sean Callanan6e12c7a2012-03-08 02:39:03 +0000229 m_compiler->getLangOpts().DebuggerSupport = true; // Features specifically for debugger clients
230 if (expr.DesiredResultType() == ClangExpression::eResultTypeId)
231 m_compiler->getLangOpts().DebuggerCastResultToId = true;
232
Sean Callanan6c797dc2012-04-17 00:49:48 +0000233 // Spell checking is a nice feature, but it ends up completing a
234 // lot of types that we didn't strictly speaking need to complete.
235 // As a result, we spend a long time parsing and importing debug
236 // information.
237 m_compiler->getLangOpts().SpellChecking = false;
238
Greg Clayton289afcb2012-02-18 05:35:26 +0000239 lldb::ProcessSP process_sp;
Greg Clayton395fc332011-02-15 21:59:32 +0000240 if (exe_scope)
Greg Clayton289afcb2012-02-18 05:35:26 +0000241 process_sp = exe_scope->CalculateProcess();
Greg Clayton395fc332011-02-15 21:59:32 +0000242
Greg Clayton289afcb2012-02-18 05:35:26 +0000243 if (process_sp && m_compiler->getLangOpts().ObjC1)
Sean Callananc7674af2011-01-17 23:42:46 +0000244 {
Greg Clayton289afcb2012-02-18 05:35:26 +0000245 if (process_sp->GetObjCLanguageRuntime())
Sean Callananc7674af2011-01-17 23:42:46 +0000246 {
Greg Clayton289afcb2012-02-18 05:35:26 +0000247 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() == eAppleObjC_V2)
Sean Callananc7674af2011-01-17 23:42:46 +0000248 {
249 m_compiler->getLangOpts().ObjCNonFragileABI = true; // NOT i386
250 m_compiler->getLangOpts().ObjCNonFragileABI2 = true; // NOT i386
251 }
Sean Callanan6e12c7a2012-03-08 02:39:03 +0000252
253 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
254 {
255 m_compiler->getLangOpts().DebuggerObjCLiteral = true;
256 }
Sean Callananc7674af2011-01-17 23:42:46 +0000257 }
258 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000259
Sean Callanan65dafa82010-08-27 01:01:44 +0000260 m_compiler->getLangOpts().ThreadsafeStatics = false;
261 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
262 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
Sean Callanandaa6efe2011-12-21 22:22:58 +0000263
Sean Callanan65dafa82010-08-27 01:01:44 +0000264 // Set CodeGen options
265 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
266 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
267
268 // Disable some warnings.
269 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
270
271 // Set the target triple.
Greg Clayton289afcb2012-02-18 05:35:26 +0000272 lldb::TargetSP target_sp;
Greg Clayton395fc332011-02-15 21:59:32 +0000273 if (exe_scope)
Greg Clayton289afcb2012-02-18 05:35:26 +0000274 target_sp = exe_scope->CalculateTarget();
Greg Clayton395fc332011-02-15 21:59:32 +0000275
276 // TODO: figure out what to really do when we don't have a valid target.
277 // Sometimes this will be ok to just use the host target triple (when we
278 // evaluate say "2+3", but other expressions like breakpoint conditions
279 // and other things that _are_ target specific really shouldn't just be
280 // using the host triple. This needs to be fixed in a better way.
Greg Clayton289afcb2012-02-18 05:35:26 +0000281 if (target_sp && target_sp->GetArchitecture().IsValid())
Sean Callanan2a8c3382011-04-14 02:01:31 +0000282 {
Greg Clayton289afcb2012-02-18 05:35:26 +0000283 std::string triple = target_sp->GetArchitecture().GetTriple().str();
Sean Callanan2a8c3382011-04-14 02:01:31 +0000284
285 int dash_count = 0;
Johnny Chen2bc9eb32011-07-19 19:48:13 +0000286 for (size_t i = 0; i < triple.size(); ++i)
Sean Callanan2a8c3382011-04-14 02:01:31 +0000287 {
288 if (triple[i] == '-')
289 dash_count++;
290 if (dash_count == 3)
291 {
292 triple.resize(i);
293 break;
294 }
295 }
296
297 m_compiler->getTargetOpts().Triple = triple;
298 }
Greg Clayton395fc332011-02-15 21:59:32 +0000299 else
Sean Callanan2a8c3382011-04-14 02:01:31 +0000300 {
Sean Callanan7537dce2011-11-04 22:46:46 +0000301 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
Sean Callanan2a8c3382011-04-14 02:01:31 +0000302 }
303
Sean Callanan65dafa82010-08-27 01:01:44 +0000304 // 3. Set up various important bits of infrastructure.
305 m_compiler->createDiagnostics(0, 0);
306
307 // Create the target instance.
308 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
309 m_compiler->getTargetOpts()));
310
311 assert (m_compiler->hasTarget());
312
313 // Inform the target of the language options
314 //
315 // FIXME: We shouldn't need to do this, the target should be immutable once
316 // created. This complexity should be lifted elsewhere.
317 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
318
319 // 4. Set up the diagnostic buffer for reporting errors
320
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000321 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000322
323 // 5. Set up the source management objects inside the compiler
324
Greg Clayton22defe82010-12-02 23:20:03 +0000325 clang::FileSystemOptions file_system_options;
326 m_file_manager.reset(new clang::FileManager(file_system_options));
Sean Callanan8a3b0a82010-11-18 02:56:27 +0000327
Sean Callanan65dafa82010-08-27 01:01:44 +0000328 if (!m_compiler->hasSourceManager())
Greg Clayton22defe82010-12-02 23:20:03 +0000329 m_compiler->createSourceManager(*m_file_manager.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000330
331 m_compiler->createFileManager();
332 m_compiler->createPreprocessor();
333
334 // 6. Most of this we get from the CompilerInstance, but we
335 // also want to give the context an ExternalASTSource.
Sean Callananee8fc722010-11-19 20:20:02 +0000336 m_selector_table.reset(new SelectorTable());
Sean Callananc1535182011-10-07 23:18:13 +0000337 m_builtin_context.reset(new Builtin::Context());
Sean Callanan65dafa82010-08-27 01:01:44 +0000338
339 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
340 m_compiler->getSourceManager(),
Sean Callananc1535182011-10-07 23:18:13 +0000341 &m_compiler->getTarget(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000342 m_compiler->getPreprocessor().getIdentifierTable(),
Sean Callananee8fc722010-11-19 20:20:02 +0000343 *m_selector_table.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000344 *m_builtin_context.get(),
345 0));
346
347 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
348
349 if (decl_map)
350 {
Sean Callananf76afff2011-10-28 23:38:38 +0000351 llvm::OwningPtr<clang::ExternalASTSource> ast_source(decl_map->CreateProxy());
352 decl_map->InstallASTContext(ast_context.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000353 ast_context->setExternalSource(ast_source);
354 }
355
356 m_compiler->setASTContext(ast_context.release());
357
Greg Clayton8de27c72010-10-15 22:48:33 +0000358 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000359
Sean Callanan279584c2011-03-15 00:17:19 +0000360 m_llvm_context.reset(new LLVMContext());
Sean Callanan65dafa82010-08-27 01:01:44 +0000361 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
362 module_name,
363 m_compiler->getCodeGenOpts(),
Sean Callanan279584c2011-03-15 00:17:19 +0000364 *m_llvm_context));
Sean Callanan65dafa82010-08-27 01:01:44 +0000365}
366
367ClangExpressionParser::~ClangExpressionParser()
368{
369}
370
371unsigned
372ClangExpressionParser::Parse (Stream &stream)
373{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000374 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
375
376 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000377
378 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
Sean Callanan142f94c2012-03-01 02:03:47 +0000379 m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000380
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000381 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000382
383 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
384
385 if (ast_transformer)
386 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
387 else
388 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
389
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000390 diag_buf->EndSourceFile();
Sean Callananfb3058e2011-05-12 23:54:16 +0000391
Sean Callanan65dafa82010-08-27 01:01:44 +0000392 TextDiagnosticBuffer::const_iterator diag_iterator;
393
394 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000395
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000396 for (diag_iterator = diag_buf->warn_begin();
397 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000398 ++diag_iterator)
399 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
400
401 num_errors = 0;
402
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000403 for (diag_iterator = diag_buf->err_begin();
404 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000405 ++diag_iterator)
406 {
407 num_errors++;
408 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
409 }
410
Sean Callanan7617c292010-11-01 20:28:09 +0000411 for (diag_iterator = diag_buf->note_begin();
412 diag_iterator != diag_buf->note_end();
413 ++diag_iterator)
414 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
415
Sean Callananfb3058e2011-05-12 23:54:16 +0000416 if (!num_errors)
417 {
418 if (m_expr.DeclMap() && !m_expr.DeclMap()->ResolveUnknownTypes())
419 {
420 stream.Printf("error: Couldn't infer the type of a variable\n");
421 num_errors++;
422 }
423 }
424
Sean Callanan65dafa82010-08-27 01:01:44 +0000425 return num_errors;
426}
427
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000428static bool FindFunctionInModule (std::string &mangled_name,
429 llvm::Module *module,
430 const char *orig_name)
431{
432 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
433 fi != fe;
434 ++fi)
435 {
436 if (fi->getName().str().find(orig_name) != std::string::npos)
437 {
438 mangled_name = fi->getName().str();
439 return true;
440 }
441 }
442
443 return false;
444}
445
Sean Callanan65dafa82010-08-27 01:01:44 +0000446Error
Sean Callanan47dc4572011-09-15 02:13:07 +0000447ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_allocation_addr,
448 lldb::addr_t &func_addr,
449 lldb::addr_t &func_end,
450 ExecutionContext &exe_ctx,
451 IRForTarget::StaticDataAllocator *data_allocator,
452 bool &evaluated_statically,
453 lldb::ClangExpressionVariableSP &const_result,
454 ExecutionPolicy execution_policy)
Sean Callanan65dafa82010-08-27 01:01:44 +0000455{
Greg Claytond0882d02011-01-19 23:00:49 +0000456 func_allocation_addr = LLDB_INVALID_ADDRESS;
457 func_addr = LLDB_INVALID_ADDRESS;
458 func_end = LLDB_INVALID_ADDRESS;
Greg Claytone005f2c2010-11-06 01:53:30 +0000459 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000460
Sean Callananddf110d2012-01-24 22:06:48 +0000461 std::auto_ptr<llvm::ExecutionEngine> execution_engine;
462
Sean Callanan65dafa82010-08-27 01:01:44 +0000463 Error err;
464
465 llvm::Module *module = m_code_generator->ReleaseModule();
466
467 if (!module)
468 {
469 err.SetErrorToGenericError();
470 err.SetErrorString("IR doesn't contain a module");
471 return err;
472 }
473
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000474 // Find the actual name of the function (it's often mangled somehow)
475
476 std::string function_name;
477
478 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
479 {
480 err.SetErrorToGenericError();
481 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
482 return err;
483 }
484 else
485 {
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000486 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000487 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
488 }
489
Sean Callanan65dafa82010-08-27 01:01:44 +0000490 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
491
492 if (decl_map)
493 {
Sean Callanan97c924e2011-01-27 01:07:04 +0000494 Stream *error_stream = NULL;
Greg Clayton567e7f32011-09-22 04:58:26 +0000495 Target *target = exe_ctx.GetTargetPtr();
496 if (target)
497 error_stream = &target->GetDebugger().GetErrorStream();
Sean Callanan97c924e2011-01-27 01:07:04 +0000498
Sean Callanan47dc4572011-09-15 02:13:07 +0000499 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000500 m_expr.NeedsVariableResolution(),
Sean Callanan47dc4572011-09-15 02:13:07 +0000501 execution_policy,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000502 const_result,
Sean Callananc0492742011-05-23 21:40:23 +0000503 data_allocator,
Sean Callanan97c924e2011-01-27 01:07:04 +0000504 error_stream,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000505 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000506
Sean Callanan8f2e3922012-02-04 08:49:35 +0000507 ir_for_target.runOnModule(*module);
Sean Callananf18d91c2010-09-01 00:58:00 +0000508
Sean Callananddf110d2012-01-24 22:06:48 +0000509 Error &interpreter_error(ir_for_target.getInterpreterError());
510
511 if (execution_policy != eExecutionPolicyAlways && interpreter_error.Success())
Sean Callanan696cf5f2011-05-07 01:06:41 +0000512 {
Johnny Chenc6134962012-01-06 00:35:38 +0000513 if (const_result)
514 const_result->TransferAddress();
Sean Callanan47dc4572011-09-15 02:13:07 +0000515 evaluated_statically = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000516 err.Clear();
517 return err;
518 }
519
Greg Clayton567e7f32011-09-22 04:58:26 +0000520 Process *process = exe_ctx.GetProcessPtr();
521
522 if (!process || execution_policy == eExecutionPolicyNever)
Sean Callanan47dc4572011-09-15 02:13:07 +0000523 {
524 err.SetErrorToGenericError();
Sean Callananddf110d2012-01-24 22:06:48 +0000525 if (execution_policy == eExecutionPolicyAlways)
526 err.SetErrorString("Execution needed to run in the target, but the target can't be run");
527 else
528 err.SetErrorStringWithFormat("Interpreting the expression locally failed: %s", interpreter_error.AsCString());
Sean Callanan8f2e3922012-02-04 08:49:35 +0000529
Sean Callanan47dc4572011-09-15 02:13:07 +0000530 return err;
531 }
532
Sean Callanan6cf6c472011-09-20 23:01:51 +0000533 if (execution_policy != eExecutionPolicyNever &&
534 m_expr.NeedsValidation() &&
Greg Clayton567e7f32011-09-22 04:58:26 +0000535 process)
Sean Callananf18d91c2010-09-01 00:58:00 +0000536 {
Greg Clayton567e7f32011-09-22 04:58:26 +0000537 if (!process->GetDynamicCheckers())
Sean Callanan6cf6c472011-09-20 23:01:51 +0000538 {
539 DynamicCheckerFunctions *dynamic_checkers = new DynamicCheckerFunctions();
540
541 StreamString install_errors;
542
543 if (!dynamic_checkers->Install(install_errors, exe_ctx))
544 {
545 if (install_errors.GetString().empty())
546 err.SetErrorString ("couldn't install checkers, unknown error");
547 else
548 err.SetErrorString (install_errors.GetString().c_str());
549
550 return err;
551 }
552
Greg Clayton567e7f32011-09-22 04:58:26 +0000553 process->SetDynamicCheckers(dynamic_checkers);
Sean Callanan6cf6c472011-09-20 23:01:51 +0000554
555 if (log)
556 log->Printf("== [ClangUserExpression::Evaluate] Finished installing dynamic checkers ==");
557 }
558
Greg Clayton567e7f32011-09-22 04:58:26 +0000559 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000560
561 if (!ir_dynamic_checks.runOnModule(*module))
562 {
563 err.SetErrorToGenericError();
564 err.SetErrorString("Couldn't add dynamic checks to the expression");
565 return err;
566 }
567 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000568 }
569
Greg Claytond0882d02011-01-19 23:00:49 +0000570 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
571 // below so we don't need to free it.
572 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000573
574 std::string error_string;
Sean Callanan7b8eb762011-11-01 17:33:54 +0000575
576 if (log)
577 {
578 std::string s;
579 raw_string_ostream oss(s);
580
581 module->print(oss, NULL);
582
583 oss.flush();
584
585 log->Printf ("Module being sent to JIT: \n%s", s.c_str());
586 }
587
Greg Clayton2f085c62011-05-15 01:25:55 +0000588 EngineBuilder builder(module);
589 builder.setEngineKind(EngineKind::JIT)
590 .setErrorStr(&error_string)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000591 .setRelocationModel(llvm::Reloc::PIC_)
Greg Clayton2f085c62011-05-15 01:25:55 +0000592 .setJITMemoryManager(jit_memory_manager)
593 .setOptLevel(CodeGenOpt::Less)
594 .setAllocateGVsWithCode(true)
595 .setCodeModel(CodeModel::Small)
Sean Callanan16b53ab2011-10-12 00:12:34 +0000596 .setUseMCJIT(true);
Sean Callananddf110d2012-01-24 22:06:48 +0000597 execution_engine.reset(builder.create());
Sean Callanan9ac3a962010-11-02 23:20:00 +0000598
Sean Callananddf110d2012-01-24 22:06:48 +0000599 if (!execution_engine.get())
Sean Callanan65dafa82010-08-27 01:01:44 +0000600 {
601 err.SetErrorToGenericError();
602 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
603 return err;
604 }
605
Sean Callananddf110d2012-01-24 22:06:48 +0000606 execution_engine->DisableLazyCompilation();
Sean Callanan65dafa82010-08-27 01:01:44 +0000607
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000608 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000609
610 // We don't actually need the function pointer here, this just forces it to get resolved.
611
Sean Callananddf110d2012-01-24 22:06:48 +0000612 void *fun_ptr = execution_engine->getPointerToFunction(function);
613
Sean Callanan65dafa82010-08-27 01:01:44 +0000614 // Errors usually cause failures in the JIT, but if we're lucky we get here.
615
Sean Callanan7b8eb762011-11-01 17:33:54 +0000616 if (!function)
617 {
618 err.SetErrorToGenericError();
619 err.SetErrorStringWithFormat("Couldn't find '%s' in the JITted module", function_name.c_str());
620 return err;
621 }
622
Sean Callanan65dafa82010-08-27 01:01:44 +0000623 if (!fun_ptr)
624 {
625 err.SetErrorToGenericError();
Sean Callanan7b8eb762011-11-01 17:33:54 +0000626 err.SetErrorStringWithFormat("'%s' was in the JITted module but wasn't lowered", function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000627 return err;
628 }
629
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000630 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000631
Greg Clayton567e7f32011-09-22 04:58:26 +0000632
633 Process *process = exe_ctx.GetProcessPtr();
634 if (process == NULL)
Sean Callanan65dafa82010-08-27 01:01:44 +0000635 {
636 err.SetErrorToGenericError();
637 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
638 return err;
639 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000640
Sean Callanan8f2e3922012-02-04 08:49:35 +0000641 jit_memory_manager->CommitAllocations(*process);
Sean Callanan142f94c2012-03-01 02:03:47 +0000642 jit_memory_manager->ReportAllocations(*execution_engine);
Sean Callanan8f2e3922012-02-04 08:49:35 +0000643 jit_memory_manager->WriteData(*process);
Sean Callanan65dafa82010-08-27 01:01:44 +0000644
645 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
646
647 for (pos = m_jitted_functions.begin(); pos != end; pos++)
648 {
Greg Claytond0882d02011-01-19 23:00:49 +0000649 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000650
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000651 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000652 {
Sean Callanan8f2e3922012-02-04 08:49:35 +0000653 RecordingMemoryManager::AddrRange func_range = jit_memory_manager->GetRemoteRangeForLocal((*pos).m_local_addr);
654 func_end = func_range.first + func_range.second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000655 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000656 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000657 }
658
Sean Callanan6dff8272010-11-08 03:49:50 +0000659 if (log)
660 {
661 log->Printf("Code can be run in the target.");
662
663 StreamString disassembly_stream;
664
Greg Claytond0882d02011-01-19 23:00:49 +0000665 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000666
667 if (!err.Success())
668 {
669 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
670 }
671 else
672 {
673 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
674 }
675 }
676
Sean Callananddf110d2012-01-24 22:06:48 +0000677 execution_engine.reset();
678
Sean Callanan65dafa82010-08-27 01:01:44 +0000679 err.Clear();
680 return err;
681}
682
683Error
Greg Claytond0882d02011-01-19 23:00:49 +0000684ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000685{
Greg Claytone005f2c2010-11-06 01:53:30 +0000686 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000687
688 const char *name = m_expr.FunctionName();
689
690 Error ret;
691
692 ret.Clear();
693
694 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
695 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
696
697 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
698
699 for (pos = m_jitted_functions.begin(); pos < end; pos++)
700 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000701 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000702 {
703 func_local_addr = pos->m_local_addr;
704 func_remote_addr = pos->m_remote_addr;
705 }
706 }
707
708 if (func_local_addr == LLDB_INVALID_ADDRESS)
709 {
710 ret.SetErrorToGenericError();
711 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
712 return ret;
713 }
714
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000715 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000716 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
717
718 std::pair <lldb::addr_t, lldb::addr_t> func_range;
719
Greg Claytond0882d02011-01-19 23:00:49 +0000720 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000721
722 if (func_range.first == 0 && func_range.second == 0)
723 {
724 ret.SetErrorToGenericError();
725 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
726 return ret;
727 }
728
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000729 if (log)
Sean Callanan8f2e3922012-02-04 08:49:35 +0000730 log->Printf("Function's code range is [0x%llx+0x%llx]", func_range.first, func_range.second);
Sean Callanan65dafa82010-08-27 01:01:44 +0000731
Greg Clayton567e7f32011-09-22 04:58:26 +0000732 Target *target = exe_ctx.GetTargetPtr();
733 if (!target)
Sean Callanan65dafa82010-08-27 01:01:44 +0000734 {
735 ret.SetErrorToGenericError();
736 ret.SetErrorString("Couldn't find the target");
737 }
738
Sean Callanan8f2e3922012-02-04 08:49:35 +0000739 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0));
Sean Callanan65dafa82010-08-27 01:01:44 +0000740
Greg Clayton567e7f32011-09-22 04:58:26 +0000741 Process *process = exe_ctx.GetProcessPtr();
Sean Callanan65dafa82010-08-27 01:01:44 +0000742 Error err;
Greg Clayton567e7f32011-09-22 04:58:26 +0000743 process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
Sean Callanan65dafa82010-08-27 01:01:44 +0000744
745 if (!err.Success())
746 {
747 ret.SetErrorToGenericError();
748 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
749 return ret;
750 }
751
Greg Clayton567e7f32011-09-22 04:58:26 +0000752 ArchSpec arch(target->GetArchitecture());
Sean Callanan65dafa82010-08-27 01:01:44 +0000753
Greg Clayton149731c2011-03-25 18:03:16 +0000754 Disassembler *disassembler = Disassembler::FindPlugin(arch, NULL);
Sean Callanan65dafa82010-08-27 01:01:44 +0000755
756 if (disassembler == NULL)
757 {
758 ret.SetErrorToGenericError();
Greg Clayton940b1032011-02-23 00:35:02 +0000759 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
Sean Callanan65dafa82010-08-27 01:01:44 +0000760 return ret;
761 }
762
Greg Clayton567e7f32011-09-22 04:58:26 +0000763 if (!process)
Sean Callanan65dafa82010-08-27 01:01:44 +0000764 {
765 ret.SetErrorToGenericError();
766 ret.SetErrorString("Couldn't find the process");
767 return ret;
768 }
769
770 DataExtractor extractor(buffer_sp,
Greg Clayton567e7f32011-09-22 04:58:26 +0000771 process->GetByteOrder(),
772 target->GetArchitecture().GetAddressByteSize());
Sean Callanan65dafa82010-08-27 01:01:44 +0000773
Greg Claytone005f2c2010-11-06 01:53:30 +0000774 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000775 {
776 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000777 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000778 0,
779 extractor.GetByteSize(),
780 func_remote_addr,
781 16,
782 DataExtractor::TypeUInt8);
783 }
784
Greg Clayton3508c382012-02-24 01:59:29 +0000785 disassembler->DecodeInstructions (Address (func_remote_addr), extractor, 0, UINT32_MAX, false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000786
Greg Clayton5c4c7462010-10-06 03:09:58 +0000787 InstructionList &instruction_list = disassembler->GetInstructionList();
Greg Clayton889fbd02011-03-26 19:14:58 +0000788 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
Sean Callanan65dafa82010-08-27 01:01:44 +0000789 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
790 instruction_index < num_instructions;
791 ++instruction_index)
792 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000793 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000794 instruction->Dump (&stream,
Greg Clayton889fbd02011-03-26 19:14:58 +0000795 max_opcode_byte_size,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000796 true,
Greg Clayton149731c2011-03-25 18:03:16 +0000797 true,
Greg Clayton0fef9682012-05-10 02:52:23 +0000798 &exe_ctx);
Sean Callanan65dafa82010-08-27 01:01:44 +0000799 stream.PutChar('\n');
Sean Callanan65dafa82010-08-27 01:01:44 +0000800 }
801
802 return ret;
803}