IRForTarget.cpp revision 341825
1170263Sdarrenr//===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===// 2255332Scy// 3170263Sdarrenr// The LLVM Compiler Infrastructure 4170263Sdarrenr// 5170263Sdarrenr// This file is distributed under the University of Illinois Open Source 6255332Scy// License. See LICENSE.TXT for details. 7170263Sdarrenr// 8170263Sdarrenr//===----------------------------------------------------------------------===// 9170263Sdarrenr 10170263Sdarrenr#include "IRForTarget.h" 11170263Sdarrenr 12255332Scy#include "ClangExpressionDeclMap.h" 13170263Sdarrenr 14170263Sdarrenr#include "llvm/IR/Constants.h" 15170263Sdarrenr#include "llvm/IR/DataLayout.h" 16170263Sdarrenr#include "llvm/IR/InstrTypes.h" 17170263Sdarrenr#include "llvm/IR/Instructions.h" 18170263Sdarrenr#include "llvm/IR/Intrinsics.h" 19170263Sdarrenr#include "llvm/IR/LegacyPassManager.h" 20170263Sdarrenr#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/Scalar.h" 29#include "lldb/Core/dwarf.h" 30#include "lldb/Expression/IRExecutionUnit.h" 31#include "lldb/Expression/IRInterpreter.h" 32#include "lldb/Symbol/ClangASTContext.h" 33#include "lldb/Symbol/ClangUtil.h" 34#include "lldb/Symbol/CompilerType.h" 35#include "lldb/Utility/ConstString.h" 36#include "lldb/Utility/DataBufferHeap.h" 37#include "lldb/Utility/Endian.h" 38#include "lldb/Utility/Log.h" 39#include "lldb/Utility/StreamString.h" 40 41#include <map> 42 43using namespace llvm; 44 45static char ID; 46 47IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) 48 : m_maker(maker), m_values() {} 49 50IRForTarget::FunctionValueCache::~FunctionValueCache() {} 51 52llvm::Value * 53IRForTarget::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 62static llvm::Value *FindEntryInstruction(llvm::Function *function) { 63 if (function->empty()) 64 return NULL; 65 66 return function->getEntryBlock().getFirstNonPHIOrDbg(); 67} 68 69IRForTarget::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 84static 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 96static 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 106IRForTarget::~IRForTarget() {} 107 108bool IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function) { 109 llvm_function.setLinkage(GlobalValue::ExternalLinkage); 110 111 return true; 112} 113 114clang::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 152clang::NamedDecl *IRForTarget::DeclForGlobal(GlobalValue *global_val) { 153 return DeclForGlobal(global_val, m_module); 154} 155 156bool 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 variable for it 267 268 // If the result is an Lvalue, it is emitted as a pointer; see 269 // ASTResultSynthesizer::SynthesizeBodyResult. 270 if (m_result_is_pointer) { 271 clang::QualType pointer_qual_type = result_var->getType(); 272 const clang::Type *pointer_type = pointer_qual_type.getTypePtr(); 273 274 const clang::PointerType *pointer_pointertype = 275 pointer_type->getAs<clang::PointerType>(); 276 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = 277 pointer_type->getAs<clang::ObjCObjectPointerType>(); 278 279 if (pointer_pointertype) { 280 clang::QualType element_qual_type = pointer_pointertype->getPointeeType(); 281 282 m_result_type = lldb_private::TypeFromParser( 283 element_qual_type.getAsOpaquePtr(), 284 lldb_private::ClangASTContext::GetASTContext( 285 &result_decl->getASTContext())); 286 } else if (pointer_objcobjpointertype) { 287 clang::QualType element_qual_type = 288 clang::QualType(pointer_objcobjpointertype->getObjectType(), 0); 289 290 m_result_type = lldb_private::TypeFromParser( 291 element_qual_type.getAsOpaquePtr(), 292 lldb_private::ClangASTContext::GetASTContext( 293 &result_decl->getASTContext())); 294 } else { 295 if (log) 296 log->PutCString("Expected result to have pointer type, but it did not"); 297 298 m_error_stream.Printf("Internal error [IRForTarget]: Lvalue result (%s) " 299 "is not a pointer variable\n", 300 result_name); 301 302 return false; 303 } 304 } else { 305 m_result_type = lldb_private::TypeFromParser( 306 result_var->getType().getAsOpaquePtr(), 307 lldb_private::ClangASTContext::GetASTContext( 308 &result_decl->getASTContext())); 309 } 310 311 lldb::TargetSP target_sp(m_execution_unit.GetTarget()); 312 lldb_private::ExecutionContext exe_ctx(target_sp, true); 313 if (m_result_type.GetBitSize(exe_ctx.GetBestExecutionContextScope()) == 0) { 314 lldb_private::StreamString type_desc_stream; 315 m_result_type.DumpTypeDescription(&type_desc_stream); 316 317 if (log) 318 log->Printf("Result type has size 0"); 319 320 m_error_stream.Printf("Error [IRForTarget]: Size of result type '%s' " 321 "couldn't be determined\n", 322 type_desc_stream.GetData()); 323 return false; 324 } 325 326 if (log) { 327 lldb_private::StreamString type_desc_stream; 328 m_result_type.DumpTypeDescription(&type_desc_stream); 329 330 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData()); 331 } 332 333 m_result_name = lldb_private::ConstString("$RESULT_NAME"); 334 335 if (log) 336 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64, 337 m_result_name.GetCString(), m_result_type.GetByteSize(nullptr)); 338 339 // Construct a new result global and set up its metadata 340 341 GlobalVariable *new_result_global = new GlobalVariable( 342 (*m_module), result_global->getType()->getElementType(), 343 false, /* not constant */ 344 GlobalValue::ExternalLinkage, NULL, /* no initializer */ 345 m_result_name.GetCString()); 346 347 // It's too late in compilation to create a new VarDecl for this, but we 348 // don't need to. We point the metadata at the old VarDecl. This creates an 349 // odd anomaly: a variable with a Value whose name is something like $0 and a 350 // Decl whose name is $__lldb_expr_result. This condition is handled in 351 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is 352 // fixed up. 353 354 ConstantInt *new_constant_int = 355 ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()), 356 reinterpret_cast<uint64_t>(result_decl), false); 357 358 llvm::Metadata *values[2]; 359 values[0] = ConstantAsMetadata::get(new_result_global); 360 values[1] = ConstantAsMetadata::get(new_constant_int); 361 362 ArrayRef<Metadata *> value_ref(values, 2); 363 364 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref); 365 NamedMDNode *named_metadata = 366 m_module->getNamedMetadata("clang.global.decl.ptrs"); 367 named_metadata->addOperand(persistent_global_md); 368 369 if (log) 370 log->Printf("Replacing \"%s\" with \"%s\"", 371 PrintValue(result_global).c_str(), 372 PrintValue(new_result_global).c_str()); 373 374 if (result_global->use_empty()) { 375 // We need to synthesize a store for this variable, because otherwise 376 // there's nothing to put into its equivalent persistent variable. 377 378 BasicBlock &entry_block(llvm_function.getEntryBlock()); 379 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg()); 380 381 if (!first_entry_instruction) 382 return false; 383 384 if (!result_global->hasInitializer()) { 385 if (log) 386 log->Printf("Couldn't find initializer for unused variable"); 387 388 m_error_stream.Printf("Internal error [IRForTarget]: Result variable " 389 "(%s) has no writes and no initializer\n", 390 result_name); 391 392 return false; 393 } 394 395 Constant *initializer = result_global->getInitializer(); 396 397 StoreInst *synthesized_store = 398 new StoreInst(initializer, new_result_global, first_entry_instruction); 399 400 if (log) 401 log->Printf("Synthesized result store \"%s\"\n", 402 PrintValue(synthesized_store).c_str()); 403 } else { 404 result_global->replaceAllUsesWith(new_result_global); 405 } 406 407 if (!m_decl_map->AddPersistentVariable( 408 result_decl, m_result_name, m_result_type, true, m_result_is_pointer)) 409 return false; 410 411 result_global->eraseFromParent(); 412 413 return true; 414} 415 416bool IRForTarget::RewriteObjCConstString(llvm::GlobalVariable *ns_str, 417 llvm::GlobalVariable *cstr) { 418 lldb_private::Log *log( 419 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 420 421 Type *ns_str_ty = ns_str->getType(); 422 423 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext()); 424 Type *i32_ty = Type::getInt32Ty(m_module->getContext()); 425 Type *i8_ty = Type::getInt8Ty(m_module->getContext()); 426 427 if (!m_CFStringCreateWithBytes) { 428 lldb::addr_t CFStringCreateWithBytes_addr; 429 430 static lldb_private::ConstString g_CFStringCreateWithBytes_str( 431 "CFStringCreateWithBytes"); 432 433 CFStringCreateWithBytes_addr = 434 m_execution_unit.FindSymbol(g_CFStringCreateWithBytes_str); 435 if (CFStringCreateWithBytes_addr == LLDB_INVALID_ADDRESS) { 436 if (log) 437 log->PutCString("Couldn't find CFStringCreateWithBytes in the target"); 438 439 m_error_stream.Printf("Error [IRForTarget]: Rewriting an Objective-C " 440 "constant string requires " 441 "CFStringCreateWithBytes\n"); 442 443 return false; 444 } 445 446 if (log) 447 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, 448 CFStringCreateWithBytes_addr); 449 450 // Build the function type: 451 // 452 // CFStringRef CFStringCreateWithBytes ( 453 // CFAllocatorRef alloc, 454 // const UInt8 *bytes, 455 // CFIndex numBytes, 456 // CFStringEncoding encoding, 457 // Boolean isExternalRepresentation 458 // ); 459 // 460 // We make the following substitutions: 461 // 462 // CFStringRef -> i8* 463 // CFAllocatorRef -> i8* 464 // UInt8 * -> i8* 465 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its 466 // pointer size for now) CFStringEncoding -> i32 Boolean -> i8 467 468 Type *arg_type_array[5]; 469 470 arg_type_array[0] = i8_ptr_ty; 471 arg_type_array[1] = i8_ptr_ty; 472 arg_type_array[2] = m_intptr_ty; 473 arg_type_array[3] = i32_ty; 474 arg_type_array[4] = i8_ty; 475 476 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5); 477 478 llvm::Type *CFSCWB_ty = 479 FunctionType::get(ns_str_ty, CFSCWB_arg_types, false); 480 481 // Build the constant containing the pointer to the function 482 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty); 483 Constant *CFSCWB_addr_int = 484 ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false); 485 m_CFStringCreateWithBytes = 486 ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty); 487 } 488 489 ConstantDataSequential *string_array = NULL; 490 491 if (cstr) 492 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer()); 493 494 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty); 495 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) 496 : Constant::getNullValue(i8_ptr_ty); 497 Constant *numBytes_arg = ConstantInt::get( 498 m_intptr_ty, cstr ? (string_array->getNumElements() - 1) * string_array->getElementByteSize() : 0, false); 499 int encoding_flags = 0; 500 switch (cstr ? string_array->getElementByteSize() : 1) { 501 case 1: 502 encoding_flags = 0x08000100; /* 0x08000100 is kCFStringEncodingUTF8 */ 503 break; 504 case 2: 505 encoding_flags = 0x0100; /* 0x0100 is kCFStringEncodingUTF16 */ 506 break; 507 case 4: 508 encoding_flags = 0x0c000100; /* 0x0c000100 is kCFStringEncodingUTF32 */ 509 break; 510 default: 511 encoding_flags = 0x0600; /* fall back to 0x0600, kCFStringEncodingASCII */ 512 LLDB_LOG(log, "Encountered an Objective-C constant string with unusual " 513 "element size {0}", 514 string_array->getElementByteSize()); 515 } 516 Constant *encoding_arg = ConstantInt::get(i32_ty, encoding_flags, false); 517 Constant *isExternal_arg = 518 ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */ 519 520 Value *argument_array[5]; 521 522 argument_array[0] = alloc_arg; 523 argument_array[1] = bytes_arg; 524 argument_array[2] = numBytes_arg; 525 argument_array[3] = encoding_arg; 526 argument_array[4] = isExternal_arg; 527 528 ArrayRef<Value *> CFSCWB_arguments(argument_array, 5); 529 530 FunctionValueCache CFSCWB_Caller( 531 [this, &CFSCWB_arguments](llvm::Function *function) -> llvm::Value * { 532 return CallInst::Create( 533 m_CFStringCreateWithBytes, CFSCWB_arguments, 534 "CFStringCreateWithBytes", 535 llvm::cast<Instruction>( 536 m_entry_instruction_finder.GetValue(function))); 537 }); 538 539 if (!UnfoldConstant(ns_str, nullptr, CFSCWB_Caller, m_entry_instruction_finder, 540 m_error_stream)) { 541 if (log) 542 log->PutCString( 543 "Couldn't replace the NSString with the result of the call"); 544 545 m_error_stream.Printf("error [IRForTarget internal]: Couldn't replace an " 546 "Objective-C constant string with a dynamic " 547 "string\n"); 548 549 return false; 550 } 551 552 ns_str->eraseFromParent(); 553 554 return true; 555} 556 557bool IRForTarget::RewriteObjCConstStrings() { 558 lldb_private::Log *log( 559 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 560 561 ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable(); 562 563 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), 564 ve = value_symbol_table.end(); 565 vi != ve; ++vi) { 566 std::string value_name = vi->first().str(); 567 const char *value_name_cstr = value_name.c_str(); 568 569 if (strstr(value_name_cstr, "_unnamed_cfstring_")) { 570 Value *nsstring_value = vi->second; 571 572 GlobalVariable *nsstring_global = 573 dyn_cast<GlobalVariable>(nsstring_value); 574 575 if (!nsstring_global) { 576 if (log) 577 log->PutCString("NSString variable is not a GlobalVariable"); 578 579 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C " 580 "constant string is not a global variable\n"); 581 582 return false; 583 } 584 585 if (!nsstring_global->hasInitializer()) { 586 if (log) 587 log->PutCString("NSString variable does not have an initializer"); 588 589 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C " 590 "constant string does not have an initializer\n"); 591 592 return false; 593 } 594 595 ConstantStruct *nsstring_struct = 596 dyn_cast<ConstantStruct>(nsstring_global->getInitializer()); 597 598 if (!nsstring_struct) { 599 if (log) 600 log->PutCString( 601 "NSString variable's initializer is not a ConstantStruct"); 602 603 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C " 604 "constant string is not a structure constant\n"); 605 606 return false; 607 } 608 609 // We expect the following structure: 610 // 611 // struct { 612 // int *isa; 613 // int flags; 614 // char *str; 615 // long length; 616 // }; 617 618 if (nsstring_struct->getNumOperands() != 4) { 619 if (log) 620 log->Printf("NSString variable's initializer structure has an " 621 "unexpected number of members. Should be 4, is %d", 622 nsstring_struct->getNumOperands()); 623 624 m_error_stream.Printf("Internal error [IRForTarget]: The struct for an " 625 "Objective-C constant string is not as " 626 "expected\n"); 627 628 return false; 629 } 630 631 Constant *nsstring_member = nsstring_struct->getOperand(2); 632 633 if (!nsstring_member) { 634 if (log) 635 log->PutCString("NSString initializer's str element was empty"); 636 637 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C " 638 "constant string does not have a string " 639 "initializer\n"); 640 641 return false; 642 } 643 644 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member); 645 646 if (!nsstring_expr) { 647 if (log) 648 log->PutCString( 649 "NSString initializer's str element is not a ConstantExpr"); 650 651 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C " 652 "constant string's string initializer is not " 653 "constant\n"); 654 655 return false; 656 } 657 658 GlobalVariable *cstr_global = nullptr; 659 660 if (nsstring_expr->getOpcode() == Instruction::GetElementPtr) { 661 Constant *nsstring_cstr = nsstring_expr->getOperand(0); 662 cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr); 663 } else if (nsstring_expr->getOpcode() == Instruction::BitCast) { 664 Constant *nsstring_cstr = nsstring_expr->getOperand(0); 665 cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr); 666 } 667 668 if (!cstr_global) { 669 if (log) 670 log->PutCString( 671 "NSString initializer's str element is not a GlobalVariable"); 672 673 m_error_stream.Printf("Internal error [IRForTarget]: Unhandled" 674 "constant string initializer\n"); 675 676 return false; 677 } 678 679 if (!cstr_global->hasInitializer()) { 680 if (log) 681 log->PutCString("NSString initializer's str element does not have an " 682 "initializer"); 683 684 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C " 685 "constant string's string initializer doesn't " 686 "point to initialized data\n"); 687 688 return false; 689 } 690 691 /* 692 if (!cstr_array) 693 { 694 if (log) 695 log->PutCString("NSString initializer's str element is not a 696 ConstantArray"); 697 698 if (m_error_stream) 699 m_error_stream.Printf("Internal error [IRForTarget]: An 700 Objective-C constant string's string initializer doesn't point to an 701 array\n"); 702 703 return false; 704 } 705 706 if (!cstr_array->isCString()) 707 { 708 if (log) 709 log->PutCString("NSString initializer's str element is not a C 710 string array"); 711 712 if (m_error_stream) 713 m_error_stream.Printf("Internal error [IRForTarget]: An 714 Objective-C constant string's string initializer doesn't point to a C 715 string\n"); 716 717 return false; 718 } 719 */ 720 721 ConstantDataArray *cstr_array = 722 dyn_cast<ConstantDataArray>(cstr_global->getInitializer()); 723 724 if (log) { 725 if (cstr_array) 726 log->Printf("Found NSString constant %s, which contains \"%s\"", 727 value_name_cstr, cstr_array->getAsString().str().c_str()); 728 else 729 log->Printf("Found NSString constant %s, which contains \"\"", 730 value_name_cstr); 731 } 732 733 if (!cstr_array) 734 cstr_global = NULL; 735 736 if (!RewriteObjCConstString(nsstring_global, cstr_global)) { 737 if (log) 738 log->PutCString("Error rewriting the constant string"); 739 740 // We don't print an error message here because RewriteObjCConstString 741 // has done so for us. 742 743 return false; 744 } 745 } 746 } 747 748 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), 749 ve = value_symbol_table.end(); 750 vi != ve; ++vi) { 751 std::string value_name = vi->first().str(); 752 const char *value_name_cstr = value_name.c_str(); 753 754 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference")) { 755 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second); 756 757 if (!gv) { 758 if (log) 759 log->PutCString( 760 "__CFConstantStringClassReference is not a global variable"); 761 762 m_error_stream.Printf("Internal error [IRForTarget]: Found a " 763 "CFConstantStringClassReference, but it is not a " 764 "global object\n"); 765 766 return false; 767 } 768 769 gv->eraseFromParent(); 770 771 break; 772 } 773 } 774 775 return true; 776} 777 778static bool IsObjCSelectorRef(Value *value) { 779 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value); 780 781 if (!global_variable || !global_variable->hasName() || 782 !global_variable->getName().startswith("OBJC_SELECTOR_REFERENCES_")) 783 return false; 784 785 return true; 786} 787 788// This function does not report errors; its callers are responsible. 789bool IRForTarget::RewriteObjCSelector(Instruction *selector_load) { 790 lldb_private::Log *log( 791 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 792 793 LoadInst *load = dyn_cast<LoadInst>(selector_load); 794 795 if (!load) 796 return false; 797 798 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend 799 // gets represented as 800 // 801 // %tmp = load i8** @"OBJC_SELECTOR_REFERENCES_" ; <i8*> %call = call 802 // i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*> 803 // 804 // where %obj is the object pointer and %tmp is the selector. 805 // 806 // @"OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called 807 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_". 808 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string. 809 810 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) 811 // and get the string from its target 812 813 GlobalVariable *_objc_selector_references_ = 814 dyn_cast<GlobalVariable>(load->getPointerOperand()); 815 816 if (!_objc_selector_references_ || 817 !_objc_selector_references_->hasInitializer()) 818 return false; 819 820 Constant *osr_initializer = _objc_selector_references_->getInitializer(); 821 822 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer); 823 824 if (!osr_initializer_expr || 825 osr_initializer_expr->getOpcode() != Instruction::GetElementPtr) 826 return false; 827 828 Value *osr_initializer_base = osr_initializer_expr->getOperand(0); 829 830 if (!osr_initializer_base) 831 return false; 832 833 // Find the string's initializer (a ConstantArray) and get the string from it 834 835 GlobalVariable *_objc_meth_var_name_ = 836 dyn_cast<GlobalVariable>(osr_initializer_base); 837 838 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer()) 839 return false; 840 841 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer(); 842 843 ConstantDataArray *omvn_initializer_array = 844 dyn_cast<ConstantDataArray>(omvn_initializer); 845 846 if (!omvn_initializer_array->isString()) 847 return false; 848 849 std::string omvn_initializer_string = omvn_initializer_array->getAsString(); 850 851 if (log) 852 log->Printf("Found Objective-C selector reference \"%s\"", 853 omvn_initializer_string.c_str()); 854 855 // Construct a call to sel_registerName 856 857 if (!m_sel_registerName) { 858 lldb::addr_t sel_registerName_addr; 859 860 static lldb_private::ConstString g_sel_registerName_str("sel_registerName"); 861 sel_registerName_addr = m_execution_unit.FindSymbol(g_sel_registerName_str); 862 if (sel_registerName_addr == LLDB_INVALID_ADDRESS) 863 return false; 864 865 if (log) 866 log->Printf("Found sel_registerName at 0x%" PRIx64, 867 sel_registerName_addr); 868 869 // Build the function type: struct objc_selector 870 // *sel_registerName(uint8_t*) 871 872 // The below code would be "more correct," but in actuality what's required 873 // is uint8_t* 874 // Type *sel_type = StructType::get(m_module->getContext()); 875 // Type *sel_ptr_type = PointerType::getUnqual(sel_type); 876 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext()); 877 878 Type *type_array[1]; 879 880 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext()); 881 882 ArrayRef<Type *> srN_arg_types(type_array, 1); 883 884 llvm::Type *srN_type = 885 FunctionType::get(sel_ptr_type, srN_arg_types, false); 886 887 // Build the constant containing the pointer to the function 888 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type); 889 Constant *srN_addr_int = 890 ConstantInt::get(m_intptr_ty, sel_registerName_addr, false); 891 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty); 892 } 893 894 Value *argument_array[1]; 895 896 Constant *omvn_pointer = ConstantExpr::getBitCast( 897 _objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext())); 898 899 argument_array[0] = omvn_pointer; 900 901 ArrayRef<Value *> srN_arguments(argument_array, 1); 902 903 CallInst *srN_call = CallInst::Create(m_sel_registerName, srN_arguments, 904 "sel_registerName", selector_load); 905 906 // Replace the load with the call in all users 907 908 selector_load->replaceAllUsesWith(srN_call); 909 910 selector_load->eraseFromParent(); 911 912 return true; 913} 914 915bool IRForTarget::RewriteObjCSelectors(BasicBlock &basic_block) { 916 lldb_private::Log *log( 917 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 918 919 BasicBlock::iterator ii; 920 921 typedef SmallVector<Instruction *, 2> InstrList; 922 typedef InstrList::iterator InstrIterator; 923 924 InstrList selector_loads; 925 926 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) { 927 Instruction &inst = *ii; 928 929 if (LoadInst *load = dyn_cast<LoadInst>(&inst)) 930 if (IsObjCSelectorRef(load->getPointerOperand())) 931 selector_loads.push_back(&inst); 932 } 933 934 InstrIterator iter; 935 936 for (iter = selector_loads.begin(); iter != selector_loads.end(); ++iter) { 937 if (!RewriteObjCSelector(*iter)) { 938 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't change a " 939 "static reference to an Objective-C selector to a " 940 "dynamic reference\n"); 941 942 if (log) 943 log->PutCString( 944 "Couldn't rewrite a reference to an Objective-C selector"); 945 946 return false; 947 } 948 } 949 950 return true; 951} 952 953static bool IsObjCClassReference(Value *value) { 954 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value); 955 956 if (!global_variable || !global_variable->hasName() || 957 !global_variable->getName().startswith("OBJC_CLASS_REFERENCES_")) 958 return false; 959 960 return true; 961} 962 963// This function does not report errors; its callers are responsible. 964bool IRForTarget::RewriteObjCClassReference(Instruction *class_load) { 965 lldb_private::Log *log( 966 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 967 968 LoadInst *load = dyn_cast<LoadInst>(class_load); 969 970 if (!load) 971 return false; 972 973 // Unpack the class name from the reference. In LLVM IR, a reference to an 974 // Objective-C class gets represented as 975 // 976 // %tmp = load %struct._objc_class*, 977 // %struct._objc_class** @OBJC_CLASS_REFERENCES_, align 4 978 // 979 // @"OBJC_CLASS_REFERENCES_ is a bitcast of a character array called 980 // @OBJC_CLASS_NAME_. @OBJC_CLASS_NAME contains the string. 981 982 // Find the pointer's initializer (a ConstantExpr with opcode BitCast) and 983 // get the string from its target 984 985 GlobalVariable *_objc_class_references_ = 986 dyn_cast<GlobalVariable>(load->getPointerOperand()); 987 988 if (!_objc_class_references_ || 989 !_objc_class_references_->hasInitializer()) 990 return false; 991 992 Constant *ocr_initializer = _objc_class_references_->getInitializer(); 993 994 ConstantExpr *ocr_initializer_expr = dyn_cast<ConstantExpr>(ocr_initializer); 995 996 if (!ocr_initializer_expr || 997 ocr_initializer_expr->getOpcode() != Instruction::BitCast) 998 return false; 999 1000 Value *ocr_initializer_base = ocr_initializer_expr->getOperand(0); 1001 1002 if (!ocr_initializer_base) 1003 return false; 1004 1005 // Find the string's initializer (a ConstantArray) and get the string from it 1006 1007 GlobalVariable *_objc_class_name_ = 1008 dyn_cast<GlobalVariable>(ocr_initializer_base); 1009 1010 if (!_objc_class_name_ || !_objc_class_name_->hasInitializer()) 1011 return false; 1012 1013 Constant *ocn_initializer = _objc_class_name_->getInitializer(); 1014 1015 ConstantDataArray *ocn_initializer_array = 1016 dyn_cast<ConstantDataArray>(ocn_initializer); 1017 1018 if (!ocn_initializer_array->isString()) 1019 return false; 1020 1021 std::string ocn_initializer_string = ocn_initializer_array->getAsString(); 1022 1023 if (log) 1024 log->Printf("Found Objective-C class reference \"%s\"", 1025 ocn_initializer_string.c_str()); 1026 1027 // Construct a call to objc_getClass 1028 1029 if (!m_objc_getClass) { 1030 lldb::addr_t objc_getClass_addr; 1031 1032 static lldb_private::ConstString g_objc_getClass_str("objc_getClass"); 1033 objc_getClass_addr = m_execution_unit.FindSymbol(g_objc_getClass_str); 1034 if (objc_getClass_addr == LLDB_INVALID_ADDRESS) 1035 return false; 1036 1037 if (log) 1038 log->Printf("Found objc_getClass at 0x%" PRIx64, 1039 objc_getClass_addr); 1040 1041 // Build the function type: %struct._objc_class *objc_getClass(i8*) 1042 1043 Type *class_type = load->getType(); 1044 Type *type_array[1]; 1045 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext()); 1046 1047 ArrayRef<Type *> ogC_arg_types(type_array, 1); 1048 1049 llvm::Type *ogC_type = 1050 FunctionType::get(class_type, ogC_arg_types, false); 1051 1052 // Build the constant containing the pointer to the function 1053 PointerType *ogC_ptr_ty = PointerType::getUnqual(ogC_type); 1054 Constant *ogC_addr_int = 1055 ConstantInt::get(m_intptr_ty, objc_getClass_addr, false); 1056 m_objc_getClass = ConstantExpr::getIntToPtr(ogC_addr_int, ogC_ptr_ty); 1057 } 1058 1059 Value *argument_array[1]; 1060 1061 Constant *ocn_pointer = ConstantExpr::getBitCast( 1062 _objc_class_name_, Type::getInt8PtrTy(m_module->getContext())); 1063 1064 argument_array[0] = ocn_pointer; 1065 1066 ArrayRef<Value *> ogC_arguments(argument_array, 1); 1067 1068 CallInst *ogC_call = CallInst::Create(m_objc_getClass, ogC_arguments, 1069 "objc_getClass", class_load); 1070 1071 // Replace the load with the call in all users 1072 1073 class_load->replaceAllUsesWith(ogC_call); 1074 1075 class_load->eraseFromParent(); 1076 1077 return true; 1078} 1079 1080bool IRForTarget::RewriteObjCClassReferences(BasicBlock &basic_block) { 1081 lldb_private::Log *log( 1082 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1083 1084 BasicBlock::iterator ii; 1085 1086 typedef SmallVector<Instruction *, 2> InstrList; 1087 typedef InstrList::iterator InstrIterator; 1088 1089 InstrList class_loads; 1090 1091 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) { 1092 Instruction &inst = *ii; 1093 1094 if (LoadInst *load = dyn_cast<LoadInst>(&inst)) 1095 if (IsObjCClassReference(load->getPointerOperand())) 1096 class_loads.push_back(&inst); 1097 } 1098 1099 InstrIterator iter; 1100 1101 for (iter = class_loads.begin(); iter != class_loads.end(); ++iter) { 1102 if (!RewriteObjCClassReference(*iter)) { 1103 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't change a " 1104 "static reference to an Objective-C class to a " 1105 "dynamic reference\n"); 1106 1107 if (log) 1108 log->PutCString( 1109 "Couldn't rewrite a reference to an Objective-C class"); 1110 1111 return false; 1112 } 1113 } 1114 1115 return true; 1116} 1117 1118// This function does not report errors; its callers are responsible. 1119bool IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc) { 1120 lldb_private::Log *log( 1121 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1122 1123 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc); 1124 1125 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr"); 1126 1127 if (!alloc_md || !alloc_md->getNumOperands()) 1128 return false; 1129 1130 ConstantInt *constant_int = 1131 mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0)); 1132 1133 if (!constant_int) 1134 return false; 1135 1136 // We attempt to register this as a new persistent variable with the DeclMap. 1137 1138 uintptr_t ptr = constant_int->getZExtValue(); 1139 1140 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr); 1141 1142 lldb_private::TypeFromParser result_decl_type( 1143 decl->getType().getAsOpaquePtr(), 1144 lldb_private::ClangASTContext::GetASTContext(&decl->getASTContext())); 1145 1146 StringRef decl_name(decl->getName()); 1147 lldb_private::ConstString persistent_variable_name(decl_name.data(), 1148 decl_name.size()); 1149 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, 1150 result_decl_type, false, false)) 1151 return false; 1152 1153 GlobalVariable *persistent_global = new GlobalVariable( 1154 (*m_module), alloc->getType(), false, /* not constant */ 1155 GlobalValue::ExternalLinkage, NULL, /* no initializer */ 1156 alloc->getName().str()); 1157 1158 // What we're going to do here is make believe this was a regular old 1159 // external variable. That means we need to make the metadata valid. 1160 1161 NamedMDNode *named_metadata = 1162 m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs"); 1163 1164 llvm::Metadata *values[2]; 1165 values[0] = ConstantAsMetadata::get(persistent_global); 1166 values[1] = ConstantAsMetadata::get(constant_int); 1167 1168 ArrayRef<llvm::Metadata *> value_ref(values, 2); 1169 1170 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref); 1171 named_metadata->addOperand(persistent_global_md); 1172 1173 // Now, since the variable is a pointer variable, we will drop in a load of 1174 // that pointer variable. 1175 1176 LoadInst *persistent_load = new LoadInst(persistent_global, "", alloc); 1177 1178 if (log) 1179 log->Printf("Replacing \"%s\" with \"%s\"", PrintValue(alloc).c_str(), 1180 PrintValue(persistent_load).c_str()); 1181 1182 alloc->replaceAllUsesWith(persistent_load); 1183 alloc->eraseFromParent(); 1184 1185 return true; 1186} 1187 1188bool IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block) { 1189 if (!m_resolve_vars) 1190 return true; 1191 1192 lldb_private::Log *log( 1193 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1194 1195 BasicBlock::iterator ii; 1196 1197 typedef SmallVector<Instruction *, 2> InstrList; 1198 typedef InstrList::iterator InstrIterator; 1199 1200 InstrList pvar_allocs; 1201 1202 for (ii = basic_block.begin(); ii != basic_block.end(); ++ii) { 1203 Instruction &inst = *ii; 1204 1205 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) { 1206 llvm::StringRef alloc_name = alloc->getName(); 1207 1208 if (alloc_name.startswith("$") && !alloc_name.startswith("$__lldb")) { 1209 if (alloc_name.find_first_of("0123456789") == 1) { 1210 if (log) 1211 log->Printf("Rejecting a numeric persistent variable."); 1212 1213 m_error_stream.Printf("Error [IRForTarget]: Names starting with $0, " 1214 "$1, ... are reserved for use as result " 1215 "names\n"); 1216 1217 return false; 1218 } 1219 1220 pvar_allocs.push_back(alloc); 1221 } 1222 } 1223 } 1224 1225 InstrIterator iter; 1226 1227 for (iter = pvar_allocs.begin(); iter != pvar_allocs.end(); ++iter) { 1228 if (!RewritePersistentAlloc(*iter)) { 1229 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite " 1230 "the creation of a persistent variable\n"); 1231 1232 if (log) 1233 log->PutCString( 1234 "Couldn't rewrite the creation of a persistent variable"); 1235 1236 return false; 1237 } 1238 } 1239 1240 return true; 1241} 1242 1243bool IRForTarget::MaterializeInitializer(uint8_t *data, Constant *initializer) { 1244 if (!initializer) 1245 return true; 1246 1247 lldb_private::Log *log( 1248 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1249 1250 if (log && log->GetVerbose()) 1251 log->Printf(" MaterializeInitializer(%p, %s)", (void *)data, 1252 PrintValue(initializer).c_str()); 1253 1254 Type *initializer_type = initializer->getType(); 1255 1256 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer)) { 1257 size_t constant_size = m_target_data->getTypeStoreSize(initializer_type); 1258 lldb_private::Scalar scalar = int_initializer->getValue().zextOrTrunc( 1259 llvm::NextPowerOf2(constant_size) * 8); 1260 1261 lldb_private::Status get_data_error; 1262 if (!scalar.GetAsMemoryData(data, constant_size, 1263 lldb_private::endian::InlHostByteOrder(), 1264 get_data_error)) 1265 return false; 1266 1267 return true; 1268 } else if (ConstantDataArray *array_initializer = 1269 dyn_cast<ConstantDataArray>(initializer)) { 1270 if (array_initializer->isString()) { 1271 std::string array_initializer_string = array_initializer->getAsString(); 1272 memcpy(data, array_initializer_string.c_str(), 1273 m_target_data->getTypeStoreSize(initializer_type)); 1274 } else { 1275 ArrayType *array_initializer_type = array_initializer->getType(); 1276 Type *array_element_type = array_initializer_type->getElementType(); 1277 1278 size_t element_size = m_target_data->getTypeAllocSize(array_element_type); 1279 1280 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i) { 1281 Value *operand_value = array_initializer->getOperand(i); 1282 Constant *operand_constant = dyn_cast<Constant>(operand_value); 1283 1284 if (!operand_constant) 1285 return false; 1286 1287 if (!MaterializeInitializer(data + (i * element_size), 1288 operand_constant)) 1289 return false; 1290 } 1291 } 1292 return true; 1293 } else if (ConstantStruct *struct_initializer = 1294 dyn_cast<ConstantStruct>(initializer)) { 1295 StructType *struct_initializer_type = struct_initializer->getType(); 1296 const StructLayout *struct_layout = 1297 m_target_data->getStructLayout(struct_initializer_type); 1298 1299 for (unsigned i = 0; i < struct_initializer->getNumOperands(); ++i) { 1300 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), 1301 struct_initializer->getOperand(i))) 1302 return false; 1303 } 1304 return true; 1305 } else if (isa<ConstantAggregateZero>(initializer)) { 1306 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type)); 1307 return true; 1308 } 1309 return false; 1310} 1311 1312// This function does not report errors; its callers are responsible. 1313bool IRForTarget::MaybeHandleVariable(Value *llvm_value_ptr) { 1314 lldb_private::Log *log( 1315 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1316 1317 if (log) 1318 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str()); 1319 1320 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) { 1321 switch (constant_expr->getOpcode()) { 1322 default: 1323 break; 1324 case Instruction::GetElementPtr: 1325 case Instruction::BitCast: 1326 Value *s = constant_expr->getOperand(0); 1327 if (!MaybeHandleVariable(s)) 1328 return false; 1329 } 1330 } else if (GlobalVariable *global_variable = 1331 dyn_cast<GlobalVariable>(llvm_value_ptr)) { 1332 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage())) 1333 return true; 1334 1335 clang::NamedDecl *named_decl = DeclForGlobal(global_variable); 1336 1337 if (!named_decl) { 1338 if (IsObjCSelectorRef(llvm_value_ptr)) 1339 return true; 1340 1341 if (!global_variable->hasExternalLinkage()) 1342 return true; 1343 1344 if (log) 1345 log->Printf("Found global variable \"%s\" without metadata", 1346 global_variable->getName().str().c_str()); 1347 1348 return false; 1349 } 1350 1351 std::string name(named_decl->getName().str()); 1352 1353 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl); 1354 if (value_decl == NULL) 1355 return false; 1356 1357 lldb_private::CompilerType compiler_type(&value_decl->getASTContext(), 1358 value_decl->getType()); 1359 1360 const Type *value_type = NULL; 1361 1362 if (name[0] == '$') { 1363 // The $__lldb_expr_result name indicates the return value has allocated 1364 // as a static variable. Per the comment at 1365 // ASTResultSynthesizer::SynthesizeBodyResult, accesses to this static 1366 // variable need to be redirected to the result of dereferencing a 1367 // pointer that is passed in as one of the arguments. 1368 // 1369 // Consequently, when reporting the size of the type, we report a pointer 1370 // type pointing 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. 1413bool 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 1448bool 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 1469bool 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 1526bool 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 1565bool 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 1585bool 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 1635static 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 1662void 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 1668static void ExciseGuardStore(Instruction *guard_store) { 1669 guard_store->eraseFromParent(); 1670} 1671 1672bool 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. 1709bool 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 1827bool 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.arg_begin()); 1849 1850 if (iter == llvm_function.arg_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.arg_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.arg_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.arg_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, 1961 // in cases where the result variable is an rvalue, we have to 1962 // synthesize a dereference of the appropriate structure entry in 1963 // order to produce the static variable that the AST thinks it is 1964 // accessing. 1965 1966 llvm::Instruction *entry_instruction = llvm::cast<Instruction>( 1967 m_entry_instruction_finder.GetValue(function)); 1968 1969 ConstantInt *offset_int( 1970 ConstantInt::get(offset_type, offset, true)); 1971 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create( 1972 nullptr, argument, offset_int, "", entry_instruction); 1973 1974 if (name == m_result_name && !m_result_is_pointer) { 1975 BitCastInst *bit_cast = new BitCastInst( 1976 get_element_ptr, value->getType()->getPointerTo(), "", 1977 entry_instruction); 1978 1979 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction); 1980 1981 return load; 1982 } else { 1983 BitCastInst *bit_cast = new BitCastInst( 1984 get_element_ptr, value->getType(), "", entry_instruction); 1985 1986 return bit_cast; 1987 } 1988 }); 1989 1990 if (Constant *constant = dyn_cast<Constant>(value)) { 1991 if (!UnfoldConstant(constant, &llvm_function, body_result_maker, 1992 m_entry_instruction_finder, m_error_stream)) { 1993 return false; 1994 } 1995 } else if (Instruction *instruction = dyn_cast<Instruction>(value)) { 1996 if (instruction->getParent()->getParent() != &llvm_function) { 1997 m_error_stream.PutCString("error: Capturing non-local variables in " 1998 "expressions is unsupported.\n"); 1999 return false; 2000 } 2001 value->replaceAllUsesWith( 2002 body_result_maker.GetValue(instruction->getParent()->getParent())); 2003 } else { 2004 if (log) 2005 log->Printf("Unhandled non-constant type: \"%s\"", 2006 PrintValue(value).c_str()); 2007 return false; 2008 } 2009 2010 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value)) 2011 var->eraseFromParent(); 2012 } 2013 } 2014 2015 if (log) 2016 log->Printf("Total structure [align %" PRId64 ", size %" PRIu64 "]", 2017 (int64_t)alignment, (uint64_t)size); 2018 2019 return true; 2020} 2021 2022llvm::Constant *IRForTarget::BuildRelocation(llvm::Type *type, 2023 uint64_t offset) { 2024 llvm::Constant *offset_int = ConstantInt::get(m_intptr_ty, offset); 2025 2026 llvm::Constant *offset_array[1]; 2027 2028 offset_array[0] = offset_int; 2029 2030 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1); 2031 llvm::Type *char_type = llvm::Type::getInt8Ty(m_module->getContext()); 2032 llvm::Type *char_pointer_type = char_type->getPointerTo(); 2033 2034 llvm::Constant *reloc_placeholder_bitcast = 2035 ConstantExpr::getBitCast(m_reloc_placeholder, char_pointer_type); 2036 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr( 2037 char_type, reloc_placeholder_bitcast, offsets); 2038 llvm::Constant *reloc_bitcast = 2039 ConstantExpr::getBitCast(reloc_getelementptr, type); 2040 2041 return reloc_bitcast; 2042} 2043 2044bool IRForTarget::runOnModule(Module &llvm_module) { 2045 lldb_private::Log *log( 2046 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 2047 2048 m_module = &llvm_module; 2049 m_target_data.reset(new DataLayout(m_module)); 2050 m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(), 2051 m_target_data->getPointerSizeInBits()); 2052 2053 if (log) { 2054 std::string s; 2055 raw_string_ostream oss(s); 2056 2057 m_module->print(oss, NULL); 2058 2059 oss.flush(); 2060 2061 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str()); 2062 } 2063 2064 Function *const main_function = 2065 m_func_name.IsEmpty() ? nullptr 2066 : m_module->getFunction(m_func_name.GetStringRef()); 2067 2068 if (!m_func_name.IsEmpty() && !main_function) { 2069 if (log) 2070 log->Printf("Couldn't find \"%s()\" in the module", 2071 m_func_name.AsCString()); 2072 2073 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't find wrapper " 2074 "'%s' in the module", 2075 m_func_name.AsCString()); 2076 2077 return false; 2078 } 2079 2080 if (main_function) { 2081 if (!FixFunctionLinkage(*main_function)) { 2082 if (log) 2083 log->Printf("Couldn't fix the linkage for the function"); 2084 2085 return false; 2086 } 2087 } 2088 2089 llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext()); 2090 2091 m_reloc_placeholder = new llvm::GlobalVariable( 2092 (*m_module), int8_ty, false /* IsConstant */, 2093 GlobalVariable::InternalLinkage, Constant::getNullValue(int8_ty), 2094 "reloc_placeholder", NULL /* InsertBefore */, 2095 GlobalVariable::NotThreadLocal /* ThreadLocal */, 0 /* AddressSpace */); 2096 2097 //////////////////////////////////////////////////////////// 2098 // Replace $__lldb_expr_result with a persistent variable 2099 // 2100 2101 if (main_function) { 2102 if (!CreateResultVariable(*main_function)) { 2103 if (log) 2104 log->Printf("CreateResultVariable() failed"); 2105 2106 // CreateResultVariable() reports its own errors, so we don't do so here 2107 2108 return false; 2109 } 2110 } 2111 2112 if (log && log->GetVerbose()) { 2113 std::string s; 2114 raw_string_ostream oss(s); 2115 2116 m_module->print(oss, NULL); 2117 2118 oss.flush(); 2119 2120 log->Printf("Module after creating the result variable: \n\"%s\"", 2121 s.c_str()); 2122 } 2123 2124 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); fi != fe; 2125 ++fi) { 2126 llvm::Function *function = &*fi; 2127 2128 if (function->begin() == function->end()) 2129 continue; 2130 2131 Function::iterator bbi; 2132 2133 for (bbi = function->begin(); bbi != function->end(); ++bbi) { 2134 if (!RemoveGuards(*bbi)) { 2135 if (log) 2136 log->Printf("RemoveGuards() failed"); 2137 2138 // RemoveGuards() reports its own errors, so we don't do so here 2139 2140 return false; 2141 } 2142 2143 if (!RewritePersistentAllocs(*bbi)) { 2144 if (log) 2145 log->Printf("RewritePersistentAllocs() failed"); 2146 2147 // RewritePersistentAllocs() reports its own errors, so we don't do so 2148 // here 2149 2150 return false; 2151 } 2152 2153 if (!RemoveCXAAtExit(*bbi)) { 2154 if (log) 2155 log->Printf("RemoveCXAAtExit() failed"); 2156 2157 // RemoveCXAAtExit() reports its own errors, so we don't do so here 2158 2159 return false; 2160 } 2161 } 2162 } 2163 2164 /////////////////////////////////////////////////////////////////////////////// 2165 // Fix all Objective-C constant strings to use NSStringWithCString:encoding: 2166 // 2167 2168 if (!RewriteObjCConstStrings()) { 2169 if (log) 2170 log->Printf("RewriteObjCConstStrings() failed"); 2171 2172 // RewriteObjCConstStrings() reports its own errors, so we don't do so here 2173 2174 return false; 2175 } 2176 2177 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); fi != fe; 2178 ++fi) { 2179 llvm::Function *function = &*fi; 2180 2181 for (llvm::Function::iterator bbi = function->begin(), 2182 bbe = function->end(); 2183 bbi != bbe; ++bbi) { 2184 if (!RewriteObjCSelectors(*bbi)) { 2185 if (log) 2186 log->Printf("RewriteObjCSelectors() failed"); 2187 2188 // RewriteObjCSelectors() reports its own errors, so we don't do so 2189 // 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 2261void IRForTarget::assignPassManager(PMStack &pass_mgr_stack, 2262 PassManagerType pass_mgr_type) {} 2263 2264PassManagerType IRForTarget::getPotentialPassManagerType() const { 2265 return PMT_ModulePassManager; 2266} 2267