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