blob: 0ff4c38f2fccae9dde9724c6f57d36403fed1756 [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 Callanan8bce6652010-07-13 21:41:46 +0000241
242 // Set CodeGen options
243 m_clang_ap->getCodeGenOpts().EmitDeclMetadata = true;
Sean Callananbc2928a2010-08-03 00:23:29 +0000244 m_clang_ap->getCodeGenOpts().InstrumentFunctions = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000245
246 // Disable some warnings.
247 m_clang_ap->getDiagnosticOpts().Warnings.push_back("no-unused-value");
248
249 // Set the target triple.
250 m_clang_ap->getTargetOpts().Triple = m_target_triple;
251
252 // 3. Set up various important bits of infrastructure.
253
254 m_clang_ap->createDiagnostics(0, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000255
256 // Create the target instance.
257 m_clang_ap->setTarget(TargetInfo::CreateTargetInfo(m_clang_ap->getDiagnostics(),
258 m_clang_ap->getTargetOpts()));
259 if (!m_clang_ap->hasTarget())
260 {
261 m_clang_ap.reset();
262 return false;
263 }
264
265 // Inform the target of the language options
266 //
267 // FIXME: We shouldn't need to do this, the target should be immutable once
268 // created. This complexity should be lifted elsewhere.
269 m_clang_ap->getTarget().setForcedLangOptions(m_clang_ap->getLangOpts());
270
271 return m_clang_ap.get();
272}
273
274Mutex &
275ClangExpression::GetClangMutex ()
276{
277 static Mutex g_clang_mutex(Mutex::eMutexTypeRecursive); // Control access to the clang compiler
278 return g_clang_mutex;
279}
280
281
282clang::ASTContext *
283ClangExpression::GetASTContext ()
284{
285 CompilerInstance *compiler_instance = GetCompilerInstance();
286 if (compiler_instance)
287 return &compiler_instance->getASTContext();
288 return NULL;
289}
290
291unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000292ClangExpression::ParseExpression (const char *expr_text,
293 Stream &stream,
294 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000295{
296 // HACK: for now we have to make a function body around our expression
297 // since there is no way to parse a single expression line in LLVM/Clang.
Sean Callanan8bce6652010-07-13 21:41:46 +0000298 std::string func_expr("extern \"C\" void ___clang_expr(void *___clang_arg)\n{\n\t");
Chris Lattner24943d22010-06-08 16:52:24 +0000299 func_expr.append(expr_text);
300 func_expr.append(";\n}");
Sean Callanan8c6934d2010-07-01 20:08:22 +0000301 return ParseBareExpression (func_expr, stream, add_result_var);
Chris Lattner24943d22010-06-08 16:52:24 +0000302
303}
304
305unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000306ClangExpression::ParseBareExpression (llvm::StringRef expr_text,
307 Stream &stream,
308 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000309{
310 Mutex::Locker locker(GetClangMutex ());
311
312 TextDiagnosticBuffer text_diagnostic_buffer;
313
314 bool IsAST = false;
315 if (!CreateCompilerInstance (IsAST))
316 {
317 stream.Printf("error: couldn't create compiler instance\n");
318 return 1;
319 }
320
321 // This code is matched below by a setClient to NULL.
322 // We cannot return out of this code without doing that.
323 m_clang_ap->getDiagnostics().setClient(&text_diagnostic_buffer);
324 text_diagnostic_buffer.FlushDiagnostics (m_clang_ap->getDiagnostics());
325
326 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
327
328 if (!m_clang_ap->hasSourceManager())
329 m_clang_ap->createSourceManager();
330
331 m_clang_ap->createFileManager();
332 m_clang_ap->createPreprocessor();
333
334 // Build the ASTContext. Most of this we inherit from the
335 // CompilerInstance, but we also want to give the context
336 // an ExternalASTSource.
337 SelectorTable selector_table;
338 std::auto_ptr<Builtin::Context> builtin_ap(new Builtin::Context(m_clang_ap->getTarget()));
339 ASTContext *Context = new ASTContext(m_clang_ap->getLangOpts(),
340 m_clang_ap->getSourceManager(),
341 m_clang_ap->getTarget(),
342 m_clang_ap->getPreprocessor().getIdentifierTable(),
343 selector_table,
Greg Clayton6e713402010-07-30 20:30:44 +0000344 *builtin_ap.get(),
345 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000346
347 llvm::OwningPtr<ExternalASTSource> ASTSource(new ClangASTSource(*Context, *m_decl_map));
348
349 if (m_decl_map)
350 {
351 Context->setExternalSource(ASTSource);
352 }
353
354 m_clang_ap->setASTContext(Context);
355
356 FileID memory_buffer_file_id = m_clang_ap->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
357 std::string module_name("test_func");
358 text_diagnostic_buffer.BeginSourceFile(m_clang_ap->getLangOpts(), &m_clang_ap->getPreprocessor());
359
360 if (m_code_generator_ptr)
361 delete m_code_generator_ptr;
362
363 m_code_generator_ptr = CreateLLVMCodeGen(m_clang_ap->getDiagnostics(),
364 module_name,
365 m_clang_ap->getCodeGenOpts(),
366 m_clang_ap->getLLVMContext());
367
368
369 // - CodeGeneration ASTConsumer (include/clang/ModuleBuilder.h), which will be passed in when you call...
370 // - Call clang::ParseAST (in lib/Sema/ParseAST.cpp) to parse the buffer. The CodeGenerator will generate code for __dbg_expr.
371 // - 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 +0000372
373 if (add_result_var)
374 {
375 ClangResultSynthesizer result_synthesizer(m_code_generator_ptr);
376 ParseAST(m_clang_ap->getPreprocessor(), &result_synthesizer, m_clang_ap->getASTContext());
377 }
378 else
379 {
380 ParseAST(m_clang_ap->getPreprocessor(), m_code_generator_ptr, m_clang_ap->getASTContext());
381 }
382
Sean Callanan848960c2010-06-23 23:18:04 +0000383
Chris Lattner24943d22010-06-08 16:52:24 +0000384 text_diagnostic_buffer.EndSourceFile();
385
386 //compiler_instance->getASTContext().getTranslationUnitDecl()->dump();
387
388 //if (compiler_instance->getFrontendOpts().ShowStats) {
389 // compiler_instance->getFileManager().PrintStats();
390 // fprintf(stderr, "\n");
391 //}
392
393 // This code resolves the setClient above.
394 m_clang_ap->getDiagnostics().setClient(0);
395
396 TextDiagnosticBuffer::const_iterator diag_iterator;
397
398 int num_errors = 0;
399
400#ifdef COUNT_WARNINGS_AND_ERRORS
401 int num_warnings = 0;
402
403 for (diag_iterator = text_diagnostic_buffer.warn_begin();
404 diag_iterator != text_diagnostic_buffer.warn_end();
405 ++diag_iterator)
406 num_warnings++;
407
408 for (diag_iterator = text_diagnostic_buffer.err_begin();
409 diag_iterator != text_diagnostic_buffer.err_end();
410 ++diag_iterator)
411 num_errors++;
412
413 if (num_warnings || num_errors)
414 {
415 if (num_warnings)
416 stream.Printf("%u warning%s%s", num_warnings, (num_warnings == 1 ? "" : "s"), (num_errors ? " and " : ""));
417 if (num_errors)
418 stream.Printf("%u error%s", num_errors, (num_errors == 1 ? "" : "s"));
419 stream.Printf("\n");
420 }
421#endif
422
423 for (diag_iterator = text_diagnostic_buffer.warn_begin();
424 diag_iterator != text_diagnostic_buffer.warn_end();
425 ++diag_iterator)
426 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
427
428 num_errors = 0;
429
430 for (diag_iterator = text_diagnostic_buffer.err_begin();
431 diag_iterator != text_diagnostic_buffer.err_end();
432 ++diag_iterator)
433 {
434 num_errors++;
435 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
436 }
437
438 return num_errors;
439}
440
Chris Lattner24943d22010-06-08 16:52:24 +0000441unsigned
442ClangExpression::ConvertExpressionToDWARF (ClangExpressionVariableList& expr_local_variable_list,
443 StreamString &dwarf_opcode_strm)
444{
445 CompilerInstance *compiler_instance = GetCompilerInstance();
446
447 DeclarationName hack_func_name(&compiler_instance->getASTContext().Idents.get("___clang_expr"));
448 DeclContext::lookup_result result = compiler_instance->getASTContext().getTranslationUnitDecl()->lookup(hack_func_name);
449
450 if (result.first != result.second)
451 {
452 Decl *decl = *result.first;
453 Stmt *decl_stmt = decl->getBody();
454 if (decl_stmt)
455 {
456 ClangStmtVisitor visitor(compiler_instance->getASTContext(), expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
457
458 visitor.Visit (decl_stmt);
459 }
460 }
461 return 0;
462}
463
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000464bool
Sean Callanandcb658b2010-07-02 21:09:36 +0000465ClangExpression::ConvertIRToDWARF (ClangExpressionVariableList &expr_local_variable_list,
Sean Callanan848960c2010-06-23 23:18:04 +0000466 StreamString &dwarf_opcode_strm)
467{
468 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
469
470 llvm::Module *module = m_code_generator_ptr->GetModule();
471
472 if (!module)
473 {
474 if (log)
475 log->Printf("IR doesn't contain a module");
476
477 return 1;
478 }
479
Sean Callanandcb658b2010-07-02 21:09:36 +0000480 IRToDWARF ir_to_dwarf("IR to DWARF", expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
Sean Callanan8c6934d2010-07-01 20:08:22 +0000481
Sean Callanandcb658b2010-07-02 21:09:36 +0000482 return ir_to_dwarf.runOnModule(*module);
Sean Callanan848960c2010-06-23 23:18:04 +0000483}
484
Chris Lattner24943d22010-06-08 16:52:24 +0000485bool
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000486ClangExpression::PrepareIRForTarget (ClangExpressionVariableList &expr_local_variable_list)
487{
488 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
489
490 llvm::Module *module = m_code_generator_ptr->GetModule();
491
492 if (!module)
493 {
494 if (log)
495 log->Printf("IR doesn't contain a module");
496
497 return 1;
498 }
499
Sean Callanan8bce6652010-07-13 21:41:46 +0000500 llvm::Triple target_triple = m_clang_ap->getTarget().getTriple();
501
502 std::string err;
503
504 const llvm::Target *target = llvm::TargetRegistry::lookupTarget(m_target_triple, err);
505
506 if (!target)
507 {
508 if (log)
509 log->Printf("Couldn't find a target for %s", m_target_triple.c_str());
510
511 return 1;
512 }
513
514 std::auto_ptr<llvm::TargetMachine> target_machine(target->createTargetMachine(m_target_triple, ""));
515
516 IRForTarget ir_for_target("IR for target", m_decl_map, target_machine->getTargetData());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000517
518 return ir_for_target.runOnModule(*module);
519}
520
521bool
Chris Lattner24943d22010-06-08 16:52:24 +0000522ClangExpression::JITFunction (const ExecutionContext &exc_context, const char *name)
523{
Sean Callanan321fe9e2010-07-28 01:00:59 +0000524 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
Chris Lattner24943d22010-06-08 16:52:24 +0000525
526 llvm::Module *module = m_code_generator_ptr->GetModule();
527
528 if (module)
529 {
530 std::string error;
531
532 if (m_jit_mm_ptr == NULL)
533 m_jit_mm_ptr = new RecordingMemoryManager();
534
535 //llvm::InitializeNativeTarget();
Sean Callanan321fe9e2010-07-28 01:00:59 +0000536
537 if (log)
538 {
539 const char *relocation_model_string;
540
541 switch (llvm::TargetMachine::getRelocationModel())
542 {
Sean Callanan1e7089a2010-07-29 19:03:08 +0000543 case llvm::Reloc::Default:
544 relocation_model_string = "Default";
545 break;
546 case llvm::Reloc::Static:
547 relocation_model_string = "Static";
548 break;
549 case llvm::Reloc::PIC_:
550 relocation_model_string = "PIC_";
551 break;
552 case llvm::Reloc::DynamicNoPIC:
553 relocation_model_string = "DynamicNoPIC";
554 break;
Sean Callanan321fe9e2010-07-28 01:00:59 +0000555 }
556
557 log->Printf("Target machine's relocation model: %s", relocation_model_string);
558 }
Sean Callanan1e7089a2010-07-29 19:03:08 +0000559
560 if (m_execution_engine.get() == 0)
561 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
562 &error,
563 m_jit_mm_ptr,
564 CodeGenOpt::Default,
565 true,
566 CodeModel::Small)); // set to small so RIP-relative relocations work in PIC
567
568 m_execution_engine->DisableLazyCompilation();
569 llvm::Function *function = module->getFunction (llvm::StringRef (name));
Sean Callanan321fe9e2010-07-28 01:00:59 +0000570
Chris Lattner24943d22010-06-08 16:52:24 +0000571 // We don't actually need the function pointer here, this just forces it to get resolved.
572 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
573 // Note, you probably won't get here on error, since the LLVM JIT tends to just
574 // exit on error at present... So be careful.
575 if (fun_ptr == 0)
576 return false;
577 m_jitted_functions.push_back(ClangExpression::JittedFunction(name, (lldb::addr_t) fun_ptr));
578
579 }
580 return true;
581}
582
583bool
584ClangExpression::WriteJITCode (const ExecutionContext &exc_context)
585{
Sean Callanan321fe9e2010-07-28 01:00:59 +0000586 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
587
Chris Lattner24943d22010-06-08 16:52:24 +0000588 if (m_jit_mm_ptr == NULL)
589 return false;
590
591 if (exc_context.process == NULL)
592 return false;
593
594 // Look over the regions allocated for the function compiled. The JIT
595 // tries to allocate the functions & stubs close together, so we should try to
596 // write them that way too...
597 // For now I only write functions with no stubs, globals, exception tables,
598 // etc. So I only need to write the functions.
599
Greg Claytonbef15832010-07-14 00:18:15 +0000600 size_t alloc_size = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000601 std::map<uint8_t *, uint8_t *>::iterator fun_pos, fun_end = m_jit_mm_ptr->m_functions.end();
602 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
603 {
Greg Claytonbef15832010-07-14 00:18:15 +0000604 alloc_size += (*fun_pos).second - (*fun_pos).first;
Chris Lattner24943d22010-06-08 16:52:24 +0000605 }
606
607 Error error;
Greg Claytonbef15832010-07-14 00:18:15 +0000608 lldb::addr_t target_addr = exc_context.process->AllocateMemory (alloc_size, lldb::ePermissionsReadable|lldb::ePermissionsExecutable, error);
Chris Lattner24943d22010-06-08 16:52:24 +0000609
610 if (target_addr == LLDB_INVALID_ADDRESS)
611 return false;
612
613 lldb::addr_t cursor = target_addr;
614 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
615 {
Sean Callanan321fe9e2010-07-28 01:00:59 +0000616 if (log)
617 log->Printf("Reading [%p-%p] from m_functions", fun_pos->first, fun_pos->second);
618
Chris Lattner24943d22010-06-08 16:52:24 +0000619 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
620 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
621 size_t size = lend - lstart;
622 exc_context.process->WriteMemory(cursor, (void *) lstart, size, error);
623 m_jit_mm_ptr->AddToLocalToRemoteMap (lstart, size, cursor);
624 cursor += size;
625 }
626
627 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
628
629 for (pos = m_jitted_functions.begin(); pos != end; pos++)
630 {
631 (*pos).m_remote_addr = m_jit_mm_ptr->GetRemoteAddressForLocal ((*pos).m_local_addr);
632 }
633 return true;
634}
635
636lldb::addr_t
637ClangExpression::GetFunctionAddress (const char *name)
638{
639 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
640
641 for (pos = m_jitted_functions.begin(); pos < end; pos++)
642 {
643 if (strcmp ((*pos).m_name.c_str(), name) == 0)
644 return (*pos).m_remote_addr;
645 }
646 return LLDB_INVALID_ADDRESS;
647}
648
Sean Callanan8541f2f2010-07-23 02:19:15 +0000649Error
650ClangExpression::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, const char *name)
651{
652 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
653
654 Error ret;
655
656 ret.Clear();
657
658 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
659 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
660
661 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
662
663 for (pos = m_jitted_functions.begin(); pos < end; pos++)
664 {
665 if (strcmp(pos->m_name.c_str(), name) == 0)
666 {
667 func_local_addr = pos->m_local_addr;
668 func_remote_addr = pos->m_remote_addr;
669 }
670 }
671
672 if (func_local_addr == LLDB_INVALID_ADDRESS)
673 {
674 ret.SetErrorToGenericError();
675 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
676 return ret;
677 }
678
679 if(log)
680 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
681
682 std::pair <lldb::addr_t, lldb::addr_t> func_range;
683
684 func_range = m_jit_mm_ptr->GetRemoteRangeForLocal(func_local_addr);
685
686 if (func_range.first == 0 && func_range.second == 0)
687 {
688 ret.SetErrorToGenericError();
689 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
690 return ret;
691 }
692
693 if(log)
694 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
695
696 if (!exe_ctx.target)
697 {
698 ret.SetErrorToGenericError();
699 ret.SetErrorString("Couldn't find the target");
700 }
701
Sean Callanan32824aa2010-07-23 22:19:18 +0000702 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
Sean Callanan8541f2f2010-07-23 02:19:15 +0000703
704 Error err;
Sean Callanan32824aa2010-07-23 22:19:18 +0000705 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
Sean Callanan8541f2f2010-07-23 02:19:15 +0000706
707 if (!err.Success())
708 {
709 ret.SetErrorToGenericError();
710 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
711 return ret;
712 }
713
714 ArchSpec arch(exe_ctx.target->GetArchitecture());
715
716 Disassembler *disassembler = Disassembler::FindPlugin(arch);
717
718 if (disassembler == NULL)
719 {
720 ret.SetErrorToGenericError();
721 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.AsCString());
722 return ret;
723 }
724
725 if (!exe_ctx.process)
726 {
727 ret.SetErrorToGenericError();
728 ret.SetErrorString("Couldn't find the process");
729 return ret;
730 }
731
732 DataExtractor extractor(buffer_sp,
733 exe_ctx.process->GetByteOrder(),
Sean Callanan32824aa2010-07-23 22:19:18 +0000734 exe_ctx.target->GetArchitecture().GetAddressByteSize());
Sean Callanan8541f2f2010-07-23 02:19:15 +0000735
736 if(log)
737 {
738 log->Printf("Function data has contents:");
739 extractor.PutToLog (log,
740 0,
741 extractor.GetByteSize(),
Sean Callanan32824aa2010-07-23 22:19:18 +0000742 func_remote_addr,
Sean Callanan8541f2f2010-07-23 02:19:15 +0000743 16,
744 DataExtractor::TypeUInt8);
745 }
746
747 disassembler->DecodeInstructions(extractor, 0, UINT32_MAX);
748
749 Disassembler::InstructionList &instruction_list = disassembler->GetInstructionList();
750
751 uint32_t bytes_offset = 0;
752
753 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
754 instruction_index < num_instructions;
755 ++instruction_index)
756 {
757 Disassembler::Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index);
Sean Callanan32824aa2010-07-23 22:19:18 +0000758 Address addr(NULL, func_remote_addr + bytes_offset);
Sean Callanan8541f2f2010-07-23 02:19:15 +0000759 instruction->Dump (&stream,
Sean Callanan32824aa2010-07-23 22:19:18 +0000760 &addr,
Sean Callanan8541f2f2010-07-23 02:19:15 +0000761 &extractor,
762 bytes_offset,
763 exe_ctx,
764 true);
765 stream.PutChar('\n');
766 bytes_offset += instruction->GetByteSize();
767 }
768
769 return ret;
770}
771
Chris Lattner24943d22010-06-08 16:52:24 +0000772unsigned
773ClangExpression::Compile()
774{
775 Mutex::Locker locker(GetClangMutex ());
776 bool IsAST = false;
777
778 if (CreateCompilerInstance(IsAST))
779 {
780 // Validate/process some options
781 if (m_clang_ap->getHeaderSearchOpts().Verbose)
782 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
783 << " based upon " << PACKAGE_STRING
784 << " hosted on " << llvm::sys::getHostTriple() << "\n";
785
786 // Enforce certain implications.
787 if (!m_clang_ap->getFrontendOpts().ViewClassInheritance.empty())
788 m_clang_ap->getFrontendOpts().ProgramAction = frontend::InheritanceView;
789// if (!compiler_instance->getFrontendOpts().FixItSuffix.empty())
790// compiler_instance->getFrontendOpts().ProgramAction = frontend::FixIt;
791
792 for (unsigned i = 0, e = m_clang_ap->getFrontendOpts().Inputs.size(); i != e; ++i) {
Chris Lattner24943d22010-06-08 16:52:24 +0000793
794 // If we aren't using an AST file, setup the file and source managers and
795 // the preprocessor.
796 if (!IsAST) {
797 if (!i) {
798 // Create a file manager object to provide access to and cache the
799 // filesystem.
800 m_clang_ap->createFileManager();
801
802 // Create the source manager.
803 m_clang_ap->createSourceManager();
804 } else {
805 // Reset the ID tables if we are reusing the SourceManager.
806 m_clang_ap->getSourceManager().clearIDTables();
807 }
808
809 // Create the preprocessor.
810 m_clang_ap->createPreprocessor();
811 }
812
813 llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(*m_clang_ap.get()));
814 if (!Act)
815 break;
816
Greg Claytone41c4b22010-06-13 17:34:29 +0000817 if (Act->BeginSourceFile(*m_clang_ap,
818 m_clang_ap->getFrontendOpts().Inputs[i].second,
819 m_clang_ap->getFrontendOpts().Inputs[i].first)) {
Chris Lattner24943d22010-06-08 16:52:24 +0000820 Act->Execute();
821 Act->EndSourceFile();
822 }
823 }
824
825 if (m_clang_ap->getDiagnosticOpts().ShowCarets)
826 {
827 unsigned NumWarnings = m_clang_ap->getDiagnostics().getNumWarnings();
828 unsigned NumErrors = m_clang_ap->getDiagnostics().getNumErrors() -
829 m_clang_ap->getDiagnostics().getNumErrorsSuppressed();
830
831 if (NumWarnings || NumErrors)
832 {
833 if (NumWarnings)
834 fprintf (stderr, "%u warning%s%s", NumWarnings, (NumWarnings == 1 ? "" : "s"), (NumErrors ? " and " : ""));
835 if (NumErrors)
836 fprintf (stderr, "%u error%s", NumErrors, (NumErrors == 1 ? "" : "s"));
837 fprintf (stderr, " generated.\n");
838 }
839 }
840
841 if (m_clang_ap->getFrontendOpts().ShowStats) {
842 m_clang_ap->getFileManager().PrintStats();
843 fprintf(stderr, "\n");
844 }
845
846 // Return the appropriate status when verifying diagnostics.
847 //
848 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
849 // this.
850 if (m_clang_ap->getDiagnosticOpts().VerifyDiagnostics)
851 return static_cast<VerifyDiagnosticsClient&>(m_clang_ap->getDiagnosticClient()).HadErrors();
852
853 return m_clang_ap->getDiagnostics().getNumErrors();
854 }
855 return 1;
856}