blob: 0da5f6d5b8aa9161adc476828530c1df0dd1e9f2 [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 Callanan06dc17f2012-09-24 22:25:51 +000046#include "clang/Rewrite/Frontend/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 Callanan06dc17f2012-09-24 22:25:51 +000052#include "llvm/Support/Debug.h"
Sean Callananc1535182011-10-07 23:18:13 +000053#include "llvm/Support/TargetSelect.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
72using namespace clang;
73using namespace llvm;
74using namespace lldb_private;
75
76//===----------------------------------------------------------------------===//
77// Utility Methods for Clang
78//===----------------------------------------------------------------------===//
79
80std::string GetBuiltinIncludePath(const char *Argv0) {
81 llvm::sys::Path P =
82 llvm::sys::Path::GetMainExecutable(Argv0,
83 (void*)(intptr_t) GetBuiltinIncludePath);
84
85 if (!P.isEmpty()) {
86 P.eraseComponent(); // Remove /clang from foo/bin/clang
87 P.eraseComponent(); // Remove /bin from foo/bin
88
89 // Get foo/lib/clang/<version>/include
90 P.appendComponent("lib");
91 P.appendComponent("clang");
92 P.appendComponent(CLANG_VERSION_STRING);
93 P.appendComponent("include");
94 }
95
96 return P.str();
97}
98
99
100//===----------------------------------------------------------------------===//
101// Main driver for Clang
102//===----------------------------------------------------------------------===//
103
104static void LLVMErrorHandler(void *UserData, const std::string &Message) {
Sean Callananc1535182011-10-07 23:18:13 +0000105 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
Sean Callanan65dafa82010-08-27 01:01:44 +0000106
107 Diags.Report(diag::err_fe_error_backend) << Message;
108
109 // We cannot recover from llvm errors.
Sean Callananc1535182011-10-07 23:18:13 +0000110 assert(0);
Sean Callanan65dafa82010-08-27 01:01:44 +0000111}
112
113static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
114 using namespace clang::frontend;
115
116 switch (CI.getFrontendOpts().ProgramAction) {
117 default:
118 llvm_unreachable("Invalid program action!");
119
120 case ASTDump: return new ASTDumpAction();
121 case ASTPrint: return new ASTPrintAction();
Sean Callanan279584c2011-03-15 00:17:19 +0000122 case ASTDumpXML: return new ASTDumpXMLAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000123 case ASTView: return new ASTViewAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000124 case DumpRawTokens: return new DumpRawTokensAction();
125 case DumpTokens: return new DumpTokensAction();
126 case EmitAssembly: return new EmitAssemblyAction();
127 case EmitBC: return new EmitBCAction();
128 case EmitHTML: return new HTMLPrintAction();
129 case EmitLLVM: return new EmitLLVMAction();
130 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
131 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
132 case EmitObj: return new EmitObjAction();
133 case FixIt: return new FixItAction();
Sean Callanan05230832011-12-01 04:31:46 +0000134 case GeneratePCH: return new GeneratePCHAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000135 case GeneratePTH: return new GeneratePTHAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000136 case InitOnly: return new InitOnlyAction();
137 case ParseSyntaxOnly: return new SyntaxOnlyAction();
138
139 case PluginAction: {
140 for (FrontendPluginRegistry::iterator it =
141 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
142 it != ie; ++it) {
143 if (it->getName() == CI.getFrontendOpts().ActionName) {
144 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
145 if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
146 return 0;
147 return P.take();
148 }
149 }
150
151 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
152 << CI.getFrontendOpts().ActionName;
153 return 0;
154 }
155
156 case PrintDeclContext: return new DeclContextPrintAction();
157 case PrintPreamble: return new PrintPreambleAction();
158 case PrintPreprocessedInput: return new PrintPreprocessedAction();
159 case RewriteMacros: return new RewriteMacrosAction();
160 case RewriteObjC: return new RewriteObjCAction();
161 case RewriteTest: return new RewriteTestAction();
Sean Callananad293092011-01-18 23:32:05 +0000162 //case RunAnalysis: return new AnalysisAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000163 case RunPreprocessorOnly: return new PreprocessOnlyAction();
164 }
165}
166
167static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
168 // Create the underlying action.
169 FrontendAction *Act = CreateFrontendBaseAction(CI);
170 if (!Act)
171 return 0;
172
173 // If there are any AST files to merge, create a frontend action
174 // adaptor to perform the merge.
175 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
Sean Callanan8f2e3922012-02-04 08:49:35 +0000176 Act = new ASTMergeAction(Act, CI.getFrontendOpts().ASTMergeFiles);
Sean Callanan65dafa82010-08-27 01:01:44 +0000177
178 return Act;
179}
180
181//===----------------------------------------------------------------------===//
182// Implementation of ClangExpressionParser
183//===----------------------------------------------------------------------===//
184
Greg Clayton395fc332011-02-15 21:59:32 +0000185ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
186 ClangExpression &expr) :
187 m_expr (expr),
Sean Callanan65dafa82010-08-27 01:01:44 +0000188 m_compiler (),
189 m_code_generator (NULL),
Sean Callanan65dafa82010-08-27 01:01:44 +0000190 m_jitted_functions ()
191{
192 // Initialize targets first, so that --version shows registered targets.
193 static struct InitializeLLVM {
194 InitializeLLVM() {
195 llvm::InitializeAllTargets();
196 llvm::InitializeAllAsmPrinters();
Sean Callanan9b6898f2011-07-30 02:42:06 +0000197 llvm::InitializeAllTargetMCs();
Sean Callanan05230832011-12-01 04:31:46 +0000198 llvm::InitializeAllDisassemblers();
Sean Callanan877e57b2012-09-06 01:39:02 +0000199
200 llvm::DisablePrettyStackTrace = true;
Sean Callanan65dafa82010-08-27 01:01:44 +0000201 }
202 } InitializeLLVM;
Sean Callanan06dc17f2012-09-24 22:25:51 +0000203
Sean Callanan65dafa82010-08-27 01:01:44 +0000204 // 1. Create a new compiler instance.
205 m_compiler.reset(new CompilerInstance());
Sean Callanan65dafa82010-08-27 01:01:44 +0000206
Sean Callanan06dc17f2012-09-24 22:25:51 +0000207 // 2. Install the target.
208
209 lldb::TargetSP target_sp;
210 if (exe_scope)
211 target_sp = exe_scope->CalculateTarget();
212
213 // TODO: figure out what to really do when we don't have a valid target.
214 // Sometimes this will be ok to just use the host target triple (when we
215 // evaluate say "2+3", but other expressions like breakpoint conditions
216 // and other things that _are_ target specific really shouldn't just be
217 // using the host triple. This needs to be fixed in a better way.
218 if (target_sp && target_sp->GetArchitecture().IsValid())
219 {
220 std::string triple = target_sp->GetArchitecture().GetTriple().str();
221
222 int dash_count = 0;
223 for (size_t i = 0; i < triple.size(); ++i)
224 {
225 if (triple[i] == '-')
226 dash_count++;
227 if (dash_count == 3)
228 {
229 triple.resize(i);
230 break;
231 }
232 }
233
234 m_compiler->getTargetOpts().Triple = triple;
235 }
236 else
237 {
238 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
239 }
240
241 if (m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos)
242 m_compiler->getTargetOpts().ABI = "apcs-gnu";
243
244 m_compiler->createDiagnostics(0, 0);
245
246 // Create the target instance.
247 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
248 m_compiler->getTargetOpts()));
249
250 assert (m_compiler->hasTarget());
251
252 // 3. Set options.
Sean Callanan65dafa82010-08-27 01:01:44 +0000253
Sean Callanan5b658cc2011-11-07 23:35:40 +0000254 lldb::LanguageType language = expr.Language();
Greg Claytonf51ed302011-01-15 01:32:14 +0000255
Sean Callanan5b658cc2011-11-07 23:35:40 +0000256 switch (language)
257 {
258 case lldb::eLanguageTypeC:
259 break;
260 case lldb::eLanguageTypeObjC:
261 m_compiler->getLangOpts().ObjC1 = true;
262 m_compiler->getLangOpts().ObjC2 = true;
263 break;
264 case lldb::eLanguageTypeC_plus_plus:
265 m_compiler->getLangOpts().CPlusPlus = true;
Sean Callananf0613182012-05-16 21:03:38 +0000266 m_compiler->getLangOpts().CPlusPlus0x = true;
Sean Callanan5b658cc2011-11-07 23:35:40 +0000267 break;
268 case lldb::eLanguageTypeObjC_plus_plus:
269 default:
270 m_compiler->getLangOpts().ObjC1 = true;
271 m_compiler->getLangOpts().ObjC2 = true;
272 m_compiler->getLangOpts().CPlusPlus = true;
Sean Callananf0613182012-05-16 21:03:38 +0000273 m_compiler->getLangOpts().CPlusPlus0x = true;
Sean Callanan5b658cc2011-11-07 23:35:40 +0000274 break;
275 }
Sean Callananc7674af2011-01-17 23:42:46 +0000276
Sean Callanan683a97c2012-10-17 22:09:59 +0000277 m_compiler->getLangOpts().Bool = true;
278 m_compiler->getLangOpts().WChar = true;
Sean Callanan6e12c7a2012-03-08 02:39:03 +0000279 m_compiler->getLangOpts().DebuggerSupport = true; // Features specifically for debugger clients
280 if (expr.DesiredResultType() == ClangExpression::eResultTypeId)
281 m_compiler->getLangOpts().DebuggerCastResultToId = true;
282
Sean Callanan6c797dc2012-04-17 00:49:48 +0000283 // Spell checking is a nice feature, but it ends up completing a
284 // lot of types that we didn't strictly speaking need to complete.
285 // As a result, we spend a long time parsing and importing debug
286 // information.
287 m_compiler->getLangOpts().SpellChecking = false;
288
Greg Clayton289afcb2012-02-18 05:35:26 +0000289 lldb::ProcessSP process_sp;
Greg Clayton395fc332011-02-15 21:59:32 +0000290 if (exe_scope)
Greg Clayton289afcb2012-02-18 05:35:26 +0000291 process_sp = exe_scope->CalculateProcess();
Greg Clayton395fc332011-02-15 21:59:32 +0000292
Greg Clayton289afcb2012-02-18 05:35:26 +0000293 if (process_sp && m_compiler->getLangOpts().ObjC1)
Sean Callananc7674af2011-01-17 23:42:46 +0000294 {
Greg Clayton289afcb2012-02-18 05:35:26 +0000295 if (process_sp->GetObjCLanguageRuntime())
Sean Callananc7674af2011-01-17 23:42:46 +0000296 {
Greg Clayton289afcb2012-02-18 05:35:26 +0000297 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() == eAppleObjC_V2)
Sean Callanan06dc17f2012-09-24 22:25:51 +0000298 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
299 else
300 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX, VersionTuple(10, 7));
Sean Callanan6e12c7a2012-03-08 02:39:03 +0000301
302 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
Sean Callanan6e12c7a2012-03-08 02:39:03 +0000303 m_compiler->getLangOpts().DebuggerObjCLiteral = true;
Sean Callananc7674af2011-01-17 23:42:46 +0000304 }
305 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000306
Sean Callanan65dafa82010-08-27 01:01:44 +0000307 m_compiler->getLangOpts().ThreadsafeStatics = false;
308 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
309 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
Sean Callanandaa6efe2011-12-21 22:22:58 +0000310
Sean Callanan65dafa82010-08-27 01:01:44 +0000311 // Set CodeGen options
312 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
313 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
314
315 // Disable some warnings.
316 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
317
Sean Callanan65dafa82010-08-27 01:01:44 +0000318 // 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
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000466 std::auto_ptr<llvm::ExecutionEngine> execution_engine_ap;
Sean Callananddf110d2012-01-24 22:06:48 +0000467
Sean Callanan65dafa82010-08-27 01:01:44 +0000468 Error err;
469
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000470 std::auto_ptr<llvm::Module> module_ap (m_code_generator->ReleaseModule());
Sean Callanan65dafa82010-08-27 01:01:44 +0000471
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000472 if (!module_ap.get())
Sean Callanan65dafa82010-08-27 01:01:44 +0000473 {
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
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000483 if (!FindFunctionInModule(function_name, module_ap.get(), m_expr.FunctionName()))
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000484 {
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
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000512 bool ir_can_run = ir_for_target.runOnModule(*module_ap);
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 }
Sean Callanan06dc17f2012-09-24 22:25:51 +0000537 else if (!ir_can_run)
538 {
539 err.SetErrorToGenericError();
540 err.SetErrorString("The expression could not be prepared to run in the target");
541
542 return err;
543 }
Sean Callanan47dc4572011-09-15 02:13:07 +0000544
Sean Callanan6cf6c472011-09-20 23:01:51 +0000545 if (execution_policy != eExecutionPolicyNever &&
546 m_expr.NeedsValidation() &&
Greg Clayton567e7f32011-09-22 04:58:26 +0000547 process)
Sean Callananf18d91c2010-09-01 00:58:00 +0000548 {
Greg Clayton567e7f32011-09-22 04:58:26 +0000549 if (!process->GetDynamicCheckers())
Sean Callanan6cf6c472011-09-20 23:01:51 +0000550 {
551 DynamicCheckerFunctions *dynamic_checkers = new DynamicCheckerFunctions();
552
553 StreamString install_errors;
554
555 if (!dynamic_checkers->Install(install_errors, exe_ctx))
556 {
557 if (install_errors.GetString().empty())
558 err.SetErrorString ("couldn't install checkers, unknown error");
559 else
560 err.SetErrorString (install_errors.GetString().c_str());
561
562 return err;
563 }
564
Greg Clayton567e7f32011-09-22 04:58:26 +0000565 process->SetDynamicCheckers(dynamic_checkers);
Sean Callanan6cf6c472011-09-20 23:01:51 +0000566
567 if (log)
568 log->Printf("== [ClangUserExpression::Evaluate] Finished installing dynamic checkers ==");
569 }
570
Greg Clayton567e7f32011-09-22 04:58:26 +0000571 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000572
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000573 if (!ir_dynamic_checks.runOnModule(*module_ap))
Sean Callanane8a59a82010-09-13 21:34:21 +0000574 {
575 err.SetErrorToGenericError();
576 err.SetErrorString("Couldn't add dynamic checks to the expression");
577 return err;
578 }
579 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000580 }
581
Greg Claytond0882d02011-01-19 23:00:49 +0000582 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
583 // below so we don't need to free it.
584 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000585
586 std::string error_string;
Sean Callanan7b8eb762011-11-01 17:33:54 +0000587
588 if (log)
589 {
590 std::string s;
591 raw_string_ostream oss(s);
592
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000593 module_ap->print(oss, NULL);
Sean Callanan7b8eb762011-11-01 17:33:54 +0000594
595 oss.flush();
596
597 log->Printf ("Module being sent to JIT: \n%s", s.c_str());
598 }
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000599 llvm::Triple triple(module_ap->getTargetTriple());
600 llvm::Function *function = module_ap->getFunction (function_name.c_str());
601 EngineBuilder builder(module_ap.release());
Greg Clayton2f085c62011-05-15 01:25:55 +0000602 builder.setEngineKind(EngineKind::JIT)
603 .setErrorStr(&error_string)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000604 .setRelocationModel(llvm::Reloc::PIC_)
Greg Clayton2f085c62011-05-15 01:25:55 +0000605 .setJITMemoryManager(jit_memory_manager)
606 .setOptLevel(CodeGenOpt::Less)
607 .setAllocateGVsWithCode(true)
608 .setCodeModel(CodeModel::Small)
Sean Callanan16b53ab2011-10-12 00:12:34 +0000609 .setUseMCJIT(true);
Sean Callanan06dc17f2012-09-24 22:25:51 +0000610
Sean Callanan06dc17f2012-09-24 22:25:51 +0000611 StringRef mArch;
612 StringRef mCPU;
613 SmallVector<std::string, 0> mAttrs;
614
615 TargetMachine *target_machine = builder.selectTarget(triple,
616 mArch,
617 mCPU,
618 mAttrs);
619
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000620 execution_engine_ap.reset(builder.create(target_machine));
Sean Callanan9ac3a962010-11-02 23:20:00 +0000621
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000622 if (!execution_engine_ap.get())
Sean Callanan65dafa82010-08-27 01:01:44 +0000623 {
624 err.SetErrorToGenericError();
625 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
626 return err;
627 }
628
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000629 execution_engine_ap->DisableLazyCompilation();
Sean Callanan65dafa82010-08-27 01:01:44 +0000630
Sean Callanan65dafa82010-08-27 01:01:44 +0000631
632 // We don't actually need the function pointer here, this just forces it to get resolved.
633
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000634 void *fun_ptr = execution_engine_ap->getPointerToFunction(function);
Sean Callananddf110d2012-01-24 22:06:48 +0000635
Sean Callanan65dafa82010-08-27 01:01:44 +0000636 // Errors usually cause failures in the JIT, but if we're lucky we get here.
637
Sean Callanan7b8eb762011-11-01 17:33:54 +0000638 if (!function)
639 {
640 err.SetErrorToGenericError();
641 err.SetErrorStringWithFormat("Couldn't find '%s' in the JITted module", function_name.c_str());
642 return err;
643 }
644
Sean Callanan65dafa82010-08-27 01:01:44 +0000645 if (!fun_ptr)
646 {
647 err.SetErrorToGenericError();
Sean Callanan7b8eb762011-11-01 17:33:54 +0000648 err.SetErrorStringWithFormat("'%s' was in the JITted module but wasn't lowered", function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000649 return err;
650 }
651
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000652 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000653
Greg Clayton567e7f32011-09-22 04:58:26 +0000654
655 Process *process = exe_ctx.GetProcessPtr();
656 if (process == NULL)
Sean Callanan65dafa82010-08-27 01:01:44 +0000657 {
658 err.SetErrorToGenericError();
659 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
660 return err;
661 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000662
Sean Callanan8f2e3922012-02-04 08:49:35 +0000663 jit_memory_manager->CommitAllocations(*process);
Greg Claytonc5fbd9a2012-10-24 17:37:53 +0000664 jit_memory_manager->ReportAllocations(*execution_engine_ap);
Sean Callanan8f2e3922012-02-04 08:49:35 +0000665 jit_memory_manager->WriteData(*process);
Sean Callanan65dafa82010-08-27 01:01:44 +0000666
667 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
668
669 for (pos = m_jitted_functions.begin(); pos != end; pos++)
670 {
Greg Claytond0882d02011-01-19 23:00:49 +0000671 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000672
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000673 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000674 {
Sean Callanan8f2e3922012-02-04 08:49:35 +0000675 RecordingMemoryManager::AddrRange func_range = jit_memory_manager->GetRemoteRangeForLocal((*pos).m_local_addr);
676 func_end = func_range.first + func_range.second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000677 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000678 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000679 }
680
Sean Callanan6dff8272010-11-08 03:49:50 +0000681 if (log)
682 {
683 log->Printf("Code can be run in the target.");
684
685 StreamString disassembly_stream;
686
Greg Claytond0882d02011-01-19 23:00:49 +0000687 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000688
689 if (!err.Success())
690 {
691 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
692 }
693 else
694 {
695 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
696 }
697 }
698
Sean Callanan65dafa82010-08-27 01:01:44 +0000699 err.Clear();
700 return err;
701}
702
703Error
Greg Claytond0882d02011-01-19 23:00:49 +0000704ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000705{
Greg Claytone005f2c2010-11-06 01:53:30 +0000706 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000707
708 const char *name = m_expr.FunctionName();
709
710 Error ret;
711
712 ret.Clear();
713
714 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
715 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
716
717 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
718
719 for (pos = m_jitted_functions.begin(); pos < end; pos++)
720 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000721 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000722 {
723 func_local_addr = pos->m_local_addr;
724 func_remote_addr = pos->m_remote_addr;
725 }
726 }
727
728 if (func_local_addr == LLDB_INVALID_ADDRESS)
729 {
730 ret.SetErrorToGenericError();
731 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
732 return ret;
733 }
734
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000735 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000736 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
737
738 std::pair <lldb::addr_t, lldb::addr_t> func_range;
739
Greg Claytond0882d02011-01-19 23:00:49 +0000740 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000741
742 if (func_range.first == 0 && func_range.second == 0)
743 {
744 ret.SetErrorToGenericError();
745 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
746 return ret;
747 }
748
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000749 if (log)
Sean Callanan8f2e3922012-02-04 08:49:35 +0000750 log->Printf("Function's code range is [0x%llx+0x%llx]", func_range.first, func_range.second);
Sean Callanan65dafa82010-08-27 01:01:44 +0000751
Greg Clayton567e7f32011-09-22 04:58:26 +0000752 Target *target = exe_ctx.GetTargetPtr();
753 if (!target)
Sean Callanan65dafa82010-08-27 01:01:44 +0000754 {
755 ret.SetErrorToGenericError();
756 ret.SetErrorString("Couldn't find the target");
Jim Ingham6f01c932012-10-12 17:34:26 +0000757 return ret;
Sean Callanan65dafa82010-08-27 01:01:44 +0000758 }
759
Sean Callanan8f2e3922012-02-04 08:49:35 +0000760 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second, 0));
Sean Callanan65dafa82010-08-27 01:01:44 +0000761
Greg Clayton567e7f32011-09-22 04:58:26 +0000762 Process *process = exe_ctx.GetProcessPtr();
Sean Callanan65dafa82010-08-27 01:01:44 +0000763 Error err;
Greg Clayton567e7f32011-09-22 04:58:26 +0000764 process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
Sean Callanan65dafa82010-08-27 01:01:44 +0000765
766 if (!err.Success())
767 {
768 ret.SetErrorToGenericError();
769 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
770 return ret;
771 }
772
Greg Clayton567e7f32011-09-22 04:58:26 +0000773 ArchSpec arch(target->GetArchitecture());
Sean Callanan65dafa82010-08-27 01:01:44 +0000774
Sean Callanan4f28c312012-08-01 18:50:59 +0000775 lldb::DisassemblerSP disassembler = Disassembler::FindPlugin(arch, NULL);
Sean Callanan65dafa82010-08-27 01:01:44 +0000776
Sean Callananb386d822012-08-09 00:50:26 +0000777 if (!disassembler)
Sean Callanan65dafa82010-08-27 01:01:44 +0000778 {
779 ret.SetErrorToGenericError();
Greg Clayton940b1032011-02-23 00:35:02 +0000780 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
Sean Callanan65dafa82010-08-27 01:01:44 +0000781 return ret;
782 }
783
Greg Clayton567e7f32011-09-22 04:58:26 +0000784 if (!process)
Sean Callanan65dafa82010-08-27 01:01:44 +0000785 {
786 ret.SetErrorToGenericError();
787 ret.SetErrorString("Couldn't find the process");
788 return ret;
789 }
790
791 DataExtractor extractor(buffer_sp,
Greg Clayton567e7f32011-09-22 04:58:26 +0000792 process->GetByteOrder(),
793 target->GetArchitecture().GetAddressByteSize());
Sean Callanan65dafa82010-08-27 01:01:44 +0000794
Greg Claytone005f2c2010-11-06 01:53:30 +0000795 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000796 {
797 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000798 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000799 0,
800 extractor.GetByteSize(),
801 func_remote_addr,
802 16,
803 DataExtractor::TypeUInt8);
804 }
805
Greg Clayton3508c382012-02-24 01:59:29 +0000806 disassembler->DecodeInstructions (Address (func_remote_addr), extractor, 0, UINT32_MAX, false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000807
Greg Clayton5c4c7462010-10-06 03:09:58 +0000808 InstructionList &instruction_list = disassembler->GetInstructionList();
Greg Clayton889fbd02011-03-26 19:14:58 +0000809 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
Sean Callanan65dafa82010-08-27 01:01:44 +0000810 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
811 instruction_index < num_instructions;
812 ++instruction_index)
813 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000814 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000815 instruction->Dump (&stream,
Greg Clayton889fbd02011-03-26 19:14:58 +0000816 max_opcode_byte_size,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000817 true,
Greg Clayton149731c2011-03-25 18:03:16 +0000818 true,
Greg Clayton0fef9682012-05-10 02:52:23 +0000819 &exe_ctx);
Sean Callanan65dafa82010-08-27 01:01:44 +0000820 stream.PutChar('\n');
Sean Callanan65dafa82010-08-27 01:01:44 +0000821 }
822
823 return ret;
824}