1 //===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Expression/IRForTarget.h"
12 #include "llvm/Support/raw_ostream.h"
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/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Transforms/IPO.h"
21 #include "llvm/IR/ValueSymbolTable.h"
23 #include "clang/AST/ASTContext.h"
25 #include "lldb/Core/dwarf.h"
26 #include "lldb/Core/ConstString.h"
27 #include "lldb/Core/DataBufferHeap.h"
28 #include "lldb/Core/Log.h"
29 #include "lldb/Core/Scalar.h"
30 #include "lldb/Core/StreamString.h"
31 #include "lldb/Expression/ClangExpressionDeclMap.h"
32 #include "lldb/Expression/IRExecutionUnit.h"
33 #include "lldb/Expression/IRInterpreter.h"
34 #include "lldb/Host/Endian.h"
35 #include "lldb/Symbol/ClangASTContext.h"
36 #include "lldb/Symbol/ClangASTType.h"
44 IRForTarget::StaticDataAllocator::StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit) :
45 m_execution_unit(execution_unit),
46 m_stream_string(lldb_private::Stream::eBinary, execution_unit.GetAddressByteSize(), execution_unit.GetByteOrder()),
47 m_allocation(LLDB_INVALID_ADDRESS)
51 IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) :
57 IRForTarget::FunctionValueCache::~FunctionValueCache()
61 llvm::Value *IRForTarget::FunctionValueCache::GetValue(llvm::Function *function)
63 if (!m_values.count(function))
65 llvm::Value *ret = m_maker(function);
66 m_values[function] = ret;
69 return m_values[function];
72 lldb::addr_t IRForTarget::StaticDataAllocator::Allocate()
74 lldb_private::Error err;
76 if (m_allocation != LLDB_INVALID_ADDRESS)
78 m_execution_unit.FreeNow(m_allocation);
79 m_allocation = LLDB_INVALID_ADDRESS;
82 m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
87 static llvm::Value *FindEntryInstruction (llvm::Function *function)
89 if (function->empty())
92 return function->getEntryBlock().getFirstNonPHIOrDbg();
95 IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
97 lldb_private::IRExecutionUnit &execution_unit,
98 lldb_private::Stream *error_stream,
99 const char *func_name) :
101 m_resolve_vars(resolve_vars),
102 m_func_name(func_name),
104 m_decl_map(decl_map),
105 m_data_allocator(execution_unit),
106 m_CFStringCreateWithBytes(NULL),
107 m_sel_registerName(NULL),
108 m_error_stream(error_stream),
109 m_result_store(NULL),
110 m_result_is_pointer(false),
111 m_reloc_placeholder(NULL),
112 m_entry_instruction_finder (FindEntryInstruction)
116 /* Handy utility functions used at several places in the code */
119 PrintValue(const Value *value, bool truncate = false)
124 raw_string_ostream rso(s);
128 s.resize(s.length() - 1);
134 PrintType(const llvm::Type *type, bool truncate = false)
137 raw_string_ostream rso(s);
141 s.resize(s.length() - 1);
145 IRForTarget::~IRForTarget()
150 IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
152 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
154 std::string name = llvm_function.getName().str();
160 IRForTarget::GetFunctionAddress (llvm::Function *fun,
162 lldb_private::ConstString &name,
163 Constant **&value_ptr)
165 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
167 fun_addr = LLDB_INVALID_ADDRESS;
171 if (fun->isIntrinsic())
173 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
175 switch (intrinsic_id)
179 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
182 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
185 case Intrinsic::memcpy:
187 static lldb_private::ConstString g_memcpy_str ("memcpy");
191 case Intrinsic::memset:
193 static lldb_private::ConstString g_memset_str ("memset");
200 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
204 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
207 // Find the address of the function.
209 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
213 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
215 lldb_private::ConstString altnernate_name;
216 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
219 // Check for an alternate mangling for "std::basic_string<char>"
220 // that is part of the itanium C++ name mangling scheme
221 const char *name_cstr = name.GetCString();
222 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
224 std::string alternate_mangling("_ZNKSs");
225 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
226 altnernate_name.SetCString(alternate_mangling.c_str());
227 found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
233 lldb_private::Mangled mangled_name(name);
234 lldb_private::Mangled alt_mangled_name(altnernate_name);
237 if (alt_mangled_name)
238 log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
239 mangled_name.GetName().GetCString(),
240 alt_mangled_name.GetName().GetCString());
242 log->Printf("Function \"%s\" had no address",
243 mangled_name.GetName().GetCString());
248 if (alt_mangled_name)
249 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
250 mangled_name.GetName().GetCString(),
251 alt_mangled_name.GetName().GetCString());
252 else if (mangled_name.GetMangledName())
253 m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
254 mangled_name.GetName().GetCString(),
255 mangled_name.GetMangledName().GetCString());
257 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
258 mangled_name.GetName().GetCString());
266 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
269 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
272 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
279 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
285 IRForTarget::BuildFunctionPointer (llvm::Type *type,
288 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
289 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
290 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
291 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
292 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
296 IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
297 llvm::Value *function_ptr,
300 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
306 if (Instruction *user_inst = dyn_cast<Instruction>(user))
308 MDString* md_name = MDString::get(context, StringRef(name));
310 MDNode *metadata = MDNode::get(context, md_name);
312 user_inst->setMetadata("lldb.call.realName", metadata);
316 RegisterFunctionMetadata (context, user, name);
322 IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module)
324 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
326 for (llvm::Module::iterator fi = llvm_module.begin();
327 fi != llvm_module.end();
332 bool is_decl = fun->isDeclaration();
335 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
340 if (fun->hasNUses(0))
343 uint64_t addr = LLDB_INVALID_ADDRESS;
344 lldb_private::ConstString name;
345 Constant **value_ptr = NULL;
347 if (!GetFunctionAddress(fun,
351 return false; // GetFunctionAddress reports its own errors
353 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
355 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
360 fun->replaceAllUsesWith(value);
368 IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
370 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
375 unsigned num_nodes = named_metadata->getNumOperands();
379 node_index < num_nodes;
382 MDNode *metadata_node = named_metadata->getOperand(node_index);
387 if (metadata_node->getNumOperands() != 2)
390 if (metadata_node->getOperand(0) != global_val)
393 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
398 uintptr_t ptr = constant_int->getZExtValue();
400 return reinterpret_cast<clang::NamedDecl *>(ptr);
407 IRForTarget::DeclForGlobal (GlobalValue *global_val)
409 return DeclForGlobal(global_val, m_module);
413 IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
415 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
420 // Find the result variable. If it doesn't exist, we can give up right here.
422 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
424 std::string result_name_str;
425 const char *result_name = NULL;
427 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
431 result_name_str = vi->first().str();
432 const char *value_name = result_name_str.c_str();
434 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
435 strncmp(value_name, "_ZGV", 4))
437 result_name = value_name;
438 m_result_is_pointer = true;
442 if (strstr(value_name, "$__lldb_expr_result") &&
443 strncmp(value_name, "_ZGV", 4))
445 result_name = value_name;
446 m_result_is_pointer = false;
454 log->PutCString("Couldn't find result variable");
460 log->Printf("Result name: \"%s\"", result_name);
462 Value *result_value = m_module->getNamedValue(result_name);
467 log->PutCString("Result variable had no data");
470 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
476 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
478 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
483 log->PutCString("Result variable isn't a GlobalVariable");
486 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
491 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
495 log->PutCString("Result variable doesn't have a corresponding Decl");
498 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name);
505 std::string decl_desc_str;
506 raw_string_ostream decl_desc_stream(decl_desc_str);
507 result_decl->print(decl_desc_stream);
508 decl_desc_stream.flush();
510 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
513 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
517 log->PutCString("Result variable Decl isn't a VarDecl");
520 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name);
525 // Get the next available result name from m_decl_map and create the persistent
528 // If the result is an Lvalue, it is emitted as a pointer; see
529 // ASTResultSynthesizer::SynthesizeBodyResult.
530 if (m_result_is_pointer)
532 clang::QualType pointer_qual_type = result_var->getType();
533 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
535 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
536 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
538 if (pointer_pointertype)
540 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
542 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
543 &result_decl->getASTContext());
545 else if (pointer_objcobjpointertype)
547 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
549 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
550 &result_decl->getASTContext());
555 log->PutCString("Expected result to have pointer type, but it did not");
558 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
565 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
566 &result_decl->getASTContext());
569 if (m_result_type.GetBitSize() == 0)
571 lldb_private::StreamString type_desc_stream;
572 m_result_type.DumpTypeDescription(&type_desc_stream);
575 log->Printf("Result type has size 0");
578 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
579 type_desc_stream.GetData());
585 lldb_private::StreamString type_desc_stream;
586 m_result_type.DumpTypeDescription(&type_desc_stream);
588 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
591 m_result_name = lldb_private::ConstString("$RESULT_NAME");
594 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
595 m_result_name.GetCString(),
596 m_result_type.GetByteSize());
598 // Construct a new result global and set up its metadata
600 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
601 result_global->getType()->getElementType(),
602 false, /* not constant */
603 GlobalValue::ExternalLinkage,
604 NULL, /* no initializer */
605 m_result_name.GetCString ());
607 // It's too late in compilation to create a new VarDecl for this, but we don't
608 // need to. We point the metadata at the old VarDecl. This creates an odd
609 // anomaly: a variable with a Value whose name is something like $0 and a
610 // Decl whose name is $__lldb_expr_result. This condition is handled in
611 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
614 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
615 reinterpret_cast<uint64_t>(result_decl),
618 llvm::Value* values[2];
619 values[0] = new_result_global;
620 values[1] = new_constant_int;
622 ArrayRef<Value*> value_ref(values, 2);
624 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
625 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
626 named_metadata->addOperand(persistent_global_md);
629 log->Printf("Replacing \"%s\" with \"%s\"",
630 PrintValue(result_global).c_str(),
631 PrintValue(new_result_global).c_str());
633 if (result_global->hasNUses(0))
635 // We need to synthesize a store for this variable, because otherwise
636 // there's nothing to put into its equivalent persistent variable.
638 BasicBlock &entry_block(llvm_function.getEntryBlock());
639 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
641 if (!first_entry_instruction)
644 if (!result_global->hasInitializer())
647 log->Printf("Couldn't find initializer for unused variable");
650 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
655 Constant *initializer = result_global->getInitializer();
657 StoreInst *synthesized_store = new StoreInst(initializer,
659 first_entry_instruction);
662 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
666 result_global->replaceAllUsesWith(new_result_global);
669 if (!m_decl_map->AddPersistentVariable(result_decl,
673 m_result_is_pointer))
676 result_global->eraseFromParent();
682 static void DebugUsers(Log *log, Value *value, uint8_t depth)
690 log->Printf(" <Begin %d users>", value->getNumUses());
692 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
697 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
698 DebugUsers(log, *ui, depth);
702 log->Printf(" <End uses>");
707 IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
708 llvm::GlobalVariable *cstr)
710 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
712 Type *ns_str_ty = ns_str->getType();
714 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
715 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
716 (m_module->getPointerSize()
717 == Module::Pointer64) ? 64 : 32);
718 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
719 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
721 if (!m_CFStringCreateWithBytes)
723 lldb::addr_t CFStringCreateWithBytes_addr;
725 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
727 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
730 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
733 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
739 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
741 // Build the function type:
743 // CFStringRef CFStringCreateWithBytes (
744 // CFAllocatorRef alloc,
745 // const UInt8 *bytes,
747 // CFStringEncoding encoding,
748 // Boolean isExternalRepresentation
751 // We make the following substitutions:
753 // CFStringRef -> i8*
754 // CFAllocatorRef -> i8*
756 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
757 // CFStringEncoding -> i32
760 Type *arg_type_array[5];
762 arg_type_array[0] = i8_ptr_ty;
763 arg_type_array[1] = i8_ptr_ty;
764 arg_type_array[2] = intptr_ty;
765 arg_type_array[3] = i32_ty;
766 arg_type_array[4] = i8_ty;
768 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
770 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
772 // Build the constant containing the pointer to the function
773 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
774 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
775 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
778 ConstantDataSequential *string_array = NULL;
781 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
783 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
784 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
785 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
786 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
787 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
789 Value *argument_array[5];
791 argument_array[0] = alloc_arg;
792 argument_array[1] = bytes_arg;
793 argument_array[2] = numBytes_arg;
794 argument_array[3] = encoding_arg;
795 argument_array[4] = isExternal_arg;
797 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
799 FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * {
800 return CallInst::Create(m_CFStringCreateWithBytes,
802 "CFStringCreateWithBytes",
803 llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)));
806 if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder))
809 log->PutCString("Couldn't replace the NSString with the result of the call");
812 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
817 ns_str->eraseFromParent();
823 IRForTarget::RewriteObjCConstStrings()
825 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
827 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
829 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
833 std::string value_name = vi->first().str();
834 const char *value_name_cstr = value_name.c_str();
836 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
838 Value *nsstring_value = vi->second;
840 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
842 if (!nsstring_global)
845 log->PutCString("NSString variable is not a GlobalVariable");
848 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
853 if (!nsstring_global->hasInitializer())
856 log->PutCString("NSString variable does not have an initializer");
859 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
864 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
866 if (!nsstring_struct)
869 log->PutCString("NSString variable's initializer is not a ConstantStruct");
872 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
877 // We expect the following structure:
886 if (nsstring_struct->getNumOperands() != 4)
889 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands());
892 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
897 Constant *nsstring_member = nsstring_struct->getOperand(2);
899 if (!nsstring_member)
902 log->PutCString("NSString initializer's str element was empty");
905 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
910 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
915 log->PutCString("NSString initializer's str element is not a ConstantExpr");
918 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
923 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
926 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
929 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
934 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
936 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
941 log->PutCString("NSString initializer's str element is not a GlobalVariable");
944 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
949 if (!cstr_global->hasInitializer())
952 log->PutCString("NSString initializer's str element does not have an initializer");
955 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
964 log->PutCString("NSString initializer's str element is not a ConstantArray");
967 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
972 if (!cstr_array->isCString())
975 log->PutCString("NSString initializer's str element is not a C string array");
978 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
984 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
989 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().str().c_str());
991 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
997 if (!RewriteObjCConstString(nsstring_global, cstr_global))
1000 log->PutCString("Error rewriting the constant string");
1002 // We don't print an error message here because RewriteObjCConstString has done so for us.
1009 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1013 std::string value_name = vi->first().str();
1014 const char *value_name_cstr = value_name.c_str();
1016 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
1018 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1023 log->PutCString("__CFConstantStringClassReference is not a global variable");
1026 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1031 gv->eraseFromParent();
1040 static bool IsObjCSelectorRef (Value *value)
1042 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
1044 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
1050 // This function does not report errors; its callers are responsible.
1052 IRForTarget::RewriteObjCSelector (Instruction* selector_load)
1054 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1056 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1061 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1063 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1064 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1066 // where %obj is the object pointer and %tmp is the selector.
1068 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1069 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
1071 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1073 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1075 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1078 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1080 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1082 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1085 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1087 if (!osr_initializer_base)
1090 // Find the string's initializer (a ConstantArray) and get the string from it
1092 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1094 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1097 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1099 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
1101 if (!omvn_initializer_array->isString())
1104 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1107 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
1109 // Construct a call to sel_registerName
1111 if (!m_sel_registerName)
1113 lldb::addr_t sel_registerName_addr;
1115 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
1116 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
1120 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
1122 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1124 // The below code would be "more correct," but in actuality what's required is uint8_t*
1125 //Type *sel_type = StructType::get(m_module->getContext());
1126 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
1127 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
1129 Type *type_array[1];
1131 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1133 ArrayRef<Type *> srN_arg_types(type_array, 1);
1135 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1137 // Build the constant containing the pointer to the function
1138 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1139 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1140 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
1141 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
1142 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1145 Value *argument_array[1];
1147 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
1149 argument_array[0] = omvn_pointer;
1151 ArrayRef<Value *> srN_arguments(argument_array, 1);
1153 CallInst *srN_call = CallInst::Create(m_sel_registerName,
1158 // Replace the load with the call in all users
1160 selector_load->replaceAllUsesWith(srN_call);
1162 selector_load->eraseFromParent();
1168 IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
1170 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1172 BasicBlock::iterator ii;
1174 typedef SmallVector <Instruction*, 2> InstrList;
1175 typedef InstrList::iterator InstrIterator;
1177 InstrList selector_loads;
1179 for (ii = basic_block.begin();
1180 ii != basic_block.end();
1183 Instruction &inst = *ii;
1185 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1186 if (IsObjCSelectorRef(load->getPointerOperand()))
1187 selector_loads.push_back(&inst);
1192 for (iter = selector_loads.begin();
1193 iter != selector_loads.end();
1196 if (!RewriteObjCSelector(*iter))
1199 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1202 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
1211 // This function does not report errors; its callers are responsible.
1213 IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
1215 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1217 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1219 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1221 if (!alloc_md || !alloc_md->getNumOperands())
1224 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1229 // We attempt to register this as a new persistent variable with the DeclMap.
1231 uintptr_t ptr = constant_int->getZExtValue();
1233 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
1235 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1236 &decl->getASTContext());
1238 StringRef decl_name (decl->getName());
1239 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
1240 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
1243 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
1245 false, /* not constant */
1246 GlobalValue::ExternalLinkage,
1247 NULL, /* no initializer */
1248 alloc->getName().str().c_str());
1250 // What we're going to do here is make believe this was a regular old external
1251 // variable. That means we need to make the metadata valid.
1253 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
1255 llvm::Value* values[2];
1256 values[0] = persistent_global;
1257 values[1] = constant_int;
1259 ArrayRef<llvm::Value*> value_ref(values, 2);
1261 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
1262 named_metadata->addOperand(persistent_global_md);
1264 // Now, since the variable is a pointer variable, we will drop in a load of that
1265 // pointer variable.
1267 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1270 log->Printf("Replacing \"%s\" with \"%s\"",
1271 PrintValue(alloc).c_str(),
1272 PrintValue(persistent_load).c_str());
1274 alloc->replaceAllUsesWith(persistent_load);
1275 alloc->eraseFromParent();
1281 IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
1283 if (!m_resolve_vars)
1286 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1288 BasicBlock::iterator ii;
1290 typedef SmallVector <Instruction*, 2> InstrList;
1291 typedef InstrList::iterator InstrIterator;
1293 InstrList pvar_allocs;
1295 for (ii = basic_block.begin();
1296 ii != basic_block.end();
1299 Instruction &inst = *ii;
1301 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
1303 llvm::StringRef alloc_name = alloc->getName();
1305 if (alloc_name.startswith("$") &&
1306 !alloc_name.startswith("$__lldb"))
1308 if (alloc_name.find_first_of("0123456789") == 1)
1311 log->Printf("Rejecting a numeric persistent variable.");
1314 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1319 pvar_allocs.push_back(alloc);
1326 for (iter = pvar_allocs.begin();
1327 iter != pvar_allocs.end();
1330 if (!RewritePersistentAlloc(*iter))
1333 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1336 log->PutCString("Couldn't rewrite the creation of a persistent variable");
1346 IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1351 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1353 if (log && log->GetVerbose())
1354 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1356 Type *initializer_type = initializer->getType();
1358 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1360 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1363 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
1365 if (array_initializer->isString())
1367 std::string array_initializer_string = array_initializer->getAsString();
1368 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1372 ArrayType *array_initializer_type = array_initializer->getType();
1373 Type *array_element_type = array_initializer_type->getElementType();
1375 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1377 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i)
1379 Value *operand_value = array_initializer->getOperand(i);
1380 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1382 if (!operand_constant)
1385 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
1391 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1393 StructType *struct_initializer_type = struct_initializer->getType();
1394 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1396 for (unsigned i = 0;
1397 i < struct_initializer->getNumOperands();
1400 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1405 else if (isa<ConstantAggregateZero>(initializer))
1407 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1414 IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1416 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1419 if (global_variable == m_reloc_placeholder)
1422 uint64_t offset = m_data_allocator.GetStream().GetSize();
1424 llvm::Type *variable_type = global_variable->getType();
1426 Constant *initializer = global_variable->getInitializer();
1428 llvm::Type *initializer_type = initializer->getType();
1430 size_t size = m_target_data->getTypeAllocSize(initializer_type);
1431 size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1433 const size_t mask = (align - 1);
1434 uint64_t aligned_offset = (offset + mask) & ~mask;
1435 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
1436 offset = aligned_offset;
1438 lldb_private::DataBufferHeap data(size, '\0');
1441 if (!MaterializeInitializer(data.GetBytes(), initializer))
1444 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
1446 Constant *new_pointer = BuildRelocation(variable_type, offset);
1448 global_variable->replaceAllUsesWith(new_pointer);
1450 global_variable->eraseFromParent();
1455 // This function does not report errors; its callers are responsible.
1457 IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
1459 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1462 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
1464 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
1466 switch (constant_expr->getOpcode())
1470 case Instruction::GetElementPtr:
1471 case Instruction::BitCast:
1472 Value *s = constant_expr->getOperand(0);
1473 if (!MaybeHandleVariable(s))
1477 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
1479 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1480 return MaterializeInternalVariable(global_variable);
1482 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
1486 if (IsObjCSelectorRef(llvm_value_ptr))
1489 if (!global_variable->hasExternalLinkage())
1493 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
1498 std::string name (named_decl->getName().str());
1500 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1501 if (value_decl == NULL)
1504 lldb_private::ClangASTType clang_type(&value_decl->getASTContext(), value_decl->getType());
1506 const Type *value_type = NULL;
1510 // The $__lldb_expr_result name indicates the the return value has allocated as
1511 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1512 // accesses to this static variable need to be redirected to the result of dereferencing
1513 // a pointer that is passed in as one of the arguments.
1515 // Consequently, when reporting the size of the type, we report a pointer type pointing
1516 // to the type of $__lldb_expr_result, not the type itself.
1518 // We also do this for any user-declared persistent variables.
1519 clang_type = clang_type.GetPointerType();
1520 value_type = PointerType::get(global_variable->getType(), 0);
1524 value_type = global_variable->getType();
1527 const uint64_t value_size = clang_type.GetByteSize();
1528 off_t value_alignment = (clang_type.GetTypeBitAlign() + 7ull) / 8ull;
1532 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
1534 clang_type.GetQualType().getAsString().c_str(),
1535 PrintType(value_type).c_str(),
1541 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
1542 lldb_private::ConstString (name.c_str()),
1547 if (!global_variable->hasExternalLinkage())
1549 else if (HandleSymbol (global_variable))
1555 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
1558 log->Printf("Function pointers aren't handled right now");
1566 // This function does not report errors; its callers are responsible.
1568 IRForTarget::HandleSymbol (Value *symbol)
1570 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1572 lldb_private::ConstString name(symbol->getName().str().c_str());
1574 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
1576 if (symbol_addr == LLDB_INVALID_ADDRESS)
1579 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1585 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
1587 Type *symbol_type = symbol->getType();
1588 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1589 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1591 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1593 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1596 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1598 symbol->replaceAllUsesWith(symbol_addr_ptr);
1604 IRForTarget::MaybeHandleCallArguments (CallInst *Old)
1606 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1609 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
1611 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
1614 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
1617 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1626 IRForTarget::HandleObjCClass(Value *classlist_reference)
1628 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1630 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1632 if (!global_variable)
1635 Constant *initializer = global_variable->getInitializer();
1640 if (!initializer->hasName())
1643 StringRef name(initializer->getName());
1644 lldb_private::ConstString name_cstr(name.str().c_str());
1645 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
1648 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1650 if (class_ptr == LLDB_INVALID_ADDRESS)
1653 if (global_variable->use_begin() == global_variable->use_end())
1656 SmallVector<LoadInst *, 2> load_instructions;
1658 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1662 if (LoadInst *load_instruction = dyn_cast<LoadInst>(*i))
1663 load_instructions.push_back(load_instruction);
1666 if (load_instructions.empty())
1669 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1670 (m_module->getPointerSize()
1671 == Module::Pointer64) ? 64 : 32);
1673 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
1675 for (LoadInst *load_instruction : load_instructions)
1677 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1679 load_instruction->replaceAllUsesWith(class_bitcast);
1681 load_instruction->eraseFromParent();
1688 IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1690 BasicBlock::iterator ii;
1692 std::vector<CallInst *> calls_to_remove;
1694 for (ii = basic_block.begin();
1695 ii != basic_block.end();
1698 Instruction &inst = *ii;
1700 CallInst *call = dyn_cast<CallInst>(&inst);
1702 // MaybeHandleCallArguments handles error reporting; we are silent here
1706 bool remove = false;
1708 llvm::Function *func = call->getCalledFunction();
1710 if (func && func->getName() == "__cxa_atexit")
1713 llvm::Value *val = call->getCalledValue();
1715 if (val && val->getName() == "__cxa_atexit")
1719 calls_to_remove.push_back(call);
1722 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1726 (*ci)->eraseFromParent();
1733 IRForTarget::ResolveCalls(BasicBlock &basic_block)
1735 /////////////////////////////////////////////////////////////////////////
1736 // Prepare the current basic block for execution in the remote process
1739 BasicBlock::iterator ii;
1741 for (ii = basic_block.begin();
1742 ii != basic_block.end();
1745 Instruction &inst = *ii;
1747 CallInst *call = dyn_cast<CallInst>(&inst);
1749 // MaybeHandleCallArguments handles error reporting; we are silent here
1750 if (call && !MaybeHandleCallArguments(call))
1758 IRForTarget::ResolveExternals (Function &llvm_function)
1760 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1762 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
1769 m_error_stream->Printf("Internal error [IRForTarget]: global variable is NULL");
1774 std::string global_name = (*global).getName().str();
1777 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1778 global_name.c_str(),
1779 DeclForGlobal(global));
1781 if (global_name.find("OBJC_IVAR") == 0)
1783 if (!HandleSymbol(global))
1786 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", global_name.c_str());
1791 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1793 if (!HandleObjCClass(global))
1796 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1801 else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos)
1803 if (!HandleObjCClass(global))
1806 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1811 else if (DeclForGlobal(global))
1813 if (!MaybeHandleVariable (global))
1816 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", global_name.c_str());
1827 IRForTarget::ReplaceStrings ()
1829 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1831 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1835 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1839 GlobalVariable *gv = gi;
1841 if (!gv->hasInitializer())
1844 Constant *gc = gv->getInitializer();
1848 if (gc->isNullValue())
1850 Type *gc_type = gc->getType();
1852 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1857 Type *gc_element_type = gc_array_type->getElementType();
1859 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1861 if (gc_integer_type->getBitWidth() != 8)
1868 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
1873 if (!gc_array->isCString())
1877 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
1879 str = gc_array->getAsString();
1882 offsets[gv] = m_data_allocator.GetStream().GetSize();
1884 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
1887 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
1889 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1893 GlobalVariable *gv = oi->first;
1894 size_t offset = oi->second;
1896 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1899 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1901 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1906 log->Printf("Found use %s", PrintValue(*ui).c_str());
1908 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1909 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1913 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1916 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1921 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1922 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1924 const_expr->replaceAllUsesWith(new_gep);
1926 else if (store_inst)
1928 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1930 store_inst->setOperand(0, bit_cast);
1935 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1941 gv->eraseFromParent();
1948 IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1950 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1952 typedef SmallVector <Value*, 2> ConstantList;
1953 typedef SmallVector <llvm::Instruction*, 2> UserList;
1954 typedef ConstantList::iterator ConstantIterator;
1955 typedef UserList::iterator UserIterator;
1957 ConstantList static_constants;
1958 UserList static_users;
1960 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1964 llvm::Instruction &inst = *ii;
1966 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1970 Value *operand_val = oi->get();
1972 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1974 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
1976 static_constants.push_back(operand_val);
1977 static_users.push_back(ii);
1982 ConstantIterator constant_iter;
1983 UserIterator user_iter;
1985 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1986 constant_iter != static_constants.end();
1987 ++constant_iter, ++user_iter)
1989 Value *operand_val = *constant_iter;
1990 llvm::Instruction *inst = *user_iter;
1992 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1994 if (operand_constant_fp)
1996 Type *operand_type = operand_constant_fp->getType();
1998 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
1999 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2001 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2002 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2007 raw_string_ostream ss(s);
2008 for (size_t index = 0;
2009 index < operand_data_size;
2012 ss << (uint32_t)operand_raw_data[index];
2017 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
2020 lldb_private::DataBufferHeap data(operand_data_size, 0);
2022 if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
2024 uint8_t *data_bytes = data.GetBytes();
2026 for (size_t index = 0;
2027 index < operand_data_size;
2030 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2035 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2038 uint64_t offset = m_data_allocator.GetStream().GetSize();
2040 size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2042 const size_t mask = (align - 1);
2043 uint64_t aligned_offset = (offset + mask) & ~mask;
2044 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
2045 offset = aligned_offset;
2047 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
2049 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
2051 Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
2053 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2055 operand_constant_fp->replaceAllUsesWith(fp_load);
2062 static bool isGuardVariableRef(Value *V)
2064 Constant *Old = NULL;
2066 if (!(Old = dyn_cast<Constant>(V)))
2069 ConstantExpr *CE = NULL;
2071 if ((CE = dyn_cast<ConstantExpr>(V)))
2073 if (CE->getOpcode() != Instruction::BitCast)
2076 Old = CE->getOperand(0);
2079 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
2081 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2088 IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
2090 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
2092 Value::use_iterator ui;
2094 for (ui = guard_load->use_begin();
2095 ui != guard_load->use_end();
2098 if (isa<Constant>(*ui))
2100 // do nothing for the moment
2104 ui->replaceUsesOfWith(guard_load, zero);
2108 guard_load->eraseFromParent();
2111 static void ExciseGuardStore(Instruction* guard_store)
2113 guard_store->eraseFromParent();
2117 IRForTarget::RemoveGuards(BasicBlock &basic_block)
2119 ///////////////////////////////////////////////////////
2120 // Eliminate any reference to guard variables found.
2123 BasicBlock::iterator ii;
2125 typedef SmallVector <Instruction*, 2> InstrList;
2126 typedef InstrList::iterator InstrIterator;
2128 InstrList guard_loads;
2129 InstrList guard_stores;
2131 for (ii = basic_block.begin();
2132 ii != basic_block.end();
2135 Instruction &inst = *ii;
2137 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2138 if (isGuardVariableRef(load->getPointerOperand()))
2139 guard_loads.push_back(&inst);
2141 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2142 if (isGuardVariableRef(store->getPointerOperand()))
2143 guard_stores.push_back(&inst);
2148 for (iter = guard_loads.begin();
2149 iter != guard_loads.end();
2151 TurnGuardLoadIntoZero(*iter);
2153 for (iter = guard_stores.begin();
2154 iter != guard_stores.end();
2156 ExciseGuardStore(*iter);
2161 // This function does not report errors; its callers are responsible.
2163 IRForTarget::UnfoldConstant(Constant *old_constant,
2164 FunctionValueCache &value_maker,
2165 FunctionValueCache &entry_instruction_finder)
2167 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2169 Value::use_iterator ui;
2171 SmallVector<User*, 16> users;
2173 // We do this because the use list might change, invalidating our iterator.
2174 // Much better to keep a work list ourselves.
2175 for (ui = old_constant->use_begin();
2176 ui != old_constant->use_end();
2178 users.push_back(*ui);
2184 User *user = users[i];
2186 if (Constant *constant = dyn_cast<Constant>(user))
2188 // synthesize a new non-constant equivalent of the constant
2190 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2192 switch (constant_expr->getOpcode())
2196 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
2198 case Instruction::BitCast:
2200 FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2202 // OperandList[0] is value
2204 if (constant_expr->getOperand(0) != old_constant)
2205 return constant_expr;
2207 return new BitCastInst(value_maker.GetValue(function),
2208 constant_expr->getType(),
2210 llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2213 if (!UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder))
2217 case Instruction::GetElementPtr:
2219 // GetElementPtrConstantExpr
2220 // OperandList[0] is base
2221 // OperandList[1]... are indices
2223 FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2224 Value *ptr = constant_expr->getOperand(0);
2226 if (ptr == old_constant)
2227 ptr = value_maker.GetValue(function);
2229 std::vector<Value*> index_vector;
2231 unsigned operand_index;
2232 unsigned num_operands = constant_expr->getNumOperands();
2234 for (operand_index = 1;
2235 operand_index < num_operands;
2238 Value *operand = constant_expr->getOperand(operand_index);
2240 if (operand == old_constant)
2241 operand = value_maker.GetValue(function);
2243 index_vector.push_back(operand);
2246 ArrayRef <Value*> indices(index_vector);
2248 return GetElementPtrInst::Create(ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2251 if (!UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder))
2260 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
2266 if (Instruction *inst = llvm::dyn_cast<Instruction>(user))
2268 inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent()));
2273 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str());
2279 if (!isa<GlobalValue>(old_constant))
2281 old_constant->destroyConstant();
2288 IRForTarget::ReplaceVariables (Function &llvm_function)
2290 if (!m_resolve_vars)
2293 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2295 m_decl_map->DoStructLayout();
2298 log->Printf("Element arrangement:");
2300 uint32_t num_elements;
2301 uint32_t element_index;
2306 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2309 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
2311 if (iter == llvm_function.getArgumentList().end())
2314 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2319 Argument *argument = iter;
2321 if (argument->getName().equals("this"))
2325 if (iter == llvm_function.getArgumentList().end())
2328 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2335 else if (argument->getName().equals("self"))
2339 if (iter == llvm_function.getArgumentList().end())
2342 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2347 if (!iter->getName().equals("_cmd"))
2350 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2357 if (iter == llvm_function.getArgumentList().end())
2360 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2368 if (!argument->getName().equals("$__lldb_arg"))
2371 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2377 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
2379 BasicBlock &entry_block(llvm_function.getEntryBlock());
2380 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
2382 if (!FirstEntryInstruction)
2385 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2390 LLVMContext &context(m_module->getContext());
2391 IntegerType *offset_type(Type::getInt32Ty(context));
2396 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2401 for (element_index = 0; element_index < num_elements; ++element_index)
2403 const clang::NamedDecl *decl = NULL;
2404 Value *value = NULL;
2406 lldb_private::ConstString name;
2408 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
2411 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2417 log->Printf(" \"%s\" (\"%s\") placed at %" PRId64,
2419 decl->getNameAsString().c_str(),
2425 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
2427 FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * {
2428 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2429 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2430 // entry in order to produce the static variable that the AST thinks it is accessing.
2432 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function));
2434 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
2435 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument,
2440 if (name == m_result_name && !m_result_is_pointer)
2442 BitCastInst *bit_cast = new BitCastInst(get_element_ptr,
2443 value->getType()->getPointerTo(),
2447 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
2453 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction);
2459 if (Constant *constant = dyn_cast<Constant>(value))
2461 UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder);
2463 else if (Instruction *instruction = dyn_cast<Instruction>(value))
2465 value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent()));
2470 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str());
2474 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2475 var->eraseFromParent();
2480 log->Printf("Total structure [align %" PRId64 ", size %lu]", alignment, size);
2486 IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
2488 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2489 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
2491 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
2493 llvm::Constant *offset_array[1];
2495 offset_array[0] = offset_int;
2497 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2499 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
2500 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2502 return reloc_getbitcast;
2506 IRForTarget::CompleteDataAllocation ()
2508 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2510 if (!m_data_allocator.GetStream().GetSize())
2513 lldb::addr_t allocation = m_data_allocator.Allocate();
2518 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2520 log->Printf("Failed to allocate static data");
2523 if (!allocation || allocation == LLDB_INVALID_ADDRESS)
2526 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2527 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
2529 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2530 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2532 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2534 m_reloc_placeholder->eraseFromParent();
2540 IRForTarget::StripAllGVs (Module &llvm_module)
2542 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2543 std::vector<GlobalVariable *> global_vars;
2544 std::set<GlobalVariable *>erased_vars;
2552 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2556 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2558 global_var->removeDeadConstantUsers();
2560 if (global_var->use_empty())
2563 log->Printf("Did remove %s",
2564 PrintValue(global_var).c_str());
2565 global_var->eraseFromParent();
2572 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2576 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2578 GlobalValue::use_iterator ui = global_var->use_begin();
2581 log->Printf("Couldn't remove %s because of %s",
2582 PrintValue(global_var).c_str(),
2583 PrintValue(*ui).c_str());
2590 IRForTarget::runOnModule (Module &llvm_module)
2592 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2594 m_module = &llvm_module;
2595 m_target_data.reset(new DataLayout(m_module));
2600 raw_string_ostream oss(s);
2602 m_module->print(oss, NULL);
2606 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2609 Function* main_function = m_module->getFunction(StringRef(m_func_name.c_str()));
2614 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
2617 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
2622 if (!FixFunctionLinkage (*main_function))
2625 log->Printf("Couldn't fix the linkage for the function");
2630 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
2632 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2634 false /* IsConstant */,
2635 GlobalVariable::InternalLinkage,
2636 Constant::getNullValue(intptr_ty),
2637 "reloc_placeholder",
2638 NULL /* InsertBefore */,
2639 GlobalVariable::NotThreadLocal /* ThreadLocal */,
2640 0 /* AddressSpace */);
2642 ////////////////////////////////////////////////////////////
2643 // Replace $__lldb_expr_result with a persistent variable
2646 if (!CreateResultVariable(*main_function))
2649 log->Printf("CreateResultVariable() failed");
2651 // CreateResultVariable() reports its own errors, so we don't do so here
2656 if (log && log->GetVerbose())
2659 raw_string_ostream oss(s);
2661 m_module->print(oss, NULL);
2665 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2668 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2672 llvm::Function *function = fi;
2674 if (function->begin() == function->end())
2677 Function::iterator bbi;
2679 for (bbi = function->begin();
2680 bbi != function->end();
2683 if (!RemoveGuards(*bbi))
2686 log->Printf("RemoveGuards() failed");
2688 // RemoveGuards() reports its own errors, so we don't do so here
2693 if (!RewritePersistentAllocs(*bbi))
2696 log->Printf("RewritePersistentAllocs() failed");
2698 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2703 if (!RemoveCXAAtExit(*bbi))
2706 log->Printf("RemoveCXAAtExit() failed");
2708 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2715 ///////////////////////////////////////////////////////////////////////////////
2716 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2719 if (!RewriteObjCConstStrings())
2722 log->Printf("RewriteObjCConstStrings() failed");
2724 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2729 ///////////////////////////////
2730 // Resolve function pointers
2733 if (!ResolveFunctionPointers(llvm_module))
2736 log->Printf("ResolveFunctionPointers() failed");
2738 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2743 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2747 llvm::Function *function = fi;
2749 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2753 if (!RewriteObjCSelectors(*bbi))
2756 log->Printf("RewriteObjCSelectors() failed");
2758 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2765 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2769 llvm::Function *function = fi;
2771 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2775 if (!ResolveCalls(*bbi))
2778 log->Printf("ResolveCalls() failed");
2780 // ResolveCalls() reports its own errors, so we don't do so here
2785 if (!ReplaceStaticLiterals(*bbi))
2788 log->Printf("ReplaceStaticLiterals() failed");
2795 ////////////////////////////////////////////////////////////////////////
2796 // Run function-level passes that only make sense on the main function
2799 if (!ResolveExternals(*main_function))
2802 log->Printf("ResolveExternals() failed");
2804 // ResolveExternals() reports its own errors, so we don't do so here
2809 if (!ReplaceVariables(*main_function))
2812 log->Printf("ReplaceVariables() failed");
2814 // ReplaceVariables() reports its own errors, so we don't do so here
2819 if (!ReplaceStrings())
2822 log->Printf("ReplaceStrings() failed");
2827 if (!CompleteDataAllocation())
2830 log->Printf("CompleteDataAllocation() failed");
2835 if (!StripAllGVs(llvm_module))
2838 log->Printf("StripAllGVs() failed");
2841 if (log && log->GetVerbose())
2844 raw_string_ostream oss(s);
2846 m_module->print(oss, NULL);
2850 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
2857 IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
2862 IRForTarget::getPotentialPassManagerType() const
2864 return PMT_ModulePassManager;