ASTResultSynthesizer.cpp revision 314564
1//===-- ASTResultSynthesizer.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#include "ASTResultSynthesizer.h" 11 12#include "ClangPersistentVariables.h" 13 14#include "lldb/Core/Log.h" 15#include "lldb/Symbol/ClangASTContext.h" 16#include "lldb/Symbol/ClangASTImporter.h" 17#include "lldb/Target/Target.h" 18#include "lldb/Utility/LLDBAssert.h" 19#include "stdlib.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" 31 32using namespace llvm; 33using namespace clang; 34using namespace lldb_private; 35 36ASTResultSynthesizer::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) { 40 if (!m_passthrough) 41 return; 42 43 m_passthrough_sema = dyn_cast<SemaConsumer>(passthrough); 44} 45 46ASTResultSynthesizer::~ASTResultSynthesizer() {} 47 48void ASTResultSynthesizer::Initialize(ASTContext &Context) { 49 m_ast_context = &Context; 50 51 if (m_passthrough) 52 m_passthrough->Initialize(Context); 53} 54 55void ASTResultSynthesizer::TransformTopLevelDecl(Decl *D) { 56 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 57 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()); 66 else 67 log->Printf("TransformTopLevelDecl(<complex>)"); 68 } 69 70 if (m_top_level) { 71 RecordPersistentDecl(named_decl); 72 } 73 } 74 75 if (LinkageSpecDecl *linkage_spec_decl = dyn_cast<LinkageSpecDecl>(D)) { 76 RecordDecl::decl_iterator decl_iterator; 77 78 for (decl_iterator = linkage_spec_decl->decls_begin(); 79 decl_iterator != linkage_spec_decl->decls_end(); ++decl_iterator) { 80 TransformTopLevelDecl(*decl_iterator); 81 } 82 } else if (!m_top_level) { 83 if (ObjCMethodDecl *method_decl = dyn_cast<ObjCMethodDecl>(D)) { 84 if (m_ast_context && 85 !method_decl->getSelector().getAsString().compare("$__lldb_expr:")) { 86 RecordPersistentTypes(method_decl); 87 SynthesizeObjCMethodResult(method_decl); 88 } 89 } else if (FunctionDecl *function_decl = dyn_cast<FunctionDecl>(D)) { 90 if (m_ast_context && 91 !function_decl->getNameInfo().getAsString().compare("$__lldb_expr")) { 92 RecordPersistentTypes(function_decl); 93 SynthesizeFunctionResult(function_decl); 94 } 95 } 96 } 97} 98 99bool ASTResultSynthesizer::HandleTopLevelDecl(DeclGroupRef D) { 100 DeclGroupRef::iterator decl_iterator; 101 102 for (decl_iterator = D.begin(); decl_iterator != D.end(); ++decl_iterator) { 103 Decl *decl = *decl_iterator; 104 105 TransformTopLevelDecl(decl); 106 } 107 108 if (m_passthrough) 109 return m_passthrough->HandleTopLevelDecl(D); 110 return true; 111} 112 113bool ASTResultSynthesizer::SynthesizeFunctionResult(FunctionDecl *FunDecl) { 114 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 115 116 if (!m_sema) 117 return false; 118 119 FunctionDecl *function_decl = FunDecl; 120 121 if (!function_decl) 122 return false; 123 124 if (log && log->GetVerbose()) { 125 std::string s; 126 raw_string_ostream os(s); 127 128 function_decl->print(os); 129 130 os.flush(); 131 132 log->Printf("Untransformed function AST:\n%s", s.c_str()); 133 } 134 135 Stmt *function_body = function_decl->getBody(); 136 CompoundStmt *compound_stmt = dyn_cast<CompoundStmt>(function_body); 137 138 bool ret = SynthesizeBodyResult(compound_stmt, function_decl); 139 140 if (log && log->GetVerbose()) { 141 std::string s; 142 raw_string_ostream os(s); 143 144 function_decl->print(os); 145 146 os.flush(); 147 148 log->Printf("Transformed function AST:\n%s", s.c_str()); 149 } 150 151 return ret; 152} 153 154bool ASTResultSynthesizer::SynthesizeObjCMethodResult( 155 ObjCMethodDecl *MethodDecl) { 156 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 157 158 if (!m_sema) 159 return false; 160 161 if (!MethodDecl) 162 return false; 163 164 if (log && log->GetVerbose()) { 165 std::string s; 166 raw_string_ostream os(s); 167 168 MethodDecl->print(os); 169 170 os.flush(); 171 172 log->Printf("Untransformed method AST:\n%s", s.c_str()); 173 } 174 175 Stmt *method_body = MethodDecl->getBody(); 176 177 if (!method_body) 178 return false; 179 180 CompoundStmt *compound_stmt = dyn_cast<CompoundStmt>(method_body); 181 182 bool ret = SynthesizeBodyResult(compound_stmt, MethodDecl); 183 184 if (log && log->GetVerbose()) { 185 std::string s; 186 raw_string_ostream os(s); 187 188 MethodDecl->print(os); 189 190 os.flush(); 191 192 log->Printf("Transformed method AST:\n%s", s.c_str()); 193 } 194 195 return ret; 196} 197 198bool ASTResultSynthesizer::SynthesizeBodyResult(CompoundStmt *Body, 199 DeclContext *DC) { 200 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 201 202 ASTContext &Ctx(*m_ast_context); 203 204 if (!Body) 205 return false; 206 207 if (Body->body_empty()) 208 return false; 209 210 Stmt **last_stmt_ptr = Body->body_end() - 1; 211 Stmt *last_stmt = *last_stmt_ptr; 212 213 while (dyn_cast<NullStmt>(last_stmt)) { 214 if (last_stmt_ptr != Body->body_begin()) { 215 last_stmt_ptr--; 216 last_stmt = *last_stmt_ptr; 217 } else { 218 return false; 219 } 220 } 221 222 Expr *last_expr = dyn_cast<Expr>(last_stmt); 223 224 if (!last_expr) 225 // No auxiliary variable necessary; expression returns void 226 return true; 227 228 // In C++11, last_expr can be a LValueToRvalue implicit cast. Strip that off 229 // if that's the 230 // case. 231 232 do { 233 ImplicitCastExpr *implicit_cast = dyn_cast<ImplicitCastExpr>(last_expr); 234 235 if (!implicit_cast) 236 break; 237 238 if (implicit_cast->getCastKind() != CK_LValueToRValue) 239 break; 240 241 last_expr = implicit_cast->getSubExpr(); 242 } while (0); 243 244 // is_lvalue is used to record whether the expression returns an assignable 245 // Lvalue or an 246 // Rvalue. This is relevant because they are handled differently. 247 // 248 // For Lvalues 249 // 250 // - In AST result synthesis (here!) the expression E is transformed into an 251 // initialization 252 // T *$__lldb_expr_result_ptr = &E. 253 // 254 // - In structure allocation, a pointer-sized slot is allocated in the 255 // struct that is to be 256 // passed into the expression. 257 // 258 // - In IR transformations, reads and writes to $__lldb_expr_result_ptr are 259 // redirected at 260 // an entry in the struct ($__lldb_arg) passed into the expression. 261 // (Other persistent 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.) 265 // 266 // - During materialization, $0 (the result persistent variable) is ignored. 267 // 268 // - During dematerialization, $0 is marked up as a load address with value 269 // equal to the 270 // contents of the structure entry. 271 // 272 // For Rvalues 273 // 274 // - In AST result synthesis the expression E is transformed into an 275 // initialization 276 // static T $__lldb_expr_result = E. 277 // 278 // - In structure allocation, a pointer-sized slot is allocated in the 279 // struct that is to be 280 // passed into the expression. 281 // 282 // - In IR transformations, an instruction is inserted at the beginning of 283 // the function to 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 287 // static variable 288 // are excised. 289 // 290 // - During materialization, $0 (the result persistent variable) is 291 // populated with the location 292 // of a newly-allocated area of memory. 293 // 294 // - During dematerialization, $0 is ignored. 295 296 bool is_lvalue = (last_expr->getValueKind() == VK_LValue || 297 last_expr->getValueKind() == VK_XValue) && 298 (last_expr->getObjectKind() == OK_Ordinary); 299 300 QualType expr_qual_type = last_expr->getType(); 301 const clang::Type *expr_type = expr_qual_type.getTypePtr(); 302 303 if (!expr_type) 304 return false; 305 306 if (expr_type->isVoidType()) 307 return true; 308 309 if (log) { 310 std::string s = expr_qual_type.getAsString(); 311 312 log->Printf("Last statement is an %s with type: %s", 313 (is_lvalue ? "lvalue" : "rvalue"), s.c_str()); 314 } 315 316 clang::VarDecl *result_decl = NULL; 317 318 if (is_lvalue) { 319 IdentifierInfo *result_ptr_id; 320 321 if (expr_type->isFunctionType()) 322 result_ptr_id = 323 &Ctx.Idents.get("$__lldb_expr_result"); // functions actually should 324 // be treated like function 325 // pointers 326 else 327 result_ptr_id = &Ctx.Idents.get("$__lldb_expr_result_ptr"); 328 329 m_sema->RequireCompleteType(SourceLocation(), expr_qual_type, 330 clang::diag::err_incomplete_type); 331 332 QualType ptr_qual_type; 333 334 if (expr_qual_type->getAs<ObjCObjectType>() != NULL) 335 ptr_qual_type = Ctx.getObjCObjectPointerType(expr_qual_type); 336 else 337 ptr_qual_type = Ctx.getPointerType(expr_qual_type); 338 339 result_decl = 340 VarDecl::Create(Ctx, DC, SourceLocation(), SourceLocation(), 341 result_ptr_id, ptr_qual_type, NULL, SC_Static); 342 343 if (!result_decl) 344 return false; 345 346 ExprResult address_of_expr = 347 m_sema->CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf, last_expr); 348 if (address_of_expr.get()) 349 m_sema->AddInitializerToDecl(result_decl, address_of_expr.get(), true); 350 else 351 return false; 352 } else { 353 IdentifierInfo &result_id = Ctx.Idents.get("$__lldb_expr_result"); 354 355 result_decl = VarDecl::Create(Ctx, DC, SourceLocation(), SourceLocation(), 356 &result_id, expr_qual_type, NULL, SC_Static); 357 358 if (!result_decl) 359 return false; 360 361 m_sema->AddInitializerToDecl(result_decl, last_expr, true); 362 } 363 364 DC->addDecl(result_decl); 365 366 /////////////////////////////// 367 // call AddInitializerToDecl 368 // 369 370 // m_sema->AddInitializerToDecl(result_decl, last_expr); 371 372 ///////////////////////////////// 373 // call ConvertDeclToDeclGroup 374 // 375 376 Sema::DeclGroupPtrTy result_decl_group_ptr; 377 378 result_decl_group_ptr = m_sema->ConvertDeclToDeclGroup(result_decl); 379 380 //////////////////////// 381 // call ActOnDeclStmt 382 // 383 384 StmtResult result_initialization_stmt_result(m_sema->ActOnDeclStmt( 385 result_decl_group_ptr, SourceLocation(), SourceLocation())); 386 387 //////////////////////////////////////////////// 388 // replace the old statement with the new one 389 // 390 391 *last_stmt_ptr = 392 reinterpret_cast<Stmt *>(result_initialization_stmt_result.get()); 393 394 return true; 395} 396 397void ASTResultSynthesizer::HandleTranslationUnit(ASTContext &Ctx) { 398 if (m_passthrough) 399 m_passthrough->HandleTranslationUnit(Ctx); 400} 401 402void ASTResultSynthesizer::RecordPersistentTypes(DeclContext *FunDeclCtx) { 403 typedef DeclContext::specific_decl_iterator<TypeDecl> TypeDeclIterator; 404 405 for (TypeDeclIterator i = TypeDeclIterator(FunDeclCtx->decls_begin()), 406 e = TypeDeclIterator(FunDeclCtx->decls_end()); 407 i != e; ++i) { 408 MaybeRecordPersistentType(*i); 409 } 410} 411 412void ASTResultSynthesizer::MaybeRecordPersistentType(TypeDecl *D) { 413 if (!D->getIdentifier()) 414 return; 415 416 StringRef name = D->getName(); 417 418 if (name.size() == 0 || name[0] != '$') 419 return; 420 421 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 422 423 ConstString name_cs(name.str().c_str()); 424 425 if (log) 426 log->Printf("Recording persistent type %s\n", name_cs.GetCString()); 427 428 m_decls.push_back(D); 429} 430 431void ASTResultSynthesizer::RecordPersistentDecl(NamedDecl *D) { 432 lldbassert(m_top_level); 433 434 if (!D->getIdentifier()) 435 return; 436 437 StringRef name = D->getName(); 438 439 if (name.size() == 0) 440 return; 441 442 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 443 444 ConstString name_cs(name.str().c_str()); 445 446 if (log) 447 log->Printf("Recording persistent decl %s\n", name_cs.GetCString()); 448 449 m_decls.push_back(D); 450} 451 452void ASTResultSynthesizer::CommitPersistentDecls() { 453 for (clang::NamedDecl *decl : m_decls) { 454 StringRef name = decl->getName(); 455 ConstString name_cs(name.str().c_str()); 456 457 Decl *D_scratch = m_target.GetClangASTImporter()->DeportDecl( 458 m_target.GetScratchClangASTContext()->getASTContext(), m_ast_context, 459 decl); 460 461 if (!D_scratch) { 462 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 463 464 if (log) { 465 std::string s; 466 llvm::raw_string_ostream ss(s); 467 decl->dump(ss); 468 ss.flush(); 469 470 log->Printf("Couldn't commit persistent decl: %s\n", s.c_str()); 471 } 472 473 continue; 474 } 475 476 if (NamedDecl *NamedDecl_scratch = dyn_cast<NamedDecl>(D_scratch)) 477 llvm::cast<ClangPersistentVariables>( 478 m_target.GetPersistentExpressionStateForLanguage( 479 lldb::eLanguageTypeC)) 480 ->RegisterPersistentDecl(name_cs, NamedDecl_scratch); 481 } 482} 483 484void ASTResultSynthesizer::HandleTagDeclDefinition(TagDecl *D) { 485 if (m_passthrough) 486 m_passthrough->HandleTagDeclDefinition(D); 487} 488 489void ASTResultSynthesizer::CompleteTentativeDefinition(VarDecl *D) { 490 if (m_passthrough) 491 m_passthrough->CompleteTentativeDefinition(D); 492} 493 494void ASTResultSynthesizer::HandleVTable(CXXRecordDecl *RD) { 495 if (m_passthrough) 496 m_passthrough->HandleVTable(RD); 497} 498 499void ASTResultSynthesizer::PrintStats() { 500 if (m_passthrough) 501 m_passthrough->PrintStats(); 502} 503 504void ASTResultSynthesizer::InitializeSema(Sema &S) { 505 m_sema = &S; 506 507 if (m_passthrough_sema) 508 m_passthrough_sema->InitializeSema(S); 509} 510 511void ASTResultSynthesizer::ForgetSema() { 512 m_sema = NULL; 513 514 if (m_passthrough_sema) 515 m_passthrough_sema->ForgetSema(); 516} 517