blob: 5dd2ce2eb51e00e5182d320693741db6925dd5eb [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 Callanan877e57b2012-09-06 01:39:02 +0000198
199 llvm::DisablePrettyStackTrace = true;
Sean Callanan65dafa82010-08-27 01:01:44 +0000200 }
201 } InitializeLLVM;
Greg Clayton395fc332011-02-15 21:59:32 +0000202
Sean Callanan65dafa82010-08-27 01:01:44 +0000203 // 1. Create a new compiler instance.
204 m_compiler.reset(new CompilerInstance());
Sean Callanan65dafa82010-08-27 01:01:44 +0000205
206 // 2. Set options.
207
Sean Callanan5b658cc2011-11-07 23:35:40 +0000208 lldb::LanguageType language = expr.Language();
Greg Claytonf51ed302011-01-15 01:32:14 +0000209
Sean Callanan5b658cc2011-11-07 23:35:40 +0000210 switch (language)
211 {
212 case lldb::eLanguageTypeC:
213 break;
214 case lldb::eLanguageTypeObjC:
215 m_compiler->getLangOpts().ObjC1 = true;
216 m_compiler->getLangOpts().ObjC2 = true;
217 break;
218 case lldb::eLanguageTypeC_plus_plus:
219 m_compiler->getLangOpts().CPlusPlus = true;
Sean Callananf0613182012-05-16 21:03:38 +0000220 m_compiler->getLangOpts().CPlusPlus0x = true;
Sean Callanan5b658cc2011-11-07 23:35:40 +0000221 break;
222 case lldb::eLanguageTypeObjC_plus_plus:
223 default:
224 m_compiler->getLangOpts().ObjC1 = true;
225 m_compiler->getLangOpts().ObjC2 = true;
226 m_compiler->getLangOpts().CPlusPlus = true;
Sean Callananf0613182012-05-16 21:03:38 +0000227 m_compiler->getLangOpts().CPlusPlus0x = true;
Sean Callanan5b658cc2011-11-07 23:35:40 +0000228 break;
229 }
Sean Callananc7674af2011-01-17 23:42:46 +0000230
Sean Callanan6e12c7a2012-03-08 02:39:03 +0000231 m_compiler->getLangOpts().DebuggerSupport = true; // Features specifically for debugger clients
232 if (expr.DesiredResultType() == ClangExpression::eResultTypeId)
233 m_compiler->getLangOpts().DebuggerCastResultToId = true;
234
Sean Callanan6c797dc2012-04-17 00:49:48 +0000235 // Spell checking is a nice feature, but it ends up completing a
236 // lot of types that we didn't strictly speaking need to complete.
237 // As a result, we spend a long time parsing and importing debug
238 // information.
239 m_compiler->getLangOpts().SpellChecking = false;
240
Greg Clayton289afcb2012-02-18 05:35:26 +0000241 lldb::ProcessSP process_sp;
Greg Clayton395fc332011-02-15 21:59:32 +0000242 if (exe_scope)
Greg Clayton289afcb2012-02-18 05:35:26 +0000243 process_sp = exe_scope->CalculateProcess();
Greg Clayton395fc332011-02-15 21:59:32 +0000244
Greg Clayton289afcb2012-02-18 05:35:26 +0000245 if (process_sp && m_compiler->getLangOpts().ObjC1)
Sean Callananc7674af2011-01-17 23:42:46 +0000246 {
Greg Clayton289afcb2012-02-18 05:35:26 +0000247 if (process_sp->GetObjCLanguageRuntime())
Sean Callananc7674af2011-01-17 23:42:46 +0000248 {
Greg Clayton289afcb2012-02-18 05:35:26 +0000249 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() == eAppleObjC_V2)
Sean Callananc7674af2011-01-17 23:42:46 +0000250 {
251 m_compiler->getLangOpts().ObjCNonFragileABI = true; // NOT i386
252 m_compiler->getLangOpts().ObjCNonFragileABI2 = true; // NOT i386
253 }
Sean Callanan6e12c7a2012-03-08 02:39:03 +0000254
255 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
256 {
257 m_compiler->getLangOpts().DebuggerObjCLiteral = true;
258 }
Sean Callananc7674af2011-01-17 23:42:46 +0000259 }
260 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000261
Sean Callanan65dafa82010-08-27 01:01:44 +0000262 m_compiler->getLangOpts().ThreadsafeStatics = false;
263 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
264 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
Sean Callanandaa6efe2011-12-21 22:22:58 +0000265
Sean Callanan65dafa82010-08-27 01:01:44 +0000266 // Set CodeGen options
267 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
268 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
269
270 // Disable some warnings.
271 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
272
273 // Set the target triple.
Greg Clayton289afcb2012-02-18 05:35:26 +0000274 lldb::TargetSP target_sp;
Greg Clayton395fc332011-02-15 21:59:32 +0000275 if (exe_scope)
Greg Clayton289afcb2012-02-18 05:35:26 +0000276 target_sp = exe_scope->CalculateTarget();
Greg Clayton395fc332011-02-15 21:59:32 +0000277
278 // TODO: figure out what to really do when we don't have a valid target.
279 // Sometimes this will be ok to just use the host target triple (when we
280 // evaluate say "2+3", but other expressions like breakpoint conditions
281 // and other things that _are_ target specific really shouldn't just be
282 // using the host triple. This needs to be fixed in a better way.
Greg Clayton289afcb2012-02-18 05:35:26 +0000283 if (target_sp && target_sp->GetArchitecture().IsValid())
Sean Callanan2a8c3382011-04-14 02:01:31 +0000284 {
Greg Clayton289afcb2012-02-18 05:35:26 +0000285 std::string triple = target_sp->GetArchitecture().GetTriple().str();
Sean Callanan2a8c3382011-04-14 02:01:31 +0000286
287 int dash_count = 0;
Johnny Chen2bc9eb32011-07-19 19:48:13 +0000288 for (size_t i = 0; i < triple.size(); ++i)
Sean Callanan2a8c3382011-04-14 02:01:31 +0000289 {
290 if (triple[i] == '-')
291 dash_count++;
292 if (dash_count == 3)
293 {
294 triple.resize(i);
295 break;
296 }
297 }
298
299 m_compiler->getTargetOpts().Triple = triple;
300 }
Greg Clayton395fc332011-02-15 21:59:32 +0000301 else
Sean Callanan2a8c3382011-04-14 02:01:31 +0000302 {
Sean Callanan7537dce2011-11-04 22:46:46 +0000303 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
Sean Callanan2a8c3382011-04-14 02:01:31 +0000304 }
Sean Callanan1d970e72012-06-08 22:20:41 +0000305
306 if (m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos)
307 m_compiler->getTargetOpts().ABI = "apcs-gnu";
Sean Callanan2a8c3382011-04-14 02:01:31 +0000308
Sean Callanan65dafa82010-08-27 01:01:44 +0000309 // 3. Set up various important bits of infrastructure.
310 m_compiler->createDiagnostics(0, 0);
311
312 // Create the target instance.
313 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
314 m_compiler->getTargetOpts()));
315
316 assert (m_compiler->hasTarget());
317
318 // Inform the target of the language options
319 //
320 // FIXME: We shouldn't need to do this, the target should be immutable once
321 // created. This complexity should be lifted elsewhere.
322 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
323
324 // 4. Set up the diagnostic buffer for reporting errors
325
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000326 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000327
328 // 5. Set up the source management objects inside the compiler
329
Greg Clayton22defe82010-12-02 23:20:03 +0000330 clang::FileSystemOptions file_system_options;
331 m_file_manager.reset(new clang::FileManager(file_system_options));
Sean Callanan8a3b0a82010-11-18 02:56:27 +0000332
Sean Callanan65dafa82010-08-27 01:01:44 +0000333 if (!m_compiler->hasSourceManager())
Greg Clayton22defe82010-12-02 23:20:03 +0000334 m_compiler->createSourceManager(*m_file_manager.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000335
336 m_compiler->createFileManager();
337 m_compiler->createPreprocessor();
338
339 // 6. Most of this we get from the CompilerInstance, but we
340 // also want to give the context an ExternalASTSource.
Sean Callananee8fc722010-11-19 20:20:02 +0000341 m_selector_table.reset(new SelectorTable());
Sean Callananc1535182011-10-07 23:18:13 +0000342 m_builtin_context.reset(new Builtin::Context());
Sean Callanan65dafa82010-08-27 01:01:44 +0000343
344 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
345 m_compiler->getSourceManager(),
Sean Callananc1535182011-10-07 23:18:13 +0000346 &m_compiler->getTarget(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000347 m_compiler->getPreprocessor().getIdentifierTable(),
Sean Callananee8fc722010-11-19 20:20:02 +0000348 *m_selector_table.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000349 *m_builtin_context.get(),
350 0));
351
352 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
353
354 if (decl_map)
355 {
Sean Callananf76afff2011-10-28 23:38:38 +0000356 llvm::OwningPtr<clang::ExternalASTSource> ast_source(decl_map->CreateProxy());
357 decl_map->InstallASTContext(ast_context.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000358 ast_context->setExternalSource(ast_source);
359 }
360
361 m_compiler->setASTContext(ast_context.release());
362
Greg Clayton8de27c72010-10-15 22:48:33 +0000363 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000364
Sean Callanan279584c2011-03-15 00:17:19 +0000365 m_llvm_context.reset(new LLVMContext());
Sean Callanan65dafa82010-08-27 01:01:44 +0000366 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
367 module_name,
368 m_compiler->getCodeGenOpts(),
Sean Callanan279584c2011-03-15 00:17:19 +0000369 *m_llvm_context));
Sean Callanan65dafa82010-08-27 01:01:44 +0000370}
371
372ClangExpressionParser::~ClangExpressionParser()
373{
374}
375
376unsigned
377ClangExpressionParser::Parse (Stream &stream)
378{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000379 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
380
381 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000382
383 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
Sean Callanan142f94c2012-03-01 02:03:47 +0000384 m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000385
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000386 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000387
388 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
389
390 if (ast_transformer)
391 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
392 else
393 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
394
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000395 diag_buf->EndSourceFile();
Sean Callananfb3058e2011-05-12 23:54:16 +0000396
Sean Callanan65dafa82010-08-27 01:01:44 +0000397 TextDiagnosticBuffer::const_iterator diag_iterator;
398
399 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000400
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000401 for (diag_iterator = diag_buf->warn_begin();
402 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000403 ++diag_iterator)
404 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
405
406 num_errors = 0;
407
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000408 for (diag_iterator = diag_buf->err_begin();
409 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000410 ++diag_iterator)
411 {
412 num_errors++;
413 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
414 }
415
Sean Callanan7617c292010-11-01 20:28:09 +0000416 for (diag_iterator = diag_buf->note_begin();
417 diag_iterator != diag_buf->note_end();
418 ++diag_iterator)
419 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
420
Sean Callananfb3058e2011-05-12 23:54:16 +0000421 if (!num_errors)
422 {
423 if (m_expr.DeclMap() && !m_expr.DeclMap()->ResolveUnknownTypes())
424 {
425 stream.Printf("error: Couldn't infer the type of a variable\n");
426 num_errors++;
427 }
428 }
429
Sean Callanan65dafa82010-08-27 01:01:44 +0000430 return num_errors;
431}
432
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000433static bool FindFunctionInModule (std::string &mangled_name,
434 llvm::Module *module,
435 const char *orig_name)
436{
437 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
438 fi != fe;
439 ++fi)
440 {
441 if (fi->getName().str().find(orig_name) != std::string::npos)
442 {
443 mangled_name = fi->getName().str();
444 return true;
445 }
446 }
447
448 return false;
449}
450
Sean Callanan65dafa82010-08-27 01:01:44 +0000451Error
Sean Callanan47dc4572011-09-15 02:13:07 +0000452ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_allocation_addr,
453 lldb::addr_t &func_addr,
454 lldb::addr_t &func_end,
455 ExecutionContext &exe_ctx,
456 IRForTarget::StaticDataAllocator *data_allocator,
457 bool &evaluated_statically,
458 lldb::ClangExpressionVariableSP &const_result,
459 ExecutionPolicy execution_policy)
Sean Callanan65dafa82010-08-27 01:01:44 +0000460{
Greg Claytond0882d02011-01-19 23:00:49 +0000461 func_allocation_addr = LLDB_INVALID_ADDRESS;
462 func_addr = LLDB_INVALID_ADDRESS;
463 func_end = LLDB_INVALID_ADDRESS;
Greg Claytone005f2c2010-11-06 01:53:30 +0000464 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000465
Sean Callananddf110d2012-01-24 22:06:48 +0000466 std::auto_ptr<llvm::ExecutionEngine> execution_engine;
467
Sean Callanan65dafa82010-08-27 01:01:44 +0000468 Error err;
469
470 llvm::Module *module = m_code_generator->ReleaseModule();
471
472 if (!module)
473 {
474 err.SetErrorToGenericError();
475 err.SetErrorString("IR doesn't contain a module");
476 return err;
477 }
478
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000479 // Find the actual name of the function (it's often mangled somehow)
480
481 std::string function_name;
482
483 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
484 {
485 err.SetErrorToGenericError();
486 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
487 return err;
488 }
489 else
490 {
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000491 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000492 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
493 }
494
Sean Callanan65dafa82010-08-27 01:01:44 +0000495 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
496
497 if (decl_map)
498 {
Sean Callanan97c924e2011-01-27 01:07:04 +0000499 Stream *error_stream = NULL;
Greg Clayton567e7f32011-09-22 04:58:26 +0000500 Target *target = exe_ctx.GetTargetPtr();
501 if (target)
502 error_stream = &target->GetDebugger().GetErrorStream();
Sean Callanan97c924e2011-01-27 01:07:04 +0000503
Sean Callanan47dc4572011-09-15 02:13:07 +0000504 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000505 m_expr.NeedsVariableResolution(),
Sean Callanan47dc4572011-09-15 02:13:07 +0000506 execution_policy,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000507 const_result,
Sean Callananc0492742011-05-23 21:40:23 +0000508 data_allocator,
Sean Callanan97c924e2011-01-27 01:07:04 +0000509 error_stream,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000510 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000511
Sean Callanan8f2e3922012-02-04 08:49:35 +0000512 ir_for_target.runOnModule(*module);
Sean Callananf18d91c2010-09-01 00:58:00 +0000513
Sean Callananddf110d2012-01-24 22:06:48 +0000514 Error &interpreter_error(ir_for_target.getInterpreterError());
515
516 if (execution_policy != eExecutionPolicyAlways && interpreter_error.Success())
Sean Callanan696cf5f2011-05-07 01:06:41 +0000517 {
Johnny Chenc6134962012-01-06 00:35:38 +0000518 if (const_result)
519 const_result->TransferAddress();
Sean Callanan47dc4572011-09-15 02:13:07 +0000520 evaluated_statically = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000521 err.Clear();
522 return err;
523 }
524
Greg Clayton567e7f32011-09-22 04:58:26 +0000525 Process *process = exe_ctx.GetProcessPtr();
526
527 if (!process || execution_policy == eExecutionPolicyNever)
Sean Callanan47dc4572011-09-15 02:13:07 +0000528 {
529 err.SetErrorToGenericError();
Sean Callananddf110d2012-01-24 22:06:48 +0000530 if (execution_policy == eExecutionPolicyAlways)
531 err.SetErrorString("Execution needed to run in the target, but the target can't be run");
532 else
533 err.SetErrorStringWithFormat("Interpreting the expression locally failed: %s", interpreter_error.AsCString());
Sean Callanan8f2e3922012-02-04 08:49:35 +0000534
Sean Callanan47dc4572011-09-15 02:13:07 +0000535 return err;
536 }
537
Sean Callanan6cf6c472011-09-20 23:01:51 +0000538 if (execution_policy != eExecutionPolicyNever &&
539 m_expr.NeedsValidation() &&
Greg Clayton567e7f32011-09-22 04:58:26 +0000540 process)
Sean Callananf18d91c2010-09-01 00:58:00 +0000541 {
Greg Clayton567e7f32011-09-22 04:58:26 +0000542 if (!process->GetDynamicCheckers())
Sean Callanan6cf6c472011-09-20 23:01:51 +0000543 {
544 DynamicCheckerFunctions *dynamic_checkers = new DynamicCheckerFunctions();
545
546 StreamString install_errors;
547
548 if (!dynamic_checkers->Install(install_errors, exe_ctx))
549 {
550 if (install_errors.GetString().empty())
551 err.SetErrorString ("couldn't install checkers, unknown error");
552 else
553 err.SetErrorString (install_errors.GetString().c_str());
554
555 return err;
556 }
557
Greg Clayton567e7f32011-09-22 04:58:26 +0000558 process->SetDynamicCheckers(dynamic_checkers);
Sean Callanan6cf6c472011-09-20 23:01:51 +0000559
560 if (log)
561 log->Printf("== [ClangUserExpression::Evaluate] Finished installing dynamic checkers ==");
562 }
563
Greg Clayton567e7f32011-09-22 04:58:26 +0000564 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000565
566 if (!ir_dynamic_checks.runOnModule(*module))
567 {
568 err.SetErrorToGenericError();
569 err.SetErrorString("Couldn't add dynamic checks to the expression");
570 return err;
571 }
572 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000573 }
574
Greg Claytond0882d02011-01-19 23:00:49 +0000575 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
576 // below so we don't need to free it.
577 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000578
579 std::string error_string;
Sean Callanan7b8eb762011-11-01 17:33:54 +0000580
581 if (log)
582 {
583 std::string s;
584 raw_string_ostream oss(s);
585
586 module->print(oss, NULL);
587
588 oss.flush();
589
590 log->Printf ("Module being sent to JIT: \n%s", s.c_str());
591 }
592
Greg Clayton2f085c62011-05-15 01:25:55 +0000593 EngineBuilder builder(module);
594 builder.setEngineKind(EngineKind::JIT)
595 .setErrorStr(&error_string)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000596 .setRelocationModel(llvm::Reloc::PIC_)
Greg Clayton2f085c62011-05-15 01:25:55 +0000597 .setJITMemoryManager(jit_memory_manager)
598 .setOptLevel(CodeGenOpt::Less)
599 .setAllocateGVsWithCode(true)
600 .setCodeModel(CodeModel::Small)
Sean Callanan16b53ab2011-10-12 00:12:34 +0000601 .setUseMCJIT(true);
Sean Callananddf110d2012-01-24 22:06:48 +0000602 execution_engine.reset(builder.create());
Sean Callanan9ac3a962010-11-02 23:20:00 +0000603
Sean Callananddf110d2012-01-24 22:06:48 +0000604 if (!execution_engine.get())
Sean Callanan65dafa82010-08-27 01:01:44 +0000605 {
606 err.SetErrorToGenericError();
607 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
608 return err;
609 }
610
Sean Callananddf110d2012-01-24 22:06:48 +0000611 execution_engine->DisableLazyCompilation();
Sean Callanan65dafa82010-08-27 01:01:44 +0000612
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000613 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000614
615 // We don't actually need the function pointer here, this just forces it to get resolved.
616
Sean Callananddf110d2012-01-24 22:06:48 +0000617 void *fun_ptr = execution_engine->getPointerToFunction(function);
618
Sean Callanan65dafa82010-08-27 01:01:44 +0000619 // Errors usually cause failures in the JIT, but if we're lucky we get here.
620
Sean Callanan7b8eb762011-11-01 17:33:54 +0000621 if (!function)
622 {
623 err.SetErrorToGenericError();
624 err.SetErrorStringWithFormat("Couldn't find '%s' in the JITted module", function_name.c_str());
625 return err;
626 }
627
Sean Callanan65dafa82010-08-27 01:01:44 +0000628 if (!fun_ptr)
629 {
630 err.SetErrorToGenericError();
Sean Callanan7b8eb762011-11-01 17:33:54 +0000631 err.SetErrorStringWithFormat("'%s' was in the JITted module but wasn't lowered", function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000632 return err;
633 }
634
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000635 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000636
Greg Clayton567e7f32011-09-22 04:58:26 +0000637
638 Process *process = exe_ctx.GetProcessPtr();
639 if (process == NULL)
Sean Callanan65dafa82010-08-27 01:01:44 +0000640 {
641 err.SetErrorToGenericError();
642 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
643 return err;
644 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000645
Sean Callanan8f2e3922012-02-04 08:49:35 +0000646 jit_memory_manager->CommitAllocations(*process);
Sean Callanan142f94c2012-03-01 02:03:47 +0000647 jit_memory_manager->ReportAllocations(*execution_engine);
Sean Callanan8f2e3922012-02-04 08:49:35 +0000648 jit_memory_manager->WriteData(*process);
Sean Callanan65dafa82010-08-27 01:01:44 +0000649
650 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
651
652 for (pos = m_jitted_functions.begin(); pos != end; pos++)
653 {
Greg Claytond0882d02011-01-19 23:00:49 +0000654 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000655
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000656 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000657 {
Sean Callanan8f2e3922012-02-04 08:49:35 +0000658 RecordingMemoryManager::AddrRange func_range = jit_memory_manager->GetRemoteRangeForLocal((*pos).m_local_addr);
659 func_end = func_range.first + func_range.second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000660 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000661 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000662 }
663
Sean Callanan6dff8272010-11-08 03:49:50 +0000664 if (log)
665 {
666 log->Printf("Code can be run in the target.");
667
668 StreamString disassembly_stream;
669
Greg Claytond0882d02011-01-19 23:00:49 +0000670 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000671
672 if (!err.Success())
673 {
674 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
675 }
676 else
677 {
678 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
679 }
680 }
681
Sean Callananddf110d2012-01-24 22:06:48 +0000682 execution_engine.reset();
683
Sean Callanan65dafa82010-08-27 01:01:44 +0000684 err.Clear();
685 return err;
686}
687
688Error
Greg Claytond0882d02011-01-19 23:00:49 +0000689ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000690{
Greg Claytone005f2c2010-11-06 01:53:30 +0000691 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000692
693 const char *name = m_expr.FunctionName();
694
695 Error ret;
696
697 ret.Clear();
698
699 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
700 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
701
702 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
703
704 for (pos = m_jitted_functions.begin(); pos < end; pos++)
705 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000706 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000707 {
708 func_local_addr = pos->m_local_addr;
709 func_remote_addr = pos->m_remote_addr;
710 }
711 }
712
713 if (func_local_addr == LLDB_INVALID_ADDRESS)
714 {
715 ret.SetErrorToGenericError();
716 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
717 return ret;
718 }
719
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000720 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000721 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
722
723 std::pair <lldb::addr_t, lldb::addr_t> func_range;
724
Greg Claytond0882d02011-01-19 23:00:49 +0000725 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000726
727 if (func_range.first == 0 && func_range.second == 0)
728 {
729 ret.SetErrorToGenericError();
730 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
731 return ret;
732 }
733
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000734 if (log)
Sean Callanan8f2e3922012-02-04 08:49:35 +0000735 log->Printf("Function's code range is [0x%llx+0x%llx]", func_range.first, func_range.second);
Sean Callanan65dafa82010-08-27 01:01:44 +0000736
Greg Clayton567e7f32011-09-22 04:58:26 +0000737 Target *target = exe_ctx.GetTargetPtr();
738 if (!target)
Sean Callanan65dafa82010-08-27 01:01:44 +0000739 {
740 ret.SetErrorToGenericError();
741 ret.SetErrorString("Couldn't find the target");
742 }
743
Sean Callanan8f2e3922012-02-04 08:49:35 +0000744 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0));
Sean Callanan65dafa82010-08-27 01:01:44 +0000745
Greg Clayton567e7f32011-09-22 04:58:26 +0000746 Process *process = exe_ctx.GetProcessPtr();
Sean Callanan65dafa82010-08-27 01:01:44 +0000747 Error err;
Greg Clayton567e7f32011-09-22 04:58:26 +0000748 process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
Sean Callanan65dafa82010-08-27 01:01:44 +0000749
750 if (!err.Success())
751 {
752 ret.SetErrorToGenericError();
753 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
754 return ret;
755 }
756
Greg Clayton567e7f32011-09-22 04:58:26 +0000757 ArchSpec arch(target->GetArchitecture());
Sean Callanan65dafa82010-08-27 01:01:44 +0000758
Sean Callanan4f28c312012-08-01 18:50:59 +0000759 lldb::DisassemblerSP disassembler = Disassembler::FindPlugin(arch, NULL);
Sean Callanan65dafa82010-08-27 01:01:44 +0000760
Sean Callananb386d822012-08-09 00:50:26 +0000761 if (!disassembler)
Sean Callanan65dafa82010-08-27 01:01:44 +0000762 {
763 ret.SetErrorToGenericError();
Greg Clayton940b1032011-02-23 00:35:02 +0000764 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
Sean Callanan65dafa82010-08-27 01:01:44 +0000765 return ret;
766 }
767
Greg Clayton567e7f32011-09-22 04:58:26 +0000768 if (!process)
Sean Callanan65dafa82010-08-27 01:01:44 +0000769 {
770 ret.SetErrorToGenericError();
771 ret.SetErrorString("Couldn't find the process");
772 return ret;
773 }
774
775 DataExtractor extractor(buffer_sp,
Greg Clayton567e7f32011-09-22 04:58:26 +0000776 process->GetByteOrder(),
777 target->GetArchitecture().GetAddressByteSize());
Sean Callanan65dafa82010-08-27 01:01:44 +0000778
Greg Claytone005f2c2010-11-06 01:53:30 +0000779 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000780 {
781 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000782 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000783 0,
784 extractor.GetByteSize(),
785 func_remote_addr,
786 16,
787 DataExtractor::TypeUInt8);
788 }
789
Greg Clayton3508c382012-02-24 01:59:29 +0000790 disassembler->DecodeInstructions (Address (func_remote_addr), extractor, 0, UINT32_MAX, false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000791
Greg Clayton5c4c7462010-10-06 03:09:58 +0000792 InstructionList &instruction_list = disassembler->GetInstructionList();
Greg Clayton889fbd02011-03-26 19:14:58 +0000793 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
Sean Callanan65dafa82010-08-27 01:01:44 +0000794 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
795 instruction_index < num_instructions;
796 ++instruction_index)
797 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000798 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000799 instruction->Dump (&stream,
Greg Clayton889fbd02011-03-26 19:14:58 +0000800 max_opcode_byte_size,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000801 true,
Greg Clayton149731c2011-03-25 18:03:16 +0000802 true,
Greg Clayton0fef9682012-05-10 02:52:23 +0000803 &exe_ctx);
Sean Callanan65dafa82010-08-27 01:01:44 +0000804 stream.PutChar('\n');
Sean Callanan65dafa82010-08-27 01:01:44 +0000805 }
806
807 return ret;
808}