blob: d338a09cf62522ea4d071b316c51e76c4db89e28 [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
110void LLVMErrorHandler(void *UserData, const std::string &Message) {
111 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
112
113 Diags.Report(diag::err_fe_error_backend) << Message;
114
115 // We cannot recover from llvm errors.
116 exit(1);
117}
118
119static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
120 using namespace clang::frontend;
121
122 switch (CI.getFrontendOpts().ProgramAction) {
123 default:
124 llvm_unreachable("Invalid program action!");
125
126 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 DumpRawTokens: return new DumpRawTokensAction();
131 case DumpTokens: return new DumpTokensAction();
132 case EmitAssembly: return new EmitAssemblyAction();
133 case EmitBC: return new EmitBCAction();
134 case EmitHTML: return new HTMLPrintAction();
135 case EmitLLVM: return new EmitLLVMAction();
136 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
137 case EmitObj: return new EmitObjAction();
138 case FixIt: return new FixItAction();
139 case GeneratePCH: return new GeneratePCHAction();
140 case GeneratePTH: return new GeneratePTHAction();
141 case InheritanceView: return new InheritanceViewAction();
142 case InitOnly: return new InitOnlyAction();
143 case ParseNoop: return new ParseOnlyAction();
144 case ParsePrintCallbacks: return new PrintParseAction();
145 case ParseSyntaxOnly: return new SyntaxOnlyAction();
146
147 case PluginAction: {
148 if (CI.getFrontendOpts().ActionName == "help") {
149 llvm::errs() << "clang -cc1 plugins:\n";
150 for (FrontendPluginRegistry::iterator it =
151 FrontendPluginRegistry::begin(),
152 ie = FrontendPluginRegistry::end();
153 it != ie; ++it)
154 llvm::errs() << " " << it->getName() << " - " << it->getDesc() << "\n";
155 return 0;
156 }
157
158 for (FrontendPluginRegistry::iterator it =
159 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
160 it != ie; ++it) {
161 if (it->getName() == CI.getFrontendOpts().ActionName)
162 return it->instantiate();
163 }
164
165 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
166 << CI.getFrontendOpts().ActionName;
167 return 0;
168 }
169
170 case PrintDeclContext: return new DeclContextPrintAction();
171 case PrintPreprocessedInput: return new PrintPreprocessedAction();
172 case RewriteMacros: return new RewriteMacrosAction();
173 case RewriteObjC: return new RewriteObjCAction();
174 case RewriteTest: return new RewriteTestAction();
175 case RunAnalysis: return new AnalysisAction();
176 case RunPreprocessorOnly: return new PreprocessOnlyAction();
177 }
178}
179
180//----------------------------------------------------------------------
181// ClangExpression constructor
182//----------------------------------------------------------------------
183ClangExpression::ClangExpression(const char *target_triple,
184 ClangExpressionDeclMap *decl_map) :
185 m_target_triple (),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000186 m_decl_map (decl_map),
187 m_clang_ap (),
Chris Lattner24943d22010-06-08 16:52:24 +0000188 m_code_generator_ptr (NULL),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000189 m_jit_mm_ptr (NULL),
190 m_execution_engine (),
191 m_jitted_functions ()
Chris Lattner24943d22010-06-08 16:52:24 +0000192{
193 if (target_triple && target_triple[0])
194 m_target_triple = target_triple;
195 else
196 m_target_triple = llvm::sys::getHostTriple();
197}
198
199
200//----------------------------------------------------------------------
201// Destructor
202//----------------------------------------------------------------------
203ClangExpression::~ClangExpression()
204{
205 if (m_code_generator_ptr && !m_execution_engine.get())
206 delete m_code_generator_ptr;
207}
208
209bool
210ClangExpression::CreateCompilerInstance (bool &IsAST)
211{
212 // Initialize targets first, so that --version shows registered targets.
213 static struct InitializeLLVM {
214 InitializeLLVM() {
215 llvm::InitializeAllTargets();
216 llvm::InitializeAllAsmPrinters();
217 }
218 } InitializeLLVM;
219
220 // 1. Create a new compiler instance.
221 m_clang_ap.reset(new CompilerInstance());
222 m_clang_ap->setLLVMContext(new LLVMContext());
223
224 // 2. Set options.
225
226 // Parse expressions as Objective C++ regardless of context.
227 // Our hook into Clang's lookup mechanism only works in C++.
228 m_clang_ap->getLangOpts().CPlusPlus = true;
229 m_clang_ap->getLangOpts().ObjC1 = true;
Sean Callanan051052f2010-07-02 22:22:28 +0000230 m_clang_ap->getLangOpts().ThreadsafeStatics = false;
Sean Callanan8bce6652010-07-13 21:41:46 +0000231
232 // Set CodeGen options
233 m_clang_ap->getCodeGenOpts().EmitDeclMetadata = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000234
235 // Disable some warnings.
236 m_clang_ap->getDiagnosticOpts().Warnings.push_back("no-unused-value");
237
238 // Set the target triple.
239 m_clang_ap->getTargetOpts().Triple = m_target_triple;
240
241 // 3. Set up various important bits of infrastructure.
242
243 m_clang_ap->createDiagnostics(0, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000244
245 // Create the target instance.
246 m_clang_ap->setTarget(TargetInfo::CreateTargetInfo(m_clang_ap->getDiagnostics(),
247 m_clang_ap->getTargetOpts()));
248 if (!m_clang_ap->hasTarget())
249 {
250 m_clang_ap.reset();
251 return false;
252 }
253
254 // Inform the target of the language options
255 //
256 // FIXME: We shouldn't need to do this, the target should be immutable once
257 // created. This complexity should be lifted elsewhere.
258 m_clang_ap->getTarget().setForcedLangOptions(m_clang_ap->getLangOpts());
259
260 return m_clang_ap.get();
261}
262
263Mutex &
264ClangExpression::GetClangMutex ()
265{
266 static Mutex g_clang_mutex(Mutex::eMutexTypeRecursive); // Control access to the clang compiler
267 return g_clang_mutex;
268}
269
270
271clang::ASTContext *
272ClangExpression::GetASTContext ()
273{
274 CompilerInstance *compiler_instance = GetCompilerInstance();
275 if (compiler_instance)
276 return &compiler_instance->getASTContext();
277 return NULL;
278}
279
280unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000281ClangExpression::ParseExpression (const char *expr_text,
282 Stream &stream,
283 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000284{
285 // HACK: for now we have to make a function body around our expression
286 // since there is no way to parse a single expression line in LLVM/Clang.
Sean Callanan8bce6652010-07-13 21:41:46 +0000287 std::string func_expr("extern \"C\" void ___clang_expr(void *___clang_arg)\n{\n\t");
Chris Lattner24943d22010-06-08 16:52:24 +0000288 func_expr.append(expr_text);
289 func_expr.append(";\n}");
Sean Callanan8c6934d2010-07-01 20:08:22 +0000290 return ParseBareExpression (func_expr, stream, add_result_var);
Chris Lattner24943d22010-06-08 16:52:24 +0000291
292}
293
294unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000295ClangExpression::ParseBareExpression (llvm::StringRef expr_text,
296 Stream &stream,
297 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000298{
299 Mutex::Locker locker(GetClangMutex ());
300
301 TextDiagnosticBuffer text_diagnostic_buffer;
302
303 bool IsAST = false;
304 if (!CreateCompilerInstance (IsAST))
305 {
306 stream.Printf("error: couldn't create compiler instance\n");
307 return 1;
308 }
309
310 // This code is matched below by a setClient to NULL.
311 // We cannot return out of this code without doing that.
312 m_clang_ap->getDiagnostics().setClient(&text_diagnostic_buffer);
313 text_diagnostic_buffer.FlushDiagnostics (m_clang_ap->getDiagnostics());
314
315 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
316
317 if (!m_clang_ap->hasSourceManager())
318 m_clang_ap->createSourceManager();
319
320 m_clang_ap->createFileManager();
321 m_clang_ap->createPreprocessor();
322
323 // Build the ASTContext. Most of this we inherit from the
324 // CompilerInstance, but we also want to give the context
325 // an ExternalASTSource.
326 SelectorTable selector_table;
327 std::auto_ptr<Builtin::Context> builtin_ap(new Builtin::Context(m_clang_ap->getTarget()));
328 ASTContext *Context = new ASTContext(m_clang_ap->getLangOpts(),
329 m_clang_ap->getSourceManager(),
330 m_clang_ap->getTarget(),
331 m_clang_ap->getPreprocessor().getIdentifierTable(),
332 selector_table,
333 *builtin_ap.get());
334
335 llvm::OwningPtr<ExternalASTSource> ASTSource(new ClangASTSource(*Context, *m_decl_map));
336
337 if (m_decl_map)
338 {
339 Context->setExternalSource(ASTSource);
340 }
341
342 m_clang_ap->setASTContext(Context);
343
344 FileID memory_buffer_file_id = m_clang_ap->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
345 std::string module_name("test_func");
346 text_diagnostic_buffer.BeginSourceFile(m_clang_ap->getLangOpts(), &m_clang_ap->getPreprocessor());
347
348 if (m_code_generator_ptr)
349 delete m_code_generator_ptr;
350
351 m_code_generator_ptr = CreateLLVMCodeGen(m_clang_ap->getDiagnostics(),
352 module_name,
353 m_clang_ap->getCodeGenOpts(),
354 m_clang_ap->getLLVMContext());
355
356
357 // - CodeGeneration ASTConsumer (include/clang/ModuleBuilder.h), which will be passed in when you call...
358 // - Call clang::ParseAST (in lib/Sema/ParseAST.cpp) to parse the buffer. The CodeGenerator will generate code for __dbg_expr.
359 // - 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 +0000360
361 if (add_result_var)
362 {
363 ClangResultSynthesizer result_synthesizer(m_code_generator_ptr);
364 ParseAST(m_clang_ap->getPreprocessor(), &result_synthesizer, m_clang_ap->getASTContext());
365 }
366 else
367 {
368 ParseAST(m_clang_ap->getPreprocessor(), m_code_generator_ptr, m_clang_ap->getASTContext());
369 }
370
Sean Callanan848960c2010-06-23 23:18:04 +0000371
Chris Lattner24943d22010-06-08 16:52:24 +0000372 text_diagnostic_buffer.EndSourceFile();
373
374 //compiler_instance->getASTContext().getTranslationUnitDecl()->dump();
375
376 //if (compiler_instance->getFrontendOpts().ShowStats) {
377 // compiler_instance->getFileManager().PrintStats();
378 // fprintf(stderr, "\n");
379 //}
380
381 // This code resolves the setClient above.
382 m_clang_ap->getDiagnostics().setClient(0);
383
384 TextDiagnosticBuffer::const_iterator diag_iterator;
385
386 int num_errors = 0;
387
388#ifdef COUNT_WARNINGS_AND_ERRORS
389 int num_warnings = 0;
390
391 for (diag_iterator = text_diagnostic_buffer.warn_begin();
392 diag_iterator != text_diagnostic_buffer.warn_end();
393 ++diag_iterator)
394 num_warnings++;
395
396 for (diag_iterator = text_diagnostic_buffer.err_begin();
397 diag_iterator != text_diagnostic_buffer.err_end();
398 ++diag_iterator)
399 num_errors++;
400
401 if (num_warnings || num_errors)
402 {
403 if (num_warnings)
404 stream.Printf("%u warning%s%s", num_warnings, (num_warnings == 1 ? "" : "s"), (num_errors ? " and " : ""));
405 if (num_errors)
406 stream.Printf("%u error%s", num_errors, (num_errors == 1 ? "" : "s"));
407 stream.Printf("\n");
408 }
409#endif
410
411 for (diag_iterator = text_diagnostic_buffer.warn_begin();
412 diag_iterator != text_diagnostic_buffer.warn_end();
413 ++diag_iterator)
414 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
415
416 num_errors = 0;
417
418 for (diag_iterator = text_diagnostic_buffer.err_begin();
419 diag_iterator != text_diagnostic_buffer.err_end();
420 ++diag_iterator)
421 {
422 num_errors++;
423 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
424 }
425
426 return num_errors;
427}
428
Chris Lattner24943d22010-06-08 16:52:24 +0000429static FrontendAction *
430CreateFrontendAction(CompilerInstance &CI)
431{
432 // Create the underlying action.
433 FrontendAction *Act = CreateFrontendBaseAction(CI);
434 if (!Act)
435 return 0;
436
437 // If there are any AST files to merge, create a frontend action
438 // adaptor to perform the merge.
439 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
440 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
441 CI.getFrontendOpts().ASTMergeFiles.size());
442
443 return Act;
444}
445
446
447unsigned
448ClangExpression::ConvertExpressionToDWARF (ClangExpressionVariableList& expr_local_variable_list,
449 StreamString &dwarf_opcode_strm)
450{
451 CompilerInstance *compiler_instance = GetCompilerInstance();
452
453 DeclarationName hack_func_name(&compiler_instance->getASTContext().Idents.get("___clang_expr"));
454 DeclContext::lookup_result result = compiler_instance->getASTContext().getTranslationUnitDecl()->lookup(hack_func_name);
455
456 if (result.first != result.second)
457 {
458 Decl *decl = *result.first;
459 Stmt *decl_stmt = decl->getBody();
460 if (decl_stmt)
461 {
462 ClangStmtVisitor visitor(compiler_instance->getASTContext(), expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
463
464 visitor.Visit (decl_stmt);
465 }
466 }
467 return 0;
468}
469
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000470bool
Sean Callanandcb658b2010-07-02 21:09:36 +0000471ClangExpression::ConvertIRToDWARF (ClangExpressionVariableList &expr_local_variable_list,
Sean Callanan848960c2010-06-23 23:18:04 +0000472 StreamString &dwarf_opcode_strm)
473{
474 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
475
476 llvm::Module *module = m_code_generator_ptr->GetModule();
477
478 if (!module)
479 {
480 if (log)
481 log->Printf("IR doesn't contain a module");
482
483 return 1;
484 }
485
Sean Callanandcb658b2010-07-02 21:09:36 +0000486 IRToDWARF ir_to_dwarf("IR to DWARF", expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
Sean Callanan8c6934d2010-07-01 20:08:22 +0000487
Sean Callanandcb658b2010-07-02 21:09:36 +0000488 return ir_to_dwarf.runOnModule(*module);
Sean Callanan848960c2010-06-23 23:18:04 +0000489}
490
Chris Lattner24943d22010-06-08 16:52:24 +0000491bool
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000492ClangExpression::PrepareIRForTarget (ClangExpressionVariableList &expr_local_variable_list)
493{
494 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
495
496 llvm::Module *module = m_code_generator_ptr->GetModule();
497
498 if (!module)
499 {
500 if (log)
501 log->Printf("IR doesn't contain a module");
502
503 return 1;
504 }
505
Sean Callanan8bce6652010-07-13 21:41:46 +0000506 llvm::Triple target_triple = m_clang_ap->getTarget().getTriple();
507
508 std::string err;
509
510 const llvm::Target *target = llvm::TargetRegistry::lookupTarget(m_target_triple, err);
511
512 if (!target)
513 {
514 if (log)
515 log->Printf("Couldn't find a target for %s", m_target_triple.c_str());
516
517 return 1;
518 }
519
520 std::auto_ptr<llvm::TargetMachine> target_machine(target->createTargetMachine(m_target_triple, ""));
521
522 IRForTarget ir_for_target("IR for target", m_decl_map, target_machine->getTargetData());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000523
524 return ir_for_target.runOnModule(*module);
525}
526
527bool
Chris Lattner24943d22010-06-08 16:52:24 +0000528ClangExpression::JITFunction (const ExecutionContext &exc_context, const char *name)
529{
Sean Callanan321fe9e2010-07-28 01:00:59 +0000530 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
Chris Lattner24943d22010-06-08 16:52:24 +0000531
532 llvm::Module *module = m_code_generator_ptr->GetModule();
533
534 if (module)
535 {
536 std::string error;
537
538 if (m_jit_mm_ptr == NULL)
539 m_jit_mm_ptr = new RecordingMemoryManager();
540
541 //llvm::InitializeNativeTarget();
Sean Callanan321fe9e2010-07-28 01:00:59 +0000542
Chris Lattner24943d22010-06-08 16:52:24 +0000543 if (m_execution_engine.get() == 0)
Sean Callanan321fe9e2010-07-28 01:00:59 +0000544 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
545 &error,
546 m_jit_mm_ptr,
547 CodeGenOpt::Default,
548 true,
549 CodeModel::Default));
550
Chris Lattner24943d22010-06-08 16:52:24 +0000551 m_execution_engine->DisableLazyCompilation();
552 llvm::Function *function = module->getFunction (llvm::StringRef (name));
Sean Callanan321fe9e2010-07-28 01:00:59 +0000553
554 if (log)
555 {
556 const char *relocation_model_string;
557
558 switch (llvm::TargetMachine::getRelocationModel())
559 {
560 case llvm::Reloc::Default:
561 relocation_model_string = "Default";
562 break;
563 case llvm::Reloc::Static:
564 relocation_model_string = "Static";
565 break;
566 case llvm::Reloc::PIC_:
567 relocation_model_string = "PIC_++";
568 break;
569 case llvm::Reloc::DynamicNoPIC:
570 relocation_model_string = "DynamicNoPIC";
571 break;
572 }
573
574 log->Printf("Target machine's relocation model: %s", relocation_model_string);
575 }
576
Chris Lattner24943d22010-06-08 16:52:24 +0000577 // We don't actually need the function pointer here, this just forces it to get resolved.
578 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
579 // Note, you probably won't get here on error, since the LLVM JIT tends to just
580 // exit on error at present... So be careful.
581 if (fun_ptr == 0)
582 return false;
583 m_jitted_functions.push_back(ClangExpression::JittedFunction(name, (lldb::addr_t) fun_ptr));
584
585 }
586 return true;
587}
588
589bool
590ClangExpression::WriteJITCode (const ExecutionContext &exc_context)
591{
Sean Callanan321fe9e2010-07-28 01:00:59 +0000592 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
593
Chris Lattner24943d22010-06-08 16:52:24 +0000594 if (m_jit_mm_ptr == NULL)
595 return false;
596
597 if (exc_context.process == NULL)
598 return false;
599
600 // Look over the regions allocated for the function compiled. The JIT
601 // tries to allocate the functions & stubs close together, so we should try to
602 // write them that way too...
603 // For now I only write functions with no stubs, globals, exception tables,
604 // etc. So I only need to write the functions.
605
Greg Claytonbef15832010-07-14 00:18:15 +0000606 size_t alloc_size = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000607 std::map<uint8_t *, uint8_t *>::iterator fun_pos, fun_end = m_jit_mm_ptr->m_functions.end();
608 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
609 {
Greg Claytonbef15832010-07-14 00:18:15 +0000610 alloc_size += (*fun_pos).second - (*fun_pos).first;
Chris Lattner24943d22010-06-08 16:52:24 +0000611 }
612
613 Error error;
Greg Claytonbef15832010-07-14 00:18:15 +0000614 lldb::addr_t target_addr = exc_context.process->AllocateMemory (alloc_size, lldb::ePermissionsReadable|lldb::ePermissionsExecutable, error);
Chris Lattner24943d22010-06-08 16:52:24 +0000615
616 if (target_addr == LLDB_INVALID_ADDRESS)
617 return false;
618
619 lldb::addr_t cursor = target_addr;
620 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
621 {
Sean Callanan321fe9e2010-07-28 01:00:59 +0000622 if (log)
623 log->Printf("Reading [%p-%p] from m_functions", fun_pos->first, fun_pos->second);
624
Chris Lattner24943d22010-06-08 16:52:24 +0000625 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
626 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
627 size_t size = lend - lstart;
628 exc_context.process->WriteMemory(cursor, (void *) lstart, size, error);
629 m_jit_mm_ptr->AddToLocalToRemoteMap (lstart, size, cursor);
630 cursor += size;
631 }
632
633 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
634
635 for (pos = m_jitted_functions.begin(); pos != end; pos++)
636 {
637 (*pos).m_remote_addr = m_jit_mm_ptr->GetRemoteAddressForLocal ((*pos).m_local_addr);
638 }
639 return true;
640}
641
642lldb::addr_t
643ClangExpression::GetFunctionAddress (const char *name)
644{
645 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
646
647 for (pos = m_jitted_functions.begin(); pos < end; pos++)
648 {
649 if (strcmp ((*pos).m_name.c_str(), name) == 0)
650 return (*pos).m_remote_addr;
651 }
652 return LLDB_INVALID_ADDRESS;
653}
654
Sean Callanan8541f2f2010-07-23 02:19:15 +0000655Error
656ClangExpression::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, const char *name)
657{
658 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
659
660 Error ret;
661
662 ret.Clear();
663
664 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
665 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
666
667 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
668
669 for (pos = m_jitted_functions.begin(); pos < end; pos++)
670 {
671 if (strcmp(pos->m_name.c_str(), name) == 0)
672 {
673 func_local_addr = pos->m_local_addr;
674 func_remote_addr = pos->m_remote_addr;
675 }
676 }
677
678 if (func_local_addr == LLDB_INVALID_ADDRESS)
679 {
680 ret.SetErrorToGenericError();
681 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
682 return ret;
683 }
684
685 if(log)
686 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
687
688 std::pair <lldb::addr_t, lldb::addr_t> func_range;
689
690 func_range = m_jit_mm_ptr->GetRemoteRangeForLocal(func_local_addr);
691
692 if (func_range.first == 0 && func_range.second == 0)
693 {
694 ret.SetErrorToGenericError();
695 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
696 return ret;
697 }
698
699 if(log)
700 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
701
702 if (!exe_ctx.target)
703 {
704 ret.SetErrorToGenericError();
705 ret.SetErrorString("Couldn't find the target");
706 }
707
Sean Callanan32824aa2010-07-23 22:19:18 +0000708 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
Sean Callanan8541f2f2010-07-23 02:19:15 +0000709
710 Error err;
Sean Callanan32824aa2010-07-23 22:19:18 +0000711 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
Sean Callanan8541f2f2010-07-23 02:19:15 +0000712
713 if (!err.Success())
714 {
715 ret.SetErrorToGenericError();
716 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
717 return ret;
718 }
719
720 ArchSpec arch(exe_ctx.target->GetArchitecture());
721
722 Disassembler *disassembler = Disassembler::FindPlugin(arch);
723
724 if (disassembler == NULL)
725 {
726 ret.SetErrorToGenericError();
727 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.AsCString());
728 return ret;
729 }
730
731 if (!exe_ctx.process)
732 {
733 ret.SetErrorToGenericError();
734 ret.SetErrorString("Couldn't find the process");
735 return ret;
736 }
737
738 DataExtractor extractor(buffer_sp,
739 exe_ctx.process->GetByteOrder(),
Sean Callanan32824aa2010-07-23 22:19:18 +0000740 exe_ctx.target->GetArchitecture().GetAddressByteSize());
Sean Callanan8541f2f2010-07-23 02:19:15 +0000741
742 if(log)
743 {
744 log->Printf("Function data has contents:");
745 extractor.PutToLog (log,
746 0,
747 extractor.GetByteSize(),
Sean Callanan32824aa2010-07-23 22:19:18 +0000748 func_remote_addr,
Sean Callanan8541f2f2010-07-23 02:19:15 +0000749 16,
750 DataExtractor::TypeUInt8);
751 }
752
753 disassembler->DecodeInstructions(extractor, 0, UINT32_MAX);
754
755 Disassembler::InstructionList &instruction_list = disassembler->GetInstructionList();
756
757 uint32_t bytes_offset = 0;
758
759 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
760 instruction_index < num_instructions;
761 ++instruction_index)
762 {
763 Disassembler::Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index);
Sean Callanan32824aa2010-07-23 22:19:18 +0000764 Address addr(NULL, func_remote_addr + bytes_offset);
Sean Callanan8541f2f2010-07-23 02:19:15 +0000765 instruction->Dump (&stream,
Sean Callanan32824aa2010-07-23 22:19:18 +0000766 &addr,
Sean Callanan8541f2f2010-07-23 02:19:15 +0000767 &extractor,
768 bytes_offset,
769 exe_ctx,
770 true);
771 stream.PutChar('\n');
772 bytes_offset += instruction->GetByteSize();
773 }
774
775 return ret;
776}
777
Chris Lattner24943d22010-06-08 16:52:24 +0000778unsigned
779ClangExpression::Compile()
780{
781 Mutex::Locker locker(GetClangMutex ());
782 bool IsAST = false;
783
784 if (CreateCompilerInstance(IsAST))
785 {
786 // Validate/process some options
787 if (m_clang_ap->getHeaderSearchOpts().Verbose)
788 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
789 << " based upon " << PACKAGE_STRING
790 << " hosted on " << llvm::sys::getHostTriple() << "\n";
791
792 // Enforce certain implications.
793 if (!m_clang_ap->getFrontendOpts().ViewClassInheritance.empty())
794 m_clang_ap->getFrontendOpts().ProgramAction = frontend::InheritanceView;
795// if (!compiler_instance->getFrontendOpts().FixItSuffix.empty())
796// compiler_instance->getFrontendOpts().ProgramAction = frontend::FixIt;
797
798 for (unsigned i = 0, e = m_clang_ap->getFrontendOpts().Inputs.size(); i != e; ++i) {
Chris Lattner24943d22010-06-08 16:52:24 +0000799
800 // If we aren't using an AST file, setup the file and source managers and
801 // the preprocessor.
802 if (!IsAST) {
803 if (!i) {
804 // Create a file manager object to provide access to and cache the
805 // filesystem.
806 m_clang_ap->createFileManager();
807
808 // Create the source manager.
809 m_clang_ap->createSourceManager();
810 } else {
811 // Reset the ID tables if we are reusing the SourceManager.
812 m_clang_ap->getSourceManager().clearIDTables();
813 }
814
815 // Create the preprocessor.
816 m_clang_ap->createPreprocessor();
817 }
818
819 llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(*m_clang_ap.get()));
820 if (!Act)
821 break;
822
Greg Claytone41c4b22010-06-13 17:34:29 +0000823 if (Act->BeginSourceFile(*m_clang_ap,
824 m_clang_ap->getFrontendOpts().Inputs[i].second,
825 m_clang_ap->getFrontendOpts().Inputs[i].first)) {
Chris Lattner24943d22010-06-08 16:52:24 +0000826 Act->Execute();
827 Act->EndSourceFile();
828 }
829 }
830
831 if (m_clang_ap->getDiagnosticOpts().ShowCarets)
832 {
833 unsigned NumWarnings = m_clang_ap->getDiagnostics().getNumWarnings();
834 unsigned NumErrors = m_clang_ap->getDiagnostics().getNumErrors() -
835 m_clang_ap->getDiagnostics().getNumErrorsSuppressed();
836
837 if (NumWarnings || NumErrors)
838 {
839 if (NumWarnings)
840 fprintf (stderr, "%u warning%s%s", NumWarnings, (NumWarnings == 1 ? "" : "s"), (NumErrors ? " and " : ""));
841 if (NumErrors)
842 fprintf (stderr, "%u error%s", NumErrors, (NumErrors == 1 ? "" : "s"));
843 fprintf (stderr, " generated.\n");
844 }
845 }
846
847 if (m_clang_ap->getFrontendOpts().ShowStats) {
848 m_clang_ap->getFileManager().PrintStats();
849 fprintf(stderr, "\n");
850 }
851
852 // Return the appropriate status when verifying diagnostics.
853 //
854 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
855 // this.
856 if (m_clang_ap->getDiagnosticOpts().VerifyDiagnostics)
857 return static_cast<VerifyDiagnosticsClient&>(m_clang_ap->getDiagnosticClient()).HadErrors();
858
859 return m_clang_ap->getDiagnostics().getNumErrors();
860 }
861 return 1;
862}