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