blob: 0e103b65efbda559e790feae47f46596db6c21ef [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ClangExpression.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// C Includes
11#include <stdio.h>
12#if HAVE_SYS_TYPES_H
13# include <sys/types.h>
14#endif
15
16// C++ Includes
17#include <cstdlib>
18#include <string>
19#include <map>
20
21// Other libraries and framework includes
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/ExternalASTSource.h"
24#include "clang/Basic/FileManager.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Basic/Version.h"
Greg Claytonc4f51102010-07-02 18:39:06 +000027#include "clang/Checker/FrontendActions.h"
28#include "clang/CodeGen/CodeGenAction.h"
Chris Lattner24943d22010-06-08 16:52:24 +000029#include "clang/CodeGen/ModuleBuilder.h"
30#include "clang/Driver/CC1Options.h"
31#include "clang/Driver/OptTable.h"
Chris Lattner24943d22010-06-08 16:52:24 +000032#include "clang/Frontend/CompilerInstance.h"
33#include "clang/Frontend/CompilerInvocation.h"
34#include "clang/Frontend/FrontendActions.h"
35#include "clang/Frontend/FrontendDiagnostic.h"
36#include "clang/Frontend/FrontendPluginRegistry.h"
37#include "clang/Frontend/TextDiagnosticBuffer.h"
38#include "clang/Frontend/TextDiagnosticPrinter.h"
39#include "clang/Frontend/VerifyDiagnosticsClient.h"
40#include "clang/Lex/Preprocessor.h"
Greg Claytonc4f51102010-07-02 18:39:06 +000041#include "clang/Rewrite/FrontendActions.h"
Chris Lattner24943d22010-06-08 16:52:24 +000042#include "clang/Sema/ParseAST.h"
Sean Callanan8c6934d2010-07-01 20:08:22 +000043#include "clang/Sema/SemaConsumer.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "llvm/ExecutionEngine/ExecutionEngine.h"
45#include "llvm/ExecutionEngine/JIT.h"
46#include "llvm/Module.h"
47#include "llvm/ADT/StringRef.h"
48#include "llvm/LLVMContext.h"
49#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/System/DynamicLibrary.h"
51#include "llvm/System/Host.h"
52#include "llvm/System/Signals.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000053#include "llvm/Target/TargetRegistry.h"
Chris Lattner24943d22010-06-08 16:52:24 +000054#include "llvm/Target/TargetSelect.h"
55
56// Project includes
Sean Callanan848960c2010-06-23 23:18:04 +000057#include "lldb/Core/Log.h"
Greg Clayton1674b122010-07-21 22:12:05 +000058#include "lldb/Core/ClangForward.h"
Sean Callanan8541f2f2010-07-23 02:19:15 +000059#include "lldb/Core/DataBufferHeap.h"
60#include "lldb/Core/Disassembler.h"
Chris Lattner24943d22010-06-08 16:52:24 +000061#include "lldb/Expression/ClangExpression.h"
62#include "lldb/Expression/ClangASTSource.h"
Sean Callanan8c6934d2010-07-01 20:08:22 +000063#include "lldb/Expression/ClangResultSynthesizer.h"
Chris Lattner24943d22010-06-08 16:52:24 +000064#include "lldb/Expression/ClangStmtVisitor.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000065#include "lldb/Expression/IRForTarget.h"
Sean Callanandcb658b2010-07-02 21:09:36 +000066#include "lldb/Expression/IRToDWARF.h"
Chris Lattner24943d22010-06-08 16:52:24 +000067#include "lldb/Symbol/ClangASTContext.h"
68#include "lldb/Expression/RecordingMemoryManager.h"
69#include "lldb/Target/ExecutionContext.h"
70#include "lldb/Target/Process.h"
Sean Callanan8541f2f2010-07-23 02:19:15 +000071#include "lldb/Target/Target.h"
Chris Lattner24943d22010-06-08 16:52:24 +000072
Chris Lattner24943d22010-06-08 16:52:24 +000073#include "lldb/Core/StreamString.h"
74#include "lldb/Host/Mutex.h"
Chris Lattner24943d22010-06-08 16:52:24 +000075
76
77using namespace lldb_private;
78using namespace clang;
79using namespace llvm;
80
Chris Lattner24943d22010-06-08 16:52:24 +000081
82//===----------------------------------------------------------------------===//
83// Utility Methods
84//===----------------------------------------------------------------------===//
85
86std::string GetBuiltinIncludePath(const char *Argv0) {
87 llvm::sys::Path P =
88 llvm::sys::Path::GetMainExecutable(Argv0,
89 (void*)(intptr_t) GetBuiltinIncludePath);
90
91 if (!P.isEmpty()) {
92 P.eraseComponent(); // Remove /clang from foo/bin/clang
93 P.eraseComponent(); // Remove /bin from foo/bin
94
95 // Get foo/lib/clang/<version>/include
96 P.appendComponent("lib");
97 P.appendComponent("clang");
98 P.appendComponent(CLANG_VERSION_STRING);
99 P.appendComponent("include");
100 }
101
102 return P.str();
103}
104
105
106//===----------------------------------------------------------------------===//
107// Main driver
108//===----------------------------------------------------------------------===//
109
Greg Clayton6e713402010-07-30 20:30:44 +0000110static void LLVMErrorHandler(void *UserData, const std::string &Message) {
111 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
Chris Lattner24943d22010-06-08 16:52:24 +0000112
Greg Clayton6e713402010-07-30 20:30:44 +0000113 Diags.Report(diag::err_fe_error_backend) << Message;
114
115 // We cannot recover from llvm errors.
116 exit(1);
Chris Lattner24943d22010-06-08 16:52:24 +0000117}
118
119static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
Greg Clayton6e713402010-07-30 20:30:44 +0000120 using namespace clang::frontend;
Chris Lattner24943d22010-06-08 16:52:24 +0000121
Greg Clayton6e713402010-07-30 20:30:44 +0000122 switch (CI.getFrontendOpts().ProgramAction) {
123 default:
124 llvm_unreachable("Invalid program action!");
Chris Lattner24943d22010-06-08 16:52:24 +0000125
Greg Clayton6e713402010-07-30 20:30:44 +0000126 case ASTDump: return new ASTDumpAction();
127 case ASTPrint: return new ASTPrintAction();
128 case ASTPrintXML: return new ASTPrintXMLAction();
129 case ASTView: return new ASTViewAction();
130 case BoostCon: return new BoostConAction();
131 case DumpRawTokens: return new DumpRawTokensAction();
132 case DumpTokens: return new DumpTokensAction();
133 case EmitAssembly: return new EmitAssemblyAction();
134 case EmitBC: return new EmitBCAction();
135 case EmitHTML: return new HTMLPrintAction();
136 case EmitLLVM: return new EmitLLVMAction();
137 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
138 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
139 case EmitObj: return new EmitObjAction();
140 case FixIt: return new FixItAction();
141 case GeneratePCH: return new GeneratePCHAction();
142 case GeneratePTH: return new GeneratePTHAction();
143 case InheritanceView: return new InheritanceViewAction();
144 case InitOnly: return new InitOnlyAction();
145 case ParseSyntaxOnly: return new SyntaxOnlyAction();
Chris Lattner24943d22010-06-08 16:52:24 +0000146
Greg Clayton6e713402010-07-30 20:30:44 +0000147 case PluginAction: {
Greg Clayton6e713402010-07-30 20:30:44 +0000148 for (FrontendPluginRegistry::iterator it =
149 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
150 it != ie; ++it) {
151 if (it->getName() == CI.getFrontendOpts().ActionName) {
Greg Clayton960d6a42010-08-03 00:35:52 +0000152 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
153 if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
154 return 0;
155 return P.take();
Greg Clayton6e713402010-07-30 20:30:44 +0000156 }
Chris Lattner24943d22010-06-08 16:52:24 +0000157 }
Greg Clayton6e713402010-07-30 20:30:44 +0000158
159 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
160 << CI.getFrontendOpts().ActionName;
161 return 0;
162 }
163
164 case PrintDeclContext: return new DeclContextPrintAction();
165 case PrintPreamble: return new PrintPreambleAction();
166 case PrintPreprocessedInput: return new PrintPreprocessedAction();
167 case RewriteMacros: return new RewriteMacrosAction();
168 case RewriteObjC: return new RewriteObjCAction();
169 case RewriteTest: return new RewriteTestAction();
170 case RunAnalysis: return new AnalysisAction();
171 case RunPreprocessorOnly: return new PreprocessOnlyAction();
172 }
173}
174
175static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
176 // Create the underlying action.
177 FrontendAction *Act = CreateFrontendBaseAction(CI);
178 if (!Act)
179 return 0;
180
181 // If there are any AST files to merge, create a frontend action
182 // adaptor to perform the merge.
183 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
184 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
185 CI.getFrontendOpts().ASTMergeFiles.size());
186
187 return Act;
Chris Lattner24943d22010-06-08 16:52:24 +0000188}
189
190//----------------------------------------------------------------------
191// ClangExpression constructor
192//----------------------------------------------------------------------
193ClangExpression::ClangExpression(const char *target_triple,
194 ClangExpressionDeclMap *decl_map) :
195 m_target_triple (),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000196 m_decl_map (decl_map),
197 m_clang_ap (),
Chris Lattner24943d22010-06-08 16:52:24 +0000198 m_code_generator_ptr (NULL),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000199 m_jit_mm_ptr (NULL),
200 m_execution_engine (),
201 m_jitted_functions ()
Chris Lattner24943d22010-06-08 16:52:24 +0000202{
203 if (target_triple && target_triple[0])
204 m_target_triple = target_triple;
205 else
206 m_target_triple = llvm::sys::getHostTriple();
207}
208
209
210//----------------------------------------------------------------------
211// Destructor
212//----------------------------------------------------------------------
213ClangExpression::~ClangExpression()
214{
215 if (m_code_generator_ptr && !m_execution_engine.get())
216 delete m_code_generator_ptr;
217}
218
219bool
220ClangExpression::CreateCompilerInstance (bool &IsAST)
221{
222 // Initialize targets first, so that --version shows registered targets.
223 static struct InitializeLLVM {
224 InitializeLLVM() {
225 llvm::InitializeAllTargets();
226 llvm::InitializeAllAsmPrinters();
227 }
228 } InitializeLLVM;
229
230 // 1. Create a new compiler instance.
231 m_clang_ap.reset(new CompilerInstance());
232 m_clang_ap->setLLVMContext(new LLVMContext());
233
234 // 2. Set options.
235
236 // Parse expressions as Objective C++ regardless of context.
237 // Our hook into Clang's lookup mechanism only works in C++.
238 m_clang_ap->getLangOpts().CPlusPlus = true;
239 m_clang_ap->getLangOpts().ObjC1 = true;
Sean Callanan051052f2010-07-02 22:22:28 +0000240 m_clang_ap->getLangOpts().ThreadsafeStatics = false;
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000241 m_clang_ap->getLangOpts().AccessControl = false; // Debuggers get universal access
Sean Callanan8bce6652010-07-13 21:41:46 +0000242
243 // Set CodeGen options
244 m_clang_ap->getCodeGenOpts().EmitDeclMetadata = true;
Sean Callananbc2928a2010-08-03 00:23:29 +0000245 m_clang_ap->getCodeGenOpts().InstrumentFunctions = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000246
247 // Disable some warnings.
248 m_clang_ap->getDiagnosticOpts().Warnings.push_back("no-unused-value");
249
250 // Set the target triple.
251 m_clang_ap->getTargetOpts().Triple = m_target_triple;
252
253 // 3. Set up various important bits of infrastructure.
254
255 m_clang_ap->createDiagnostics(0, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000256
257 // Create the target instance.
258 m_clang_ap->setTarget(TargetInfo::CreateTargetInfo(m_clang_ap->getDiagnostics(),
259 m_clang_ap->getTargetOpts()));
260 if (!m_clang_ap->hasTarget())
261 {
262 m_clang_ap.reset();
263 return false;
264 }
265
266 // Inform the target of the language options
267 //
268 // FIXME: We shouldn't need to do this, the target should be immutable once
269 // created. This complexity should be lifted elsewhere.
270 m_clang_ap->getTarget().setForcedLangOptions(m_clang_ap->getLangOpts());
271
272 return m_clang_ap.get();
273}
274
275Mutex &
276ClangExpression::GetClangMutex ()
277{
278 static Mutex g_clang_mutex(Mutex::eMutexTypeRecursive); // Control access to the clang compiler
279 return g_clang_mutex;
280}
281
282
283clang::ASTContext *
284ClangExpression::GetASTContext ()
285{
286 CompilerInstance *compiler_instance = GetCompilerInstance();
287 if (compiler_instance)
288 return &compiler_instance->getASTContext();
289 return NULL;
290}
291
292unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000293ClangExpression::ParseExpression (const char *expr_text,
294 Stream &stream,
295 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000296{
297 // HACK: for now we have to make a function body around our expression
298 // since there is no way to parse a single expression line in LLVM/Clang.
Sean Callanan8bce6652010-07-13 21:41:46 +0000299 std::string func_expr("extern \"C\" void ___clang_expr(void *___clang_arg)\n{\n\t");
Chris Lattner24943d22010-06-08 16:52:24 +0000300 func_expr.append(expr_text);
301 func_expr.append(";\n}");
Sean Callanan8c6934d2010-07-01 20:08:22 +0000302 return ParseBareExpression (func_expr, stream, add_result_var);
Chris Lattner24943d22010-06-08 16:52:24 +0000303
304}
305
306unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000307ClangExpression::ParseBareExpression (llvm::StringRef expr_text,
308 Stream &stream,
309 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000310{
311 Mutex::Locker locker(GetClangMutex ());
312
313 TextDiagnosticBuffer text_diagnostic_buffer;
314
315 bool IsAST = false;
316 if (!CreateCompilerInstance (IsAST))
317 {
318 stream.Printf("error: couldn't create compiler instance\n");
319 return 1;
320 }
321
322 // This code is matched below by a setClient to NULL.
323 // We cannot return out of this code without doing that.
324 m_clang_ap->getDiagnostics().setClient(&text_diagnostic_buffer);
325 text_diagnostic_buffer.FlushDiagnostics (m_clang_ap->getDiagnostics());
326
327 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
328
329 if (!m_clang_ap->hasSourceManager())
330 m_clang_ap->createSourceManager();
331
332 m_clang_ap->createFileManager();
333 m_clang_ap->createPreprocessor();
334
335 // Build the ASTContext. Most of this we inherit from the
336 // CompilerInstance, but we also want to give the context
337 // an ExternalASTSource.
338 SelectorTable selector_table;
339 std::auto_ptr<Builtin::Context> builtin_ap(new Builtin::Context(m_clang_ap->getTarget()));
340 ASTContext *Context = new ASTContext(m_clang_ap->getLangOpts(),
341 m_clang_ap->getSourceManager(),
342 m_clang_ap->getTarget(),
343 m_clang_ap->getPreprocessor().getIdentifierTable(),
344 selector_table,
Greg Clayton6e713402010-07-30 20:30:44 +0000345 *builtin_ap.get(),
346 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000347
348 llvm::OwningPtr<ExternalASTSource> ASTSource(new ClangASTSource(*Context, *m_decl_map));
349
350 if (m_decl_map)
351 {
352 Context->setExternalSource(ASTSource);
353 }
354
355 m_clang_ap->setASTContext(Context);
356
357 FileID memory_buffer_file_id = m_clang_ap->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
358 std::string module_name("test_func");
359 text_diagnostic_buffer.BeginSourceFile(m_clang_ap->getLangOpts(), &m_clang_ap->getPreprocessor());
360
361 if (m_code_generator_ptr)
362 delete m_code_generator_ptr;
363
364 m_code_generator_ptr = CreateLLVMCodeGen(m_clang_ap->getDiagnostics(),
365 module_name,
366 m_clang_ap->getCodeGenOpts(),
367 m_clang_ap->getLLVMContext());
368
369
370 // - CodeGeneration ASTConsumer (include/clang/ModuleBuilder.h), which will be passed in when you call...
371 // - Call clang::ParseAST (in lib/Sema/ParseAST.cpp) to parse the buffer. The CodeGenerator will generate code for __dbg_expr.
372 // - Once ParseAST completes, you can grab the llvm::Module from the CodeGenerator, which will have an llvm::Function you can hand off to the JIT.
Sean Callanan8c6934d2010-07-01 20:08:22 +0000373
374 if (add_result_var)
375 {
376 ClangResultSynthesizer result_synthesizer(m_code_generator_ptr);
377 ParseAST(m_clang_ap->getPreprocessor(), &result_synthesizer, m_clang_ap->getASTContext());
378 }
379 else
380 {
381 ParseAST(m_clang_ap->getPreprocessor(), m_code_generator_ptr, m_clang_ap->getASTContext());
382 }
383
Sean Callanan848960c2010-06-23 23:18:04 +0000384
Chris Lattner24943d22010-06-08 16:52:24 +0000385 text_diagnostic_buffer.EndSourceFile();
386
387 //compiler_instance->getASTContext().getTranslationUnitDecl()->dump();
388
389 //if (compiler_instance->getFrontendOpts().ShowStats) {
390 // compiler_instance->getFileManager().PrintStats();
391 // fprintf(stderr, "\n");
392 //}
393
394 // This code resolves the setClient above.
395 m_clang_ap->getDiagnostics().setClient(0);
396
397 TextDiagnosticBuffer::const_iterator diag_iterator;
398
399 int num_errors = 0;
400
401#ifdef COUNT_WARNINGS_AND_ERRORS
402 int num_warnings = 0;
403
404 for (diag_iterator = text_diagnostic_buffer.warn_begin();
405 diag_iterator != text_diagnostic_buffer.warn_end();
406 ++diag_iterator)
407 num_warnings++;
408
409 for (diag_iterator = text_diagnostic_buffer.err_begin();
410 diag_iterator != text_diagnostic_buffer.err_end();
411 ++diag_iterator)
412 num_errors++;
413
414 if (num_warnings || num_errors)
415 {
416 if (num_warnings)
417 stream.Printf("%u warning%s%s", num_warnings, (num_warnings == 1 ? "" : "s"), (num_errors ? " and " : ""));
418 if (num_errors)
419 stream.Printf("%u error%s", num_errors, (num_errors == 1 ? "" : "s"));
420 stream.Printf("\n");
421 }
422#endif
423
424 for (diag_iterator = text_diagnostic_buffer.warn_begin();
425 diag_iterator != text_diagnostic_buffer.warn_end();
426 ++diag_iterator)
427 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
428
429 num_errors = 0;
430
431 for (diag_iterator = text_diagnostic_buffer.err_begin();
432 diag_iterator != text_diagnostic_buffer.err_end();
433 ++diag_iterator)
434 {
435 num_errors++;
436 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
437 }
438
439 return num_errors;
440}
441
Chris Lattner24943d22010-06-08 16:52:24 +0000442unsigned
443ClangExpression::ConvertExpressionToDWARF (ClangExpressionVariableList& expr_local_variable_list,
444 StreamString &dwarf_opcode_strm)
445{
446 CompilerInstance *compiler_instance = GetCompilerInstance();
447
448 DeclarationName hack_func_name(&compiler_instance->getASTContext().Idents.get("___clang_expr"));
449 DeclContext::lookup_result result = compiler_instance->getASTContext().getTranslationUnitDecl()->lookup(hack_func_name);
450
451 if (result.first != result.second)
452 {
453 Decl *decl = *result.first;
454 Stmt *decl_stmt = decl->getBody();
455 if (decl_stmt)
456 {
457 ClangStmtVisitor visitor(compiler_instance->getASTContext(), expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
458
459 visitor.Visit (decl_stmt);
460 }
461 }
462 return 0;
463}
464
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000465bool
Sean Callanandcb658b2010-07-02 21:09:36 +0000466ClangExpression::ConvertIRToDWARF (ClangExpressionVariableList &expr_local_variable_list,
Sean Callanan848960c2010-06-23 23:18:04 +0000467 StreamString &dwarf_opcode_strm)
468{
469 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
470
471 llvm::Module *module = m_code_generator_ptr->GetModule();
472
473 if (!module)
474 {
475 if (log)
476 log->Printf("IR doesn't contain a module");
477
478 return 1;
479 }
480
Sean Callanandcb658b2010-07-02 21:09:36 +0000481 IRToDWARF ir_to_dwarf("IR to DWARF", expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
Sean Callanan8c6934d2010-07-01 20:08:22 +0000482
Sean Callanandcb658b2010-07-02 21:09:36 +0000483 return ir_to_dwarf.runOnModule(*module);
Sean Callanan848960c2010-06-23 23:18:04 +0000484}
485
Chris Lattner24943d22010-06-08 16:52:24 +0000486bool
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000487ClangExpression::PrepareIRForTarget (ClangExpressionVariableList &expr_local_variable_list)
488{
489 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
490
491 llvm::Module *module = m_code_generator_ptr->GetModule();
492
493 if (!module)
494 {
495 if (log)
496 log->Printf("IR doesn't contain a module");
497
498 return 1;
499 }
500
Sean Callanan8bce6652010-07-13 21:41:46 +0000501 llvm::Triple target_triple = m_clang_ap->getTarget().getTriple();
502
503 std::string err;
504
505 const llvm::Target *target = llvm::TargetRegistry::lookupTarget(m_target_triple, err);
506
507 if (!target)
508 {
509 if (log)
510 log->Printf("Couldn't find a target for %s", m_target_triple.c_str());
511
512 return 1;
513 }
514
515 std::auto_ptr<llvm::TargetMachine> target_machine(target->createTargetMachine(m_target_triple, ""));
516
517 IRForTarget ir_for_target("IR for target", m_decl_map, target_machine->getTargetData());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000518
519 return ir_for_target.runOnModule(*module);
520}
521
522bool
Chris Lattner24943d22010-06-08 16:52:24 +0000523ClangExpression::JITFunction (const ExecutionContext &exc_context, const char *name)
524{
Sean Callanan321fe9e2010-07-28 01:00:59 +0000525 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
Chris Lattner24943d22010-06-08 16:52:24 +0000526
527 llvm::Module *module = m_code_generator_ptr->GetModule();
528
529 if (module)
530 {
531 std::string error;
532
533 if (m_jit_mm_ptr == NULL)
534 m_jit_mm_ptr = new RecordingMemoryManager();
535
536 //llvm::InitializeNativeTarget();
Sean Callanan321fe9e2010-07-28 01:00:59 +0000537
538 if (log)
539 {
540 const char *relocation_model_string;
541
542 switch (llvm::TargetMachine::getRelocationModel())
543 {
Sean Callanan1e7089a2010-07-29 19:03:08 +0000544 case llvm::Reloc::Default:
545 relocation_model_string = "Default";
546 break;
547 case llvm::Reloc::Static:
548 relocation_model_string = "Static";
549 break;
550 case llvm::Reloc::PIC_:
551 relocation_model_string = "PIC_";
552 break;
553 case llvm::Reloc::DynamicNoPIC:
554 relocation_model_string = "DynamicNoPIC";
555 break;
Sean Callanan321fe9e2010-07-28 01:00:59 +0000556 }
557
558 log->Printf("Target machine's relocation model: %s", relocation_model_string);
559 }
Sean Callanan1e7089a2010-07-29 19:03:08 +0000560
561 if (m_execution_engine.get() == 0)
562 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
563 &error,
564 m_jit_mm_ptr,
565 CodeGenOpt::Default,
566 true,
567 CodeModel::Small)); // set to small so RIP-relative relocations work in PIC
568
569 m_execution_engine->DisableLazyCompilation();
570 llvm::Function *function = module->getFunction (llvm::StringRef (name));
Sean Callanan321fe9e2010-07-28 01:00:59 +0000571
Chris Lattner24943d22010-06-08 16:52:24 +0000572 // We don't actually need the function pointer here, this just forces it to get resolved.
573 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
574 // Note, you probably won't get here on error, since the LLVM JIT tends to just
575 // exit on error at present... So be careful.
576 if (fun_ptr == 0)
577 return false;
578 m_jitted_functions.push_back(ClangExpression::JittedFunction(name, (lldb::addr_t) fun_ptr));
579
580 }
581 return true;
582}
583
584bool
585ClangExpression::WriteJITCode (const ExecutionContext &exc_context)
586{
Sean Callanan321fe9e2010-07-28 01:00:59 +0000587 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
588
Chris Lattner24943d22010-06-08 16:52:24 +0000589 if (m_jit_mm_ptr == NULL)
590 return false;
591
592 if (exc_context.process == NULL)
593 return false;
594
595 // Look over the regions allocated for the function compiled. The JIT
596 // tries to allocate the functions & stubs close together, so we should try to
597 // write them that way too...
598 // For now I only write functions with no stubs, globals, exception tables,
599 // etc. So I only need to write the functions.
600
Greg Claytonbef15832010-07-14 00:18:15 +0000601 size_t alloc_size = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000602 std::map<uint8_t *, uint8_t *>::iterator fun_pos, fun_end = m_jit_mm_ptr->m_functions.end();
603 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
604 {
Greg Claytonbef15832010-07-14 00:18:15 +0000605 alloc_size += (*fun_pos).second - (*fun_pos).first;
Chris Lattner24943d22010-06-08 16:52:24 +0000606 }
607
608 Error error;
Greg Claytonbef15832010-07-14 00:18:15 +0000609 lldb::addr_t target_addr = exc_context.process->AllocateMemory (alloc_size, lldb::ePermissionsReadable|lldb::ePermissionsExecutable, error);
Chris Lattner24943d22010-06-08 16:52:24 +0000610
611 if (target_addr == LLDB_INVALID_ADDRESS)
612 return false;
613
614 lldb::addr_t cursor = target_addr;
615 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
616 {
Sean Callanan321fe9e2010-07-28 01:00:59 +0000617 if (log)
618 log->Printf("Reading [%p-%p] from m_functions", fun_pos->first, fun_pos->second);
619
Chris Lattner24943d22010-06-08 16:52:24 +0000620 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
621 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
622 size_t size = lend - lstart;
623 exc_context.process->WriteMemory(cursor, (void *) lstart, size, error);
624 m_jit_mm_ptr->AddToLocalToRemoteMap (lstart, size, cursor);
625 cursor += size;
626 }
627
628 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
629
630 for (pos = m_jitted_functions.begin(); pos != end; pos++)
631 {
632 (*pos).m_remote_addr = m_jit_mm_ptr->GetRemoteAddressForLocal ((*pos).m_local_addr);
633 }
634 return true;
635}
636
637lldb::addr_t
638ClangExpression::GetFunctionAddress (const char *name)
639{
640 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
641
642 for (pos = m_jitted_functions.begin(); pos < end; pos++)
643 {
644 if (strcmp ((*pos).m_name.c_str(), name) == 0)
645 return (*pos).m_remote_addr;
646 }
647 return LLDB_INVALID_ADDRESS;
648}
649
Sean Callanan8541f2f2010-07-23 02:19:15 +0000650Error
651ClangExpression::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, const char *name)
652{
653 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
654
655 Error ret;
656
657 ret.Clear();
658
659 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
660 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
661
662 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
663
664 for (pos = m_jitted_functions.begin(); pos < end; pos++)
665 {
666 if (strcmp(pos->m_name.c_str(), name) == 0)
667 {
668 func_local_addr = pos->m_local_addr;
669 func_remote_addr = pos->m_remote_addr;
670 }
671 }
672
673 if (func_local_addr == LLDB_INVALID_ADDRESS)
674 {
675 ret.SetErrorToGenericError();
676 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
677 return ret;
678 }
679
680 if(log)
681 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
682
683 std::pair <lldb::addr_t, lldb::addr_t> func_range;
684
685 func_range = m_jit_mm_ptr->GetRemoteRangeForLocal(func_local_addr);
686
687 if (func_range.first == 0 && func_range.second == 0)
688 {
689 ret.SetErrorToGenericError();
690 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
691 return ret;
692 }
693
694 if(log)
695 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
696
697 if (!exe_ctx.target)
698 {
699 ret.SetErrorToGenericError();
700 ret.SetErrorString("Couldn't find the target");
701 }
702
Sean Callanan32824aa2010-07-23 22:19:18 +0000703 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
Sean Callanan8541f2f2010-07-23 02:19:15 +0000704
705 Error err;
Sean Callanan32824aa2010-07-23 22:19:18 +0000706 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
Sean Callanan8541f2f2010-07-23 02:19:15 +0000707
708 if (!err.Success())
709 {
710 ret.SetErrorToGenericError();
711 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
712 return ret;
713 }
714
715 ArchSpec arch(exe_ctx.target->GetArchitecture());
716
717 Disassembler *disassembler = Disassembler::FindPlugin(arch);
718
719 if (disassembler == NULL)
720 {
721 ret.SetErrorToGenericError();
722 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.AsCString());
723 return ret;
724 }
725
726 if (!exe_ctx.process)
727 {
728 ret.SetErrorToGenericError();
729 ret.SetErrorString("Couldn't find the process");
730 return ret;
731 }
732
733 DataExtractor extractor(buffer_sp,
734 exe_ctx.process->GetByteOrder(),
Sean Callanan32824aa2010-07-23 22:19:18 +0000735 exe_ctx.target->GetArchitecture().GetAddressByteSize());
Sean Callanan8541f2f2010-07-23 02:19:15 +0000736
737 if(log)
738 {
739 log->Printf("Function data has contents:");
740 extractor.PutToLog (log,
741 0,
742 extractor.GetByteSize(),
Sean Callanan32824aa2010-07-23 22:19:18 +0000743 func_remote_addr,
Sean Callanan8541f2f2010-07-23 02:19:15 +0000744 16,
745 DataExtractor::TypeUInt8);
746 }
747
748 disassembler->DecodeInstructions(extractor, 0, UINT32_MAX);
749
750 Disassembler::InstructionList &instruction_list = disassembler->GetInstructionList();
751
752 uint32_t bytes_offset = 0;
753
754 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
755 instruction_index < num_instructions;
756 ++instruction_index)
757 {
758 Disassembler::Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index);
Sean Callanan32824aa2010-07-23 22:19:18 +0000759 Address addr(NULL, func_remote_addr + bytes_offset);
Sean Callanan8541f2f2010-07-23 02:19:15 +0000760 instruction->Dump (&stream,
Sean Callanan32824aa2010-07-23 22:19:18 +0000761 &addr,
Sean Callanan8541f2f2010-07-23 02:19:15 +0000762 &extractor,
763 bytes_offset,
764 exe_ctx,
765 true);
766 stream.PutChar('\n');
767 bytes_offset += instruction->GetByteSize();
768 }
769
770 return ret;
771}
772
Chris Lattner24943d22010-06-08 16:52:24 +0000773unsigned
774ClangExpression::Compile()
775{
776 Mutex::Locker locker(GetClangMutex ());
777 bool IsAST = false;
778
779 if (CreateCompilerInstance(IsAST))
780 {
781 // Validate/process some options
782 if (m_clang_ap->getHeaderSearchOpts().Verbose)
783 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
784 << " based upon " << PACKAGE_STRING
785 << " hosted on " << llvm::sys::getHostTriple() << "\n";
786
787 // Enforce certain implications.
788 if (!m_clang_ap->getFrontendOpts().ViewClassInheritance.empty())
789 m_clang_ap->getFrontendOpts().ProgramAction = frontend::InheritanceView;
790// if (!compiler_instance->getFrontendOpts().FixItSuffix.empty())
791// compiler_instance->getFrontendOpts().ProgramAction = frontend::FixIt;
792
793 for (unsigned i = 0, e = m_clang_ap->getFrontendOpts().Inputs.size(); i != e; ++i) {
Chris Lattner24943d22010-06-08 16:52:24 +0000794
795 // If we aren't using an AST file, setup the file and source managers and
796 // the preprocessor.
797 if (!IsAST) {
798 if (!i) {
799 // Create a file manager object to provide access to and cache the
800 // filesystem.
801 m_clang_ap->createFileManager();
802
803 // Create the source manager.
804 m_clang_ap->createSourceManager();
805 } else {
806 // Reset the ID tables if we are reusing the SourceManager.
807 m_clang_ap->getSourceManager().clearIDTables();
808 }
809
810 // Create the preprocessor.
811 m_clang_ap->createPreprocessor();
812 }
813
814 llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(*m_clang_ap.get()));
815 if (!Act)
816 break;
817
Greg Claytone41c4b22010-06-13 17:34:29 +0000818 if (Act->BeginSourceFile(*m_clang_ap,
819 m_clang_ap->getFrontendOpts().Inputs[i].second,
820 m_clang_ap->getFrontendOpts().Inputs[i].first)) {
Chris Lattner24943d22010-06-08 16:52:24 +0000821 Act->Execute();
822 Act->EndSourceFile();
823 }
824 }
825
826 if (m_clang_ap->getDiagnosticOpts().ShowCarets)
827 {
828 unsigned NumWarnings = m_clang_ap->getDiagnostics().getNumWarnings();
829 unsigned NumErrors = m_clang_ap->getDiagnostics().getNumErrors() -
830 m_clang_ap->getDiagnostics().getNumErrorsSuppressed();
831
832 if (NumWarnings || NumErrors)
833 {
834 if (NumWarnings)
835 fprintf (stderr, "%u warning%s%s", NumWarnings, (NumWarnings == 1 ? "" : "s"), (NumErrors ? " and " : ""));
836 if (NumErrors)
837 fprintf (stderr, "%u error%s", NumErrors, (NumErrors == 1 ? "" : "s"));
838 fprintf (stderr, " generated.\n");
839 }
840 }
841
842 if (m_clang_ap->getFrontendOpts().ShowStats) {
843 m_clang_ap->getFileManager().PrintStats();
844 fprintf(stderr, "\n");
845 }
846
847 // Return the appropriate status when verifying diagnostics.
848 //
849 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
850 // this.
851 if (m_clang_ap->getDiagnosticOpts().VerifyDiagnostics)
852 return static_cast<VerifyDiagnosticsClient&>(m_clang_ap->getDiagnosticClient()).HadErrors();
853
854 return m_clang_ap->getDiagnostics().getNumErrors();
855 }
856 return 1;
857}