blob: c7d58b79d4366bc7cd3e61a7cf6142abcc029f03 [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();
Sean Callanan1e7089a2010-07-29 19:03:08 +0000197
198 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
Chris Lattner24943d22010-06-08 16:52:24 +0000199}
200
201
202//----------------------------------------------------------------------
203// Destructor
204//----------------------------------------------------------------------
205ClangExpression::~ClangExpression()
206{
207 if (m_code_generator_ptr && !m_execution_engine.get())
208 delete m_code_generator_ptr;
209}
210
211bool
212ClangExpression::CreateCompilerInstance (bool &IsAST)
213{
214 // Initialize targets first, so that --version shows registered targets.
215 static struct InitializeLLVM {
216 InitializeLLVM() {
217 llvm::InitializeAllTargets();
218 llvm::InitializeAllAsmPrinters();
219 }
220 } InitializeLLVM;
221
222 // 1. Create a new compiler instance.
223 m_clang_ap.reset(new CompilerInstance());
224 m_clang_ap->setLLVMContext(new LLVMContext());
225
226 // 2. Set options.
227
228 // Parse expressions as Objective C++ regardless of context.
229 // Our hook into Clang's lookup mechanism only works in C++.
230 m_clang_ap->getLangOpts().CPlusPlus = true;
231 m_clang_ap->getLangOpts().ObjC1 = true;
Sean Callanan051052f2010-07-02 22:22:28 +0000232 m_clang_ap->getLangOpts().ThreadsafeStatics = false;
Sean Callanan8bce6652010-07-13 21:41:46 +0000233
234 // Set CodeGen options
235 m_clang_ap->getCodeGenOpts().EmitDeclMetadata = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000236
237 // Disable some warnings.
238 m_clang_ap->getDiagnosticOpts().Warnings.push_back("no-unused-value");
239
240 // Set the target triple.
241 m_clang_ap->getTargetOpts().Triple = m_target_triple;
242
243 // 3. Set up various important bits of infrastructure.
244
245 m_clang_ap->createDiagnostics(0, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000246
247 // Create the target instance.
248 m_clang_ap->setTarget(TargetInfo::CreateTargetInfo(m_clang_ap->getDiagnostics(),
249 m_clang_ap->getTargetOpts()));
250 if (!m_clang_ap->hasTarget())
251 {
252 m_clang_ap.reset();
253 return false;
254 }
255
256 // Inform the target of the language options
257 //
258 // FIXME: We shouldn't need to do this, the target should be immutable once
259 // created. This complexity should be lifted elsewhere.
260 m_clang_ap->getTarget().setForcedLangOptions(m_clang_ap->getLangOpts());
261
262 return m_clang_ap.get();
263}
264
265Mutex &
266ClangExpression::GetClangMutex ()
267{
268 static Mutex g_clang_mutex(Mutex::eMutexTypeRecursive); // Control access to the clang compiler
269 return g_clang_mutex;
270}
271
272
273clang::ASTContext *
274ClangExpression::GetASTContext ()
275{
276 CompilerInstance *compiler_instance = GetCompilerInstance();
277 if (compiler_instance)
278 return &compiler_instance->getASTContext();
279 return NULL;
280}
281
282unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000283ClangExpression::ParseExpression (const char *expr_text,
284 Stream &stream,
285 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000286{
287 // HACK: for now we have to make a function body around our expression
288 // since there is no way to parse a single expression line in LLVM/Clang.
Sean Callanan8bce6652010-07-13 21:41:46 +0000289 std::string func_expr("extern \"C\" void ___clang_expr(void *___clang_arg)\n{\n\t");
Chris Lattner24943d22010-06-08 16:52:24 +0000290 func_expr.append(expr_text);
291 func_expr.append(";\n}");
Sean Callanan8c6934d2010-07-01 20:08:22 +0000292 return ParseBareExpression (func_expr, stream, add_result_var);
Chris Lattner24943d22010-06-08 16:52:24 +0000293
294}
295
296unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000297ClangExpression::ParseBareExpression (llvm::StringRef expr_text,
298 Stream &stream,
299 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000300{
301 Mutex::Locker locker(GetClangMutex ());
302
303 TextDiagnosticBuffer text_diagnostic_buffer;
304
305 bool IsAST = false;
306 if (!CreateCompilerInstance (IsAST))
307 {
308 stream.Printf("error: couldn't create compiler instance\n");
309 return 1;
310 }
311
312 // This code is matched below by a setClient to NULL.
313 // We cannot return out of this code without doing that.
314 m_clang_ap->getDiagnostics().setClient(&text_diagnostic_buffer);
315 text_diagnostic_buffer.FlushDiagnostics (m_clang_ap->getDiagnostics());
316
317 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
318
319 if (!m_clang_ap->hasSourceManager())
320 m_clang_ap->createSourceManager();
321
322 m_clang_ap->createFileManager();
323 m_clang_ap->createPreprocessor();
324
325 // Build the ASTContext. Most of this we inherit from the
326 // CompilerInstance, but we also want to give the context
327 // an ExternalASTSource.
328 SelectorTable selector_table;
329 std::auto_ptr<Builtin::Context> builtin_ap(new Builtin::Context(m_clang_ap->getTarget()));
330 ASTContext *Context = new ASTContext(m_clang_ap->getLangOpts(),
331 m_clang_ap->getSourceManager(),
332 m_clang_ap->getTarget(),
333 m_clang_ap->getPreprocessor().getIdentifierTable(),
334 selector_table,
335 *builtin_ap.get());
336
337 llvm::OwningPtr<ExternalASTSource> ASTSource(new ClangASTSource(*Context, *m_decl_map));
338
339 if (m_decl_map)
340 {
341 Context->setExternalSource(ASTSource);
342 }
343
344 m_clang_ap->setASTContext(Context);
345
346 FileID memory_buffer_file_id = m_clang_ap->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
347 std::string module_name("test_func");
348 text_diagnostic_buffer.BeginSourceFile(m_clang_ap->getLangOpts(), &m_clang_ap->getPreprocessor());
349
350 if (m_code_generator_ptr)
351 delete m_code_generator_ptr;
352
353 m_code_generator_ptr = CreateLLVMCodeGen(m_clang_ap->getDiagnostics(),
354 module_name,
355 m_clang_ap->getCodeGenOpts(),
356 m_clang_ap->getLLVMContext());
357
358
359 // - CodeGeneration ASTConsumer (include/clang/ModuleBuilder.h), which will be passed in when you call...
360 // - Call clang::ParseAST (in lib/Sema/ParseAST.cpp) to parse the buffer. The CodeGenerator will generate code for __dbg_expr.
361 // - 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 +0000362
363 if (add_result_var)
364 {
365 ClangResultSynthesizer result_synthesizer(m_code_generator_ptr);
366 ParseAST(m_clang_ap->getPreprocessor(), &result_synthesizer, m_clang_ap->getASTContext());
367 }
368 else
369 {
370 ParseAST(m_clang_ap->getPreprocessor(), m_code_generator_ptr, m_clang_ap->getASTContext());
371 }
372
Sean Callanan848960c2010-06-23 23:18:04 +0000373
Chris Lattner24943d22010-06-08 16:52:24 +0000374 text_diagnostic_buffer.EndSourceFile();
375
376 //compiler_instance->getASTContext().getTranslationUnitDecl()->dump();
377
378 //if (compiler_instance->getFrontendOpts().ShowStats) {
379 // compiler_instance->getFileManager().PrintStats();
380 // fprintf(stderr, "\n");
381 //}
382
383 // This code resolves the setClient above.
384 m_clang_ap->getDiagnostics().setClient(0);
385
386 TextDiagnosticBuffer::const_iterator diag_iterator;
387
388 int num_errors = 0;
389
390#ifdef COUNT_WARNINGS_AND_ERRORS
391 int num_warnings = 0;
392
393 for (diag_iterator = text_diagnostic_buffer.warn_begin();
394 diag_iterator != text_diagnostic_buffer.warn_end();
395 ++diag_iterator)
396 num_warnings++;
397
398 for (diag_iterator = text_diagnostic_buffer.err_begin();
399 diag_iterator != text_diagnostic_buffer.err_end();
400 ++diag_iterator)
401 num_errors++;
402
403 if (num_warnings || num_errors)
404 {
405 if (num_warnings)
406 stream.Printf("%u warning%s%s", num_warnings, (num_warnings == 1 ? "" : "s"), (num_errors ? " and " : ""));
407 if (num_errors)
408 stream.Printf("%u error%s", num_errors, (num_errors == 1 ? "" : "s"));
409 stream.Printf("\n");
410 }
411#endif
412
413 for (diag_iterator = text_diagnostic_buffer.warn_begin();
414 diag_iterator != text_diagnostic_buffer.warn_end();
415 ++diag_iterator)
416 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
417
418 num_errors = 0;
419
420 for (diag_iterator = text_diagnostic_buffer.err_begin();
421 diag_iterator != text_diagnostic_buffer.err_end();
422 ++diag_iterator)
423 {
424 num_errors++;
425 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
426 }
427
428 return num_errors;
429}
430
Chris Lattner24943d22010-06-08 16:52:24 +0000431static FrontendAction *
432CreateFrontendAction(CompilerInstance &CI)
433{
434 // Create the underlying action.
435 FrontendAction *Act = CreateFrontendBaseAction(CI);
436 if (!Act)
437 return 0;
438
439 // If there are any AST files to merge, create a frontend action
440 // adaptor to perform the merge.
441 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
442 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
443 CI.getFrontendOpts().ASTMergeFiles.size());
444
445 return Act;
446}
447
448
449unsigned
450ClangExpression::ConvertExpressionToDWARF (ClangExpressionVariableList& expr_local_variable_list,
451 StreamString &dwarf_opcode_strm)
452{
453 CompilerInstance *compiler_instance = GetCompilerInstance();
454
455 DeclarationName hack_func_name(&compiler_instance->getASTContext().Idents.get("___clang_expr"));
456 DeclContext::lookup_result result = compiler_instance->getASTContext().getTranslationUnitDecl()->lookup(hack_func_name);
457
458 if (result.first != result.second)
459 {
460 Decl *decl = *result.first;
461 Stmt *decl_stmt = decl->getBody();
462 if (decl_stmt)
463 {
464 ClangStmtVisitor visitor(compiler_instance->getASTContext(), expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
465
466 visitor.Visit (decl_stmt);
467 }
468 }
469 return 0;
470}
471
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000472bool
Sean Callanandcb658b2010-07-02 21:09:36 +0000473ClangExpression::ConvertIRToDWARF (ClangExpressionVariableList &expr_local_variable_list,
Sean Callanan848960c2010-06-23 23:18:04 +0000474 StreamString &dwarf_opcode_strm)
475{
476 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
477
478 llvm::Module *module = m_code_generator_ptr->GetModule();
479
480 if (!module)
481 {
482 if (log)
483 log->Printf("IR doesn't contain a module");
484
485 return 1;
486 }
487
Sean Callanandcb658b2010-07-02 21:09:36 +0000488 IRToDWARF ir_to_dwarf("IR to DWARF", expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
Sean Callanan8c6934d2010-07-01 20:08:22 +0000489
Sean Callanandcb658b2010-07-02 21:09:36 +0000490 return ir_to_dwarf.runOnModule(*module);
Sean Callanan848960c2010-06-23 23:18:04 +0000491}
492
Chris Lattner24943d22010-06-08 16:52:24 +0000493bool
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000494ClangExpression::PrepareIRForTarget (ClangExpressionVariableList &expr_local_variable_list)
495{
496 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
497
498 llvm::Module *module = m_code_generator_ptr->GetModule();
499
500 if (!module)
501 {
502 if (log)
503 log->Printf("IR doesn't contain a module");
504
505 return 1;
506 }
507
Sean Callanan8bce6652010-07-13 21:41:46 +0000508 llvm::Triple target_triple = m_clang_ap->getTarget().getTriple();
509
510 std::string err;
511
512 const llvm::Target *target = llvm::TargetRegistry::lookupTarget(m_target_triple, err);
513
514 if (!target)
515 {
516 if (log)
517 log->Printf("Couldn't find a target for %s", m_target_triple.c_str());
518
519 return 1;
520 }
521
522 std::auto_ptr<llvm::TargetMachine> target_machine(target->createTargetMachine(m_target_triple, ""));
523
524 IRForTarget ir_for_target("IR for target", m_decl_map, target_machine->getTargetData());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000525
526 return ir_for_target.runOnModule(*module);
527}
528
529bool
Chris Lattner24943d22010-06-08 16:52:24 +0000530ClangExpression::JITFunction (const ExecutionContext &exc_context, const char *name)
531{
Sean Callanan321fe9e2010-07-28 01:00:59 +0000532 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
Chris Lattner24943d22010-06-08 16:52:24 +0000533
534 llvm::Module *module = m_code_generator_ptr->GetModule();
535
536 if (module)
537 {
538 std::string error;
539
540 if (m_jit_mm_ptr == NULL)
541 m_jit_mm_ptr = new RecordingMemoryManager();
542
543 //llvm::InitializeNativeTarget();
Sean Callanan321fe9e2010-07-28 01:00:59 +0000544
545 if (log)
546 {
547 const char *relocation_model_string;
548
549 switch (llvm::TargetMachine::getRelocationModel())
550 {
Sean Callanan1e7089a2010-07-29 19:03:08 +0000551 case llvm::Reloc::Default:
552 relocation_model_string = "Default";
553 break;
554 case llvm::Reloc::Static:
555 relocation_model_string = "Static";
556 break;
557 case llvm::Reloc::PIC_:
558 relocation_model_string = "PIC_";
559 break;
560 case llvm::Reloc::DynamicNoPIC:
561 relocation_model_string = "DynamicNoPIC";
562 break;
Sean Callanan321fe9e2010-07-28 01:00:59 +0000563 }
564
565 log->Printf("Target machine's relocation model: %s", relocation_model_string);
566 }
Sean Callanan1e7089a2010-07-29 19:03:08 +0000567
568 if (m_execution_engine.get() == 0)
569 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
570 &error,
571 m_jit_mm_ptr,
572 CodeGenOpt::Default,
573 true,
574 CodeModel::Small)); // set to small so RIP-relative relocations work in PIC
575
576 m_execution_engine->DisableLazyCompilation();
577 llvm::Function *function = module->getFunction (llvm::StringRef (name));
Sean Callanan321fe9e2010-07-28 01:00:59 +0000578
Chris Lattner24943d22010-06-08 16:52:24 +0000579 // We don't actually need the function pointer here, this just forces it to get resolved.
580 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
581 // Note, you probably won't get here on error, since the LLVM JIT tends to just
582 // exit on error at present... So be careful.
583 if (fun_ptr == 0)
584 return false;
585 m_jitted_functions.push_back(ClangExpression::JittedFunction(name, (lldb::addr_t) fun_ptr));
586
587 }
588 return true;
589}
590
591bool
592ClangExpression::WriteJITCode (const ExecutionContext &exc_context)
593{
Sean Callanan321fe9e2010-07-28 01:00:59 +0000594 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
595
Chris Lattner24943d22010-06-08 16:52:24 +0000596 if (m_jit_mm_ptr == NULL)
597 return false;
598
599 if (exc_context.process == NULL)
600 return false;
601
602 // Look over the regions allocated for the function compiled. The JIT
603 // tries to allocate the functions & stubs close together, so we should try to
604 // write them that way too...
605 // For now I only write functions with no stubs, globals, exception tables,
606 // etc. So I only need to write the functions.
607
Greg Claytonbef15832010-07-14 00:18:15 +0000608 size_t alloc_size = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000609 std::map<uint8_t *, uint8_t *>::iterator fun_pos, fun_end = m_jit_mm_ptr->m_functions.end();
610 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
611 {
Greg Claytonbef15832010-07-14 00:18:15 +0000612 alloc_size += (*fun_pos).second - (*fun_pos).first;
Chris Lattner24943d22010-06-08 16:52:24 +0000613 }
614
615 Error error;
Greg Claytonbef15832010-07-14 00:18:15 +0000616 lldb::addr_t target_addr = exc_context.process->AllocateMemory (alloc_size, lldb::ePermissionsReadable|lldb::ePermissionsExecutable, error);
Chris Lattner24943d22010-06-08 16:52:24 +0000617
618 if (target_addr == LLDB_INVALID_ADDRESS)
619 return false;
620
621 lldb::addr_t cursor = target_addr;
622 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
623 {
Sean Callanan321fe9e2010-07-28 01:00:59 +0000624 if (log)
625 log->Printf("Reading [%p-%p] from m_functions", fun_pos->first, fun_pos->second);
626
Chris Lattner24943d22010-06-08 16:52:24 +0000627 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
628 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
629 size_t size = lend - lstart;
630 exc_context.process->WriteMemory(cursor, (void *) lstart, size, error);
631 m_jit_mm_ptr->AddToLocalToRemoteMap (lstart, size, cursor);
632 cursor += size;
633 }
634
635 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
636
637 for (pos = m_jitted_functions.begin(); pos != end; pos++)
638 {
639 (*pos).m_remote_addr = m_jit_mm_ptr->GetRemoteAddressForLocal ((*pos).m_local_addr);
640 }
641 return true;
642}
643
644lldb::addr_t
645ClangExpression::GetFunctionAddress (const char *name)
646{
647 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
648
649 for (pos = m_jitted_functions.begin(); pos < end; pos++)
650 {
651 if (strcmp ((*pos).m_name.c_str(), name) == 0)
652 return (*pos).m_remote_addr;
653 }
654 return LLDB_INVALID_ADDRESS;
655}
656
Sean Callanan8541f2f2010-07-23 02:19:15 +0000657Error
658ClangExpression::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, const char *name)
659{
660 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
661
662 Error ret;
663
664 ret.Clear();
665
666 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
667 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
668
669 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
670
671 for (pos = m_jitted_functions.begin(); pos < end; pos++)
672 {
673 if (strcmp(pos->m_name.c_str(), name) == 0)
674 {
675 func_local_addr = pos->m_local_addr;
676 func_remote_addr = pos->m_remote_addr;
677 }
678 }
679
680 if (func_local_addr == LLDB_INVALID_ADDRESS)
681 {
682 ret.SetErrorToGenericError();
683 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
684 return ret;
685 }
686
687 if(log)
688 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
689
690 std::pair <lldb::addr_t, lldb::addr_t> func_range;
691
692 func_range = m_jit_mm_ptr->GetRemoteRangeForLocal(func_local_addr);
693
694 if (func_range.first == 0 && func_range.second == 0)
695 {
696 ret.SetErrorToGenericError();
697 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
698 return ret;
699 }
700
701 if(log)
702 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
703
704 if (!exe_ctx.target)
705 {
706 ret.SetErrorToGenericError();
707 ret.SetErrorString("Couldn't find the target");
708 }
709
Sean Callanan32824aa2010-07-23 22:19:18 +0000710 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
Sean Callanan8541f2f2010-07-23 02:19:15 +0000711
712 Error err;
Sean Callanan32824aa2010-07-23 22:19:18 +0000713 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
Sean Callanan8541f2f2010-07-23 02:19:15 +0000714
715 if (!err.Success())
716 {
717 ret.SetErrorToGenericError();
718 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
719 return ret;
720 }
721
722 ArchSpec arch(exe_ctx.target->GetArchitecture());
723
724 Disassembler *disassembler = Disassembler::FindPlugin(arch);
725
726 if (disassembler == NULL)
727 {
728 ret.SetErrorToGenericError();
729 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.AsCString());
730 return ret;
731 }
732
733 if (!exe_ctx.process)
734 {
735 ret.SetErrorToGenericError();
736 ret.SetErrorString("Couldn't find the process");
737 return ret;
738 }
739
740 DataExtractor extractor(buffer_sp,
741 exe_ctx.process->GetByteOrder(),
Sean Callanan32824aa2010-07-23 22:19:18 +0000742 exe_ctx.target->GetArchitecture().GetAddressByteSize());
Sean Callanan8541f2f2010-07-23 02:19:15 +0000743
744 if(log)
745 {
746 log->Printf("Function data has contents:");
747 extractor.PutToLog (log,
748 0,
749 extractor.GetByteSize(),
Sean Callanan32824aa2010-07-23 22:19:18 +0000750 func_remote_addr,
Sean Callanan8541f2f2010-07-23 02:19:15 +0000751 16,
752 DataExtractor::TypeUInt8);
753 }
754
755 disassembler->DecodeInstructions(extractor, 0, UINT32_MAX);
756
757 Disassembler::InstructionList &instruction_list = disassembler->GetInstructionList();
758
759 uint32_t bytes_offset = 0;
760
761 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
762 instruction_index < num_instructions;
763 ++instruction_index)
764 {
765 Disassembler::Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index);
Sean Callanan32824aa2010-07-23 22:19:18 +0000766 Address addr(NULL, func_remote_addr + bytes_offset);
Sean Callanan8541f2f2010-07-23 02:19:15 +0000767 instruction->Dump (&stream,
Sean Callanan32824aa2010-07-23 22:19:18 +0000768 &addr,
Sean Callanan8541f2f2010-07-23 02:19:15 +0000769 &extractor,
770 bytes_offset,
771 exe_ctx,
772 true);
773 stream.PutChar('\n');
774 bytes_offset += instruction->GetByteSize();
775 }
776
777 return ret;
778}
779
Chris Lattner24943d22010-06-08 16:52:24 +0000780unsigned
781ClangExpression::Compile()
782{
783 Mutex::Locker locker(GetClangMutex ());
784 bool IsAST = false;
785
786 if (CreateCompilerInstance(IsAST))
787 {
788 // Validate/process some options
789 if (m_clang_ap->getHeaderSearchOpts().Verbose)
790 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
791 << " based upon " << PACKAGE_STRING
792 << " hosted on " << llvm::sys::getHostTriple() << "\n";
793
794 // Enforce certain implications.
795 if (!m_clang_ap->getFrontendOpts().ViewClassInheritance.empty())
796 m_clang_ap->getFrontendOpts().ProgramAction = frontend::InheritanceView;
797// if (!compiler_instance->getFrontendOpts().FixItSuffix.empty())
798// compiler_instance->getFrontendOpts().ProgramAction = frontend::FixIt;
799
800 for (unsigned i = 0, e = m_clang_ap->getFrontendOpts().Inputs.size(); i != e; ++i) {
Chris Lattner24943d22010-06-08 16:52:24 +0000801
802 // If we aren't using an AST file, setup the file and source managers and
803 // the preprocessor.
804 if (!IsAST) {
805 if (!i) {
806 // Create a file manager object to provide access to and cache the
807 // filesystem.
808 m_clang_ap->createFileManager();
809
810 // Create the source manager.
811 m_clang_ap->createSourceManager();
812 } else {
813 // Reset the ID tables if we are reusing the SourceManager.
814 m_clang_ap->getSourceManager().clearIDTables();
815 }
816
817 // Create the preprocessor.
818 m_clang_ap->createPreprocessor();
819 }
820
821 llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(*m_clang_ap.get()));
822 if (!Act)
823 break;
824
Greg Claytone41c4b22010-06-13 17:34:29 +0000825 if (Act->BeginSourceFile(*m_clang_ap,
826 m_clang_ap->getFrontendOpts().Inputs[i].second,
827 m_clang_ap->getFrontendOpts().Inputs[i].first)) {
Chris Lattner24943d22010-06-08 16:52:24 +0000828 Act->Execute();
829 Act->EndSourceFile();
830 }
831 }
832
833 if (m_clang_ap->getDiagnosticOpts().ShowCarets)
834 {
835 unsigned NumWarnings = m_clang_ap->getDiagnostics().getNumWarnings();
836 unsigned NumErrors = m_clang_ap->getDiagnostics().getNumErrors() -
837 m_clang_ap->getDiagnostics().getNumErrorsSuppressed();
838
839 if (NumWarnings || NumErrors)
840 {
841 if (NumWarnings)
842 fprintf (stderr, "%u warning%s%s", NumWarnings, (NumWarnings == 1 ? "" : "s"), (NumErrors ? " and " : ""));
843 if (NumErrors)
844 fprintf (stderr, "%u error%s", NumErrors, (NumErrors == 1 ? "" : "s"));
845 fprintf (stderr, " generated.\n");
846 }
847 }
848
849 if (m_clang_ap->getFrontendOpts().ShowStats) {
850 m_clang_ap->getFileManager().PrintStats();
851 fprintf(stderr, "\n");
852 }
853
854 // Return the appropriate status when verifying diagnostics.
855 //
856 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
857 // this.
858 if (m_clang_ap->getDiagnosticOpts().VerifyDiagnostics)
859 return static_cast<VerifyDiagnosticsClient&>(m_clang_ap->getDiagnosticClient()).HadErrors();
860
861 return m_clang_ap->getDiagnostics().getNumErrors();
862 }
863 return 1;
864}