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