blob: 9468a706c0bfd7933fbe243f1d4dfff15691b3c1 [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"
Chris Lattner24943d22010-06-08 16:52:24 +000059#include "lldb/Expression/ClangExpression.h"
60#include "lldb/Expression/ClangASTSource.h"
Sean Callanan8c6934d2010-07-01 20:08:22 +000061#include "lldb/Expression/ClangResultSynthesizer.h"
Chris Lattner24943d22010-06-08 16:52:24 +000062#include "lldb/Expression/ClangStmtVisitor.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000063#include "lldb/Expression/IRForTarget.h"
Sean Callanandcb658b2010-07-02 21:09:36 +000064#include "lldb/Expression/IRToDWARF.h"
Chris Lattner24943d22010-06-08 16:52:24 +000065#include "lldb/Symbol/ClangASTContext.h"
66#include "lldb/Expression/RecordingMemoryManager.h"
67#include "lldb/Target/ExecutionContext.h"
68#include "lldb/Target/Process.h"
69
Chris Lattner24943d22010-06-08 16:52:24 +000070#include "lldb/Core/StreamString.h"
71#include "lldb/Host/Mutex.h"
Chris Lattner24943d22010-06-08 16:52:24 +000072
73
74using namespace lldb_private;
75using namespace clang;
76using namespace llvm;
77
Chris Lattner24943d22010-06-08 16:52:24 +000078
79//===----------------------------------------------------------------------===//
80// Utility Methods
81//===----------------------------------------------------------------------===//
82
83std::string GetBuiltinIncludePath(const char *Argv0) {
84 llvm::sys::Path P =
85 llvm::sys::Path::GetMainExecutable(Argv0,
86 (void*)(intptr_t) GetBuiltinIncludePath);
87
88 if (!P.isEmpty()) {
89 P.eraseComponent(); // Remove /clang from foo/bin/clang
90 P.eraseComponent(); // Remove /bin from foo/bin
91
92 // Get foo/lib/clang/<version>/include
93 P.appendComponent("lib");
94 P.appendComponent("clang");
95 P.appendComponent(CLANG_VERSION_STRING);
96 P.appendComponent("include");
97 }
98
99 return P.str();
100}
101
102
103//===----------------------------------------------------------------------===//
104// Main driver
105//===----------------------------------------------------------------------===//
106
107void LLVMErrorHandler(void *UserData, const std::string &Message) {
108 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
109
110 Diags.Report(diag::err_fe_error_backend) << Message;
111
112 // We cannot recover from llvm errors.
113 exit(1);
114}
115
116static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
117 using namespace clang::frontend;
118
119 switch (CI.getFrontendOpts().ProgramAction) {
120 default:
121 llvm_unreachable("Invalid program action!");
122
123 case ASTDump: return new ASTDumpAction();
124 case ASTPrint: return new ASTPrintAction();
125 case ASTPrintXML: return new ASTPrintXMLAction();
126 case ASTView: return new ASTViewAction();
127 case DumpRawTokens: return new DumpRawTokensAction();
128 case DumpTokens: return new DumpTokensAction();
129 case EmitAssembly: return new EmitAssemblyAction();
130 case EmitBC: return new EmitBCAction();
131 case EmitHTML: return new HTMLPrintAction();
132 case EmitLLVM: return new EmitLLVMAction();
133 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
134 case EmitObj: return new EmitObjAction();
135 case FixIt: return new FixItAction();
136 case GeneratePCH: return new GeneratePCHAction();
137 case GeneratePTH: return new GeneratePTHAction();
138 case InheritanceView: return new InheritanceViewAction();
139 case InitOnly: return new InitOnlyAction();
140 case ParseNoop: return new ParseOnlyAction();
141 case ParsePrintCallbacks: return new PrintParseAction();
142 case ParseSyntaxOnly: return new SyntaxOnlyAction();
143
144 case PluginAction: {
145 if (CI.getFrontendOpts().ActionName == "help") {
146 llvm::errs() << "clang -cc1 plugins:\n";
147 for (FrontendPluginRegistry::iterator it =
148 FrontendPluginRegistry::begin(),
149 ie = FrontendPluginRegistry::end();
150 it != ie; ++it)
151 llvm::errs() << " " << it->getName() << " - " << it->getDesc() << "\n";
152 return 0;
153 }
154
155 for (FrontendPluginRegistry::iterator it =
156 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
157 it != ie; ++it) {
158 if (it->getName() == CI.getFrontendOpts().ActionName)
159 return it->instantiate();
160 }
161
162 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
163 << CI.getFrontendOpts().ActionName;
164 return 0;
165 }
166
167 case PrintDeclContext: return new DeclContextPrintAction();
168 case PrintPreprocessedInput: return new PrintPreprocessedAction();
169 case RewriteMacros: return new RewriteMacrosAction();
170 case RewriteObjC: return new RewriteObjCAction();
171 case RewriteTest: return new RewriteTestAction();
172 case RunAnalysis: return new AnalysisAction();
173 case RunPreprocessorOnly: return new PreprocessOnlyAction();
174 }
175}
176
177//----------------------------------------------------------------------
178// ClangExpression constructor
179//----------------------------------------------------------------------
180ClangExpression::ClangExpression(const char *target_triple,
181 ClangExpressionDeclMap *decl_map) :
182 m_target_triple (),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000183 m_decl_map (decl_map),
184 m_clang_ap (),
Chris Lattner24943d22010-06-08 16:52:24 +0000185 m_code_generator_ptr (NULL),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000186 m_jit_mm_ptr (NULL),
187 m_execution_engine (),
188 m_jitted_functions ()
Chris Lattner24943d22010-06-08 16:52:24 +0000189{
190 if (target_triple && target_triple[0])
191 m_target_triple = target_triple;
192 else
193 m_target_triple = llvm::sys::getHostTriple();
194}
195
196
197//----------------------------------------------------------------------
198// Destructor
199//----------------------------------------------------------------------
200ClangExpression::~ClangExpression()
201{
202 if (m_code_generator_ptr && !m_execution_engine.get())
203 delete m_code_generator_ptr;
204}
205
206bool
207ClangExpression::CreateCompilerInstance (bool &IsAST)
208{
209 // Initialize targets first, so that --version shows registered targets.
210 static struct InitializeLLVM {
211 InitializeLLVM() {
212 llvm::InitializeAllTargets();
213 llvm::InitializeAllAsmPrinters();
214 }
215 } InitializeLLVM;
216
217 // 1. Create a new compiler instance.
218 m_clang_ap.reset(new CompilerInstance());
219 m_clang_ap->setLLVMContext(new LLVMContext());
220
221 // 2. Set options.
222
223 // Parse expressions as Objective C++ regardless of context.
224 // Our hook into Clang's lookup mechanism only works in C++.
225 m_clang_ap->getLangOpts().CPlusPlus = true;
226 m_clang_ap->getLangOpts().ObjC1 = true;
Sean Callanan051052f2010-07-02 22:22:28 +0000227 m_clang_ap->getLangOpts().ThreadsafeStatics = false;
Sean Callanan8bce6652010-07-13 21:41:46 +0000228
229 // Set CodeGen options
230 m_clang_ap->getCodeGenOpts().EmitDeclMetadata = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000231
232 // Disable some warnings.
233 m_clang_ap->getDiagnosticOpts().Warnings.push_back("no-unused-value");
234
235 // Set the target triple.
236 m_clang_ap->getTargetOpts().Triple = m_target_triple;
237
238 // 3. Set up various important bits of infrastructure.
239
240 m_clang_ap->createDiagnostics(0, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000241
242 // Create the target instance.
243 m_clang_ap->setTarget(TargetInfo::CreateTargetInfo(m_clang_ap->getDiagnostics(),
244 m_clang_ap->getTargetOpts()));
245 if (!m_clang_ap->hasTarget())
246 {
247 m_clang_ap.reset();
248 return false;
249 }
250
251 // Inform the target of the language options
252 //
253 // FIXME: We shouldn't need to do this, the target should be immutable once
254 // created. This complexity should be lifted elsewhere.
255 m_clang_ap->getTarget().setForcedLangOptions(m_clang_ap->getLangOpts());
256
257 return m_clang_ap.get();
258}
259
260Mutex &
261ClangExpression::GetClangMutex ()
262{
263 static Mutex g_clang_mutex(Mutex::eMutexTypeRecursive); // Control access to the clang compiler
264 return g_clang_mutex;
265}
266
267
268clang::ASTContext *
269ClangExpression::GetASTContext ()
270{
271 CompilerInstance *compiler_instance = GetCompilerInstance();
272 if (compiler_instance)
273 return &compiler_instance->getASTContext();
274 return NULL;
275}
276
277unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000278ClangExpression::ParseExpression (const char *expr_text,
279 Stream &stream,
280 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000281{
282 // HACK: for now we have to make a function body around our expression
283 // since there is no way to parse a single expression line in LLVM/Clang.
Sean Callanan8bce6652010-07-13 21:41:46 +0000284 std::string func_expr("extern \"C\" void ___clang_expr(void *___clang_arg)\n{\n\t");
Chris Lattner24943d22010-06-08 16:52:24 +0000285 func_expr.append(expr_text);
286 func_expr.append(";\n}");
Sean Callanan8c6934d2010-07-01 20:08:22 +0000287 return ParseBareExpression (func_expr, stream, add_result_var);
Chris Lattner24943d22010-06-08 16:52:24 +0000288
289}
290
291unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000292ClangExpression::ParseBareExpression (llvm::StringRef expr_text,
293 Stream &stream,
294 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000295{
296 Mutex::Locker locker(GetClangMutex ());
297
298 TextDiagnosticBuffer text_diagnostic_buffer;
299
300 bool IsAST = false;
301 if (!CreateCompilerInstance (IsAST))
302 {
303 stream.Printf("error: couldn't create compiler instance\n");
304 return 1;
305 }
306
307 // This code is matched below by a setClient to NULL.
308 // We cannot return out of this code without doing that.
309 m_clang_ap->getDiagnostics().setClient(&text_diagnostic_buffer);
310 text_diagnostic_buffer.FlushDiagnostics (m_clang_ap->getDiagnostics());
311
312 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
313
314 if (!m_clang_ap->hasSourceManager())
315 m_clang_ap->createSourceManager();
316
317 m_clang_ap->createFileManager();
318 m_clang_ap->createPreprocessor();
319
320 // Build the ASTContext. Most of this we inherit from the
321 // CompilerInstance, but we also want to give the context
322 // an ExternalASTSource.
323 SelectorTable selector_table;
324 std::auto_ptr<Builtin::Context> builtin_ap(new Builtin::Context(m_clang_ap->getTarget()));
325 ASTContext *Context = new ASTContext(m_clang_ap->getLangOpts(),
326 m_clang_ap->getSourceManager(),
327 m_clang_ap->getTarget(),
328 m_clang_ap->getPreprocessor().getIdentifierTable(),
329 selector_table,
330 *builtin_ap.get());
331
332 llvm::OwningPtr<ExternalASTSource> ASTSource(new ClangASTSource(*Context, *m_decl_map));
333
334 if (m_decl_map)
335 {
336 Context->setExternalSource(ASTSource);
337 }
338
339 m_clang_ap->setASTContext(Context);
340
341 FileID memory_buffer_file_id = m_clang_ap->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
342 std::string module_name("test_func");
343 text_diagnostic_buffer.BeginSourceFile(m_clang_ap->getLangOpts(), &m_clang_ap->getPreprocessor());
344
345 if (m_code_generator_ptr)
346 delete m_code_generator_ptr;
347
348 m_code_generator_ptr = CreateLLVMCodeGen(m_clang_ap->getDiagnostics(),
349 module_name,
350 m_clang_ap->getCodeGenOpts(),
351 m_clang_ap->getLLVMContext());
352
353
354 // - CodeGeneration ASTConsumer (include/clang/ModuleBuilder.h), which will be passed in when you call...
355 // - Call clang::ParseAST (in lib/Sema/ParseAST.cpp) to parse the buffer. The CodeGenerator will generate code for __dbg_expr.
356 // - 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 +0000357
358 if (add_result_var)
359 {
360 ClangResultSynthesizer result_synthesizer(m_code_generator_ptr);
361 ParseAST(m_clang_ap->getPreprocessor(), &result_synthesizer, m_clang_ap->getASTContext());
362 }
363 else
364 {
365 ParseAST(m_clang_ap->getPreprocessor(), m_code_generator_ptr, m_clang_ap->getASTContext());
366 }
367
Sean Callanan848960c2010-06-23 23:18:04 +0000368
Chris Lattner24943d22010-06-08 16:52:24 +0000369 text_diagnostic_buffer.EndSourceFile();
370
371 //compiler_instance->getASTContext().getTranslationUnitDecl()->dump();
372
373 //if (compiler_instance->getFrontendOpts().ShowStats) {
374 // compiler_instance->getFileManager().PrintStats();
375 // fprintf(stderr, "\n");
376 //}
377
378 // This code resolves the setClient above.
379 m_clang_ap->getDiagnostics().setClient(0);
380
381 TextDiagnosticBuffer::const_iterator diag_iterator;
382
383 int num_errors = 0;
384
385#ifdef COUNT_WARNINGS_AND_ERRORS
386 int num_warnings = 0;
387
388 for (diag_iterator = text_diagnostic_buffer.warn_begin();
389 diag_iterator != text_diagnostic_buffer.warn_end();
390 ++diag_iterator)
391 num_warnings++;
392
393 for (diag_iterator = text_diagnostic_buffer.err_begin();
394 diag_iterator != text_diagnostic_buffer.err_end();
395 ++diag_iterator)
396 num_errors++;
397
398 if (num_warnings || num_errors)
399 {
400 if (num_warnings)
401 stream.Printf("%u warning%s%s", num_warnings, (num_warnings == 1 ? "" : "s"), (num_errors ? " and " : ""));
402 if (num_errors)
403 stream.Printf("%u error%s", num_errors, (num_errors == 1 ? "" : "s"));
404 stream.Printf("\n");
405 }
406#endif
407
408 for (diag_iterator = text_diagnostic_buffer.warn_begin();
409 diag_iterator != text_diagnostic_buffer.warn_end();
410 ++diag_iterator)
411 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
412
413 num_errors = 0;
414
415 for (diag_iterator = text_diagnostic_buffer.err_begin();
416 diag_iterator != text_diagnostic_buffer.err_end();
417 ++diag_iterator)
418 {
419 num_errors++;
420 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
421 }
422
423 return num_errors;
424}
425
Chris Lattner24943d22010-06-08 16:52:24 +0000426static FrontendAction *
427CreateFrontendAction(CompilerInstance &CI)
428{
429 // Create the underlying action.
430 FrontendAction *Act = CreateFrontendBaseAction(CI);
431 if (!Act)
432 return 0;
433
434 // If there are any AST files to merge, create a frontend action
435 // adaptor to perform the merge.
436 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
437 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
438 CI.getFrontendOpts().ASTMergeFiles.size());
439
440 return Act;
441}
442
443
444unsigned
445ClangExpression::ConvertExpressionToDWARF (ClangExpressionVariableList& expr_local_variable_list,
446 StreamString &dwarf_opcode_strm)
447{
448 CompilerInstance *compiler_instance = GetCompilerInstance();
449
450 DeclarationName hack_func_name(&compiler_instance->getASTContext().Idents.get("___clang_expr"));
451 DeclContext::lookup_result result = compiler_instance->getASTContext().getTranslationUnitDecl()->lookup(hack_func_name);
452
453 if (result.first != result.second)
454 {
455 Decl *decl = *result.first;
456 Stmt *decl_stmt = decl->getBody();
457 if (decl_stmt)
458 {
459 ClangStmtVisitor visitor(compiler_instance->getASTContext(), expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
460
461 visitor.Visit (decl_stmt);
462 }
463 }
464 return 0;
465}
466
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000467bool
Sean Callanandcb658b2010-07-02 21:09:36 +0000468ClangExpression::ConvertIRToDWARF (ClangExpressionVariableList &expr_local_variable_list,
Sean Callanan848960c2010-06-23 23:18:04 +0000469 StreamString &dwarf_opcode_strm)
470{
471 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
472
473 llvm::Module *module = m_code_generator_ptr->GetModule();
474
475 if (!module)
476 {
477 if (log)
478 log->Printf("IR doesn't contain a module");
479
480 return 1;
481 }
482
Sean Callanandcb658b2010-07-02 21:09:36 +0000483 IRToDWARF ir_to_dwarf("IR to DWARF", expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
Sean Callanan8c6934d2010-07-01 20:08:22 +0000484
Sean Callanandcb658b2010-07-02 21:09:36 +0000485 return ir_to_dwarf.runOnModule(*module);
Sean Callanan848960c2010-06-23 23:18:04 +0000486}
487
Chris Lattner24943d22010-06-08 16:52:24 +0000488bool
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000489ClangExpression::PrepareIRForTarget (ClangExpressionVariableList &expr_local_variable_list)
490{
491 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
492
493 llvm::Module *module = m_code_generator_ptr->GetModule();
494
495 if (!module)
496 {
497 if (log)
498 log->Printf("IR doesn't contain a module");
499
500 return 1;
501 }
502
Sean Callanan8bce6652010-07-13 21:41:46 +0000503 llvm::Triple target_triple = m_clang_ap->getTarget().getTriple();
504
505 std::string err;
506
507 const llvm::Target *target = llvm::TargetRegistry::lookupTarget(m_target_triple, err);
508
509 if (!target)
510 {
511 if (log)
512 log->Printf("Couldn't find a target for %s", m_target_triple.c_str());
513
514 return 1;
515 }
516
517 std::auto_ptr<llvm::TargetMachine> target_machine(target->createTargetMachine(m_target_triple, ""));
518
519 IRForTarget ir_for_target("IR for target", m_decl_map, target_machine->getTargetData());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000520
521 return ir_for_target.runOnModule(*module);
522}
523
524bool
Chris Lattner24943d22010-06-08 16:52:24 +0000525ClangExpression::JITFunction (const ExecutionContext &exc_context, const char *name)
526{
527
528 llvm::Module *module = m_code_generator_ptr->GetModule();
529
530 if (module)
531 {
532 std::string error;
533
534 if (m_jit_mm_ptr == NULL)
535 m_jit_mm_ptr = new RecordingMemoryManager();
536
537 //llvm::InitializeNativeTarget();
538 if (m_execution_engine.get() == 0)
539 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module, &error, m_jit_mm_ptr));
540 m_execution_engine->DisableLazyCompilation();
541 llvm::Function *function = module->getFunction (llvm::StringRef (name));
542
543 // We don't actually need the function pointer here, this just forces it to get resolved.
544 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
545 // Note, you probably won't get here on error, since the LLVM JIT tends to just
546 // exit on error at present... So be careful.
547 if (fun_ptr == 0)
548 return false;
549 m_jitted_functions.push_back(ClangExpression::JittedFunction(name, (lldb::addr_t) fun_ptr));
550
551 }
552 return true;
553}
554
555bool
556ClangExpression::WriteJITCode (const ExecutionContext &exc_context)
557{
558 if (m_jit_mm_ptr == NULL)
559 return false;
560
561 if (exc_context.process == NULL)
562 return false;
563
564 // Look over the regions allocated for the function compiled. The JIT
565 // tries to allocate the functions & stubs close together, so we should try to
566 // write them that way too...
567 // For now I only write functions with no stubs, globals, exception tables,
568 // etc. So I only need to write the functions.
569
Greg Claytonbef15832010-07-14 00:18:15 +0000570 size_t alloc_size = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000571 std::map<uint8_t *, uint8_t *>::iterator fun_pos, fun_end = m_jit_mm_ptr->m_functions.end();
572 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
573 {
Greg Claytonbef15832010-07-14 00:18:15 +0000574 alloc_size += (*fun_pos).second - (*fun_pos).first;
Chris Lattner24943d22010-06-08 16:52:24 +0000575 }
576
577 Error error;
Greg Claytonbef15832010-07-14 00:18:15 +0000578 lldb::addr_t target_addr = exc_context.process->AllocateMemory (alloc_size, lldb::ePermissionsReadable|lldb::ePermissionsExecutable, error);
Chris Lattner24943d22010-06-08 16:52:24 +0000579
580 if (target_addr == LLDB_INVALID_ADDRESS)
581 return false;
582
583 lldb::addr_t cursor = target_addr;
584 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
585 {
586 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
587 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
588 size_t size = lend - lstart;
589 exc_context.process->WriteMemory(cursor, (void *) lstart, size, error);
590 m_jit_mm_ptr->AddToLocalToRemoteMap (lstart, size, cursor);
591 cursor += size;
592 }
593
594 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
595
596 for (pos = m_jitted_functions.begin(); pos != end; pos++)
597 {
598 (*pos).m_remote_addr = m_jit_mm_ptr->GetRemoteAddressForLocal ((*pos).m_local_addr);
599 }
600 return true;
601}
602
603lldb::addr_t
604ClangExpression::GetFunctionAddress (const char *name)
605{
606 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
607
608 for (pos = m_jitted_functions.begin(); pos < end; pos++)
609 {
610 if (strcmp ((*pos).m_name.c_str(), name) == 0)
611 return (*pos).m_remote_addr;
612 }
613 return LLDB_INVALID_ADDRESS;
614}
615
616unsigned
617ClangExpression::Compile()
618{
619 Mutex::Locker locker(GetClangMutex ());
620 bool IsAST = false;
621
622 if (CreateCompilerInstance(IsAST))
623 {
624 // Validate/process some options
625 if (m_clang_ap->getHeaderSearchOpts().Verbose)
626 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
627 << " based upon " << PACKAGE_STRING
628 << " hosted on " << llvm::sys::getHostTriple() << "\n";
629
630 // Enforce certain implications.
631 if (!m_clang_ap->getFrontendOpts().ViewClassInheritance.empty())
632 m_clang_ap->getFrontendOpts().ProgramAction = frontend::InheritanceView;
633// if (!compiler_instance->getFrontendOpts().FixItSuffix.empty())
634// compiler_instance->getFrontendOpts().ProgramAction = frontend::FixIt;
635
636 for (unsigned i = 0, e = m_clang_ap->getFrontendOpts().Inputs.size(); i != e; ++i) {
Chris Lattner24943d22010-06-08 16:52:24 +0000637
638 // If we aren't using an AST file, setup the file and source managers and
639 // the preprocessor.
640 if (!IsAST) {
641 if (!i) {
642 // Create a file manager object to provide access to and cache the
643 // filesystem.
644 m_clang_ap->createFileManager();
645
646 // Create the source manager.
647 m_clang_ap->createSourceManager();
648 } else {
649 // Reset the ID tables if we are reusing the SourceManager.
650 m_clang_ap->getSourceManager().clearIDTables();
651 }
652
653 // Create the preprocessor.
654 m_clang_ap->createPreprocessor();
655 }
656
657 llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(*m_clang_ap.get()));
658 if (!Act)
659 break;
660
Greg Claytone41c4b22010-06-13 17:34:29 +0000661 if (Act->BeginSourceFile(*m_clang_ap,
662 m_clang_ap->getFrontendOpts().Inputs[i].second,
663 m_clang_ap->getFrontendOpts().Inputs[i].first)) {
Chris Lattner24943d22010-06-08 16:52:24 +0000664 Act->Execute();
665 Act->EndSourceFile();
666 }
667 }
668
669 if (m_clang_ap->getDiagnosticOpts().ShowCarets)
670 {
671 unsigned NumWarnings = m_clang_ap->getDiagnostics().getNumWarnings();
672 unsigned NumErrors = m_clang_ap->getDiagnostics().getNumErrors() -
673 m_clang_ap->getDiagnostics().getNumErrorsSuppressed();
674
675 if (NumWarnings || NumErrors)
676 {
677 if (NumWarnings)
678 fprintf (stderr, "%u warning%s%s", NumWarnings, (NumWarnings == 1 ? "" : "s"), (NumErrors ? " and " : ""));
679 if (NumErrors)
680 fprintf (stderr, "%u error%s", NumErrors, (NumErrors == 1 ? "" : "s"));
681 fprintf (stderr, " generated.\n");
682 }
683 }
684
685 if (m_clang_ap->getFrontendOpts().ShowStats) {
686 m_clang_ap->getFileManager().PrintStats();
687 fprintf(stderr, "\n");
688 }
689
690 // Return the appropriate status when verifying diagnostics.
691 //
692 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
693 // this.
694 if (m_clang_ap->getDiagnosticOpts().VerifyDiagnostics)
695 return static_cast<VerifyDiagnosticsClient&>(m_clang_ap->getDiagnosticClient()).HadErrors();
696
697 return m_clang_ap->getDiagnostics().getNumErrors();
698 }
699 return 1;
700}