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