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