IRForTarget.cpp revision c0492741dc594cd02736521048fe0d8f4c9a0a61
1//===-- IRForTarget.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 "lldb/Expression/IRForTarget.h" 11 12#include "llvm/Support/raw_ostream.h" 13#include "llvm/Constants.h" 14#include "llvm/InstrTypes.h" 15#include "llvm/Instructions.h" 16#include "llvm/Intrinsics.h" 17#include "llvm/Module.h" 18#include "llvm/Target/TargetData.h" 19#include "llvm/ValueSymbolTable.h" 20 21#include "clang/AST/ASTContext.h" 22 23#include "lldb/Core/ConstString.h" 24#include "lldb/Core/dwarf.h" 25#include "lldb/Core/Log.h" 26#include "lldb/Core/Scalar.h" 27#include "lldb/Core/StreamString.h" 28#include "lldb/Expression/ClangExpressionDeclMap.h" 29#include "lldb/Host/Endian.h" 30#include "lldb/Symbol/ClangASTContext.h" 31 32#include <map> 33 34using namespace llvm; 35 36static char ID; 37 38IRForTarget::StaticDataAllocator::StaticDataAllocator() 39{ 40} 41 42IRForTarget::StaticDataAllocator::~StaticDataAllocator() 43{ 44} 45 46IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map, 47 bool resolve_vars, 48 lldb::ClangExpressionVariableSP &const_result, 49 StaticDataAllocator *data_allocator, 50 lldb_private::Stream *error_stream, 51 const char *func_name) : 52 ModulePass(ID), 53 m_resolve_vars(resolve_vars), 54 m_func_name(func_name), 55 m_decl_map(decl_map), 56 m_module(NULL), 57 m_CFStringCreateWithBytes(NULL), 58 m_sel_registerName(NULL), 59 m_error_stream(error_stream), 60 m_has_side_effects(false), 61 m_result_store(NULL), 62 m_result_is_pointer(false), 63 m_const_result(const_result), 64 m_data_allocator(data_allocator), 65 m_reloc_placeholder(NULL) 66{ 67} 68 69/* Handy utility functions used at several places in the code */ 70 71static std::string 72PrintValue(const Value *value, bool truncate = false) 73{ 74 std::string s; 75 raw_string_ostream rso(s); 76 value->print(rso); 77 rso.flush(); 78 if (truncate) 79 s.resize(s.length() - 1); 80 return s; 81} 82 83static std::string 84PrintType(const Type *type, bool truncate = false) 85{ 86 std::string s; 87 raw_string_ostream rso(s); 88 type->print(rso); 89 rso.flush(); 90 if (truncate) 91 s.resize(s.length() - 1); 92 return s; 93} 94 95IRForTarget::~IRForTarget() 96{ 97} 98 99bool 100IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function) 101{ 102 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 103 104 llvm_function.setLinkage(GlobalValue::ExternalLinkage); 105 106 std::string name = llvm_function.getNameStr(); 107 108 return true; 109} 110 111bool 112IRForTarget::HasSideEffects (llvm::Function &llvm_function) 113{ 114 llvm::Function::iterator bbi; 115 BasicBlock::iterator ii; 116 117 for (bbi = llvm_function.begin(); 118 bbi != llvm_function.end(); 119 ++bbi) 120 { 121 BasicBlock &basic_block = *bbi; 122 123 for (ii = basic_block.begin(); 124 ii != basic_block.end(); 125 ++ii) 126 { 127 switch (ii->getOpcode()) 128 { 129 default: 130 return true; 131 case Instruction::Store: 132 { 133 StoreInst *store_inst = dyn_cast<StoreInst>(ii); 134 135 Value *store_ptr = store_inst->getPointerOperand(); 136 137 std::string ptr_name; 138 139 if (store_ptr->hasName()) 140 ptr_name = store_ptr->getNameStr(); 141 142 if (isa <AllocaInst> (store_ptr)) 143 break; 144 145 if (ptr_name.find("$__lldb_expr_result") != std::string::npos) 146 { 147 if (ptr_name.find("GV") == std::string::npos) 148 m_result_store = store_inst; 149 } 150 else 151 { 152 return true; 153 } 154 155 break; 156 } 157 case Instruction::Load: 158 case Instruction::Alloca: 159 case Instruction::GetElementPtr: 160 case Instruction::BitCast: 161 case Instruction::Ret: 162 case Instruction::ICmp: 163 case Instruction::Br: 164 break; 165 } 166 } 167 } 168 169 return false; 170} 171 172clang::NamedDecl * 173IRForTarget::DeclForGlobal (GlobalValue *global_val) 174{ 175 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 176 177 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs"); 178 179 if (!named_metadata) 180 return NULL; 181 182 unsigned num_nodes = named_metadata->getNumOperands(); 183 unsigned node_index; 184 185 for (node_index = 0; 186 node_index < num_nodes; 187 ++node_index) 188 { 189 MDNode *metadata_node = named_metadata->getOperand(node_index); 190 191 if (!metadata_node) 192 return NULL; 193 194 if (metadata_node->getNumOperands() != 2) 195 continue; 196 197 if (metadata_node->getOperand(0) != global_val) 198 continue; 199 200 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1)); 201 202 if (!constant_int) 203 return NULL; 204 205 uintptr_t ptr = constant_int->getZExtValue(); 206 207 return reinterpret_cast<clang::NamedDecl *>(ptr); 208 } 209 210 return NULL; 211} 212 213void 214IRForTarget::MaybeSetConstantResult (llvm::Constant *initializer, 215 const lldb_private::ConstString &name, 216 lldb_private::TypeFromParser type) 217{ 218 if (llvm::ConstantExpr *init_expr = dyn_cast<llvm::ConstantExpr>(initializer)) 219 { 220 switch (init_expr->getOpcode()) 221 { 222 default: 223 return; 224 case Instruction::IntToPtr: 225 MaybeSetConstantResult (init_expr->getOperand(0), name, type); 226 return; 227 } 228 } 229 else if (llvm::ConstantInt *init_int = dyn_cast<llvm::ConstantInt>(initializer)) 230 { 231 m_const_result = m_decl_map->BuildIntegerVariable(name, type, init_int->getValue()); 232 } 233} 234 235void 236IRForTarget::MaybeSetCastResult (lldb_private::TypeFromParser type) 237{ 238 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 239 240 if (!m_result_store) 241 return; 242 243 LoadInst *original_load = NULL; 244 245 for (llvm::Value *current_value = m_result_store->getValueOperand(), *next_value; 246 current_value != NULL; 247 current_value = next_value) 248 { 249 CastInst *cast_inst = dyn_cast<CastInst>(current_value); 250 LoadInst *load_inst = dyn_cast<LoadInst>(current_value); 251 252 if (cast_inst) 253 { 254 next_value = cast_inst->getOperand(0); 255 } 256 else if(load_inst) 257 { 258 if (isa<LoadInst>(load_inst->getPointerOperand())) 259 { 260 next_value = load_inst->getPointerOperand(); 261 } 262 else 263 { 264 original_load = load_inst; 265 break; 266 } 267 } 268 else 269 { 270 return; 271 } 272 } 273 274 Value *loaded_value = original_load->getPointerOperand(); 275 GlobalVariable *loaded_global = dyn_cast<GlobalVariable>(loaded_value); 276 277 if (!loaded_global) 278 return; 279 280 clang::NamedDecl *loaded_decl = DeclForGlobal(loaded_global); 281 282 if (!loaded_decl) 283 return; 284 285 clang::VarDecl *loaded_var = dyn_cast<clang::VarDecl>(loaded_decl); 286 287 if (!loaded_var) 288 return; 289 290 if (log) 291 { 292 lldb_private::StreamString type_desc_stream; 293 type.DumpTypeDescription(&type_desc_stream); 294 295 log->Printf("Type to cast variable to: \"%s\"", type_desc_stream.GetString().c_str()); 296 } 297 298 m_const_result = m_decl_map->BuildCastVariable(m_result_name, loaded_var, type); 299} 300 301bool 302IRForTarget::CreateResultVariable (llvm::Function &llvm_function) 303{ 304 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 305 306 if (!m_resolve_vars) 307 return true; 308 309 // Find the result variable. If it doesn't exist, we can give up right here. 310 311 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable(); 312 313 const char *result_name = NULL; 314 315 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end(); 316 vi != ve; 317 ++vi) 318 { 319 if (strstr(vi->first(), "$__lldb_expr_result_ptr") && 320 !strstr(vi->first(), "GV")) 321 { 322 result_name = vi->first(); 323 m_result_is_pointer = true; 324 break; 325 } 326 327 if (strstr(vi->first(), "$__lldb_expr_result") && 328 !strstr(vi->first(), "GV")) 329 { 330 result_name = vi->first(); 331 m_result_is_pointer = false; 332 break; 333 } 334 } 335 336 if (!result_name) 337 { 338 if (log) 339 log->PutCString("Couldn't find result variable"); 340 341 return true; 342 } 343 344 if (log) 345 log->Printf("Result name: \"%s\"", result_name); 346 347 Value *result_value = m_module->getNamedValue(result_name); 348 349 if (!result_value) 350 { 351 if (log) 352 log->PutCString("Result variable had no data"); 353 354 if (m_error_stream) 355 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name); 356 357 return false; 358 } 359 360 if (log) 361 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str()); 362 363 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value); 364 365 if (!result_global) 366 { 367 if (log) 368 log->PutCString("Result variable isn't a GlobalVariable"); 369 370 if (m_error_stream) 371 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name); 372 373 return false; 374 } 375 376 clang::NamedDecl *result_decl = DeclForGlobal (result_global); 377 if (!result_decl) 378 { 379 if (log) 380 log->PutCString("Result variable doesn't have a corresponding Decl"); 381 382 if (m_error_stream) 383 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name); 384 385 return false; 386 } 387 388 if (log) 389 { 390 std::string decl_desc_str; 391 raw_string_ostream decl_desc_stream(decl_desc_str); 392 result_decl->print(decl_desc_stream); 393 decl_desc_stream.flush(); 394 395 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str()); 396 } 397 398 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl); 399 if (!result_var) 400 { 401 if (log) 402 log->PutCString("Result variable Decl isn't a VarDecl"); 403 404 if (m_error_stream) 405 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name); 406 407 return false; 408 } 409 410 // Get the next available result name from m_decl_map and create the persistent 411 // variable for it 412 413 lldb_private::TypeFromParser result_decl_type; 414 415 // If the result is an Lvalue, it is emitted as a pointer; see 416 // ASTResultSynthesizer::SynthesizeBodyResult. 417 if (m_result_is_pointer) 418 { 419 clang::QualType pointer_qual_type = result_var->getType(); 420 const clang::Type *pointer_type = pointer_qual_type.getTypePtr(); 421 const clang::PointerType *pointer_pointertype = dyn_cast<clang::PointerType>(pointer_type); 422 423 if (!pointer_pointertype) 424 { 425 if (log) 426 log->PutCString("Expected result to have pointer type, but it did not"); 427 428 if (m_error_stream) 429 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name); 430 431 return false; 432 } 433 434 clang::QualType element_qual_type = pointer_pointertype->getPointeeType(); 435 436 result_decl_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(), 437 &result_decl->getASTContext()); 438 } 439 else 440 { 441 result_decl_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(), 442 &result_decl->getASTContext()); 443 } 444 445 if (log) 446 { 447 lldb_private::StreamString type_desc_stream; 448 result_decl_type.DumpTypeDescription(&type_desc_stream); 449 450 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetString().c_str()); 451 } 452 453 m_result_name = m_decl_map->GetPersistentResultName(); 454 455 if (log) 456 log->Printf("Creating a new result global: \"%s\"", m_result_name.GetCString()); 457 458 // Construct a new result global and set up its metadata 459 460 GlobalVariable *new_result_global = new GlobalVariable((*m_module), 461 result_global->getType()->getElementType(), 462 false, /* not constant */ 463 GlobalValue::ExternalLinkage, 464 NULL, /* no initializer */ 465 m_result_name.GetCString ()); 466 467 // It's too late in compilation to create a new VarDecl for this, but we don't 468 // need to. We point the metadata at the old VarDecl. This creates an odd 469 // anomaly: a variable with a Value whose name is something like $0 and a 470 // Decl whose name is $__lldb_expr_result. This condition is handled in 471 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is 472 // fixed up. 473 474 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()), 475 reinterpret_cast<uint64_t>(result_decl), 476 false); 477 478 llvm::Value* values[2]; 479 values[0] = new_result_global; 480 values[1] = new_constant_int; 481 482 ArrayRef<Value*> value_ref(values, 2); 483 484 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref); 485 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs"); 486 named_metadata->addOperand(persistent_global_md); 487 488 if (log) 489 log->Printf("Replacing \"%s\" with \"%s\"", 490 PrintValue(result_global).c_str(), 491 PrintValue(new_result_global).c_str()); 492 493 if (result_global->hasNUses(0)) 494 { 495 // We need to synthesize a store for this variable, because otherwise 496 // there's nothing to put into its equivalent persistent variable. 497 498 BasicBlock &entry_block(llvm_function.getEntryBlock()); 499 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg()); 500 501 if (!first_entry_instruction) 502 return false; 503 504 if (!result_global->hasInitializer()) 505 { 506 if (log) 507 log->Printf("Couldn't find initializer for unused variable"); 508 509 if (m_error_stream) 510 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name); 511 512 return false; 513 } 514 515 Constant *initializer = result_global->getInitializer(); 516 517 // Here we write the initializer into a result variable assuming it 518 // can be computed statically. 519 520 if (!m_has_side_effects) 521 { 522 MaybeSetConstantResult (initializer, 523 m_result_name, 524 result_decl_type); 525 } 526 527 StoreInst *synthesized_store = new StoreInst(initializer, 528 new_result_global, 529 first_entry_instruction); 530 531 if (log) 532 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str()); 533 } 534 else 535 { 536 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (result_decl_type.GetOpaqueQualType())) 537 { 538 MaybeSetCastResult (result_decl_type); 539 } 540 541 result_global->replaceAllUsesWith(new_result_global); 542 } 543 544 if (!m_const_result) 545 m_decl_map->AddPersistentVariable(result_decl, 546 m_result_name, 547 result_decl_type, 548 true, 549 m_result_is_pointer); 550 551 result_global->eraseFromParent(); 552 553 return true; 554} 555 556static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth) 557{ 558 if (!depth) 559 return; 560 561 depth--; 562 563 log->Printf(" <Begin %d users>", value->getNumUses()); 564 565 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end(); 566 ui != ue; 567 ++ui) 568 { 569 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str()); 570 DebugUsers(log, *ui, depth); 571 } 572 573 log->Printf(" <End uses>"); 574} 575 576bool 577IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str, 578 llvm::GlobalVariable *cstr, 579 Instruction *FirstEntryInstruction) 580{ 581 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 582 583 const Type *ns_str_ty = ns_str->getType(); 584 585 const Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext()); 586 const IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(), 587 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32); 588 const Type *i32_ty = Type::getInt32Ty(m_module->getContext()); 589 const Type *i8_ty = Type::getInt8Ty(m_module->getContext()); 590 591 if (!m_CFStringCreateWithBytes) 592 { 593 lldb::addr_t CFStringCreateWithBytes_addr; 594 595 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes"); 596 597 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr)) 598 { 599 if (log) 600 log->PutCString("Couldn't find CFStringCreateWithBytes in the target"); 601 602 if (m_error_stream) 603 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n"); 604 605 return false; 606 } 607 608 if (log) 609 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr); 610 611 // Build the function type: 612 // 613 // CFStringRef CFStringCreateWithBytes ( 614 // CFAllocatorRef alloc, 615 // const UInt8 *bytes, 616 // CFIndex numBytes, 617 // CFStringEncoding encoding, 618 // Boolean isExternalRepresentation 619 // ); 620 // 621 // We make the following substitutions: 622 // 623 // CFStringRef -> i8* 624 // CFAllocatorRef -> i8* 625 // UInt8 * -> i8* 626 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now) 627 // CFStringEncoding -> i32 628 // Boolean -> i8 629 630 std::vector <const Type *> CFSCWB_arg_types; 631 CFSCWB_arg_types.push_back(i8_ptr_ty); 632 CFSCWB_arg_types.push_back(i8_ptr_ty); 633 CFSCWB_arg_types.push_back(intptr_ty); 634 CFSCWB_arg_types.push_back(i32_ty); 635 CFSCWB_arg_types.push_back(i8_ty); 636 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false); 637 638 // Build the constant containing the pointer to the function 639 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty); 640 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false); 641 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty); 642 } 643 644 ConstantArray *string_array; 645 646 if (cstr) 647 string_array = dyn_cast<ConstantArray>(cstr->getInitializer()); 648 else 649 string_array = NULL; 650 651 SmallVector <Value*, 5> CFSCWB_arguments; 652 653 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty); 654 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty); 655 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getType()->getNumElements() - 1 : 0, false); 656 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */ 657 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */ 658 659 CFSCWB_arguments.push_back(alloc_arg); 660 CFSCWB_arguments.push_back(bytes_arg); 661 CFSCWB_arguments.push_back(numBytes_arg); 662 CFSCWB_arguments.push_back(encoding_arg); 663 CFSCWB_arguments.push_back(isExternal_arg); 664 665 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes, 666 CFSCWB_arguments.begin(), 667 CFSCWB_arguments.end(), 668 "CFStringCreateWithBytes", 669 FirstEntryInstruction); 670 671 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction)) 672 { 673 if (log) 674 log->PutCString("Couldn't replace the NSString with the result of the call"); 675 676 if (m_error_stream) 677 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n"); 678 679 return false; 680 } 681 682 ns_str->eraseFromParent(); 683 684 return true; 685} 686 687bool 688IRForTarget::RewriteObjCConstStrings(Function &llvm_function) 689{ 690 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 691 692 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable(); 693 694 BasicBlock &entry_block(llvm_function.getEntryBlock()); 695 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg()); 696 697 if (!FirstEntryInstruction) 698 { 699 if (log) 700 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings"); 701 702 if (m_error_stream) 703 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n"); 704 705 return false; 706 } 707 708 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end(); 709 vi != ve; 710 ++vi) 711 { 712 if (strstr(vi->first(), "_unnamed_cfstring_")) 713 { 714 Value *nsstring_value = vi->second; 715 716 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value); 717 718 if (!nsstring_global) 719 { 720 if (log) 721 log->PutCString("NSString variable is not a GlobalVariable"); 722 723 if (m_error_stream) 724 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n"); 725 726 return false; 727 } 728 729 if (!nsstring_global->hasInitializer()) 730 { 731 if (log) 732 log->PutCString("NSString variable does not have an initializer"); 733 734 if (m_error_stream) 735 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n"); 736 737 return false; 738 } 739 740 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer()); 741 742 if (!nsstring_struct) 743 { 744 if (log) 745 log->PutCString("NSString variable's initializer is not a ConstantStruct"); 746 747 if (m_error_stream) 748 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n"); 749 750 return false; 751 } 752 753 // We expect the following structure: 754 // 755 // struct { 756 // int *isa; 757 // int flags; 758 // char *str; 759 // long length; 760 // }; 761 762 if (nsstring_struct->getNumOperands() != 4) 763 { 764 if (log) 765 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands()); 766 767 if (m_error_stream) 768 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n"); 769 770 return false; 771 } 772 773 Constant *nsstring_member = nsstring_struct->getOperand(2); 774 775 if (!nsstring_member) 776 { 777 if (log) 778 log->PutCString("NSString initializer's str element was empty"); 779 780 if (m_error_stream) 781 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n"); 782 783 return false; 784 } 785 786 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member); 787 788 if (!nsstring_expr) 789 { 790 if (log) 791 log->PutCString("NSString initializer's str element is not a ConstantExpr"); 792 793 if (m_error_stream) 794 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n"); 795 796 return false; 797 } 798 799 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr) 800 { 801 if (log) 802 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName()); 803 804 if (m_error_stream) 805 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n"); 806 807 return false; 808 } 809 810 Constant *nsstring_cstr = nsstring_expr->getOperand(0); 811 812 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr); 813 814 if (!cstr_global) 815 { 816 if (log) 817 log->PutCString("NSString initializer's str element is not a GlobalVariable"); 818 819 if (m_error_stream) 820 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n"); 821 822 return false; 823 } 824 825 if (!cstr_global->hasInitializer()) 826 { 827 if (log) 828 log->PutCString("NSString initializer's str element does not have an initializer"); 829 830 if (m_error_stream) 831 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n"); 832 833 return false; 834 } 835 836 /* 837 if (!cstr_array) 838 { 839 if (log) 840 log->PutCString("NSString initializer's str element is not a ConstantArray"); 841 842 if (m_error_stream) 843 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n"); 844 845 return false; 846 } 847 848 if (!cstr_array->isCString()) 849 { 850 if (log) 851 log->PutCString("NSString initializer's str element is not a C string array"); 852 853 if (m_error_stream) 854 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n"); 855 856 return false; 857 } 858 */ 859 860 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer()); 861 862 if (log) 863 { 864 if (cstr_array) 865 log->Printf("Found NSString constant %s, which contains \"%s\"", vi->first(), cstr_array->getAsString().c_str()); 866 else 867 log->Printf("Found NSString constant %s, which contains \"\"", vi->first()); 868 } 869 870 if (!cstr_array) 871 cstr_global = NULL; 872 873 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction)) 874 { 875 if (log) 876 log->PutCString("Error rewriting the constant string"); 877 878 // We don't print an error message here because RewriteObjCConstString has done so for us. 879 880 return false; 881 } 882 } 883 } 884 885 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end(); 886 vi != ve; 887 ++vi) 888 { 889 if (!strcmp(vi->first(), "__CFConstantStringClassReference")) 890 { 891 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second); 892 893 if (!gv) 894 { 895 if (log) 896 log->PutCString("__CFConstantStringClassReference is not a global variable"); 897 898 if (m_error_stream) 899 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n"); 900 901 return false; 902 } 903 904 gv->eraseFromParent(); 905 906 break; 907 } 908 } 909 910 return true; 911} 912 913static bool IsObjCSelectorRef (Value *value) 914{ 915 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value); 916 917 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_")) 918 return false; 919 920 return true; 921} 922 923// This function does not report errors; its callers are responsible. 924bool 925IRForTarget::RewriteObjCSelector (Instruction* selector_load) 926{ 927 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 928 929 LoadInst *load = dyn_cast<LoadInst>(selector_load); 930 931 if (!load) 932 return false; 933 934 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as 935 // 936 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*> 937 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*> 938 // 939 // where %obj is the object pointer and %tmp is the selector. 940 // 941 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_". 942 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string. 943 944 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target 945 946 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand()); 947 948 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer()) 949 return false; 950 951 Constant *osr_initializer = _objc_selector_references_->getInitializer(); 952 953 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer); 954 955 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr) 956 return false; 957 958 Value *osr_initializer_base = osr_initializer_expr->getOperand(0); 959 960 if (!osr_initializer_base) 961 return false; 962 963 // Find the string's initializer (a ConstantArray) and get the string from it 964 965 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base); 966 967 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer()) 968 return false; 969 970 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer(); 971 972 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer); 973 974 if (!omvn_initializer_array->isString()) 975 return false; 976 977 std::string omvn_initializer_string = omvn_initializer_array->getAsString(); 978 979 if (log) 980 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str()); 981 982 // Construct a call to sel_registerName 983 984 if (!m_sel_registerName) 985 { 986 lldb::addr_t sel_registerName_addr; 987 988 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName"); 989 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr)) 990 return false; 991 992 if (log) 993 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr); 994 995 // Build the function type: struct objc_selector *sel_registerName(uint8_t*) 996 997 // The below code would be "more correct," but in actuality what's required is uint8_t* 998 //Type *sel_type = StructType::get(m_module->getContext()); 999 //Type *sel_ptr_type = PointerType::getUnqual(sel_type); 1000 const Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext()); 1001 1002 std::vector <const Type *> srN_arg_types; 1003 srN_arg_types.push_back(Type::getInt8PtrTy(m_module->getContext())); 1004 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false); 1005 1006 // Build the constant containing the pointer to the function 1007 const IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(), 1008 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32); 1009 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type); 1010 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false); 1011 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty); 1012 } 1013 1014 SmallVector <Value*, 1> srN_arguments; 1015 1016 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext())); 1017 1018 srN_arguments.push_back(omvn_pointer); 1019 1020 CallInst *srN_call = CallInst::Create(m_sel_registerName, 1021 srN_arguments.begin(), 1022 srN_arguments.end(), 1023 "sel_registerName", 1024 selector_load); 1025 1026 // Replace the load with the call in all users 1027 1028 selector_load->replaceAllUsesWith(srN_call); 1029 1030 selector_load->eraseFromParent(); 1031 1032 return true; 1033} 1034 1035bool 1036IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block) 1037{ 1038 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1039 1040 BasicBlock::iterator ii; 1041 1042 typedef SmallVector <Instruction*, 2> InstrList; 1043 typedef InstrList::iterator InstrIterator; 1044 1045 InstrList selector_loads; 1046 1047 for (ii = basic_block.begin(); 1048 ii != basic_block.end(); 1049 ++ii) 1050 { 1051 Instruction &inst = *ii; 1052 1053 if (LoadInst *load = dyn_cast<LoadInst>(&inst)) 1054 if (IsObjCSelectorRef(load->getPointerOperand())) 1055 selector_loads.push_back(&inst); 1056 } 1057 1058 InstrIterator iter; 1059 1060 for (iter = selector_loads.begin(); 1061 iter != selector_loads.end(); 1062 ++iter) 1063 { 1064 if (!RewriteObjCSelector(*iter)) 1065 { 1066 if (m_error_stream) 1067 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n"); 1068 1069 if(log) 1070 log->PutCString("Couldn't rewrite a reference to an Objective-C selector"); 1071 1072 return false; 1073 } 1074 } 1075 1076 return true; 1077} 1078 1079// This function does not report errors; its callers are responsible. 1080bool 1081IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc) 1082{ 1083 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1084 1085 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc); 1086 1087 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr"); 1088 1089 if (!alloc_md || !alloc_md->getNumOperands()) 1090 return false; 1091 1092 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0)); 1093 1094 if (!constant_int) 1095 return false; 1096 1097 // We attempt to register this as a new persistent variable with the DeclMap. 1098 1099 uintptr_t ptr = constant_int->getZExtValue(); 1100 1101 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr); 1102 1103 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(), 1104 &decl->getASTContext()); 1105 1106 StringRef decl_name (decl->getName()); 1107 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size()); 1108 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false)) 1109 return false; 1110 1111 GlobalVariable *persistent_global = new GlobalVariable((*m_module), 1112 alloc->getType(), 1113 false, /* not constant */ 1114 GlobalValue::ExternalLinkage, 1115 NULL, /* no initializer */ 1116 alloc->getName().str().c_str()); 1117 1118 // What we're going to do here is make believe this was a regular old external 1119 // variable. That means we need to make the metadata valid. 1120 1121 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs"); 1122 1123 llvm::Value* values[2]; 1124 values[0] = persistent_global; 1125 values[1] = constant_int; 1126 1127 ArrayRef<llvm::Value*> value_ref(values, 2); 1128 1129 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref); 1130 named_metadata->addOperand(persistent_global_md); 1131 1132 // Now, since the variable is a pointer variable, we will drop in a load of that 1133 // pointer variable. 1134 1135 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc); 1136 1137 if (log) 1138 log->Printf("Replacing \"%s\" with \"%s\"", 1139 PrintValue(alloc).c_str(), 1140 PrintValue(persistent_load).c_str()); 1141 1142 alloc->replaceAllUsesWith(persistent_load); 1143 alloc->eraseFromParent(); 1144 1145 return true; 1146} 1147 1148bool 1149IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block) 1150{ 1151 if (!m_resolve_vars) 1152 return true; 1153 1154 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1155 1156 BasicBlock::iterator ii; 1157 1158 typedef SmallVector <Instruction*, 2> InstrList; 1159 typedef InstrList::iterator InstrIterator; 1160 1161 InstrList pvar_allocs; 1162 1163 for (ii = basic_block.begin(); 1164 ii != basic_block.end(); 1165 ++ii) 1166 { 1167 Instruction &inst = *ii; 1168 1169 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) 1170 { 1171 llvm::StringRef alloc_name = alloc->getName(); 1172 1173 if (alloc_name.startswith("$") && 1174 !alloc_name.startswith("$__lldb")) 1175 { 1176 if (alloc_name.find_first_of("0123456789") == 1) 1177 { 1178 if (log) 1179 log->Printf("Rejecting a numeric persistent variable."); 1180 1181 if (m_error_stream) 1182 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n"); 1183 1184 return false; 1185 } 1186 1187 pvar_allocs.push_back(alloc); 1188 } 1189 } 1190 } 1191 1192 InstrIterator iter; 1193 1194 for (iter = pvar_allocs.begin(); 1195 iter != pvar_allocs.end(); 1196 ++iter) 1197 { 1198 if (!RewritePersistentAlloc(*iter)) 1199 { 1200 if (m_error_stream) 1201 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n"); 1202 1203 if(log) 1204 log->PutCString("Couldn't rewrite the creation of a persistent variable"); 1205 1206 return false; 1207 } 1208 } 1209 1210 return true; 1211} 1212 1213// This function does not report errors; its callers are responsible. 1214bool 1215IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr) 1216{ 1217 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1218 1219 if (log) 1220 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str()); 1221 1222 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) 1223 { 1224 switch (constant_expr->getOpcode()) 1225 { 1226 default: 1227 break; 1228 case Instruction::GetElementPtr: 1229 case Instruction::BitCast: 1230 Value *s = constant_expr->getOperand(0); 1231 if (!MaybeHandleVariable(s)) 1232 return false; 1233 } 1234 } 1235 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr)) 1236 { 1237 clang::NamedDecl *named_decl = DeclForGlobal(global_variable); 1238 1239 if (!named_decl) 1240 { 1241 if (IsObjCSelectorRef(llvm_value_ptr)) 1242 return true; 1243 1244 if (!global_variable->hasExternalLinkage()) 1245 return true; 1246 1247 if (log) 1248 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str()); 1249 1250 return false; 1251 } 1252 1253 std::string name (named_decl->getName().str()); 1254 1255 void *opaque_type = NULL; 1256 clang::ASTContext *ast_context = NULL; 1257 1258 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl)) 1259 { 1260 opaque_type = value_decl->getType().getAsOpaquePtr(); 1261 ast_context = &value_decl->getASTContext(); 1262 } 1263 else 1264 { 1265 return false; 1266 } 1267 1268 clang::QualType qual_type; 1269 const Type *value_type; 1270 1271 if (name[0] == '$') 1272 { 1273 // The $__lldb_expr_result name indicates the the return value has allocated as 1274 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, 1275 // accesses to this static variable need to be redirected to the result of dereferencing 1276 // a pointer that is passed in as one of the arguments. 1277 // 1278 // Consequently, when reporting the size of the type, we report a pointer type pointing 1279 // to the type of $__lldb_expr_result, not the type itself. 1280 // 1281 // We also do this for any user-declared persistent variables. 1282 1283 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type)); 1284 value_type = PointerType::get(global_variable->getType(), 0); 1285 } 1286 else 1287 { 1288 qual_type = clang::QualType::getFromOpaquePtr(opaque_type); 1289 value_type = global_variable->getType(); 1290 } 1291 1292 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8; 1293 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8; 1294 1295 if (log) 1296 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %d, align %d]", 1297 name.c_str(), 1298 qual_type.getAsString().c_str(), 1299 PrintType(value_type).c_str(), 1300 value_size, 1301 value_alignment); 1302 1303 1304 if (named_decl && !m_decl_map->AddValueToStruct(named_decl, 1305 lldb_private::ConstString (name.c_str()), 1306 llvm_value_ptr, 1307 value_size, 1308 value_alignment)) 1309 return false; 1310 } 1311 else if (dyn_cast<llvm::Function>(llvm_value_ptr)) 1312 { 1313 if (log) 1314 log->Printf("Function pointers aren't handled right now"); 1315 1316 return false; 1317 } 1318 1319 return true; 1320} 1321 1322// This function does not report errors; its callers are responsible. 1323bool 1324IRForTarget::HandleSymbol (Value *symbol) 1325{ 1326 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1327 1328 lldb_private::ConstString name(symbol->getName().str().c_str()); 1329 1330 uint64_t symbol_addr; 1331 1332 if (!m_decl_map->GetSymbolAddress (name, symbol_addr)) 1333 { 1334 if (log) 1335 log->Printf ("Symbol \"%s\" had no address", name.GetCString()); 1336 1337 return false; 1338 } 1339 1340 if (log) 1341 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), symbol_addr); 1342 1343 const Type *symbol_type = symbol->getType(); 1344 1345 const IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(), 1346 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32); 1347 1348 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false); 1349 1350 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type); 1351 1352 if (log) 1353 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str()); 1354 1355 symbol->replaceAllUsesWith(symbol_addr_ptr); 1356 1357 return true; 1358} 1359 1360bool 1361IRForTarget::MaybeHandleCallArguments (CallInst *Old) 1362{ 1363 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1364 1365 if (log) 1366 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str()); 1367 1368 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands(); 1369 op_index < num_ops; 1370 ++op_index) 1371 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store 1372 { 1373 if (m_error_stream) 1374 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n"); 1375 1376 return false; 1377 } 1378 1379 return true; 1380} 1381 1382bool 1383IRForTarget::MaybeHandleCall (CallInst *llvm_call_inst) 1384{ 1385 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1386 1387 Function *fun = llvm_call_inst->getCalledFunction(); 1388 1389 if (fun == NULL) 1390 { 1391 Value *val = llvm_call_inst->getCalledValue(); 1392 1393 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(val); 1394 LoadInst *load_inst = dyn_cast<LoadInst>(val); 1395 1396 if (const_expr && const_expr->getOpcode() == Instruction::BitCast) 1397 { 1398 fun = dyn_cast<Function>(const_expr->getOperand(0)); 1399 1400 if (!fun) 1401 { 1402 if (m_error_stream) 1403 m_error_stream->Printf("Internal error [IRForTarget]: Called entity is a cast of something not a function\n"); 1404 1405 return false; 1406 } 1407 } 1408 else if (const_expr && const_expr->getOpcode() == Instruction::IntToPtr) 1409 { 1410 return true; // already resolved 1411 } 1412 else if (load_inst) 1413 { 1414 return true; // virtual method call 1415 } 1416 else 1417 { 1418 if (m_error_stream) 1419 m_error_stream->Printf("Internal error [IRForTarget]: Called entity is not a function\n"); 1420 1421 return false; 1422 } 1423 } 1424 1425 lldb_private::ConstString str; 1426 1427 if (fun->isIntrinsic()) 1428 { 1429 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID(); 1430 1431 switch (intrinsic_id) 1432 { 1433 default: 1434 if (log) 1435 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str()); 1436 1437 if (m_error_stream) 1438 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str()); 1439 1440 return false; 1441 case Intrinsic::memcpy: 1442 { 1443 static lldb_private::ConstString g_memcpy_str ("memcpy"); 1444 str = g_memcpy_str; 1445 } 1446 break; 1447 } 1448 1449 if (log && str) 1450 log->Printf("Resolved intrinsic name \"%s\"", str.GetCString()); 1451 } 1452 else 1453 { 1454 str.SetCStringWithLength (fun->getName().data(), fun->getName().size()); 1455 } 1456 1457 clang::NamedDecl *fun_decl = DeclForGlobal (fun); 1458 lldb::addr_t fun_addr = LLDB_INVALID_ADDRESS; 1459 Value **fun_value_ptr = NULL; 1460 1461 if (fun_decl) 1462 { 1463 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_value_ptr, fun_addr)) 1464 { 1465 fun_value_ptr = NULL; 1466 1467 if (!m_decl_map->GetFunctionAddress (str, fun_addr)) 1468 { 1469 if (log) 1470 log->Printf("Function \"%s\" had no address", str.GetCString()); 1471 1472 if (m_error_stream) 1473 m_error_stream->Printf("Error [IRForTarget]: Call to a function '%s' that is not present in the target\n", str.GetCString()); 1474 1475 return false; 1476 } 1477 } 1478 } 1479 else 1480 { 1481 if (!m_decl_map->GetFunctionAddress (str, fun_addr)) 1482 { 1483 if (log) 1484 log->Printf ("Metadataless function \"%s\" had no address", str.GetCString()); 1485 1486 if (m_error_stream) 1487 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", str.GetCString()); 1488 1489 return false; 1490 } 1491 } 1492 1493 if (log) 1494 log->Printf("Found \"%s\" at 0x%llx", str.GetCString(), fun_addr); 1495 1496 Value *fun_addr_ptr; 1497 1498 if (!fun_value_ptr || !*fun_value_ptr) 1499 { 1500 const IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(), 1501 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32); 1502 const FunctionType *fun_ty = fun->getFunctionType(); 1503 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty); 1504 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false); 1505 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty); 1506 1507 if (fun_value_ptr) 1508 *fun_value_ptr = fun_addr_ptr; 1509 } 1510 1511 if (fun_value_ptr) 1512 fun_addr_ptr = *fun_value_ptr; 1513 1514 llvm_call_inst->setCalledFunction(fun_addr_ptr); 1515 1516 ConstantArray *func_name = (ConstantArray*)ConstantArray::get(m_module->getContext(), str.GetCString()); 1517 1518 Value *values[1]; 1519 values[0] = func_name; 1520 ArrayRef<Value*> value_ref(values, 1); 1521 1522 MDNode *func_metadata = MDNode::get(m_module->getContext(), value_ref); 1523 1524 llvm_call_inst->setMetadata("lldb.call.realName", func_metadata); 1525 1526 if (log) 1527 log->Printf("Set metadata for %p [%d, \"%s\"]", llvm_call_inst, func_name->isString(), func_name->getAsString().c_str()); 1528 1529 return true; 1530} 1531 1532bool 1533IRForTarget::ResolveCalls(BasicBlock &basic_block) 1534{ 1535 ///////////////////////////////////////////////////////////////////////// 1536 // Prepare the current basic block for execution in the remote process 1537 // 1538 1539 BasicBlock::iterator ii; 1540 1541 for (ii = basic_block.begin(); 1542 ii != basic_block.end(); 1543 ++ii) 1544 { 1545 Instruction &inst = *ii; 1546 1547 CallInst *call = dyn_cast<CallInst>(&inst); 1548 1549 // MaybeHandleCall handles error reporting; we are silent here 1550 if (call && !MaybeHandleCall(call)) 1551 return false; 1552 1553 // MaybeHandleCallArguments handles error reporting; we are silent here 1554 if (call && !MaybeHandleCallArguments(call)) 1555 return false; 1556 } 1557 1558 return true; 1559} 1560 1561bool 1562IRForTarget::ResolveExternals (Function &llvm_function) 1563{ 1564 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1565 1566 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end(); 1567 global != end; 1568 ++global) 1569 { 1570 if (log) 1571 log->Printf("Examining %s, DeclForGlobalValue returns %p", 1572 (*global).getName().str().c_str(), 1573 DeclForGlobal(global)); 1574 1575 if ((*global).getName().str().find("OBJC_IVAR") == 0) 1576 { 1577 if (!HandleSymbol(global)) 1578 { 1579 if (m_error_stream) 1580 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str()); 1581 1582 return false; 1583 } 1584 } 1585 else if (DeclForGlobal(global)) 1586 { 1587 if (!MaybeHandleVariable (global)) 1588 { 1589 if (m_error_stream) 1590 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str()); 1591 1592 return false; 1593 } 1594 } 1595 } 1596 1597 return true; 1598} 1599 1600bool 1601IRForTarget::ReplaceStrings () 1602{ 1603 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1604 1605 if (!m_data_allocator) 1606 return true; // hope for the best; some clients may not want static allocation! 1607 1608 typedef std::map <GlobalVariable *, size_t> OffsetsTy; 1609 1610 OffsetsTy offsets; 1611 1612 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end(); 1613 gi != ge; 1614 ++gi) 1615 { 1616 GlobalVariable *gv = gi; 1617 1618 if (!gv->hasInitializer()) 1619 continue; 1620 1621 Constant *gc = gv->getInitializer(); 1622 1623 ConstantArray *gc_array = dyn_cast<ConstantArray>(gc); 1624 1625 if (!gc_array) 1626 continue; 1627 1628 if (!gc_array->isCString()) 1629 continue; 1630 1631 if (log) 1632 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str()); 1633 1634 std::string str = gc_array->getAsString(); 1635 1636 offsets[gv] = m_data_allocator->GetStream().GetSize(); 1637 1638 m_data_allocator->GetStream().Write(str.c_str(), str.length() + 1); 1639 } 1640 1641 const Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext()); 1642 1643 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end(); 1644 oi != oe; 1645 ++oi) 1646 { 1647 GlobalVariable *gv = oi->first; 1648 size_t offset = oi->second; 1649 1650 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset); 1651 1652 if (log) 1653 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str()); 1654 1655 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end(); 1656 ui != ue; 1657 ++ui) 1658 { 1659 if (log) 1660 log->Printf("Found use %s", PrintValue(*ui).c_str()); 1661 1662 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui); 1663 StoreInst *store_inst = dyn_cast<StoreInst>(*ui); 1664 1665 if (const_expr) 1666 { 1667 if (const_expr->getOpcode() != Instruction::GetElementPtr) 1668 { 1669 if (log) 1670 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str()); 1671 1672 return false; 1673 } 1674 1675 const_expr->replaceAllUsesWith(new_initializer); 1676 } 1677 else if (store_inst) 1678 { 1679 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType()); 1680 1681 store_inst->setOperand(0, bit_cast); 1682 } 1683 else 1684 { 1685 if (log) 1686 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str()); 1687 1688 return false; 1689 } 1690 } 1691 1692 gv->eraseFromParent(); 1693 } 1694 1695 return true; 1696} 1697 1698bool 1699IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block) 1700{ 1701 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1702 1703 if (!m_data_allocator) 1704 return true; 1705 1706 typedef SmallVector <Value*, 2> ConstantList; 1707 typedef SmallVector <llvm::Instruction*, 2> UserList; 1708 typedef ConstantList::iterator ConstantIterator; 1709 typedef UserList::iterator UserIterator; 1710 1711 ConstantList static_constants; 1712 UserList static_users; 1713 1714 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end(); 1715 ii != ie; 1716 ++ii) 1717 { 1718 llvm::Instruction &inst = *ii; 1719 1720 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end(); 1721 oi != oe; 1722 ++oi) 1723 { 1724 Value *operand_val = oi->get(); 1725 1726 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val); 1727 1728 if (operand_constant_fp && operand_constant_fp->getType()->isX86_FP80Ty()) 1729 { 1730 static_constants.push_back(operand_val); 1731 static_users.push_back(ii); 1732 } 1733 } 1734 } 1735 1736 ConstantIterator constant_iter; 1737 UserIterator user_iter; 1738 1739 const Type *intptr_ty = Type::getIntNTy(m_module->getContext(), 1740 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32); 1741 1742 for (constant_iter = static_constants.begin(), user_iter = static_users.begin(); 1743 constant_iter != static_constants.end(); 1744 ++constant_iter, ++user_iter) 1745 { 1746 Value *operand_val = *constant_iter; 1747 llvm::Instruction *inst = *user_iter; 1748 1749 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val); 1750 1751 if (operand_constant_fp) 1752 { 1753 APFloat operand_apfloat = operand_constant_fp->getValueAPF(); 1754 APInt operand_apint = operand_apfloat.bitcastToAPInt(); 1755 1756 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData(); 1757 size_t operand_data_size = operand_apint.getBitWidth() / 8; 1758 1759 if (log) 1760 { 1761 std::string s; 1762 raw_string_ostream ss(s); 1763 for (size_t index = 0; 1764 index < operand_data_size; 1765 ++index) 1766 { 1767 ss << (uint32_t)operand_raw_data[index]; 1768 ss << " "; 1769 } 1770 ss.flush(); 1771 1772 log->Printf("Found ConstantFP with size %d and raw data %s", operand_data_size, s.c_str()); 1773 } 1774 1775 lldb_private::DataBufferHeap data(operand_data_size, 0); 1776 1777 if (lldb::endian::InlHostByteOrder() != m_data_allocator->GetStream().GetByteOrder()) 1778 { 1779 uint8_t *data_bytes = data.GetBytes(); 1780 1781 for (size_t index = 0; 1782 index < operand_data_size; 1783 ++index) 1784 { 1785 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)]; 1786 } 1787 } 1788 else 1789 { 1790 memcpy(data.GetBytes(), operand_raw_data, operand_data_size); 1791 } 1792 1793 uint64_t offset = m_data_allocator->GetStream().GetSize(); 1794 1795 m_data_allocator->GetStream().Write(data.GetBytes(), operand_data_size); 1796 1797 const llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo(); 1798 1799 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset); 1800 1801 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst); 1802 1803 operand_constant_fp->replaceAllUsesWith(fp_load); 1804 } 1805 } 1806 1807 return true; 1808} 1809 1810static bool isGuardVariableRef(Value *V) 1811{ 1812 Constant *Old; 1813 1814 if (!(Old = dyn_cast<Constant>(V))) 1815 return false; 1816 1817 ConstantExpr *CE; 1818 1819 if ((CE = dyn_cast<ConstantExpr>(V))) 1820 { 1821 if (CE->getOpcode() != Instruction::BitCast) 1822 return false; 1823 1824 Old = CE->getOperand(0); 1825 } 1826 1827 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old); 1828 1829 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV")) 1830 return false; 1831 1832 return true; 1833} 1834 1835void 1836IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load) 1837{ 1838 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true)); 1839 1840 Value::use_iterator ui; 1841 1842 for (ui = guard_load->use_begin(); 1843 ui != guard_load->use_end(); 1844 ++ui) 1845 { 1846 if (isa<Constant>(*ui)) 1847 { 1848 // do nothing for the moment 1849 } 1850 else 1851 { 1852 ui->replaceUsesOfWith(guard_load, zero); 1853 } 1854 } 1855 1856 guard_load->eraseFromParent(); 1857} 1858 1859static void ExciseGuardStore(Instruction* guard_store) 1860{ 1861 guard_store->eraseFromParent(); 1862} 1863 1864bool 1865IRForTarget::RemoveGuards(BasicBlock &basic_block) 1866{ 1867 /////////////////////////////////////////////////////// 1868 // Eliminate any reference to guard variables found. 1869 // 1870 1871 BasicBlock::iterator ii; 1872 1873 typedef SmallVector <Instruction*, 2> InstrList; 1874 typedef InstrList::iterator InstrIterator; 1875 1876 InstrList guard_loads; 1877 InstrList guard_stores; 1878 1879 for (ii = basic_block.begin(); 1880 ii != basic_block.end(); 1881 ++ii) 1882 { 1883 Instruction &inst = *ii; 1884 1885 if (LoadInst *load = dyn_cast<LoadInst>(&inst)) 1886 if (isGuardVariableRef(load->getPointerOperand())) 1887 guard_loads.push_back(&inst); 1888 1889 if (StoreInst *store = dyn_cast<StoreInst>(&inst)) 1890 if (isGuardVariableRef(store->getPointerOperand())) 1891 guard_stores.push_back(&inst); 1892 } 1893 1894 InstrIterator iter; 1895 1896 for (iter = guard_loads.begin(); 1897 iter != guard_loads.end(); 1898 ++iter) 1899 TurnGuardLoadIntoZero(*iter); 1900 1901 for (iter = guard_stores.begin(); 1902 iter != guard_stores.end(); 1903 ++iter) 1904 ExciseGuardStore(*iter); 1905 1906 return true; 1907} 1908 1909// This function does not report errors; its callers are responsible. 1910bool 1911IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst) 1912{ 1913 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1914 1915 Value::use_iterator ui; 1916 1917 SmallVector<User*, 16> users; 1918 1919 // We do this because the use list might change, invalidating our iterator. 1920 // Much better to keep a work list ourselves. 1921 for (ui = old_constant->use_begin(); 1922 ui != old_constant->use_end(); 1923 ++ui) 1924 users.push_back(*ui); 1925 1926 for (int i = 0; 1927 i < users.size(); 1928 ++i) 1929 { 1930 User *user = users[i]; 1931 1932 if (Constant *constant = dyn_cast<Constant>(user)) 1933 { 1934 // synthesize a new non-constant equivalent of the constant 1935 1936 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) 1937 { 1938 switch (constant_expr->getOpcode()) 1939 { 1940 default: 1941 if (log) 1942 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str()); 1943 return false; 1944 case Instruction::BitCast: 1945 { 1946 // UnaryExpr 1947 // OperandList[0] is value 1948 1949 Value *s = constant_expr->getOperand(0); 1950 1951 if (s == old_constant) 1952 s = new_constant; 1953 1954 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst)); 1955 1956 UnfoldConstant(constant_expr, bit_cast, first_entry_inst); 1957 } 1958 break; 1959 case Instruction::GetElementPtr: 1960 { 1961 // GetElementPtrConstantExpr 1962 // OperandList[0] is base 1963 // OperandList[1]... are indices 1964 1965 Value *ptr = constant_expr->getOperand(0); 1966 1967 if (ptr == old_constant) 1968 ptr = new_constant; 1969 1970 SmallVector<Value*, 16> indices; 1971 1972 unsigned operand_index; 1973 unsigned num_operands = constant_expr->getNumOperands(); 1974 1975 for (operand_index = 1; 1976 operand_index < num_operands; 1977 ++operand_index) 1978 { 1979 Value *operand = constant_expr->getOperand(operand_index); 1980 1981 if (operand == old_constant) 1982 operand = new_constant; 1983 1984 indices.push_back(operand); 1985 } 1986 1987 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_inst)); 1988 1989 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst); 1990 } 1991 break; 1992 } 1993 } 1994 else 1995 { 1996 if (log) 1997 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str()); 1998 return false; 1999 } 2000 } 2001 else 2002 { 2003 // simple fall-through case for non-constants 2004 user->replaceUsesOfWith(old_constant, new_constant); 2005 } 2006 } 2007 2008 return true; 2009} 2010 2011bool 2012IRForTarget::ReplaceVariables (Function &llvm_function) 2013{ 2014 if (!m_resolve_vars) 2015 return true; 2016 2017 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 2018 2019 m_decl_map->DoStructLayout(); 2020 2021 if (log) 2022 log->Printf("Element arrangement:"); 2023 2024 uint32_t num_elements; 2025 uint32_t element_index; 2026 2027 size_t size; 2028 off_t alignment; 2029 2030 if (!m_decl_map->GetStructInfo (num_elements, size, alignment)) 2031 return false; 2032 2033 Function::arg_iterator iter(llvm_function.getArgumentList().begin()); 2034 2035 if (iter == llvm_function.getArgumentList().end()) 2036 { 2037 if (m_error_stream) 2038 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)"); 2039 2040 return false; 2041 } 2042 2043 Argument *argument = iter; 2044 2045 if (argument->getName().equals("this")) 2046 { 2047 ++iter; 2048 2049 if (iter == llvm_function.getArgumentList().end()) 2050 { 2051 if (m_error_stream) 2052 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)"); 2053 2054 return false; 2055 } 2056 2057 argument = iter; 2058 } 2059 else if (argument->getName().equals("self")) 2060 { 2061 ++iter; 2062 2063 if (iter == llvm_function.getArgumentList().end()) 2064 { 2065 if (m_error_stream) 2066 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)"); 2067 2068 return false; 2069 } 2070 2071 if (!iter->getName().equals("_cmd")) 2072 { 2073 if (m_error_stream) 2074 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str()); 2075 2076 return false; 2077 } 2078 2079 ++iter; 2080 2081 if (iter == llvm_function.getArgumentList().end()) 2082 { 2083 if (m_error_stream) 2084 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)"); 2085 2086 return false; 2087 } 2088 2089 argument = iter; 2090 } 2091 2092 if (!argument->getName().equals("$__lldb_arg")) 2093 { 2094 if (m_error_stream) 2095 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str()); 2096 2097 return false; 2098 } 2099 2100 if (log) 2101 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str()); 2102 2103 BasicBlock &entry_block(llvm_function.getEntryBlock()); 2104 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg()); 2105 2106 if (!FirstEntryInstruction) 2107 { 2108 if (m_error_stream) 2109 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting"); 2110 2111 return false; 2112 } 2113 2114 LLVMContext &context(m_module->getContext()); 2115 const IntegerType *offset_type(Type::getInt32Ty(context)); 2116 2117 if (!offset_type) 2118 { 2119 if (m_error_stream) 2120 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type"); 2121 2122 return false; 2123 } 2124 2125 for (element_index = 0; element_index < num_elements; ++element_index) 2126 { 2127 const clang::NamedDecl *decl; 2128 Value *value; 2129 off_t offset; 2130 lldb_private::ConstString name; 2131 2132 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index)) 2133 { 2134 if (m_error_stream) 2135 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete"); 2136 2137 return false; 2138 } 2139 2140 if (log) 2141 log->Printf(" \"%s\" [\"%s\"] (\"%s\") placed at %d", 2142 value->getName().str().c_str(), 2143 name.GetCString(), 2144 PrintValue(value, true).c_str(), 2145 offset); 2146 2147 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset)); 2148 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction); 2149 2150 Value *replacement; 2151 2152 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result 2153 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure 2154 // entry in order to produce the static variable that the AST thinks it is accessing. 2155 if (name == m_result_name && !m_result_is_pointer) 2156 { 2157 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction); 2158 2159 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction); 2160 2161 replacement = load; 2162 } 2163 else 2164 { 2165 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction); 2166 2167 replacement = bit_cast; 2168 } 2169 2170 if (Constant *constant = dyn_cast<Constant>(value)) 2171 UnfoldConstant(constant, replacement, FirstEntryInstruction); 2172 else 2173 value->replaceAllUsesWith(replacement); 2174 2175 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value)) 2176 var->eraseFromParent(); 2177 } 2178 2179 if (log) 2180 log->Printf("Total structure [align %d, size %d]", alignment, size); 2181 2182 return true; 2183} 2184 2185llvm::Constant * 2186IRForTarget::BuildRelocation(const llvm::Type *type, 2187 uint64_t offset) 2188{ 2189 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 2190 2191 const IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(), 2192 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32); 2193 2194 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset); 2195 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, &offset_int, 1); 2196 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type); 2197 2198 return reloc_getbitcast; 2199} 2200 2201bool 2202IRForTarget::CompleteDataAllocation () 2203{ 2204 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 2205 2206 if (!m_data_allocator->GetStream().GetSize()) 2207 return true; 2208 2209 lldb::addr_t allocation = m_data_allocator->Allocate(); 2210 2211 if (log) 2212 { 2213 if (allocation) 2214 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation); 2215 else 2216 log->Printf("Failed to allocate static data"); 2217 } 2218 2219 if (!allocation) 2220 return false; 2221 2222 const IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(), 2223 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32); 2224 2225 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation); 2226 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext())); 2227 2228 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast); 2229 2230 m_reloc_placeholder->eraseFromParent(); 2231 2232 return true; 2233} 2234 2235bool 2236IRForTarget::runOnModule (Module &llvm_module) 2237{ 2238 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 2239 2240 m_module = &llvm_module; 2241 2242 Function* function = m_module->getFunction(StringRef(m_func_name.c_str())); 2243 2244 if (!function) 2245 { 2246 if (log) 2247 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str()); 2248 2249 if (m_error_stream) 2250 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str()); 2251 2252 return false; 2253 } 2254 2255 if (!FixFunctionLinkage (*function)) 2256 { 2257 if (log) 2258 log->Printf("Couldn't fix the linkage for the function"); 2259 2260 return false; 2261 } 2262 2263 const llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext()); 2264 2265 m_reloc_placeholder = new llvm::GlobalVariable((*m_module), 2266 intptr_ty, 2267 false /* isConstant */, 2268 GlobalVariable::InternalLinkage, 2269 Constant::getNullValue(intptr_ty), 2270 "reloc_placeholder", 2271 NULL /* InsertBefore */, 2272 false /* ThreadLocal */, 2273 0 /* AddressSpace */); 2274 2275 Function::iterator bbi; 2276 2277 m_has_side_effects = HasSideEffects(*function); 2278 2279 //////////////////////////////////////////////////////////// 2280 // Replace $__lldb_expr_result with a persistent variable 2281 // 2282 2283 if (!CreateResultVariable(*function)) 2284 { 2285 if (log) 2286 log->Printf("CreateResultVariable() failed"); 2287 2288 // CreateResultVariable() reports its own errors, so we don't do so here 2289 2290 return false; 2291 } 2292 2293 if (m_const_result) 2294 return true; 2295 2296 if (log) 2297 { 2298 std::string s; 2299 raw_string_ostream oss(s); 2300 2301 m_module->print(oss, NULL); 2302 2303 oss.flush(); 2304 2305 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str()); 2306 } 2307 2308 /////////////////////////////////////////////////////////////////////////////// 2309 // Fix all Objective-C constant strings to use NSStringWithCString:encoding: 2310 // 2311 2312 if (!RewriteObjCConstStrings(*function)) 2313 { 2314 if (log) 2315 log->Printf("RewriteObjCConstStrings() failed"); 2316 2317 // RewriteObjCConstStrings() reports its own errors, so we don't do so here 2318 2319 return false; 2320 } 2321 2322 ////////////////////////////////// 2323 // Run basic-block level passes 2324 // 2325 2326 for (bbi = function->begin(); 2327 bbi != function->end(); 2328 ++bbi) 2329 { 2330 if (!RemoveGuards(*bbi)) 2331 { 2332 if (log) 2333 log->Printf("RemoveGuards() failed"); 2334 2335 // RemoveGuards() reports its own errors, so we don't do so here 2336 2337 return false; 2338 } 2339 2340 if (!RewritePersistentAllocs(*bbi)) 2341 { 2342 if (log) 2343 log->Printf("RewritePersistentAllocs() failed"); 2344 2345 // RewritePersistentAllocs() reports its own errors, so we don't do so here 2346 2347 return false; 2348 } 2349 2350 if (!RewriteObjCSelectors(*bbi)) 2351 { 2352 if (log) 2353 log->Printf("RewriteObjCSelectors() failed"); 2354 2355 // RewriteObjCSelectors() reports its own errors, so we don't do so here 2356 2357 return false; 2358 } 2359 2360 if (!ResolveCalls(*bbi)) 2361 { 2362 if (log) 2363 log->Printf("ResolveCalls() failed"); 2364 2365 // ResolveCalls() reports its own errors, so we don't do so here 2366 2367 return false; 2368 } 2369 2370 if (!ReplaceStaticLiterals(*bbi)) 2371 { 2372 if (log) 2373 log->Printf("ReplaceStaticLiterals() failed"); 2374 2375 return false; 2376 } 2377 } 2378 2379 /////////////////////////////// 2380 // Run function-level passes 2381 // 2382 2383 if (!ResolveExternals(*function)) 2384 { 2385 if (log) 2386 log->Printf("ResolveExternals() failed"); 2387 2388 // ResolveExternals() reports its own errors, so we don't do so here 2389 2390 return false; 2391 } 2392 2393 if (!ReplaceVariables(*function)) 2394 { 2395 if (log) 2396 log->Printf("ReplaceVariables() failed"); 2397 2398 // ReplaceVariables() reports its own errors, so we don't do so here 2399 2400 return false; 2401 } 2402 2403 if (!ReplaceStrings()) 2404 { 2405 if (log) 2406 log->Printf("ReplaceStrings() failed"); 2407 2408 return false; 2409 } 2410 2411 if (!CompleteDataAllocation()) 2412 { 2413 if (log) 2414 log->Printf("CompleteDataAllocation() failed"); 2415 2416 return false; 2417 } 2418 2419 if (log) 2420 { 2421 std::string s; 2422 raw_string_ostream oss(s); 2423 2424 m_module->print(oss, NULL); 2425 2426 oss.flush(); 2427 2428 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str()); 2429 } 2430 2431 return true; 2432} 2433 2434void 2435IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type) 2436{ 2437} 2438 2439PassManagerType 2440IRForTarget::getPotentialPassManagerType() const 2441{ 2442 return PMT_ModulePassManager; 2443} 2444