1 //===-- ASTResultSynthesizer.cpp --------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "ASTResultSynthesizer.h"
12 #include "ClangPersistentVariables.h"
14 #include "lldb/Symbol/ClangASTContext.h"
15 #include "lldb/Symbol/ClangASTImporter.h"
16 #include "lldb/Target/Target.h"
17 #include "lldb/Utility/LLDBAssert.h"
18 #include "lldb/Utility/Log.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclGroup.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/Stmt.h"
27 #include "clang/Parse/Parser.h"
28 #include "clang/Sema/SemaDiagnostic.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/raw_ostream.h"
33 using namespace clang;
34 using namespace lldb_private;
36 ASTResultSynthesizer::ASTResultSynthesizer(ASTConsumer *passthrough,
37 bool top_level, Target &target)
38 : m_ast_context(NULL), m_passthrough(passthrough), m_passthrough_sema(NULL),
39 m_target(target), m_sema(NULL), m_top_level(top_level) {
43 m_passthrough_sema = dyn_cast<SemaConsumer>(passthrough);
46 ASTResultSynthesizer::~ASTResultSynthesizer() {}
48 void ASTResultSynthesizer::Initialize(ASTContext &Context) {
49 m_ast_context = &Context;
52 m_passthrough->Initialize(Context);
55 void ASTResultSynthesizer::TransformTopLevelDecl(Decl *D) {
56 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
58 if (NamedDecl *named_decl = dyn_cast<NamedDecl>(D)) {
59 if (log && log->GetVerbose()) {
60 if (named_decl->getIdentifier())
61 log->Printf("TransformTopLevelDecl(%s)",
62 named_decl->getIdentifier()->getNameStart());
63 else if (ObjCMethodDecl *method_decl = dyn_cast<ObjCMethodDecl>(D))
64 log->Printf("TransformTopLevelDecl(%s)",
65 method_decl->getSelector().getAsString().c_str());
67 log->Printf("TransformTopLevelDecl(<complex>)");
71 RecordPersistentDecl(named_decl);
75 if (LinkageSpecDecl *linkage_spec_decl = dyn_cast<LinkageSpecDecl>(D)) {
76 RecordDecl::decl_iterator decl_iterator;
78 for (decl_iterator = linkage_spec_decl->decls_begin();
79 decl_iterator != linkage_spec_decl->decls_end(); ++decl_iterator) {
80 TransformTopLevelDecl(*decl_iterator);
82 } else if (!m_top_level) {
83 if (ObjCMethodDecl *method_decl = dyn_cast<ObjCMethodDecl>(D)) {
85 !method_decl->getSelector().getAsString().compare("$__lldb_expr:")) {
86 RecordPersistentTypes(method_decl);
87 SynthesizeObjCMethodResult(method_decl);
89 } else if (FunctionDecl *function_decl = dyn_cast<FunctionDecl>(D)) {
90 // When completing user input the body of the function may be a nullptr.
91 if (m_ast_context && function_decl->hasBody() &&
92 !function_decl->getNameInfo().getAsString().compare("$__lldb_expr")) {
93 RecordPersistentTypes(function_decl);
94 SynthesizeFunctionResult(function_decl);
100 bool ASTResultSynthesizer::HandleTopLevelDecl(DeclGroupRef D) {
101 DeclGroupRef::iterator decl_iterator;
103 for (decl_iterator = D.begin(); decl_iterator != D.end(); ++decl_iterator) {
104 Decl *decl = *decl_iterator;
106 TransformTopLevelDecl(decl);
110 return m_passthrough->HandleTopLevelDecl(D);
114 bool ASTResultSynthesizer::SynthesizeFunctionResult(FunctionDecl *FunDecl) {
115 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
120 FunctionDecl *function_decl = FunDecl;
125 if (log && log->GetVerbose()) {
127 raw_string_ostream os(s);
129 function_decl->print(os);
133 log->Printf("Untransformed function AST:\n%s", s.c_str());
136 Stmt *function_body = function_decl->getBody();
137 CompoundStmt *compound_stmt = dyn_cast<CompoundStmt>(function_body);
139 bool ret = SynthesizeBodyResult(compound_stmt, function_decl);
141 if (log && log->GetVerbose()) {
143 raw_string_ostream os(s);
145 function_decl->print(os);
149 log->Printf("Transformed function AST:\n%s", s.c_str());
155 bool ASTResultSynthesizer::SynthesizeObjCMethodResult(
156 ObjCMethodDecl *MethodDecl) {
157 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
165 if (log && log->GetVerbose()) {
167 raw_string_ostream os(s);
169 MethodDecl->print(os);
173 log->Printf("Untransformed method AST:\n%s", s.c_str());
176 Stmt *method_body = MethodDecl->getBody();
181 CompoundStmt *compound_stmt = dyn_cast<CompoundStmt>(method_body);
183 bool ret = SynthesizeBodyResult(compound_stmt, MethodDecl);
185 if (log && log->GetVerbose()) {
187 raw_string_ostream os(s);
189 MethodDecl->print(os);
193 log->Printf("Transformed method AST:\n%s", s.c_str());
199 bool ASTResultSynthesizer::SynthesizeBodyResult(CompoundStmt *Body,
201 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
203 ASTContext &Ctx(*m_ast_context);
208 if (Body->body_empty())
211 Stmt **last_stmt_ptr = Body->body_end() - 1;
212 Stmt *last_stmt = *last_stmt_ptr;
214 while (dyn_cast<NullStmt>(last_stmt)) {
215 if (last_stmt_ptr != Body->body_begin()) {
217 last_stmt = *last_stmt_ptr;
223 Expr *last_expr = dyn_cast<Expr>(last_stmt);
226 // No auxiliary variable necessary; expression returns void
229 // In C++11, last_expr can be a LValueToRvalue implicit cast. Strip that off
230 // if that's the case.
233 ImplicitCastExpr *implicit_cast = dyn_cast<ImplicitCastExpr>(last_expr);
238 if (implicit_cast->getCastKind() != CK_LValueToRValue)
241 last_expr = implicit_cast->getSubExpr();
244 // is_lvalue is used to record whether the expression returns an assignable
245 // Lvalue or an Rvalue. This is relevant because they are handled
250 // - In AST result synthesis (here!) the expression E is transformed into an
252 // T *$__lldb_expr_result_ptr = &E.
254 // - In structure allocation, a pointer-sized slot is allocated in the
255 // struct that is to be
256 // passed into the expression.
258 // - In IR transformations, reads and writes to $__lldb_expr_result_ptr are
260 // an entry in the struct ($__lldb_arg) passed into the expression.
262 // variables are treated similarly, having been materialized as
263 // references, but in those
264 // cases the value of the reference itself is never modified.)
266 // - During materialization, $0 (the result persistent variable) is ignored.
268 // - During dematerialization, $0 is marked up as a load address with value
270 // contents of the structure entry.
274 // - In AST result synthesis the expression E is transformed into an
276 // static T $__lldb_expr_result = E.
278 // - In structure allocation, a pointer-sized slot is allocated in the
279 // struct that is to be
280 // passed into the expression.
282 // - In IR transformations, an instruction is inserted at the beginning of
284 // dereference the pointer resident in the slot. Reads and writes to
285 // $__lldb_expr_result
286 // are redirected at that dereferenced version. Guard variables for the
290 // - During materialization, $0 (the result persistent variable) is
291 // populated with the location
292 // of a newly-allocated area of memory.
294 // - During dematerialization, $0 is ignored.
296 bool is_lvalue = last_expr->getValueKind() == VK_LValue &&
297 last_expr->getObjectKind() == OK_Ordinary;
299 QualType expr_qual_type = last_expr->getType();
300 const clang::Type *expr_type = expr_qual_type.getTypePtr();
305 if (expr_type->isVoidType())
309 std::string s = expr_qual_type.getAsString();
311 log->Printf("Last statement is an %s with type: %s",
312 (is_lvalue ? "lvalue" : "rvalue"), s.c_str());
315 clang::VarDecl *result_decl = NULL;
318 IdentifierInfo *result_ptr_id;
320 if (expr_type->isFunctionType())
322 &Ctx.Idents.get("$__lldb_expr_result"); // functions actually should
323 // be treated like function
326 result_ptr_id = &Ctx.Idents.get("$__lldb_expr_result_ptr");
328 m_sema->RequireCompleteType(SourceLocation(), expr_qual_type,
329 clang::diag::err_incomplete_type);
331 QualType ptr_qual_type;
333 if (expr_qual_type->getAs<ObjCObjectType>() != NULL)
334 ptr_qual_type = Ctx.getObjCObjectPointerType(expr_qual_type);
336 ptr_qual_type = Ctx.getPointerType(expr_qual_type);
339 VarDecl::Create(Ctx, DC, SourceLocation(), SourceLocation(),
340 result_ptr_id, ptr_qual_type, NULL, SC_Static);
345 ExprResult address_of_expr =
346 m_sema->CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf, last_expr);
347 if (address_of_expr.get())
348 m_sema->AddInitializerToDecl(result_decl, address_of_expr.get(), true);
352 IdentifierInfo &result_id = Ctx.Idents.get("$__lldb_expr_result");
354 result_decl = VarDecl::Create(Ctx, DC, SourceLocation(), SourceLocation(),
355 &result_id, expr_qual_type, NULL, SC_Static);
360 m_sema->AddInitializerToDecl(result_decl, last_expr, true);
363 DC->addDecl(result_decl);
365 ///////////////////////////////
366 // call AddInitializerToDecl
369 // m_sema->AddInitializerToDecl(result_decl, last_expr);
371 /////////////////////////////////
372 // call ConvertDeclToDeclGroup
375 Sema::DeclGroupPtrTy result_decl_group_ptr;
377 result_decl_group_ptr = m_sema->ConvertDeclToDeclGroup(result_decl);
379 ////////////////////////
380 // call ActOnDeclStmt
383 StmtResult result_initialization_stmt_result(m_sema->ActOnDeclStmt(
384 result_decl_group_ptr, SourceLocation(), SourceLocation()));
386 ////////////////////////////////////////////////
387 // replace the old statement with the new one
391 reinterpret_cast<Stmt *>(result_initialization_stmt_result.get());
396 void ASTResultSynthesizer::HandleTranslationUnit(ASTContext &Ctx) {
398 m_passthrough->HandleTranslationUnit(Ctx);
401 void ASTResultSynthesizer::RecordPersistentTypes(DeclContext *FunDeclCtx) {
402 typedef DeclContext::specific_decl_iterator<TypeDecl> TypeDeclIterator;
404 for (TypeDeclIterator i = TypeDeclIterator(FunDeclCtx->decls_begin()),
405 e = TypeDeclIterator(FunDeclCtx->decls_end());
407 MaybeRecordPersistentType(*i);
411 void ASTResultSynthesizer::MaybeRecordPersistentType(TypeDecl *D) {
412 if (!D->getIdentifier())
415 StringRef name = D->getName();
417 if (name.size() == 0 || name[0] != '$')
420 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
422 ConstString name_cs(name.str().c_str());
425 log->Printf("Recording persistent type %s\n", name_cs.GetCString());
427 m_decls.push_back(D);
430 void ASTResultSynthesizer::RecordPersistentDecl(NamedDecl *D) {
431 lldbassert(m_top_level);
433 if (!D->getIdentifier())
436 StringRef name = D->getName();
438 if (name.size() == 0)
441 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
443 ConstString name_cs(name.str().c_str());
446 log->Printf("Recording persistent decl %s\n", name_cs.GetCString());
448 m_decls.push_back(D);
451 void ASTResultSynthesizer::CommitPersistentDecls() {
452 for (clang::NamedDecl *decl : m_decls) {
453 StringRef name = decl->getName();
454 ConstString name_cs(name.str().c_str());
456 Decl *D_scratch = m_target.GetClangASTImporter()->DeportDecl(
457 m_target.GetScratchClangASTContext()->getASTContext(), m_ast_context,
461 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
465 llvm::raw_string_ostream ss(s);
469 log->Printf("Couldn't commit persistent decl: %s\n", s.c_str());
475 if (NamedDecl *NamedDecl_scratch = dyn_cast<NamedDecl>(D_scratch))
476 llvm::cast<ClangPersistentVariables>(
477 m_target.GetPersistentExpressionStateForLanguage(
478 lldb::eLanguageTypeC))
479 ->RegisterPersistentDecl(name_cs, NamedDecl_scratch);
483 void ASTResultSynthesizer::HandleTagDeclDefinition(TagDecl *D) {
485 m_passthrough->HandleTagDeclDefinition(D);
488 void ASTResultSynthesizer::CompleteTentativeDefinition(VarDecl *D) {
490 m_passthrough->CompleteTentativeDefinition(D);
493 void ASTResultSynthesizer::HandleVTable(CXXRecordDecl *RD) {
495 m_passthrough->HandleVTable(RD);
498 void ASTResultSynthesizer::PrintStats() {
500 m_passthrough->PrintStats();
503 void ASTResultSynthesizer::InitializeSema(Sema &S) {
506 if (m_passthrough_sema)
507 m_passthrough_sema->InitializeSema(S);
510 void ASTResultSynthesizer::ForgetSema() {
513 if (m_passthrough_sema)
514 m_passthrough_sema->ForgetSema();