16#include "llvm/IR/Constants.h"
17#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/InstrTypes.h"
19#include "llvm/IR/Instructions.h"
20#include "llvm/IR/Intrinsics.h"
21#include "llvm/IR/LegacyPassManager.h"
22#include "llvm/IR/Metadata.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/Operator.h"
25#include "llvm/IR/ValueSymbolTable.h"
26#include "llvm/Support/ErrorExtras.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Transforms/IPO.h"
30#include "clang/AST/ASTContext.h"
60 llvm::Value *ret =
m_maker(function);
68 if (function->empty())
71 return &*function->getEntryBlock().getFirstNonPHIOrDbg();
79 const char *func_name)
91 raw_string_ostream rso(s);
96static std::string
PrintType(
const llvm::Type *type) {
100 raw_string_ostream rso(s);
106 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
113 NamedMDNode *named_metadata =
114 module->getNamedMetadata("clang.global.decl.ptrs");
119 unsigned num_nodes = named_metadata->getNumOperands();
122 for (node_index = 0; node_index < num_nodes; ++node_index) {
123 llvm::MDNode *metadata_node =
124 dyn_cast<llvm::MDNode>(named_metadata->getOperand(node_index));
128 if (metadata_node->getNumOperands() != 2)
131 if (mdconst::dyn_extract_or_null<GlobalValue>(
132 metadata_node->getOperand(0)) != global_val)
135 ConstantInt *constant_int =
136 mdconst::dyn_extract<ConstantInt>(metadata_node->getOperand(1));
141 uintptr_t ptr = constant_int->getZExtValue();
143 return reinterpret_cast<clang::NamedDecl *
>(ptr);
155 bool check_ms_abi =
true) {
157 mangled_symbol.starts_with(
"_ZGV");
159 result |= mangled_symbol.ends_with(
"@4IA");
171 ValueSymbolTable &value_symbol_table =
m_module->getValueSymbolTable();
173 llvm::StringRef result_name;
174 bool found_result =
false;
176 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
177 result_name = value_symbol.first();
185 if (!isa<GlobalVariable>(value_symbol.second))
188 if (result_name.contains(
"$__lldb_expr_result_ptr") && !is_guard_var) {
194 if (result_name.contains(
"$__lldb_expr_result") && !is_guard_var) {
202 LLDB_LOG(log,
"Couldn't find result variable");
207 LLDB_LOG(log,
"Result name: \"{0}\"", result_name);
209 Value *result_value =
m_module->getNamedValue(result_name);
212 LLDB_LOG(log,
"Result variable had no data");
214 m_error_stream.Format(
"Internal error [IRForTarget]: Result variable's "
215 "name ({0}) exists, but not its definition\n",
223 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
225 if (!result_global) {
226 LLDB_LOG(log,
"Result variable isn't a GlobalVariable");
228 m_error_stream.Format(
"Internal error [IRForTarget]: Result variable ({0}) "
229 "is defined, but is not a global variable\n",
235 clang::NamedDecl *result_decl =
DeclForGlobal(result_global);
237 LLDB_LOG(log,
"Result variable doesn't have a corresponding Decl");
239 m_error_stream.Format(
"Internal error [IRForTarget]: Result variable ({0}) "
240 "does not have a corresponding Clang entity\n",
247 std::string decl_desc_str;
248 raw_string_ostream decl_desc_stream(decl_desc_str);
249 result_decl->print(decl_desc_stream);
251 LLDB_LOG(log,
"Found result decl: \"{0}\"", decl_desc_str);
254 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
256 LLDB_LOG(log,
"Result variable Decl isn't a VarDecl");
258 m_error_stream.Format(
"Internal error [IRForTarget]: Result variable "
259 "({0})'s corresponding Clang entity isn't a "
272 clang::QualType pointer_qual_type = result_var->getType();
273 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
275 const clang::PointerType *pointer_pointertype =
276 pointer_type->getAs<clang::PointerType>();
277 const clang::ObjCObjectPointerType *pointer_objcobjpointertype =
278 pointer_type->getAs<clang::ObjCObjectPointerType>();
280 if (pointer_pointertype) {
281 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
284 m_decl_map->GetTypeSystem()->GetType(element_qual_type));
285 }
else if (pointer_objcobjpointertype) {
286 clang::QualType element_qual_type =
287 clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
290 m_decl_map->GetTypeSystem()->GetType(element_qual_type));
292 LLDB_LOG(log,
"Expected result to have pointer type, but it did not");
294 m_error_stream.Format(
"Internal error [IRForTarget]: Lvalue result ({0}) "
295 "is not a pointer variable\n",
302 m_decl_map->GetTypeSystem()->GetType(result_var->getType()));
306 auto bit_size_or_err =
m_result_type.GetBitSize(target_sp.get());
307 if (!bit_size_or_err) {
311 LLDB_LOG(log,
"Result type has unknown size");
313 m_error_stream.Printf(
"Error [IRForTarget]: Size of result type '%s' "
314 "couldn't be determined\n%s",
316 llvm::toString(bit_size_or_err.takeError()).c_str());
324 LLDB_LOG(log,
"Result decl type: \"{0}\"", type_desc_stream.
GetData());
329 LLDB_LOG(log,
"Creating a new result global: \"{0}\" with size {1}",
331 llvm::expectedToOptional(
m_result_type.GetByteSize(target_sp.get()))
336 GlobalVariable *new_result_global =
new GlobalVariable(
337 (*
m_module), result_global->getValueType(),
false,
338 GlobalValue::ExternalLinkage,
nullptr,
348 ConstantInt *new_constant_int =
349 ConstantInt::get(llvm::Type::getInt64Ty(
m_module->getContext()),
350 reinterpret_cast<uintptr_t
>(result_decl),
false);
352 llvm::Metadata *values[2];
353 values[0] = ConstantAsMetadata::get(new_result_global);
354 values[1] = ConstantAsMetadata::get(new_constant_int);
356 ArrayRef<Metadata *> value_ref(values, 2);
358 MDNode *persistent_global_md = MDNode::get(
m_module->getContext(), value_ref);
359 NamedMDNode *named_metadata =
360 m_module->getNamedMetadata(
"clang.global.decl.ptrs");
361 named_metadata->addOperand(persistent_global_md);
366 if (result_global->use_empty()) {
370 BasicBlock &entry_block(llvm_function.getEntryBlock());
371 Instruction *first_entry_instruction(&*entry_block.getFirstNonPHIOrDbg());
373 if (!first_entry_instruction)
376 if (!result_global->hasInitializer()) {
377 LLDB_LOG(log,
"Couldn't find initializer for unused variable");
379 m_error_stream.Format(
"Internal error [IRForTarget]: Result variable "
380 "({0}) has no writes and no initializer\n",
386 Constant *initializer = result_global->getInitializer();
388 StoreInst *synthesized_store =
new StoreInst(
389 initializer, new_result_global, first_entry_instruction->getIterator());
391 LLDB_LOG(log,
"Synthesized result store \"{0}\"\n",
394 result_global->replaceAllUsesWith(new_result_global);
401 result_global->eraseFromParent();
407 llvm::GlobalVariable *cstr) {
410 Type *ns_str_ty = ns_str->getType();
412 Type *i8_ptr_ty = PointerType::getUnqual(
m_module->getContext());
413 Type *i32_ty = Type::getInt32Ty(
m_module->getContext());
414 Type *i8_ty = Type::getInt8Ty(
m_module->getContext());
420 "CFStringCreateWithBytes");
422 bool missing_weak =
false;
424 g_CFStringCreateWithBytes_str, missing_weak);
426 LLDB_LOG(log,
"Couldn't find CFStringCreateWithBytes in the target");
428 m_error_stream.Printf(
"Error [IRForTarget]: Rewriting an Objective-C "
429 "constant string requires "
430 "CFStringCreateWithBytes\n");
435 LLDB_LOG(log,
"Found CFStringCreateWithBytes at {0:x}",
436 CFStringCreateWithBytes_addr);
456 Type *arg_type_array[5];
458 arg_type_array[0] = i8_ptr_ty;
459 arg_type_array[1] = i8_ptr_ty;
461 arg_type_array[3] = i32_ty;
462 arg_type_array[4] = i8_ty;
464 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
466 llvm::FunctionType *CFSCWB_ty =
467 FunctionType::get(ns_str_ty, CFSCWB_arg_types,
false);
470 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(
m_module->getContext());
471 Constant *CFSCWB_addr_int =
472 ConstantInt::get(
m_intptr_ty, CFStringCreateWithBytes_addr,
false);
474 CFSCWB_ty, ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty)};
477 ConstantDataSequential *string_array =
nullptr;
480 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
482 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
483 Constant *bytes_arg = cstr ? cstr : Constant::getNullValue(i8_ptr_ty);
484 Constant *numBytes_arg = ConstantInt::get(
485 m_intptr_ty, cstr ? (string_array->getNumElements() - 1) * string_array->getElementByteSize() : 0,
false);
486 int encoding_flags = 0;
487 switch (cstr ? string_array->getElementByteSize() : 1) {
489 encoding_flags = 0x08000100;
492 encoding_flags = 0x0100;
495 encoding_flags = 0x0c000100;
498 encoding_flags = 0x0600;
499 LLDB_LOG(log,
"Encountered an Objective-C constant string with unusual "
501 string_array->getElementByteSize());
503 Constant *encoding_arg = ConstantInt::get(i32_ty, encoding_flags,
false);
504 Constant *isExternal_arg =
505 ConstantInt::get(i8_ty, 0x0,
false);
507 Value *argument_array[5];
509 argument_array[0] = alloc_arg;
510 argument_array[1] = bytes_arg;
511 argument_array[2] = numBytes_arg;
512 argument_array[3] = encoding_arg;
513 argument_array[4] = isExternal_arg;
515 ArrayRef<Value *> CFSCWB_arguments(argument_array, 5);
518 [
this, &CFSCWB_arguments](llvm::Function *function) -> llvm::Value * {
519 return CallInst::Create(
521 "CFStringCreateWithBytes",
522 llvm::cast<Instruction>(
529 std::string error_msg = llvm::toString(std::move(err));
531 "Couldn't replace the NSString with the result of the call: {0}",
534 m_error_stream.Format(
"error [IRForTarget internal]: Couldn't replace an "
535 "Objective-C constant string with a dynamic "
542 ns_str->eraseFromParent();
550 ValueSymbolTable &value_symbol_table =
m_module->getValueSymbolTable();
552 std::vector<std::pair<GlobalVariable *, GlobalVariable *>>
553 nsstring_to_cstr_list;
555 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
556 llvm::StringRef value_name = value_symbol.first();
558 if (value_name.contains(
"_unnamed_cfstring_")) {
559 Value *nsstring_value = value_symbol.second;
561 GlobalVariable *nsstring_global =
562 dyn_cast<GlobalVariable>(nsstring_value);
564 if (!nsstring_global) {
565 LLDB_LOG(log,
"NSString variable is not a GlobalVariable");
567 m_error_stream.Printf(
"Internal error [IRForTarget]: An Objective-C "
568 "constant string is not a global variable\n");
573 if (!nsstring_global->hasInitializer()) {
574 LLDB_LOG(log,
"NSString variable does not have an initializer");
576 m_error_stream.Printf(
"Internal error [IRForTarget]: An Objective-C "
577 "constant string does not have an initializer\n");
582 ConstantStruct *nsstring_struct =
583 dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
585 if (!nsstring_struct) {
587 "NSString variable's initializer is not a ConstantStruct");
589 m_error_stream.Printf(
"Internal error [IRForTarget]: An Objective-C "
590 "constant string is not a structure constant\n");
604 if (nsstring_struct->getNumOperands() != 4) {
607 "NSString variable's initializer structure has an "
608 "unexpected number of members. Should be 4, is {0}",
609 nsstring_struct->getNumOperands());
611 m_error_stream.Printf(
"Internal error [IRForTarget]: The struct for an "
612 "Objective-C constant string is not as "
618 Constant *nsstring_member = nsstring_struct->getOperand(2);
620 if (!nsstring_member) {
621 LLDB_LOG(log,
"NSString initializer's str element was empty");
623 m_error_stream.Printf(
"Internal error [IRForTarget]: An Objective-C "
624 "constant string does not have a string "
630 auto *cstr_global = dyn_cast<GlobalVariable>(nsstring_member);
633 "NSString initializer's str element is not a GlobalVariable");
636 "constant string initializer\n");
641 if (!cstr_global->hasInitializer()) {
642 LLDB_LOG(log,
"NSString initializer's str element does not have an "
645 m_error_stream.Printf(
"Internal error [IRForTarget]: An Objective-C "
646 "constant string's string initializer doesn't "
647 "point to initialized data\n");
682 ConstantDataArray *cstr_array =
683 dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
686 LLDB_LOG(log,
"Found NSString constant {0}, which contains \"{1}\"",
687 value_name, cstr_array->getAsString());
689 LLDB_LOG(log,
"Found NSString constant {0}, which contains \"\"",
693 cstr_global =
nullptr;
697 nsstring_to_cstr_list.emplace_back(nsstring_global, cstr_global);
701 for (
auto [nsstring_global, cstr_global] : nsstring_to_cstr_list) {
703 LLDB_LOG(log,
"Error rewriting the constant string");
708 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
709 llvm::StringRef value_name = value_symbol.first();
711 if (value_name ==
"__CFConstantStringClassReference") {
712 GlobalVariable *gv = dyn_cast<GlobalVariable>(value_symbol.second);
716 "__CFConstantStringClassReference is not a global variable");
719 "CFConstantStringClassReference, but it is not a "
725 gv->eraseFromParent();
735 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
738 !global_variable || !global_variable->hasName() ||
739 !global_variable->getName().starts_with(
"OBJC_SELECTOR_REFERENCES_"));
746 LoadInst *load = dyn_cast<LoadInst>(selector_load);
765 GlobalVariable *_objc_selector_references_ =
766 dyn_cast<GlobalVariable>(load->getPointerOperand());
768 if (!_objc_selector_references_ ||
769 !_objc_selector_references_->hasInitializer())
772 Constant *osr_initializer = _objc_selector_references_->getInitializer();
773 if (!osr_initializer)
778 GlobalVariable *_objc_meth_var_name_ =
779 dyn_cast<GlobalVariable>(osr_initializer);
781 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
784 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
786 ConstantDataArray *omvn_initializer_array =
787 dyn_cast<ConstantDataArray>(omvn_initializer);
789 if (!omvn_initializer_array->isString())
792 std::string omvn_initializer_string =
793 std::string(omvn_initializer_array->getAsString());
795 LLDB_LOG(log,
"Found Objective-C selector reference \"{0}\"",
796 omvn_initializer_string);
803 bool missing_weak =
false;
810 LLDB_LOG(log,
"Found sel_registerName at {0:x}", sel_registerName_addr);
819 Type *sel_ptr_type = PointerType::getUnqual(
m_module->getContext());
823 type_array[0] = llvm::PointerType::getUnqual(
m_module->getContext());
825 ArrayRef<Type *> srN_arg_types(type_array, 1);
827 llvm::FunctionType *srN_type =
828 FunctionType::get(sel_ptr_type, srN_arg_types,
false);
831 PointerType *srN_ptr_ty = PointerType::getUnqual(
m_module->getContext());
832 Constant *srN_addr_int =
833 ConstantInt::get(
m_intptr_ty, sel_registerName_addr,
false);
835 ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty)};
840 "sel_registerName", selector_load->getIterator());
844 selector_load->replaceAllUsesWith(srN_call);
846 selector_load->eraseFromParent();
856 for (Instruction &inst : basic_block) {
857 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
859 selector_loads.push_back(&inst);
862 for (Instruction *inst : selector_loads) {
864 m_error_stream.Printf(
"Internal error [IRForTarget]: Couldn't change a "
865 "static reference to an Objective-C selector to a "
866 "dynamic reference\n");
868 LLDB_LOG(log,
"Couldn't rewrite a reference to an Objective-C selector");
881 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
883 MDNode *alloc_md = alloc->getMetadata(
"clang.decl.ptr");
885 if (!alloc_md || !alloc_md->getNumOperands())
888 ConstantInt *constant_int =
889 mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0));
896 uintptr_t ptr = constant_int->getZExtValue();
898 clang::VarDecl *decl =
reinterpret_cast<clang::VarDecl *
>(ptr);
901 m_decl_map->GetTypeSystem()->GetType(decl->getType()));
903 StringRef decl_name(decl->getName());
905 if (!
m_decl_map->AddPersistentVariable(decl, persistent_variable_name,
906 result_decl_type,
false,
false))
909 GlobalVariable *persistent_global =
new GlobalVariable(
910 (*
m_module), alloc->getType(),
false,
911 GlobalValue::ExternalLinkage,
nullptr,
912 alloc->getName().str());
917 NamedMDNode *named_metadata =
918 m_module->getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
920 llvm::Metadata *values[2];
921 values[0] = ConstantAsMetadata::get(persistent_global);
922 values[1] = ConstantAsMetadata::get(constant_int);
924 ArrayRef<llvm::Metadata *> value_ref(values, 2);
926 MDNode *persistent_global_md = MDNode::get(
m_module->getContext(), value_ref);
927 named_metadata->addOperand(persistent_global_md);
932 LoadInst *persistent_load =
933 new LoadInst(persistent_global->getValueType(), persistent_global,
"",
934 alloc->getIterator());
939 alloc->replaceAllUsesWith(persistent_load);
940 alloc->eraseFromParent();
953 for (Instruction &inst : basic_block) {
955 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) {
956 llvm::StringRef alloc_name = alloc->getName();
958 if (alloc_name.starts_with(
"$") && !alloc_name.starts_with(
"$__lldb")) {
959 if (alloc_name.find_first_of(
"0123456789") == 1) {
960 LLDB_LOG(log,
"Rejecting a numeric persistent variable.");
962 m_error_stream.Printf(
"Error [IRForTarget]: Names starting with $0, "
963 "$1, ... are reserved for use as result "
969 pvar_allocs.push_back(alloc);
974 for (Instruction *inst : pvar_allocs) {
976 m_error_stream.Printf(
"Internal error [IRForTarget]: Couldn't rewrite "
977 "the creation of a persistent variable\n");
979 LLDB_LOG(log,
"Couldn't rewrite the creation of a persistent variable");
994 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) {
995 switch (constant_expr->getOpcode()) {
998 case Instruction::GetElementPtr:
999 case Instruction::BitCast:
1000 Value *s = constant_expr->getOperand(0);
1004 }
else if (GlobalVariable *global_variable =
1005 dyn_cast<GlobalVariable>(llvm_value_ptr)) {
1006 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1009 clang::NamedDecl *named_decl =
DeclForGlobal(global_variable);
1015 if (!global_variable->hasExternalLinkage())
1018 LLDB_LOG(log,
"Found global variable \"{0}\" without metadata",
1019 global_variable->getName());
1024 llvm::StringRef name(named_decl->getName());
1026 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1027 if (value_decl ==
nullptr)
1031 m_decl_map->GetTypeSystem()->GetType(value_decl->getType());
1033 const Type *value_type =
nullptr;
1035 if (name.starts_with(
"$")) {
1047 value_type = PointerType::getUnqual(global_variable->getContext());
1049 value_type = global_variable->getType();
1053 std::optional<uint64_t> value_size =
1054 llvm::expectedToOptional(compiler_type.
GetByteSize(target));
1057 std::optional<size_t> opt_alignment = compiler_type.
GetTypeBitAlign(target);
1063 "Type of \"{0}\" is [clang \"{1}\", llvm \"{2}\"] [size {3}, "
1067 PrintType(value_type), *value_size, value_alignment);
1071 llvm_value_ptr, *value_size,
1073 }
else if (isa<llvm::Function>(llvm_value_ptr)) {
1074 LLDB_LOG(log,
"Function pointers aren't handled right now");
1092 LLDB_LOG(log,
"Symbol \"{0}\" had no address", name);
1097 LLDB_LOG(log,
"Found \"{0}\" at {1:x}", name, symbol_addr);
1099 Type *symbol_type = symbol->getType();
1101 Constant *symbol_addr_int = ConstantInt::get(
m_intptr_ty, symbol_addr,
false);
1103 Value *symbol_addr_ptr =
1104 ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1109 symbol->replaceAllUsesWith(symbol_addr_ptr);
1119 for (
unsigned op_index = 0, num_ops = Old->arg_size();
1120 op_index < num_ops; ++op_index)
1123 m_error_stream.Printf(
"Internal error [IRForTarget]: Couldn't rewrite "
1124 "one of the arguments of a function call.\n");
1135 GlobalVariable *global_variable =
1136 dyn_cast<GlobalVariable>(classlist_reference);
1138 if (!global_variable)
1141 Constant *initializer = global_variable->getInitializer();
1146 if (!initializer->hasName())
1149 StringRef name(initializer->getName());
1154 LLDB_LOG(log,
"Found reference to Objective-C class {0} ({1:x})", name,
1155 (
unsigned long long)class_ptr);
1160 if (global_variable->use_empty())
1163 SmallVector<LoadInst *, 2> load_instructions;
1165 for (llvm::User *u : global_variable->users()) {
1166 if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
1167 load_instructions.push_back(load_instruction);
1170 if (load_instructions.empty())
1173 Constant *class_addr = ConstantInt::get(
m_intptr_ty, (uint64_t)class_ptr);
1175 for (LoadInst *load_instruction : load_instructions) {
1176 Constant *class_bitcast =
1177 ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1179 load_instruction->replaceAllUsesWith(class_bitcast);
1181 load_instruction->eraseFromParent();
1188 std::vector<CallInst *> calls_to_remove;
1189 llvm::SmallVector<llvm::Function *, 2> dead_atexit_callbacks;
1191 for (Instruction &inst : basic_block) {
1192 CallInst *call = dyn_cast<CallInst>(&inst);
1198 bool remove =
false;
1200 llvm::Function *func = call->getCalledFunction();
1204 (func->getName() ==
"__cxa_atexit" || func->getName() ==
"atexit"))
1207 llvm::Value *val = call->getCalledOperand();
1209 if (val && (val->getName() ==
"__cxa_atexit" || val->getName() ==
"atexit"))
1215 if (call->arg_size() > 0)
1216 if (
auto *cb = dyn_cast<llvm::Function>(
1217 call->getArgOperand(0)->stripPointerCasts()))
1218 if (cb->hasInternalLinkage() && cb->getName().starts_with(
"??__F"))
1219 dead_atexit_callbacks.push_back(cb);
1220 calls_to_remove.push_back(call);
1224 for (CallInst *ci : calls_to_remove)
1225 ci->eraseFromParent();
1229 for (llvm::Function *cb : dead_atexit_callbacks) {
1230 if (!cb->use_empty())
1233 llvm::BasicBlock *entry =
1234 llvm::BasicBlock::Create(cb->getContext(),
"", cb);
1235 llvm::ReturnInst::Create(cb->getContext(), entry);
1244 for (Instruction &inst : basic_block) {
1245 CallInst *call = dyn_cast<CallInst>(&inst);
1258 for (GlobalVariable &global_var :
m_module->globals()) {
1259 llvm::StringRef global_name = global_var.getName();
1261 LLDB_LOG(log,
"Examining {0}, DeclForGlobalValue returns {1}", global_name,
1264 if (global_name.starts_with(
"OBJC_IVAR")) {
1266 m_error_stream.Format(
"Error [IRForTarget]: Couldn't find Objective-C "
1267 "indirect ivar symbol {0}\n",
1272 }
else if (global_name.contains(
"OBJC_CLASSLIST_REFERENCES_$")) {
1274 m_error_stream.Printf(
"Error [IRForTarget]: Couldn't resolve the class "
1275 "for an Objective-C static method call\n");
1279 }
else if (global_name.contains(
"OBJC_CLASSLIST_SUP_REFS_$")) {
1281 m_error_stream.Printf(
"Error [IRForTarget]: Couldn't resolve the class "
1282 "for an Objective-C static method call\n");
1288 m_error_stream.Format(
"Internal error [IRForTarget]: Couldn't rewrite "
1289 "external variable {0}\n",
1301 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
1310 Constant *zero(Constant::getNullValue(guard_load->getType()));
1311 guard_load->replaceAllUsesWith(zero);
1312 guard_load->eraseFromParent();
1316 guard_store->eraseFromParent();
1325 for (Instruction &inst : basic_block) {
1327 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1329 guard_loads.push_back(&inst);
1331 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1333 guard_stores.push_back(&inst);
1336 for (Instruction *inst : guard_loads)
1339 for (Instruction *inst : guard_stores)
1347 llvm::Function *llvm_function,
1351 SmallVector<User *, 16> users;
1355 for (llvm::User *u : old_constant->users())
1358 for (User *user : users) {
1359 if (Constant *constant = dyn_cast<Constant>(user)) {
1362 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
1363 switch (constant_expr->getOpcode()) {
1365 return llvm::createStringErrorV(
1366 "unhandled constant expression type: \"{0}\".",
1369 case Instruction::BitCast: {
1371 [&value_maker, &entry_instruction_finder, old_constant,
1372 constant_expr](llvm::Function *function) -> llvm::Value * {
1376 if (constant_expr->getOperand(0) != old_constant)
1377 return constant_expr;
1379 return new BitCastInst(
1380 value_maker.
GetValue(function), constant_expr->getType(),
1382 llvm::cast<Instruction>(
1383 entry_instruction_finder.
GetValue(function))
1389 entry_instruction_finder, error_stream))
1392 case Instruction::GetElementPtr: {
1398 [&value_maker, &entry_instruction_finder, old_constant,
1399 constant_expr](llvm::Function *function) -> llvm::Value * {
1400 auto *gep = cast<llvm::GEPOperator>(constant_expr);
1401 Value *ptr = gep->getPointerOperand();
1403 if (ptr == old_constant)
1404 ptr = value_maker.
GetValue(function);
1406 std::vector<Value *> index_vector;
1407 for (Value *operand : gep->indices()) {
1408 if (operand == old_constant)
1409 operand = value_maker.
GetValue(function);
1411 index_vector.push_back(operand);
1414 ArrayRef<Value *> indices(index_vector);
1416 return GetElementPtrInst::Create(
1417 gep->getSourceElementType(), ptr, indices,
"",
1418 llvm::cast<Instruction>(
1419 entry_instruction_finder.
GetValue(function))
1424 get_element_pointer_maker,
1425 entry_instruction_finder, error_stream))
1429 }
else if (ConstantPtrAuth *constant_ptr_auth =
1430 dyn_cast<ConstantPtrAuth>(constant)) {
1433 if (constant_ptr_auth->hasAddressDiscriminator() &&
1434 constant_ptr_auth->getAddrDiscriminator() == old_constant)
1437 return llvm::createStringErrorV(
"unhandled constant type \"{0}\".",
1440 return llvm::createStringErrorV(
"unhandled constant type \"{0}\".",
1443 }
else if (Instruction *inst = llvm::dyn_cast<Instruction>(user)) {
1444 if (llvm_function && inst->getParent()->getParent() != llvm_function)
1445 return llvm::createStringError(
1446 "capturing non-local variables in expressions is unsupported.");
1448 inst->replaceUsesOfWith(
1449 old_constant, value_maker.
GetValue(inst->getParent()->getParent()));
1451 return llvm::createStringErrorV(
"unhandled non-constant type: \"{0}\".",
1456 if (!isa<GlobalValue>(old_constant)) {
1457 old_constant->destroyConstant();
1460 return llvm::Error::success();
1471 LLDB_LOG(log,
"Element arrangement:");
1473 uint32_t num_elements;
1474 uint32_t element_index;
1479 if (!
m_decl_map->GetStructInfo(num_elements, size, alignment))
1482 Function::arg_iterator iter(llvm_function.arg_begin());
1484 if (iter == llvm_function.arg_end()) {
1485 m_error_stream.Printf(
"Internal error [IRForTarget]: Wrapper takes no "
1486 "arguments (should take at least a struct pointer)");
1491 Argument *argument = &*iter;
1493 if (argument->getName() ==
"this") {
1496 if (iter == llvm_function.arg_end()) {
1497 m_error_stream.Printf(
"Internal error [IRForTarget]: Wrapper takes only "
1498 "'this' argument (should take a struct pointer "
1505 }
else if (argument->getName() ==
"self") {
1508 if (iter == llvm_function.arg_end()) {
1509 m_error_stream.Printf(
"Internal error [IRForTarget]: Wrapper takes only "
1510 "'self' argument (should take '_cmd' and a struct "
1516 if (iter->getName() !=
"_cmd") {
1517 m_error_stream.Format(
"Internal error [IRForTarget]: Wrapper takes '{0}' "
1518 "after 'self' argument (should take '_cmd')",
1526 if (iter == llvm_function.arg_end()) {
1527 m_error_stream.Printf(
"Internal error [IRForTarget]: Wrapper takes only "
1528 "'self' and '_cmd' arguments (should take a struct "
1537 if (argument->getName() !=
"$__lldb_arg") {
1538 m_error_stream.Format(
"Internal error [IRForTarget]: Wrapper takes an "
1539 "argument named '{0}' instead of the struct pointer",
1540 argument->getName());
1547 BasicBlock &entry_block(llvm_function.getEntryBlock());
1548 Instruction *FirstEntryInstruction(&*entry_block.getFirstNonPHIOrDbg());
1550 if (!FirstEntryInstruction) {
1551 m_error_stream.Printf(
"Internal error [IRForTarget]: Couldn't find the "
1552 "first instruction in the wrapper for use in "
1558 LLVMContext &context(
m_module->getContext());
1559 IntegerType *offset_type(Type::getInt32Ty(context));
1563 "Internal error [IRForTarget]: Couldn't produce an offset type");
1568 for (element_index = 0; element_index < num_elements; ++element_index) {
1569 const clang::NamedDecl *decl =
nullptr;
1570 Value *value =
nullptr;
1574 if (!
m_decl_map->GetStructElement(decl, value, offset, name,
1577 "Internal error [IRForTarget]: Structure information is incomplete");
1582 LLDB_LOG(log,
" \"{0}\" (\"{1}\") placed at {2}", name,
1583 decl->getNameAsString(), offset);
1589 [
this, name, offset_type, offset, argument,
1590 value](llvm::Function *function) -> llvm::Value * {
1597 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(
1600 Type *int8Ty = Type::getInt8Ty(function->getContext());
1601 ConstantInt *offset_int(
1602 ConstantInt::get(offset_type, offset,
true));
1603 GetElementPtrInst *get_element_ptr =
1604 GetElementPtrInst::Create(int8Ty, argument, offset_int,
"",
1605 entry_instruction->getIterator());
1609 new LoadInst(value->getType(), get_element_ptr,
"",
1610 entry_instruction->getIterator());
1614 return get_element_ptr;
1618 if (Constant *constant = dyn_cast<Constant>(value)) {
1625 }
else if (Instruction *instruction = dyn_cast<Instruction>(value)) {
1626 if (instruction->getParent()->getParent() != &llvm_function) {
1627 m_error_stream.PutCString(
"error: Capturing non-local variables in "
1628 "expressions is unsupported.\n");
1631 value->replaceAllUsesWith(
1632 body_result_maker.GetValue(instruction->getParent()->getParent()));
1634 LLDB_LOG(log,
"Unhandled non-constant type: \"{0}\"",
1639 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
1640 var->eraseFromParent();
1644 LLDB_LOG(log,
"Total structure [align {0}, size {1}]", (int64_t)alignment,
1660 raw_string_ostream oss(s);
1664 LLDB_LOG(log,
"Module as passed in to IRForTarget: \n\"{0}\"", s);
1667 Function *
const main_function =
1674 m_error_stream.Format(
"Internal error [IRForTarget]: Couldn't find wrapper "
1675 "'{0}' in the module",
1681 if (main_function) {
1683 LLDB_LOG(log,
"Couldn't fix the linkage for the function");
1690 if (main_function) {
1692 LLDB_LOG(log,
"CreateResultVariable() failed");
1702 raw_string_ostream oss(s);
1706 LLDB_LOG(log,
"Module after creating the result variable: \n\"{0}\"", s);
1709 for (llvm::Function &function : *
m_module) {
1710 for (BasicBlock &bb : function) {
1712 LLDB_LOG(log,
"RemoveGuards() failed");
1720 LLDB_LOG(log,
"RewritePersistentAllocs() failed");
1729 LLDB_LOG(log,
"RemoveCXAAtExit() failed");
1740 LLDB_LOG(log,
"RewriteObjCConstStrings() failed");
1747 for (llvm::Function &function : *
m_module) {
1748 for (llvm::BasicBlock &bb : function) {
1750 LLDB_LOG(log,
"RewriteObjCSelectors() failed");
1760 for (llvm::Function &function : *
m_module) {
1761 for (BasicBlock &bb : function) {
1763 LLDB_LOG(log,
"ResolveCalls() failed");
1773 if (main_function) {
1775 LLDB_LOG(log,
"ResolveExternals() failed");
1783 LLDB_LOG(log,
"ReplaceVariables() failed");
1792 if (llvm::Error
error =
1795 "InsertPointerSigningFixups() failed: {0}");
1801 raw_string_ostream oss(s);
1805 LLDB_LOG(log,
"Module after preparing for execution: \n\"{0}\"", s);
static llvm::raw_ostream & error(Stream &strm)
static std::string PrintValue(const Value *value)
static bool isGuardVariableSymbol(llvm::StringRef mangled_symbol, bool check_ms_abi=true)
Returns true iff the mangled symbol is for a static guard variable.
static void ExciseGuardStore(Instruction *guard_store)
static llvm::Value * FindEntryInstruction(llvm::Function *function)
static bool IsObjCSelectorRef(Value *value)
SmallVector< Instruction *, 2 > InstrList
static bool isGuardVariableRef(Value *V)
static std::string PrintType(const llvm::Type *type)
static std::string PrintValue(const Value *value, bool truncate=false)
static std::string PrintType(const Type *type, bool truncate=false)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
#define LLDB_LOG_ERROR(log, error,...)
FunctionValueCache(Maker const &maker)
llvm::Value * GetValue(llvm::Function *function)
std::function< llvm::Value *(llvm::Function *)> Maker
FunctionValueMap m_values
static llvm::Error UnfoldConstant(llvm::Constant *old_constant, llvm::Function *llvm_function, FunctionValueCache &value_maker, FunctionValueCache &entry_instruction_finder, lldb_private::Stream &error_stream)
UnfoldConstant operates on a constant [Old] which has just been replaced with a value [New].
lldb_private::ConstString m_func_name
The name of the function to translate.
IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map, bool resolve_vars, lldb_private::IRExecutionUnit &execution_unit, lldb_private::Stream &error_stream, lldb_private::ExecutionPolicy execution_policy, const char *func_name="$__lldb_expr")
Constructor.
bool MaybeHandleVariable(llvm::Value *value)
A function-level pass to find all external variables and functions used in the IR.
bool FixFunctionLinkage(llvm::Function &llvm_function)
Ensures that the current function's linkage is set to external.
lldb_private::IRExecutionUnit & m_execution_unit
The execution unit containing the IR being created.
bool CreateResultVariable(llvm::Function &llvm_function)
The top-level pass implementation.
llvm::Module * m_module
The module being processed, or NULL if that has not been determined yet.
bool HandleSymbol(llvm::Value *symbol)
Handle a single externally-defined symbol.
bool RewriteObjCConstStrings()
The top-level pass implementation.
bool ResolveCalls(llvm::BasicBlock &basic_block)
Resolve variable references in calls to external functions.
bool m_result_is_pointer
True if the function's result in the AST is a pointer (see comments in ASTResultSynthesizer::Synthesi...
bool RewriteObjCConstString(llvm::GlobalVariable *NSStr, llvm::GlobalVariable *CStr)
A module-level pass to find Objective-C constant strings and transform them to calls to CFStringCreat...
bool RemoveGuards(llvm::BasicBlock &basic_block)
The top-level pass implementation.
lldb_private::Stream & m_error_stream
The stream on which errors should be printed.
bool HandleObjCClass(llvm::Value *classlist_reference)
Handle a single externally-defined Objective-C class.
bool m_resolve_vars
True if external variable references and persistent variable references should be resolved.
static clang::NamedDecl * DeclForGlobal(const llvm::GlobalValue *global_val, llvm::Module *module)
A function-level pass to take the generated global value $__lldb_expr_result and make it into a persi...
lldb_private::TypeFromParser m_result_type
The type of the result variable.
llvm::FunctionCallee m_CFStringCreateWithBytes
The address of the function CFStringCreateWithBytes, cast to the appropriate function pointer type.
bool MaybeHandleCallArguments(llvm::CallInst *call_inst)
Handle all the arguments to a function call.
lldb_private::ExecutionPolicy m_policy
bool runOnModule(llvm::Module &llvm_module)
Run this IR transformer on a single module.
bool RewriteObjCSelectors(llvm::BasicBlock &basic_block)
The top-level pass implementation.
lldb_private::ConstString m_result_name
The name of the result variable ($0, $1, ...)
lldb_private::ClangExpressionDeclMap * m_decl_map
The DeclMap containing the Decls.
bool RemoveCXAAtExit(llvm::BasicBlock &basic_block)
Remove calls to __cxa_atexit, which should never be generated by expressions.
bool RewritePersistentAllocs(llvm::BasicBlock &basic_block)
The top-level pass implementation.
bool RewritePersistentAlloc(llvm::Instruction *persistent_alloc)
A basic block-level pass to find all newly-declared persistent variables and register them with the C...
void TurnGuardLoadIntoZero(llvm::Instruction *guard_load)
A basic block-level pass to excise guard variables from the code.
FunctionValueCache m_entry_instruction_finder
const llvm::DataLayout * m_target_data
The target data for the module being processed, or nullptr if there is no module.
llvm::FunctionCallee m_sel_registerName
The address of the function sel_registerName, cast to the appropriate function pointer type.
llvm::IntegerType * m_intptr_ty
The type of an integer large enough to hold a pointer.
bool RewriteObjCSelector(llvm::Instruction *selector_load)
A basic block-level pass to find all Objective-C method calls and rewrite them to use sel_registerNam...
bool ResolveExternals(llvm::Function &llvm_function)
The top-level pass implementation.
bool ReplaceVariables(llvm::Function &llvm_function)
A function-level pass to make all external variable references point at the correct offsets from the ...
"lldb/Expression/ClangExpressionDeclMap.h" Manages named entities that are defined in LLDB's debug in...
Generic representation of a type in a programming language.
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
llvm::Expected< uint64_t > GetByteSize(ExecutionContextScope *exe_scope) const
Return the size of the type in bytes.
std::optional< size_t > GetTypeBitAlign(ExecutionContextScope *exe_scope) const
A uniqued constant string class.
"lldb/Expression/IRExecutionUnit.h" Contains the IR and, optionally, JIT- compiled code for a module.
const char * GetData() const
A stream class that can stream formatted output to a file.
#define LLDB_INVALID_ADDRESS
Error InjectPointerSigningFixupCode(llvm::Module &M, ExecutionPolicy execution_policy)
TaggedASTType< 0 > TypeFromParser
ExecutionPolicy
Expression execution policies.
std::shared_ptr< lldb_private::Target > TargetSP
static clang::QualType GetQualType(const CompilerType &ct)