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