IRForTarget.cpp revision 309124
1187517Sgonzo//===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===// 2187517Sgonzo// 3187517Sgonzo// The LLVM Compiler Infrastructure 4187517Sgonzo// 5187517Sgonzo// This file is distributed under the University of Illinois Open Source 6187517Sgonzo// License. See LICENSE.TXT for details. 7187517Sgonzo// 8187517Sgonzo//===----------------------------------------------------------------------===// 9187517Sgonzo 10187517Sgonzo#include "IRForTarget.h" 11187517Sgonzo 12187517Sgonzo#include "ClangExpressionDeclMap.h" 13187517Sgonzo 14187517Sgonzo#include "llvm/Support/raw_ostream.h" 15187517Sgonzo#include "llvm/IR/Constants.h" 16187517Sgonzo#include "llvm/IR/DataLayout.h" 17187517Sgonzo#include "llvm/IR/InstrTypes.h" 18187517Sgonzo#include "llvm/IR/Instructions.h" 19187517Sgonzo#include "llvm/IR/Intrinsics.h" 20187517Sgonzo#include "llvm/IR/Module.h" 21187517Sgonzo#include "llvm/IR/LegacyPassManager.h" 22187517Sgonzo#include "llvm/Transforms/IPO.h" 23187517Sgonzo#include "llvm/IR/Metadata.h" 24187517Sgonzo#include "llvm/IR/ValueSymbolTable.h" 25187517Sgonzo 26187517Sgonzo#include "clang/AST/ASTContext.h" 27187517Sgonzo 28187517Sgonzo#include "lldb/Core/ConstString.h" 29187517Sgonzo#include "lldb/Core/DataBufferHeap.h" 30187517Sgonzo#include "lldb/Core/Log.h" 31187517Sgonzo#include "lldb/Core/Scalar.h" 32187517Sgonzo#include "lldb/Core/StreamString.h" 33187517Sgonzo#include "lldb/Core/dwarf.h" 34187517Sgonzo#include "lldb/Expression/IRExecutionUnit.h" 35187517Sgonzo#include "lldb/Expression/IRInterpreter.h" 36187517Sgonzo#include "lldb/Host/Endian.h" 37187517Sgonzo#include "lldb/Symbol/ClangASTContext.h" 38187517Sgonzo#include "lldb/Symbol/ClangUtil.h" 39187517Sgonzo#include "lldb/Symbol/CompilerType.h" 40187517Sgonzo 41187517Sgonzo#include <map> 42187517Sgonzo 43187517Sgonzousing namespace llvm; 44187517Sgonzo 45187517Sgonzostatic char ID; 46187517Sgonzo 47187517SgonzoIRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) : 48187517Sgonzo m_maker(maker), 49187517Sgonzo m_values() 50187517Sgonzo{ 51187517Sgonzo} 52187517Sgonzo 53187517SgonzoIRForTarget::FunctionValueCache::~FunctionValueCache() 54187517Sgonzo{ 55187517Sgonzo} 56187517Sgonzo 57187517Sgonzollvm::Value * 58187517SgonzoIRForTarget::FunctionValueCache::GetValue(llvm::Function *function) 59187517Sgonzo{ 60187517Sgonzo if (!m_values.count(function)) 61187517Sgonzo { 62187517Sgonzo llvm::Value *ret = m_maker(function); 63187517Sgonzo m_values[function] = ret; 64187517Sgonzo return ret; 65187517Sgonzo } 66187517Sgonzo return m_values[function]; 67187517Sgonzo} 68187517Sgonzo 69187517Sgonzostatic llvm::Value * 70187517SgonzoFindEntryInstruction (llvm::Function *function) 71187517Sgonzo{ 72187517Sgonzo if (function->empty()) 73187517Sgonzo return NULL; 74187517Sgonzo 75187517Sgonzo return function->getEntryBlock().getFirstNonPHIOrDbg(); 76187517Sgonzo} 77187517Sgonzo 78187517SgonzoIRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map, 79187517Sgonzo bool resolve_vars, 80187517Sgonzo lldb_private::IRExecutionUnit &execution_unit, 81187517Sgonzo lldb_private::Stream *error_stream, 82187517Sgonzo const char *func_name) : 83187517Sgonzo ModulePass(ID), 84187517Sgonzo m_resolve_vars(resolve_vars), 85187517Sgonzo m_func_name(func_name), 86187517Sgonzo m_module(NULL), 87187517Sgonzo m_decl_map(decl_map), 88187517Sgonzo m_CFStringCreateWithBytes(NULL), 89187517Sgonzo m_sel_registerName(NULL), 90187517Sgonzo m_intptr_ty(NULL), 91187517Sgonzo m_error_stream(error_stream), 92187517Sgonzo m_execution_unit(execution_unit), 93187517Sgonzo m_result_store(NULL), 94187517Sgonzo m_result_is_pointer(false), 95187517Sgonzo m_reloc_placeholder(NULL), 96187517Sgonzo m_entry_instruction_finder (FindEntryInstruction) 97187517Sgonzo{ 98187517Sgonzo} 99187517Sgonzo 100187517Sgonzo/* Handy utility functions used at several places in the code */ 101187517Sgonzo 102187517Sgonzostatic std::string 103187517SgonzoPrintValue(const Value *value, bool truncate = false) 104187517Sgonzo{ 105187517Sgonzo std::string s; 106187517Sgonzo if (value) 107187517Sgonzo { 108187517Sgonzo raw_string_ostream rso(s); 109187517Sgonzo value->print(rso); 110187517Sgonzo rso.flush(); 111187517Sgonzo if (truncate) 112187517Sgonzo s.resize(s.length() - 1); 113187517Sgonzo } 114187517Sgonzo return s; 115187517Sgonzo} 116187517Sgonzo 117187517Sgonzostatic std::string 118187517SgonzoPrintType(const llvm::Type *type, bool truncate = false) 119187517Sgonzo{ 120187517Sgonzo std::string s; 121187517Sgonzo raw_string_ostream rso(s); 122187517Sgonzo type->print(rso); 123187517Sgonzo rso.flush(); 124187517Sgonzo if (truncate) 125187517Sgonzo s.resize(s.length() - 1); 126187517Sgonzo return s; 127187517Sgonzo} 128187517Sgonzo 129187517SgonzoIRForTarget::~IRForTarget() 130187517Sgonzo{ 131187517Sgonzo} 132187517Sgonzo 133187517Sgonzobool 134187517SgonzoIRForTarget::FixFunctionLinkage(llvm::Function &llvm_function) 135187517Sgonzo{ 136187517Sgonzo llvm_function.setLinkage(GlobalValue::ExternalLinkage); 137187517Sgonzo 138187517Sgonzo return true; 139187517Sgonzo} 140187517Sgonzo 141187517Sgonzoclang::NamedDecl * 142187517SgonzoIRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module) 143187517Sgonzo{ 144187517Sgonzo NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs"); 145187517Sgonzo 146187517Sgonzo if (!named_metadata) 147187517Sgonzo return NULL; 148187517Sgonzo 149187517Sgonzo unsigned num_nodes = named_metadata->getNumOperands(); 150187517Sgonzo unsigned node_index; 151187517Sgonzo 152187517Sgonzo for (node_index = 0; 153187517Sgonzo node_index < num_nodes; 154187517Sgonzo ++node_index) 155187517Sgonzo { 156187517Sgonzo llvm::MDNode *metadata_node = dyn_cast<llvm::MDNode>(named_metadata->getOperand(node_index)); 157187517Sgonzo if (!metadata_node) 158187517Sgonzo return NULL; 159187517Sgonzo 160187517Sgonzo if (metadata_node->getNumOperands() != 2) 161187517Sgonzo continue; 162187517Sgonzo 163187517Sgonzo if (mdconst::dyn_extract_or_null<GlobalValue>(metadata_node->getOperand(0)) != global_val) 164187517Sgonzo continue; 165187517Sgonzo 166187517Sgonzo ConstantInt *constant_int = mdconst::dyn_extract<ConstantInt>(metadata_node->getOperand(1)); 167187517Sgonzo 168187517Sgonzo if (!constant_int) 169187517Sgonzo return NULL; 170187517Sgonzo 171187517Sgonzo uintptr_t ptr = constant_int->getZExtValue(); 172187517Sgonzo 173187517Sgonzo return reinterpret_cast<clang::NamedDecl *>(ptr); 174187517Sgonzo } 175187517Sgonzo 176187517Sgonzo return NULL; 177187517Sgonzo} 178187517Sgonzo 179187517Sgonzoclang::NamedDecl * 180187517SgonzoIRForTarget::DeclForGlobal (GlobalValue *global_val) 181187517Sgonzo{ 182187517Sgonzo return DeclForGlobal(global_val, m_module); 183187517Sgonzo} 184187517Sgonzo 185187517Sgonzobool 186187517SgonzoIRForTarget::CreateResultVariable (llvm::Function &llvm_function) 187187517Sgonzo{ 188187517Sgonzo lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 189187517Sgonzo 190187517Sgonzo if (!m_resolve_vars) 191187517Sgonzo return true; 192187517Sgonzo 193187517Sgonzo // Find the result variable. If it doesn't exist, we can give up right here. 194187517Sgonzo 195187517Sgonzo ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable(); 196187517Sgonzo 197187517Sgonzo std::string result_name_str; 198187517Sgonzo const char *result_name = NULL; 199187517Sgonzo 200187517Sgonzo for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end(); 201187517Sgonzo vi != ve; 202187517Sgonzo ++vi) 203187517Sgonzo { 204187517Sgonzo result_name_str = vi->first().str(); 205187517Sgonzo const char *value_name = result_name_str.c_str(); 206187517Sgonzo 207187517Sgonzo if (strstr(value_name, "$__lldb_expr_result_ptr") && 208187517Sgonzo strncmp(value_name, "_ZGV", 4)) 209187517Sgonzo { 210187517Sgonzo result_name = value_name; 211187517Sgonzo m_result_is_pointer = true; 212187517Sgonzo break; 213187517Sgonzo } 214187517Sgonzo 215187517Sgonzo if (strstr(value_name, "$__lldb_expr_result") && 216187517Sgonzo strncmp(value_name, "_ZGV", 4)) 217187517Sgonzo { 218187517Sgonzo result_name = value_name; 219187517Sgonzo m_result_is_pointer = false; 220187517Sgonzo break; 221187517Sgonzo } 222187517Sgonzo } 223187517Sgonzo 224187517Sgonzo if (!result_name) 225187517Sgonzo { 226187517Sgonzo if (log) 227187517Sgonzo log->PutCString("Couldn't find result variable"); 228187517Sgonzo 229187517Sgonzo return true; 230187517Sgonzo } 231187517Sgonzo 232187517Sgonzo if (log) 233187517Sgonzo log->Printf("Result name: \"%s\"", result_name); 234187517Sgonzo 235187517Sgonzo Value *result_value = m_module->getNamedValue(result_name); 236187517Sgonzo 237187517Sgonzo if (!result_value) 238187517Sgonzo { 239187517Sgonzo if (log) 240187517Sgonzo log->PutCString("Result variable had no data"); 241187517Sgonzo 242187517Sgonzo if (m_error_stream) 243187517Sgonzo m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name); 244187517Sgonzo 245187517Sgonzo return false; 246187517Sgonzo } 247187517Sgonzo 248187517Sgonzo if (log) 249187517Sgonzo log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str()); 250187517Sgonzo 251187517Sgonzo GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value); 252187517Sgonzo 253187517Sgonzo if (!result_global) 254187517Sgonzo { 255187517Sgonzo if (log) 256187517Sgonzo log->PutCString("Result variable isn't a GlobalVariable"); 257187517Sgonzo 258187517Sgonzo if (m_error_stream) 259187517Sgonzo m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name); 260187517Sgonzo 261187517Sgonzo return false; 262187517Sgonzo } 263187517Sgonzo 264187517Sgonzo clang::NamedDecl *result_decl = DeclForGlobal (result_global); 265187517Sgonzo if (!result_decl) 266187517Sgonzo { 267187517Sgonzo if (log) 268187517Sgonzo log->PutCString("Result variable doesn't have a corresponding Decl"); 269187517Sgonzo 270187517Sgonzo if (m_error_stream) 271187517Sgonzo m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name); 272187517Sgonzo 273187517Sgonzo return false; 274187517Sgonzo } 275187517Sgonzo 276187517Sgonzo if (log) 277187517Sgonzo { 278187517Sgonzo std::string decl_desc_str; 279187517Sgonzo raw_string_ostream decl_desc_stream(decl_desc_str); 280187517Sgonzo result_decl->print(decl_desc_stream); 281187517Sgonzo decl_desc_stream.flush(); 282187517Sgonzo 283187517Sgonzo log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str()); 284187517Sgonzo } 285187517Sgonzo 286187517Sgonzo clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl); 287187517Sgonzo if (!result_var) 288187517Sgonzo { 289187517Sgonzo if (log) 290187517Sgonzo log->PutCString("Result variable Decl isn't a VarDecl"); 291187517Sgonzo 292187517Sgonzo if (m_error_stream) 293187517Sgonzo m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name); 294187517Sgonzo 295187517Sgonzo return false; 296187517Sgonzo } 297187517Sgonzo 298187517Sgonzo // Get the next available result name from m_decl_map and create the persistent 299187517Sgonzo // variable for it 300187517Sgonzo 301187517Sgonzo // If the result is an Lvalue, it is emitted as a pointer; see 302187517Sgonzo // ASTResultSynthesizer::SynthesizeBodyResult. 303187517Sgonzo if (m_result_is_pointer) 304187517Sgonzo { 305187517Sgonzo clang::QualType pointer_qual_type = result_var->getType(); 306187517Sgonzo const clang::Type *pointer_type = pointer_qual_type.getTypePtr(); 307187517Sgonzo 308187517Sgonzo const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>(); 309187517Sgonzo const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>(); 310187517Sgonzo 311187517Sgonzo if (pointer_pointertype) 312187517Sgonzo { 313187517Sgonzo clang::QualType element_qual_type = pointer_pointertype->getPointeeType(); 314187517Sgonzo 315187517Sgonzo m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(), 316187517Sgonzo lldb_private::ClangASTContext::GetASTContext(&result_decl->getASTContext())); 317187517Sgonzo } 318187517Sgonzo else if (pointer_objcobjpointertype) 319187517Sgonzo { 320187517Sgonzo clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0); 321187517Sgonzo 322187517Sgonzo m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(), 323187517Sgonzo lldb_private::ClangASTContext::GetASTContext(&result_decl->getASTContext())); 324187517Sgonzo } 325187517Sgonzo else 326187517Sgonzo { 327187517Sgonzo if (log) 328187517Sgonzo log->PutCString("Expected result to have pointer type, but it did not"); 329187517Sgonzo 330187517Sgonzo if (m_error_stream) 331187517Sgonzo m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name); 332187517Sgonzo 333187517Sgonzo return false; 334187517Sgonzo } 335187517Sgonzo } 336187517Sgonzo else 337187517Sgonzo { 338187517Sgonzo m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(), 339187517Sgonzo lldb_private::ClangASTContext::GetASTContext(&result_decl->getASTContext())); 340187517Sgonzo } 341187517Sgonzo 342187517Sgonzo 343187517Sgonzo lldb::TargetSP target_sp (m_execution_unit.GetTarget()); 344187517Sgonzo lldb_private::ExecutionContext exe_ctx (target_sp, true); 345187517Sgonzo if (m_result_type.GetBitSize(exe_ctx.GetBestExecutionContextScope()) == 0) 346187517Sgonzo { 347187517Sgonzo lldb_private::StreamString type_desc_stream; 348187517Sgonzo m_result_type.DumpTypeDescription(&type_desc_stream); 349187517Sgonzo 350187517Sgonzo if (log) 351187517Sgonzo log->Printf("Result type has size 0"); 352187517Sgonzo 353187517Sgonzo if (m_error_stream) 354187517Sgonzo m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n", 355187517Sgonzo type_desc_stream.GetData()); 356187517Sgonzo return false; 357187517Sgonzo } 358187517Sgonzo 359187517Sgonzo if (log) 360187517Sgonzo { 361187517Sgonzo lldb_private::StreamString type_desc_stream; 362187517Sgonzo m_result_type.DumpTypeDescription(&type_desc_stream); 363187517Sgonzo 364187517Sgonzo log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData()); 365187517Sgonzo } 366187517Sgonzo 367187517Sgonzo m_result_name = lldb_private::ConstString("$RESULT_NAME"); 368187517Sgonzo 369187517Sgonzo if (log) 370187517Sgonzo log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64, 371187517Sgonzo m_result_name.GetCString(), 372187517Sgonzo m_result_type.GetByteSize(nullptr)); 373187517Sgonzo 374187517Sgonzo // Construct a new result global and set up its metadata 375187517Sgonzo 376187517Sgonzo GlobalVariable *new_result_global = new GlobalVariable((*m_module), 377187517Sgonzo result_global->getType()->getElementType(), 378187517Sgonzo false, /* not constant */ 379187517Sgonzo GlobalValue::ExternalLinkage, 380187517Sgonzo NULL, /* no initializer */ 381187517Sgonzo m_result_name.GetCString ()); 382187517Sgonzo 383187517Sgonzo // It's too late in compilation to create a new VarDecl for this, but we don't 384187517Sgonzo // need to. We point the metadata at the old VarDecl. This creates an odd 385187517Sgonzo // anomaly: a variable with a Value whose name is something like $0 and a 386187517Sgonzo // Decl whose name is $__lldb_expr_result. This condition is handled in 387187517Sgonzo // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is 388187517Sgonzo // fixed up. 389187517Sgonzo 390187517Sgonzo ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()), 391187517Sgonzo reinterpret_cast<uint64_t>(result_decl), 392187517Sgonzo false); 393187517Sgonzo 394187517Sgonzo llvm::Metadata *values[2]; 395187517Sgonzo values[0] = ConstantAsMetadata::get(new_result_global); 396187517Sgonzo values[1] = ConstantAsMetadata::get(new_constant_int); 397187517Sgonzo 398187517Sgonzo ArrayRef<Metadata *> value_ref(values, 2); 399187517Sgonzo 400187517Sgonzo MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref); 401187517Sgonzo NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs"); 402187517Sgonzo named_metadata->addOperand(persistent_global_md); 403187517Sgonzo 404187517Sgonzo if (log) 405187517Sgonzo log->Printf("Replacing \"%s\" with \"%s\"", 406187517Sgonzo PrintValue(result_global).c_str(), 407187517Sgonzo PrintValue(new_result_global).c_str()); 408187517Sgonzo 409187517Sgonzo if (result_global->use_empty()) 410187517Sgonzo { 411187517Sgonzo // We need to synthesize a store for this variable, because otherwise 412187517Sgonzo // there's nothing to put into its equivalent persistent variable. 413187517Sgonzo 414187517Sgonzo BasicBlock &entry_block(llvm_function.getEntryBlock()); 415187517Sgonzo Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg()); 416187517Sgonzo 417187517Sgonzo if (!first_entry_instruction) 418187517Sgonzo return false; 419187517Sgonzo 420187517Sgonzo if (!result_global->hasInitializer()) 421187517Sgonzo { 422187517Sgonzo if (log) 423187517Sgonzo log->Printf("Couldn't find initializer for unused variable"); 424187517Sgonzo 425 if (m_error_stream) 426 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name); 427 428 return false; 429 } 430 431 Constant *initializer = result_global->getInitializer(); 432 433 StoreInst *synthesized_store = new StoreInst(initializer, 434 new_result_global, 435 first_entry_instruction); 436 437 if (log) 438 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str()); 439 } 440 else 441 { 442 result_global->replaceAllUsesWith(new_result_global); 443 } 444 445 if (!m_decl_map->AddPersistentVariable(result_decl, 446 m_result_name, 447 m_result_type, 448 true, 449 m_result_is_pointer)) 450 return false; 451 452 result_global->eraseFromParent(); 453 454 return true; 455} 456 457bool 458IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str, 459 llvm::GlobalVariable *cstr) 460{ 461 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 462 463 Type *ns_str_ty = ns_str->getType(); 464 465 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext()); 466 Type *i32_ty = Type::getInt32Ty(m_module->getContext()); 467 Type *i8_ty = Type::getInt8Ty(m_module->getContext()); 468 469 if (!m_CFStringCreateWithBytes) 470 { 471 lldb::addr_t CFStringCreateWithBytes_addr; 472 473 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes"); 474 475 CFStringCreateWithBytes_addr = m_execution_unit.FindSymbol (g_CFStringCreateWithBytes_str); 476 if (CFStringCreateWithBytes_addr == LLDB_INVALID_ADDRESS) 477 { 478 if (log) 479 log->PutCString("Couldn't find CFStringCreateWithBytes in the target"); 480 481 if (m_error_stream) 482 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n"); 483 484 return false; 485 } 486 487 if (log) 488 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr); 489 490 // Build the function type: 491 // 492 // CFStringRef CFStringCreateWithBytes ( 493 // CFAllocatorRef alloc, 494 // const UInt8 *bytes, 495 // CFIndex numBytes, 496 // CFStringEncoding encoding, 497 // Boolean isExternalRepresentation 498 // ); 499 // 500 // We make the following substitutions: 501 // 502 // CFStringRef -> i8* 503 // CFAllocatorRef -> i8* 504 // UInt8 * -> i8* 505 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now) 506 // CFStringEncoding -> i32 507 // Boolean -> i8 508 509 Type *arg_type_array[5]; 510 511 arg_type_array[0] = i8_ptr_ty; 512 arg_type_array[1] = i8_ptr_ty; 513 arg_type_array[2] = m_intptr_ty; 514 arg_type_array[3] = i32_ty; 515 arg_type_array[4] = i8_ty; 516 517 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5); 518 519 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false); 520 521 // Build the constant containing the pointer to the function 522 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty); 523 Constant *CFSCWB_addr_int = ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false); 524 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty); 525 } 526 527 ConstantDataSequential *string_array = NULL; 528 529 if (cstr) 530 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer()); 531 532 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty); 533 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty); 534 Constant *numBytes_arg = ConstantInt::get(m_intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false); 535 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */ 536 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */ 537 538 Value *argument_array[5]; 539 540 argument_array[0] = alloc_arg; 541 argument_array[1] = bytes_arg; 542 argument_array[2] = numBytes_arg; 543 argument_array[3] = encoding_arg; 544 argument_array[4] = isExternal_arg; 545 546 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5); 547 548 FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * { 549 return CallInst::Create(m_CFStringCreateWithBytes, 550 CFSCWB_arguments, 551 "CFStringCreateWithBytes", 552 llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function))); 553 }); 554 555 if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder)) 556 { 557 if (log) 558 log->PutCString("Couldn't replace the NSString with the result of the call"); 559 560 if (m_error_stream) 561 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n"); 562 563 return false; 564 } 565 566 ns_str->eraseFromParent(); 567 568 return true; 569} 570 571bool 572IRForTarget::RewriteObjCConstStrings() 573{ 574 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 575 576 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable(); 577 578 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end(); 579 vi != ve; 580 ++vi) 581 { 582 std::string value_name = vi->first().str(); 583 const char *value_name_cstr = value_name.c_str(); 584 585 if (strstr(value_name_cstr, "_unnamed_cfstring_")) 586 { 587 Value *nsstring_value = vi->second; 588 589 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value); 590 591 if (!nsstring_global) 592 { 593 if (log) 594 log->PutCString("NSString variable is not a GlobalVariable"); 595 596 if (m_error_stream) 597 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n"); 598 599 return false; 600 } 601 602 if (!nsstring_global->hasInitializer()) 603 { 604 if (log) 605 log->PutCString("NSString variable does not have an initializer"); 606 607 if (m_error_stream) 608 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n"); 609 610 return false; 611 } 612 613 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer()); 614 615 if (!nsstring_struct) 616 { 617 if (log) 618 log->PutCString("NSString variable's initializer is not a ConstantStruct"); 619 620 if (m_error_stream) 621 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n"); 622 623 return false; 624 } 625 626 // We expect the following structure: 627 // 628 // struct { 629 // int *isa; 630 // int flags; 631 // char *str; 632 // long length; 633 // }; 634 635 if (nsstring_struct->getNumOperands() != 4) 636 { 637 if (log) 638 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands()); 639 640 if (m_error_stream) 641 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n"); 642 643 return false; 644 } 645 646 Constant *nsstring_member = nsstring_struct->getOperand(2); 647 648 if (!nsstring_member) 649 { 650 if (log) 651 log->PutCString("NSString initializer's str element was empty"); 652 653 if (m_error_stream) 654 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n"); 655 656 return false; 657 } 658 659 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member); 660 661 if (!nsstring_expr) 662 { 663 if (log) 664 log->PutCString("NSString initializer's str element is not a ConstantExpr"); 665 666 if (m_error_stream) 667 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n"); 668 669 return false; 670 } 671 672 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr) 673 { 674 if (log) 675 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName()); 676 677 if (m_error_stream) 678 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n"); 679 680 return false; 681 } 682 683 Constant *nsstring_cstr = nsstring_expr->getOperand(0); 684 685 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr); 686 687 if (!cstr_global) 688 { 689 if (log) 690 log->PutCString("NSString initializer's str element is not a GlobalVariable"); 691 692 if (m_error_stream) 693 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n"); 694 695 return false; 696 } 697 698 if (!cstr_global->hasInitializer()) 699 { 700 if (log) 701 log->PutCString("NSString initializer's str element does not have an initializer"); 702 703 if (m_error_stream) 704 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n"); 705 706 return false; 707 } 708 709 /* 710 if (!cstr_array) 711 { 712 if (log) 713 log->PutCString("NSString initializer's str element is not a ConstantArray"); 714 715 if (m_error_stream) 716 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n"); 717 718 return false; 719 } 720 721 if (!cstr_array->isCString()) 722 { 723 if (log) 724 log->PutCString("NSString initializer's str element is not a C string array"); 725 726 if (m_error_stream) 727 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n"); 728 729 return false; 730 } 731 */ 732 733 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer()); 734 735 if (log) 736 { 737 if (cstr_array) 738 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().str().c_str()); 739 else 740 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr); 741 } 742 743 if (!cstr_array) 744 cstr_global = NULL; 745 746 if (!RewriteObjCConstString(nsstring_global, cstr_global)) 747 { 748 if (log) 749 log->PutCString("Error rewriting the constant string"); 750 751 // We don't print an error message here because RewriteObjCConstString has done so for us. 752 753 return false; 754 } 755 } 756 } 757 758 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end(); 759 vi != ve; 760 ++vi) 761 { 762 std::string value_name = vi->first().str(); 763 const char *value_name_cstr = value_name.c_str(); 764 765 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference")) 766 { 767 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second); 768 769 if (!gv) 770 { 771 if (log) 772 log->PutCString("__CFConstantStringClassReference is not a global variable"); 773 774 if (m_error_stream) 775 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n"); 776 777 return false; 778 } 779 780 gv->eraseFromParent(); 781 782 break; 783 } 784 } 785 786 return true; 787} 788 789static bool IsObjCSelectorRef (Value *value) 790{ 791 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value); 792 793 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("OBJC_SELECTOR_REFERENCES_")) 794 return false; 795 796 return true; 797} 798 799// This function does not report errors; its callers are responsible. 800bool 801IRForTarget::RewriteObjCSelector (Instruction* selector_load) 802{ 803 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 804 805 LoadInst *load = dyn_cast<LoadInst>(selector_load); 806 807 if (!load) 808 return false; 809 810 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as 811 // 812 // %tmp = load i8** @"OBJC_SELECTOR_REFERENCES_" ; <i8*> 813 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*> 814 // 815 // where %obj is the object pointer and %tmp is the selector. 816 // 817 // @"OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_". 818 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string. 819 820 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target 821 822 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand()); 823 824 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer()) 825 return false; 826 827 Constant *osr_initializer = _objc_selector_references_->getInitializer(); 828 829 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer); 830 831 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr) 832 return false; 833 834 Value *osr_initializer_base = osr_initializer_expr->getOperand(0); 835 836 if (!osr_initializer_base) 837 return false; 838 839 // Find the string's initializer (a ConstantArray) and get the string from it 840 841 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base); 842 843 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer()) 844 return false; 845 846 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer(); 847 848 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer); 849 850 if (!omvn_initializer_array->isString()) 851 return false; 852 853 std::string omvn_initializer_string = omvn_initializer_array->getAsString(); 854 855 if (log) 856 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str()); 857 858 // Construct a call to sel_registerName 859 860 if (!m_sel_registerName) 861 { 862 lldb::addr_t sel_registerName_addr; 863 864 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName"); 865 sel_registerName_addr = m_execution_unit.FindSymbol (g_sel_registerName_str); 866 if (sel_registerName_addr == LLDB_INVALID_ADDRESS) 867 return false; 868 869 if (log) 870 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr); 871 872 // Build the function type: struct objc_selector *sel_registerName(uint8_t*) 873 874 // The below code would be "more correct," but in actuality what's required is uint8_t* 875 //Type *sel_type = StructType::get(m_module->getContext()); 876 //Type *sel_ptr_type = PointerType::getUnqual(sel_type); 877 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext()); 878 879 Type *type_array[1]; 880 881 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext()); 882 883 ArrayRef<Type *> srN_arg_types(type_array, 1); 884 885 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false); 886 887 // Build the constant containing the pointer to the function 888 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type); 889 Constant *srN_addr_int = ConstantInt::get(m_intptr_ty, sel_registerName_addr, false); 890 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty); 891 } 892 893 Value *argument_array[1]; 894 895 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext())); 896 897 argument_array[0] = omvn_pointer; 898 899 ArrayRef<Value *> srN_arguments(argument_array, 1); 900 901 CallInst *srN_call = CallInst::Create(m_sel_registerName, 902 srN_arguments, 903 "sel_registerName", 904 selector_load); 905 906 // Replace the load with the call in all users 907 908 selector_load->replaceAllUsesWith(srN_call); 909 910 selector_load->eraseFromParent(); 911 912 return true; 913} 914 915bool 916IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block) 917{ 918 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 919 920 BasicBlock::iterator ii; 921 922 typedef SmallVector <Instruction*, 2> InstrList; 923 typedef InstrList::iterator InstrIterator; 924 925 InstrList selector_loads; 926 927 for (ii = basic_block.begin(); 928 ii != basic_block.end(); 929 ++ii) 930 { 931 Instruction &inst = *ii; 932 933 if (LoadInst *load = dyn_cast<LoadInst>(&inst)) 934 if (IsObjCSelectorRef(load->getPointerOperand())) 935 selector_loads.push_back(&inst); 936 } 937 938 InstrIterator iter; 939 940 for (iter = selector_loads.begin(); 941 iter != selector_loads.end(); 942 ++iter) 943 { 944 if (!RewriteObjCSelector(*iter)) 945 { 946 if (m_error_stream) 947 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n"); 948 949 if (log) 950 log->PutCString("Couldn't rewrite a reference to an Objective-C selector"); 951 952 return false; 953 } 954 } 955 956 return true; 957} 958 959// This function does not report errors; its callers are responsible. 960bool 961IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc) 962{ 963 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 964 965 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc); 966 967 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr"); 968 969 if (!alloc_md || !alloc_md->getNumOperands()) 970 return false; 971 972 ConstantInt *constant_int = mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0)); 973 974 if (!constant_int) 975 return false; 976 977 // We attempt to register this as a new persistent variable with the DeclMap. 978 979 uintptr_t ptr = constant_int->getZExtValue(); 980 981 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr); 982 983 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(), 984 lldb_private::ClangASTContext::GetASTContext(&decl->getASTContext())); 985 986 StringRef decl_name (decl->getName()); 987 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size()); 988 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false)) 989 return false; 990 991 GlobalVariable *persistent_global = new GlobalVariable((*m_module), 992 alloc->getType(), 993 false, /* not constant */ 994 GlobalValue::ExternalLinkage, 995 NULL, /* no initializer */ 996 alloc->getName().str().c_str()); 997 998 // What we're going to do here is make believe this was a regular old external 999 // variable. That means we need to make the metadata valid. 1000 1001 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs"); 1002 1003 llvm::Metadata *values[2]; 1004 values[0] = ConstantAsMetadata::get(persistent_global); 1005 values[1] = ConstantAsMetadata::get(constant_int); 1006 1007 ArrayRef<llvm::Metadata *> value_ref(values, 2); 1008 1009 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref); 1010 named_metadata->addOperand(persistent_global_md); 1011 1012 // Now, since the variable is a pointer variable, we will drop in a load of that 1013 // pointer variable. 1014 1015 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc); 1016 1017 if (log) 1018 log->Printf("Replacing \"%s\" with \"%s\"", 1019 PrintValue(alloc).c_str(), 1020 PrintValue(persistent_load).c_str()); 1021 1022 alloc->replaceAllUsesWith(persistent_load); 1023 alloc->eraseFromParent(); 1024 1025 return true; 1026} 1027 1028bool 1029IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block) 1030{ 1031 if (!m_resolve_vars) 1032 return true; 1033 1034 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1035 1036 BasicBlock::iterator ii; 1037 1038 typedef SmallVector <Instruction*, 2> InstrList; 1039 typedef InstrList::iterator InstrIterator; 1040 1041 InstrList pvar_allocs; 1042 1043 for (ii = basic_block.begin(); 1044 ii != basic_block.end(); 1045 ++ii) 1046 { 1047 Instruction &inst = *ii; 1048 1049 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) 1050 { 1051 llvm::StringRef alloc_name = alloc->getName(); 1052 1053 if (alloc_name.startswith("$") && 1054 !alloc_name.startswith("$__lldb")) 1055 { 1056 if (alloc_name.find_first_of("0123456789") == 1) 1057 { 1058 if (log) 1059 log->Printf("Rejecting a numeric persistent variable."); 1060 1061 if (m_error_stream) 1062 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n"); 1063 1064 return false; 1065 } 1066 1067 pvar_allocs.push_back(alloc); 1068 } 1069 } 1070 } 1071 1072 InstrIterator iter; 1073 1074 for (iter = pvar_allocs.begin(); 1075 iter != pvar_allocs.end(); 1076 ++iter) 1077 { 1078 if (!RewritePersistentAlloc(*iter)) 1079 { 1080 if (m_error_stream) 1081 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n"); 1082 1083 if (log) 1084 log->PutCString("Couldn't rewrite the creation of a persistent variable"); 1085 1086 return false; 1087 } 1088 } 1089 1090 return true; 1091} 1092 1093bool 1094IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer) 1095{ 1096 if (!initializer) 1097 return true; 1098 1099 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1100 1101 if (log && log->GetVerbose()) 1102 log->Printf(" MaterializeInitializer(%p, %s)", (void *)data, PrintValue(initializer).c_str()); 1103 1104 Type *initializer_type = initializer->getType(); 1105 1106 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer)) 1107 { 1108 size_t constant_size = m_target_data->getTypeStoreSize(initializer_type); 1109 lldb_private::Scalar scalar = int_initializer->getValue().zextOrTrunc(llvm::NextPowerOf2(constant_size) * 8); 1110 1111 lldb_private::Error get_data_error; 1112 if (!scalar.GetAsMemoryData(data, constant_size, lldb_private::endian::InlHostByteOrder(), get_data_error)) 1113 return false; 1114 1115 return true; 1116 } 1117 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer)) 1118 { 1119 if (array_initializer->isString()) 1120 { 1121 std::string array_initializer_string = array_initializer->getAsString(); 1122 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type)); 1123 } 1124 else 1125 { 1126 ArrayType *array_initializer_type = array_initializer->getType(); 1127 Type *array_element_type = array_initializer_type->getElementType(); 1128 1129 size_t element_size = m_target_data->getTypeAllocSize(array_element_type); 1130 1131 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i) 1132 { 1133 Value *operand_value = array_initializer->getOperand(i); 1134 Constant *operand_constant = dyn_cast<Constant>(operand_value); 1135 1136 if (!operand_constant) 1137 return false; 1138 1139 if (!MaterializeInitializer(data + (i * element_size), operand_constant)) 1140 return false; 1141 } 1142 } 1143 return true; 1144 } 1145 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer)) 1146 { 1147 StructType *struct_initializer_type = struct_initializer->getType(); 1148 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type); 1149 1150 for (unsigned i = 0; 1151 i < struct_initializer->getNumOperands(); 1152 ++i) 1153 { 1154 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i))) 1155 return false; 1156 } 1157 return true; 1158 } 1159 else if (isa<ConstantAggregateZero>(initializer)) 1160 { 1161 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type)); 1162 return true; 1163 } 1164 return false; 1165} 1166 1167// This function does not report errors; its callers are responsible. 1168bool 1169IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr) 1170{ 1171 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1172 1173 if (log) 1174 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str()); 1175 1176 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) 1177 { 1178 switch (constant_expr->getOpcode()) 1179 { 1180 default: 1181 break; 1182 case Instruction::GetElementPtr: 1183 case Instruction::BitCast: 1184 Value *s = constant_expr->getOperand(0); 1185 if (!MaybeHandleVariable(s)) 1186 return false; 1187 } 1188 } 1189 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr)) 1190 { 1191 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage())) 1192 return true; 1193 1194 clang::NamedDecl *named_decl = DeclForGlobal(global_variable); 1195 1196 if (!named_decl) 1197 { 1198 if (IsObjCSelectorRef(llvm_value_ptr)) 1199 return true; 1200 1201 if (!global_variable->hasExternalLinkage()) 1202 return true; 1203 1204 if (log) 1205 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str()); 1206 1207 return false; 1208 } 1209 1210 std::string name (named_decl->getName().str()); 1211 1212 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl); 1213 if (value_decl == NULL) 1214 return false; 1215 1216 lldb_private::CompilerType compiler_type(&value_decl->getASTContext(), value_decl->getType()); 1217 1218 const Type *value_type = NULL; 1219 1220 if (name[0] == '$') 1221 { 1222 // The $__lldb_expr_result name indicates the return value has allocated as 1223 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, 1224 // accesses to this static variable need to be redirected to the result of dereferencing 1225 // a pointer that is passed in as one of the arguments. 1226 // 1227 // Consequently, when reporting the size of the type, we report a pointer type pointing 1228 // to the type of $__lldb_expr_result, not the type itself. 1229 // 1230 // We also do this for any user-declared persistent variables. 1231 compiler_type = compiler_type.GetPointerType(); 1232 value_type = PointerType::get(global_variable->getType(), 0); 1233 } 1234 else 1235 { 1236 value_type = global_variable->getType(); 1237 } 1238 1239 const uint64_t value_size = compiler_type.GetByteSize(nullptr); 1240 lldb::offset_t value_alignment = (compiler_type.GetTypeBitAlign() + 7ull) / 8ull; 1241 1242 if (log) 1243 { 1244 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRIu64 "]", 1245 name.c_str(), lldb_private::ClangUtil::GetQualType(compiler_type).getAsString().c_str(), 1246 PrintType(value_type).c_str(), value_size, value_alignment); 1247 } 1248 1249 1250 if (named_decl && !m_decl_map->AddValueToStruct(named_decl, 1251 lldb_private::ConstString (name.c_str()), 1252 llvm_value_ptr, 1253 value_size, 1254 value_alignment)) 1255 { 1256 if (!global_variable->hasExternalLinkage()) 1257 return true; 1258 else 1259 return true; 1260 } 1261 } 1262 else if (dyn_cast<llvm::Function>(llvm_value_ptr)) 1263 { 1264 if (log) 1265 log->Printf("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. 1274bool 1275IRForTarget::HandleSymbol (Value *symbol) 1276{ 1277 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1278 1279 lldb_private::ConstString name(symbol->getName().str().c_str()); 1280 1281 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny); 1282 1283 if (symbol_addr == LLDB_INVALID_ADDRESS) 1284 { 1285 if (log) 1286 log->Printf ("Symbol \"%s\" had no address", name.GetCString()); 1287 1288 return false; 1289 } 1290 1291 if (log) 1292 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr); 1293 1294 Type *symbol_type = symbol->getType(); 1295 1296 Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false); 1297 1298 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type); 1299 1300 if (log) 1301 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str()); 1302 1303 symbol->replaceAllUsesWith(symbol_addr_ptr); 1304 1305 return true; 1306} 1307 1308bool 1309IRForTarget::MaybeHandleCallArguments (CallInst *Old) 1310{ 1311 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1312 1313 if (log) 1314 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str()); 1315 1316 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands(); 1317 op_index < num_ops; 1318 ++op_index) 1319 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store 1320 { 1321 if (m_error_stream) 1322 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n"); 1323 1324 return false; 1325 } 1326 1327 return true; 1328} 1329 1330bool 1331IRForTarget::HandleObjCClass(Value *classlist_reference) 1332{ 1333 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1334 1335 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference); 1336 1337 if (!global_variable) 1338 return false; 1339 1340 Constant *initializer = global_variable->getInitializer(); 1341 1342 if (!initializer) 1343 return false; 1344 1345 if (!initializer->hasName()) 1346 return false; 1347 1348 StringRef name(initializer->getName()); 1349 lldb_private::ConstString name_cstr(name.str().c_str()); 1350 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass); 1351 1352 if (log) 1353 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr); 1354 1355 if (class_ptr == LLDB_INVALID_ADDRESS) 1356 return false; 1357 1358 if (global_variable->use_empty()) 1359 return false; 1360 1361 SmallVector<LoadInst *, 2> load_instructions; 1362 1363 for (llvm::User *u : global_variable->users()) 1364 { 1365 if (LoadInst *load_instruction = dyn_cast<LoadInst>(u)) 1366 load_instructions.push_back(load_instruction); 1367 } 1368 1369 if (load_instructions.empty()) 1370 return false; 1371 1372 Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr); 1373 1374 for (LoadInst *load_instruction : load_instructions) 1375 { 1376 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType()); 1377 1378 load_instruction->replaceAllUsesWith(class_bitcast); 1379 1380 load_instruction->eraseFromParent(); 1381 } 1382 1383 return true; 1384} 1385 1386bool 1387IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block) 1388{ 1389 BasicBlock::iterator ii; 1390 1391 std::vector<CallInst *> calls_to_remove; 1392 1393 for (ii = basic_block.begin(); 1394 ii != basic_block.end(); 1395 ++ii) 1396 { 1397 Instruction &inst = *ii; 1398 1399 CallInst *call = dyn_cast<CallInst>(&inst); 1400 1401 // MaybeHandleCallArguments handles error reporting; we are silent here 1402 if (!call) 1403 continue; 1404 1405 bool remove = false; 1406 1407 llvm::Function *func = call->getCalledFunction(); 1408 1409 if (func && func->getName() == "__cxa_atexit") 1410 remove = true; 1411 1412 llvm::Value *val = call->getCalledValue(); 1413 1414 if (val && val->getName() == "__cxa_atexit") 1415 remove = true; 1416 1417 if (remove) 1418 calls_to_remove.push_back(call); 1419 } 1420 1421 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end(); 1422 ci != ce; 1423 ++ci) 1424 { 1425 (*ci)->eraseFromParent(); 1426 } 1427 1428 return true; 1429} 1430 1431bool 1432IRForTarget::ResolveCalls(BasicBlock &basic_block) 1433{ 1434 ///////////////////////////////////////////////////////////////////////// 1435 // Prepare the current basic block for execution in the remote process 1436 // 1437 1438 BasicBlock::iterator ii; 1439 1440 for (ii = basic_block.begin(); 1441 ii != basic_block.end(); 1442 ++ii) 1443 { 1444 Instruction &inst = *ii; 1445 1446 CallInst *call = dyn_cast<CallInst>(&inst); 1447 1448 // MaybeHandleCallArguments handles error reporting; we are silent here 1449 if (call && !MaybeHandleCallArguments(call)) 1450 return false; 1451 } 1452 1453 return true; 1454} 1455 1456bool 1457IRForTarget::ResolveExternals (Function &llvm_function) 1458{ 1459 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1460 1461 for (GlobalVariable &global_var : m_module->globals()) 1462 { 1463 std::string global_name = global_var.getName().str(); 1464 1465 if (log) 1466 log->Printf("Examining %s, DeclForGlobalValue returns %p", 1467 global_name.c_str(), 1468 static_cast<void*>(DeclForGlobal(&global_var))); 1469 1470 if (global_name.find("OBJC_IVAR") == 0) 1471 { 1472 if (!HandleSymbol(&global_var)) 1473 { 1474 if (m_error_stream) 1475 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", global_name.c_str()); 1476 1477 return false; 1478 } 1479 } 1480 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos) 1481 { 1482 if (!HandleObjCClass(&global_var)) 1483 { 1484 if (m_error_stream) 1485 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n"); 1486 1487 return false; 1488 } 1489 } 1490 else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos) 1491 { 1492 if (!HandleObjCClass(&global_var)) 1493 { 1494 if (m_error_stream) 1495 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n"); 1496 1497 return false; 1498 } 1499 } 1500 else if (DeclForGlobal(&global_var)) 1501 { 1502 if (!MaybeHandleVariable (&global_var)) 1503 { 1504 if (m_error_stream) 1505 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", global_name.c_str()); 1506 1507 return false; 1508 } 1509 } 1510 } 1511 1512 return true; 1513} 1514 1515static bool isGuardVariableRef(Value *V) 1516{ 1517 Constant *Old = NULL; 1518 1519 if (!(Old = dyn_cast<Constant>(V))) 1520 return false; 1521 1522 ConstantExpr *CE = NULL; 1523 1524 if ((CE = dyn_cast<ConstantExpr>(V))) 1525 { 1526 if (CE->getOpcode() != Instruction::BitCast) 1527 return false; 1528 1529 Old = CE->getOperand(0); 1530 } 1531 1532 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old); 1533 1534 if (!GV || !GV->hasName() || 1535 (!GV->getName().startswith("_ZGV") && // Itanium ABI guard variable 1536 !GV->getName().endswith("@4IA"))) // Microsoft ABI guard variable 1537 { 1538 return false; 1539 } 1540 1541 return true; 1542} 1543 1544void 1545IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load) 1546{ 1547 Constant *zero(Constant::getNullValue(guard_load->getType())); 1548 guard_load->replaceAllUsesWith(zero); 1549 guard_load->eraseFromParent(); 1550} 1551 1552static void ExciseGuardStore(Instruction* guard_store) 1553{ 1554 guard_store->eraseFromParent(); 1555} 1556 1557bool 1558IRForTarget::RemoveGuards(BasicBlock &basic_block) 1559{ 1560 /////////////////////////////////////////////////////// 1561 // Eliminate any reference to guard variables found. 1562 // 1563 1564 BasicBlock::iterator ii; 1565 1566 typedef SmallVector <Instruction*, 2> InstrList; 1567 typedef InstrList::iterator InstrIterator; 1568 1569 InstrList guard_loads; 1570 InstrList guard_stores; 1571 1572 for (ii = basic_block.begin(); 1573 ii != basic_block.end(); 1574 ++ii) 1575 { 1576 Instruction &inst = *ii; 1577 1578 if (LoadInst *load = dyn_cast<LoadInst>(&inst)) 1579 if (isGuardVariableRef(load->getPointerOperand())) 1580 guard_loads.push_back(&inst); 1581 1582 if (StoreInst *store = dyn_cast<StoreInst>(&inst)) 1583 if (isGuardVariableRef(store->getPointerOperand())) 1584 guard_stores.push_back(&inst); 1585 } 1586 1587 InstrIterator iter; 1588 1589 for (iter = guard_loads.begin(); 1590 iter != guard_loads.end(); 1591 ++iter) 1592 TurnGuardLoadIntoZero(*iter); 1593 1594 for (iter = guard_stores.begin(); 1595 iter != guard_stores.end(); 1596 ++iter) 1597 ExciseGuardStore(*iter); 1598 1599 return true; 1600} 1601 1602// This function does not report errors; its callers are responsible. 1603bool 1604IRForTarget::UnfoldConstant(Constant *old_constant, 1605 FunctionValueCache &value_maker, 1606 FunctionValueCache &entry_instruction_finder) 1607{ 1608 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1609 1610 SmallVector<User*, 16> users; 1611 1612 // We do this because the use list might change, invalidating our iterator. 1613 // Much better to keep a work list ourselves. 1614 for (llvm::User *u : old_constant->users()) 1615 users.push_back(u); 1616 1617 for (size_t i = 0; 1618 i < users.size(); 1619 ++i) 1620 { 1621 User *user = users[i]; 1622 1623 if (Constant *constant = dyn_cast<Constant>(user)) 1624 { 1625 // synthesize a new non-constant equivalent of the constant 1626 1627 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) 1628 { 1629 switch (constant_expr->getOpcode()) 1630 { 1631 default: 1632 if (log) 1633 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str()); 1634 return false; 1635 case Instruction::BitCast: 1636 { 1637 FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* { 1638 // UnaryExpr 1639 // OperandList[0] is value 1640 1641 if (constant_expr->getOperand(0) != old_constant) 1642 return constant_expr; 1643 1644 return new BitCastInst(value_maker.GetValue(function), 1645 constant_expr->getType(), 1646 "", 1647 llvm::cast<Instruction>(entry_instruction_finder.GetValue(function))); 1648 }); 1649 1650 if (!UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder)) 1651 return false; 1652 } 1653 break; 1654 case Instruction::GetElementPtr: 1655 { 1656 // GetElementPtrConstantExpr 1657 // OperandList[0] is base 1658 // OperandList[1]... are indices 1659 1660 FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* { 1661 Value *ptr = constant_expr->getOperand(0); 1662 1663 if (ptr == old_constant) 1664 ptr = value_maker.GetValue(function); 1665 1666 std::vector<Value*> index_vector; 1667 1668 unsigned operand_index; 1669 unsigned num_operands = constant_expr->getNumOperands(); 1670 1671 for (operand_index = 1; 1672 operand_index < num_operands; 1673 ++operand_index) 1674 { 1675 Value *operand = constant_expr->getOperand(operand_index); 1676 1677 if (operand == old_constant) 1678 operand = value_maker.GetValue(function); 1679 1680 index_vector.push_back(operand); 1681 } 1682 1683 ArrayRef <Value*> indices(index_vector); 1684 1685 return GetElementPtrInst::Create(nullptr, ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function))); 1686 }); 1687 1688 if (!UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder)) 1689 return false; 1690 } 1691 break; 1692 } 1693 } 1694 else 1695 { 1696 if (log) 1697 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str()); 1698 return false; 1699 } 1700 } 1701 else 1702 { 1703 if (Instruction *inst = llvm::dyn_cast<Instruction>(user)) 1704 { 1705 inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent())); 1706 } 1707 else 1708 { 1709 if (log) 1710 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str()); 1711 return false; 1712 } 1713 } 1714 } 1715 1716 if (!isa<GlobalValue>(old_constant)) 1717 { 1718 old_constant->destroyConstant(); 1719 } 1720 1721 return true; 1722} 1723 1724bool 1725IRForTarget::ReplaceVariables (Function &llvm_function) 1726{ 1727 if (!m_resolve_vars) 1728 return true; 1729 1730 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1731 1732 m_decl_map->DoStructLayout(); 1733 1734 if (log) 1735 log->Printf("Element arrangement:"); 1736 1737 uint32_t num_elements; 1738 uint32_t element_index; 1739 1740 size_t size; 1741 lldb::offset_t alignment; 1742 1743 if (!m_decl_map->GetStructInfo (num_elements, size, alignment)) 1744 return false; 1745 1746 Function::arg_iterator iter(llvm_function.getArgumentList().begin()); 1747 1748 if (iter == llvm_function.getArgumentList().end()) 1749 { 1750 if (m_error_stream) 1751 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)"); 1752 1753 return false; 1754 } 1755 1756 Argument *argument = &*iter; 1757 1758 if (argument->getName().equals("this")) 1759 { 1760 ++iter; 1761 1762 if (iter == llvm_function.getArgumentList().end()) 1763 { 1764 if (m_error_stream) 1765 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)"); 1766 1767 return false; 1768 } 1769 1770 argument = &*iter; 1771 } 1772 else if (argument->getName().equals("self")) 1773 { 1774 ++iter; 1775 1776 if (iter == llvm_function.getArgumentList().end()) 1777 { 1778 if (m_error_stream) 1779 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)"); 1780 1781 return false; 1782 } 1783 1784 if (!iter->getName().equals("_cmd")) 1785 { 1786 if (m_error_stream) 1787 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str()); 1788 1789 return false; 1790 } 1791 1792 ++iter; 1793 1794 if (iter == llvm_function.getArgumentList().end()) 1795 { 1796 if (m_error_stream) 1797 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)"); 1798 1799 return false; 1800 } 1801 1802 argument = &*iter; 1803 } 1804 1805 if (!argument->getName().equals("$__lldb_arg")) 1806 { 1807 if (m_error_stream) 1808 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str()); 1809 1810 return false; 1811 } 1812 1813 if (log) 1814 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str()); 1815 1816 BasicBlock &entry_block(llvm_function.getEntryBlock()); 1817 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg()); 1818 1819 if (!FirstEntryInstruction) 1820 { 1821 if (m_error_stream) 1822 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting"); 1823 1824 return false; 1825 } 1826 1827 LLVMContext &context(m_module->getContext()); 1828 IntegerType *offset_type(Type::getInt32Ty(context)); 1829 1830 if (!offset_type) 1831 { 1832 if (m_error_stream) 1833 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type"); 1834 1835 return false; 1836 } 1837 1838 for (element_index = 0; element_index < num_elements; ++element_index) 1839 { 1840 const clang::NamedDecl *decl = NULL; 1841 Value *value = NULL; 1842 lldb::offset_t offset; 1843 lldb_private::ConstString name; 1844 1845 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index)) 1846 { 1847 if (m_error_stream) 1848 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete"); 1849 1850 return false; 1851 } 1852 1853 if (log) 1854 log->Printf(" \"%s\" (\"%s\") placed at %" PRIu64, 1855 name.GetCString(), 1856 decl->getNameAsString().c_str(), 1857 offset); 1858 1859 if (value) 1860 { 1861 if (log) 1862 log->Printf(" Replacing [%s]", PrintValue(value).c_str()); 1863 1864 FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * { 1865 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result 1866 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure 1867 // entry in order to produce the static variable that the AST thinks it is accessing. 1868 1869 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)); 1870 1871 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true)); 1872 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(nullptr, 1873 argument, 1874 offset_int, 1875 "", 1876 entry_instruction); 1877 1878 if (name == m_result_name && !m_result_is_pointer) 1879 { 1880 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, 1881 value->getType()->getPointerTo(), 1882 "", 1883 entry_instruction); 1884 1885 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction); 1886 1887 return load; 1888 } 1889 else 1890 { 1891 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction); 1892 1893 return bit_cast; 1894 } 1895 }); 1896 1897 if (Constant *constant = dyn_cast<Constant>(value)) 1898 { 1899 UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder); 1900 } 1901 else if (Instruction *instruction = dyn_cast<Instruction>(value)) 1902 { 1903 value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent())); 1904 } 1905 else 1906 { 1907 if (log) 1908 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str()); 1909 return false; 1910 } 1911 1912 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value)) 1913 var->eraseFromParent(); 1914 } 1915 } 1916 1917 if (log) 1918 log->Printf("Total structure [align %" PRId64 ", size %" PRIu64 "]", (int64_t)alignment, (uint64_t)size); 1919 1920 return true; 1921} 1922 1923llvm::Constant * 1924IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset) 1925{ 1926 llvm::Constant *offset_int = ConstantInt::get(m_intptr_ty, offset); 1927 1928 llvm::Constant *offset_array[1]; 1929 1930 offset_array[0] = offset_int; 1931 1932 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1); 1933 llvm::Type *char_type = llvm::Type::getInt8Ty(m_module->getContext()); 1934 llvm::Type *char_pointer_type = char_type->getPointerTo(); 1935 1936 llvm::Constant *reloc_placeholder_bitcast = ConstantExpr::getBitCast(m_reloc_placeholder, char_pointer_type); 1937 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(char_type, reloc_placeholder_bitcast, offsets); 1938 llvm::Constant *reloc_bitcast = ConstantExpr::getBitCast(reloc_getelementptr, type); 1939 1940 return reloc_bitcast; 1941} 1942 1943bool 1944IRForTarget::runOnModule (Module &llvm_module) 1945{ 1946 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS)); 1947 1948 m_module = &llvm_module; 1949 m_target_data.reset(new DataLayout(m_module)); 1950 m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(), m_target_data->getPointerSizeInBits()); 1951 1952 if (log) 1953 { 1954 std::string s; 1955 raw_string_ostream oss(s); 1956 1957 m_module->print(oss, NULL); 1958 1959 oss.flush(); 1960 1961 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str()); 1962 } 1963 1964 Function *const main_function = m_func_name.IsEmpty() ? nullptr : m_module->getFunction(m_func_name.GetStringRef()); 1965 1966 if (!m_func_name.IsEmpty() && !main_function) 1967 { 1968 if (log) 1969 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.AsCString()); 1970 1971 if (m_error_stream) 1972 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", 1973 m_func_name.AsCString()); 1974 1975 return false; 1976 } 1977 1978 if (main_function) 1979 { 1980 if (!FixFunctionLinkage(*main_function)) 1981 { 1982 if (log) 1983 log->Printf("Couldn't fix the linkage for the function"); 1984 1985 return false; 1986 } 1987 } 1988 1989 llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext()); 1990 1991 m_reloc_placeholder = new llvm::GlobalVariable((*m_module), 1992 int8_ty, 1993 false /* IsConstant */, 1994 GlobalVariable::InternalLinkage, 1995 Constant::getNullValue(int8_ty), 1996 "reloc_placeholder", 1997 NULL /* InsertBefore */, 1998 GlobalVariable::NotThreadLocal /* ThreadLocal */, 1999 0 /* AddressSpace */); 2000 2001 //////////////////////////////////////////////////////////// 2002 // Replace $__lldb_expr_result with a persistent variable 2003 // 2004 2005 if (main_function) 2006 { 2007 if (!CreateResultVariable(*main_function)) 2008 { 2009 if (log) 2010 log->Printf("CreateResultVariable() failed"); 2011 2012 // CreateResultVariable() reports its own errors, so we don't do so here 2013 2014 return false; 2015 } 2016 } 2017 2018 if (log && log->GetVerbose()) 2019 { 2020 std::string s; 2021 raw_string_ostream oss(s); 2022 2023 m_module->print(oss, NULL); 2024 2025 oss.flush(); 2026 2027 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str()); 2028 } 2029 2030 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); 2031 fi != fe; 2032 ++fi) 2033 { 2034 llvm::Function *function = &*fi; 2035 2036 if (function->begin() == function->end()) 2037 continue; 2038 2039 Function::iterator bbi; 2040 2041 for (bbi = function->begin(); 2042 bbi != function->end(); 2043 ++bbi) 2044 { 2045 if (!RemoveGuards(*bbi)) 2046 { 2047 if (log) 2048 log->Printf("RemoveGuards() failed"); 2049 2050 // RemoveGuards() reports its own errors, so we don't do so here 2051 2052 return false; 2053 } 2054 2055 if (!RewritePersistentAllocs(*bbi)) 2056 { 2057 if (log) 2058 log->Printf("RewritePersistentAllocs() failed"); 2059 2060 // RewritePersistentAllocs() reports its own errors, so we don't do so here 2061 2062 return false; 2063 } 2064 2065 if (!RemoveCXAAtExit(*bbi)) 2066 { 2067 if (log) 2068 log->Printf("RemoveCXAAtExit() failed"); 2069 2070 // RemoveCXAAtExit() reports its own errors, so we don't do so here 2071 2072 return false; 2073 } 2074 } 2075 } 2076 2077 /////////////////////////////////////////////////////////////////////////////// 2078 // Fix all Objective-C constant strings to use NSStringWithCString:encoding: 2079 // 2080 2081 if (!RewriteObjCConstStrings()) 2082 { 2083 if (log) 2084 log->Printf("RewriteObjCConstStrings() failed"); 2085 2086 // RewriteObjCConstStrings() reports its own errors, so we don't do so here 2087 2088 return false; 2089 } 2090 2091 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); 2092 fi != fe; 2093 ++fi) 2094 { 2095 llvm::Function *function = &*fi; 2096 2097 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end(); 2098 bbi != bbe; 2099 ++bbi) 2100 { 2101 if (!RewriteObjCSelectors(*bbi)) 2102 { 2103 if (log) 2104 log->Printf("RewriteObjCSelectors() failed"); 2105 2106 // RewriteObjCSelectors() reports its own errors, so we don't do so here 2107 2108 return false; 2109 } 2110 } 2111 } 2112 2113 for (Module::iterator fi = m_module->begin(), fe = m_module->end(); 2114 fi != fe; 2115 ++fi) 2116 { 2117 llvm::Function *function = &*fi; 2118 2119 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end(); 2120 bbi != bbe; 2121 ++bbi) 2122 { 2123 if (!ResolveCalls(*bbi)) 2124 { 2125 if (log) 2126 log->Printf("ResolveCalls() failed"); 2127 2128 // ResolveCalls() reports its own errors, so we don't do so here 2129 2130 return false; 2131 } 2132 } 2133 } 2134 2135 //////////////////////////////////////////////////////////////////////// 2136 // Run function-level passes that only make sense on the main function 2137 // 2138 2139 if (main_function) 2140 { 2141 if (!ResolveExternals(*main_function)) 2142 { 2143 if (log) 2144 log->Printf("ResolveExternals() failed"); 2145 2146 // ResolveExternals() reports its own errors, so we don't do so here 2147 2148 return false; 2149 } 2150 2151 if (!ReplaceVariables(*main_function)) 2152 { 2153 if (log) 2154 log->Printf("ReplaceVariables() failed"); 2155 2156 // ReplaceVariables() reports its own errors, so we don't do so here 2157 2158 return false; 2159 } 2160 } 2161 2162 if (log && log->GetVerbose()) 2163 { 2164 std::string s; 2165 raw_string_ostream oss(s); 2166 2167 m_module->print(oss, NULL); 2168 2169 oss.flush(); 2170 2171 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str()); 2172 } 2173 2174 return true; 2175} 2176 2177void 2178IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type) 2179{ 2180} 2181 2182PassManagerType 2183IRForTarget::getPotentialPassManagerType() const 2184{ 2185 return PMT_ModulePassManager; 2186} 2187