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