15#include "llvm/IR/Constants.h"
16#include "llvm/IR/DataLayout.h"
17#include "llvm/IR/Operator.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/ValueSymbolTable.h"
25#include "llvm/Support/raw_ostream.h"
26#include "llvm/Transforms/IPO.h"
28#include "clang/AST/ASTContext.h"
51 : m_maker(maker), m_values() {}
57 if (!m_values.count(function)) {
58 llvm::Value *ret = m_maker(function);
59 m_values[function] = ret;
62 return m_values[function];
66 if (function->empty())
69 return function->getEntryBlock().getFirstNonPHIOrDbg();
76 const char *func_name)
84static std::string
PrintValue(
const Value *value,
bool truncate =
false) {
87 raw_string_ostream rso(s);
90 s.resize(s.length() - 1);
95static std::string
PrintType(
const llvm::Type *type,
bool truncate =
false) {
97 raw_string_ostream rso(s);
100 s.resize(s.length() - 1);
105 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
112 NamedMDNode *named_metadata =
113 module->getNamedMetadata(
"clang.global.decl.ptrs");
118 unsigned num_nodes = named_metadata->getNumOperands();
121 for (node_index = 0; node_index < num_nodes; ++node_index) {
122 llvm::MDNode *metadata_node =
123 dyn_cast<llvm::MDNode>(named_metadata->getOperand(node_index));
127 if (metadata_node->getNumOperands() != 2)
130 if (mdconst::dyn_extract_or_null<GlobalValue>(
131 metadata_node->getOperand(0)) != global_val)
134 ConstantInt *constant_int =
135 mdconst::dyn_extract<ConstantInt>(metadata_node->getOperand(1));
140 uintptr_t ptr = constant_int->getZExtValue();
142 return reinterpret_cast<clang::NamedDecl *
>(ptr);
154 bool check_ms_abi =
true) {
156 mangled_symbol.starts_with(
"_ZGV");
158 result |= mangled_symbol.ends_with(
"@4IA");
170 ValueSymbolTable &value_symbol_table =
m_module->getValueSymbolTable();
172 llvm::StringRef result_name;
173 bool found_result =
false;
175 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
176 result_name = value_symbol.first();
182 if (result_name.contains(
"$__lldb_expr_result_ptr") && !is_guard_var) {
188 if (result_name.contains(
"$__lldb_expr_result") && !is_guard_var) {
196 LLDB_LOG(log,
"Couldn't find result variable");
201 LLDB_LOG(log,
"Result name: \"{0}\"", result_name);
203 Value *result_value =
m_module->getNamedValue(result_name);
206 LLDB_LOG(log,
"Result variable had no data");
209 "name ({0}) exists, but not its definition\n",
215 LLDB_LOG(log,
"Found result in the IR: \"{0}\"",
218 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
220 if (!result_global) {
221 LLDB_LOG(log,
"Result variable isn't a GlobalVariable");
224 "is defined, but is not a global variable\n",
230 clang::NamedDecl *result_decl =
DeclForGlobal(result_global);
232 LLDB_LOG(log,
"Result variable doesn't have a corresponding Decl");
235 "does not have a corresponding Clang entity\n",
242 std::string decl_desc_str;
243 raw_string_ostream decl_desc_stream(decl_desc_str);
244 result_decl->print(decl_desc_stream);
246 LLDB_LOG(log,
"Found result decl: \"{0}\"", decl_desc_str);
249 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
251 LLDB_LOG(log,
"Result variable Decl isn't a VarDecl");
254 "({0})'s corresponding Clang entity isn't a "
267 clang::QualType pointer_qual_type = result_var->getType();
268 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
270 const clang::PointerType *pointer_pointertype =
271 pointer_type->getAs<clang::PointerType>();
272 const clang::ObjCObjectPointerType *pointer_objcobjpointertype =
273 pointer_type->getAs<clang::ObjCObjectPointerType>();
275 if (pointer_pointertype) {
276 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
280 }
else if (pointer_objcobjpointertype) {
281 clang::QualType element_qual_type =
282 clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
287 LLDB_LOG(log,
"Expected result to have pointer type, but it did not");
290 "is not a pointer variable\n",
301 std::optional<uint64_t> bit_size =
m_result_type.GetBitSize(target_sp.get());
306 LLDB_LOG(log,
"Result type has unknown size");
309 "couldn't be determined\n",
318 LLDB_LOG(log,
"Result decl type: \"{0}\"", type_desc_stream.
GetData());
323 LLDB_LOG(log,
"Creating a new result global: \"{0}\" with size {1}",
329 GlobalVariable *new_result_global =
new GlobalVariable(
330 (*
m_module), result_global->getValueType(),
false,
331 GlobalValue::ExternalLinkage,
nullptr,
341 ConstantInt *new_constant_int =
342 ConstantInt::get(llvm::Type::getInt64Ty(
m_module->getContext()),
343 reinterpret_cast<uintptr_t
>(result_decl),
false);
345 llvm::Metadata *values[2];
346 values[0] = ConstantAsMetadata::get(new_result_global);
347 values[1] = ConstantAsMetadata::get(new_constant_int);
349 ArrayRef<Metadata *> value_ref(values, 2);
351 MDNode *persistent_global_md = MDNode::get(
m_module->getContext(), value_ref);
352 NamedMDNode *named_metadata =
353 m_module->getNamedMetadata(
"clang.global.decl.ptrs");
354 named_metadata->addOperand(persistent_global_md);
359 if (result_global->use_empty()) {
363 BasicBlock &entry_block(llvm_function.getEntryBlock());
364 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
366 if (!first_entry_instruction)
369 if (!result_global->hasInitializer()) {
370 LLDB_LOG(log,
"Couldn't find initializer for unused variable");
373 "({0}) has no writes and no initializer\n",
379 Constant *initializer = result_global->getInitializer();
381 StoreInst *synthesized_store =
new StoreInst(
382 initializer, new_result_global, first_entry_instruction->getIterator());
384 LLDB_LOG(log,
"Synthesized result store \"{0}\"\n",
387 result_global->replaceAllUsesWith(new_result_global);
394 result_global->eraseFromParent();
400 llvm::GlobalVariable *cstr) {
403 Type *ns_str_ty = ns_str->getType();
405 Type *i8_ptr_ty = PointerType::getUnqual(
m_module->getContext());
406 Type *i32_ty = Type::getInt32Ty(
m_module->getContext());
407 Type *i8_ty = Type::getInt8Ty(
m_module->getContext());
413 "CFStringCreateWithBytes");
415 bool missing_weak =
false;
417 g_CFStringCreateWithBytes_str, missing_weak);
419 LLDB_LOG(log,
"Couldn't find CFStringCreateWithBytes in the target");
422 "constant string requires "
423 "CFStringCreateWithBytes\n");
428 LLDB_LOG(log,
"Found CFStringCreateWithBytes at {0}",
429 CFStringCreateWithBytes_addr);
449 Type *arg_type_array[5];
451 arg_type_array[0] = i8_ptr_ty;
452 arg_type_array[1] = i8_ptr_ty;
454 arg_type_array[3] = i32_ty;
455 arg_type_array[4] = i8_ty;
457 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
459 llvm::FunctionType *CFSCWB_ty =
460 FunctionType::get(ns_str_ty, CFSCWB_arg_types,
false);
463 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
464 Constant *CFSCWB_addr_int =
465 ConstantInt::get(
m_intptr_ty, CFStringCreateWithBytes_addr,
false);
467 CFSCWB_ty, ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty)};
470 ConstantDataSequential *string_array =
nullptr;
473 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
475 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
476 Constant *bytes_arg = cstr ? cstr : Constant::getNullValue(i8_ptr_ty);
477 Constant *numBytes_arg = ConstantInt::get(
478 m_intptr_ty, cstr ? (string_array->getNumElements() - 1) * string_array->getElementByteSize() : 0,
false);
479 int encoding_flags = 0;
480 switch (cstr ? string_array->getElementByteSize() : 1) {
482 encoding_flags = 0x08000100;
485 encoding_flags = 0x0100;
488 encoding_flags = 0x0c000100;
491 encoding_flags = 0x0600;
492 LLDB_LOG(log,
"Encountered an Objective-C constant string with unusual "
494 string_array->getElementByteSize());
496 Constant *encoding_arg = ConstantInt::get(i32_ty, encoding_flags,
false);
497 Constant *isExternal_arg =
498 ConstantInt::get(i8_ty, 0x0,
false);
500 Value *argument_array[5];
502 argument_array[0] = alloc_arg;
503 argument_array[1] = bytes_arg;
504 argument_array[2] = numBytes_arg;
505 argument_array[3] = encoding_arg;
506 argument_array[4] = isExternal_arg;
508 ArrayRef<Value *> CFSCWB_arguments(argument_array, 5);
511 [
this, &CFSCWB_arguments](llvm::Function *function) -> llvm::Value * {
512 return CallInst::Create(
514 "CFStringCreateWithBytes",
515 llvm::cast<Instruction>(
522 LLDB_LOG(log,
"Couldn't replace the NSString with the result of the call");
525 "Objective-C constant string with a dynamic "
531 ns_str->eraseFromParent();
539 ValueSymbolTable &value_symbol_table =
m_module->getValueSymbolTable();
541 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
542 llvm::StringRef value_name = value_symbol.first();
544 if (value_name.contains(
"_unnamed_cfstring_")) {
545 Value *nsstring_value = value_symbol.second;
547 GlobalVariable *nsstring_global =
548 dyn_cast<GlobalVariable>(nsstring_value);
550 if (!nsstring_global) {
551 LLDB_LOG(log,
"NSString variable is not a GlobalVariable");
554 "constant string is not a global variable\n");
559 if (!nsstring_global->hasInitializer()) {
560 LLDB_LOG(log,
"NSString variable does not have an initializer");
563 "constant string does not have an initializer\n");
568 ConstantStruct *nsstring_struct =
569 dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
571 if (!nsstring_struct) {
573 "NSString variable's initializer is not a ConstantStruct");
576 "constant string is not a structure constant\n");
590 if (nsstring_struct->getNumOperands() != 4) {
593 "NSString variable's initializer structure has an "
594 "unexpected number of members. Should be 4, is {0}",
595 nsstring_struct->getNumOperands());
598 "Objective-C constant string is not as "
604 Constant *nsstring_member = nsstring_struct->getOperand(2);
606 if (!nsstring_member) {
607 LLDB_LOG(log,
"NSString initializer's str element was empty");
610 "constant string does not have a string "
616 auto *cstr_global = dyn_cast<GlobalVariable>(nsstring_member);
619 "NSString initializer's str element is not a GlobalVariable");
622 "constant string initializer\n");
627 if (!cstr_global->hasInitializer()) {
628 LLDB_LOG(log,
"NSString initializer's str element does not have an "
632 "constant string's string initializer doesn't "
633 "point to initialized data\n");
668 ConstantDataArray *cstr_array =
669 dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
672 LLDB_LOG(log,
"Found NSString constant {0}, which contains \"{1}\"",
673 value_name, cstr_array->getAsString());
675 LLDB_LOG(log,
"Found NSString constant {0}, which contains \"\"",
679 cstr_global =
nullptr;
682 LLDB_LOG(log,
"Error rewriting the constant string");
692 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
693 llvm::StringRef value_name = value_symbol.first();
695 if (value_name ==
"__CFConstantStringClassReference") {
696 GlobalVariable *gv = dyn_cast<GlobalVariable>(value_symbol.second);
700 "__CFConstantStringClassReference is not a global variable");
703 "CFConstantStringClassReference, but it is not a "
709 gv->eraseFromParent();
719 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
722 !global_variable || !global_variable->hasName() ||
723 !global_variable->getName().starts_with(
"OBJC_SELECTOR_REFERENCES_"));
730 LoadInst *load = dyn_cast<LoadInst>(selector_load);
749 GlobalVariable *_objc_selector_references_ =
750 dyn_cast<GlobalVariable>(load->getPointerOperand());
752 if (!_objc_selector_references_ ||
753 !_objc_selector_references_->hasInitializer())
756 Constant *osr_initializer = _objc_selector_references_->getInitializer();
757 if (!osr_initializer)
762 GlobalVariable *_objc_meth_var_name_ =
763 dyn_cast<GlobalVariable>(osr_initializer);
765 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
768 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
770 ConstantDataArray *omvn_initializer_array =
771 dyn_cast<ConstantDataArray>(omvn_initializer);
773 if (!omvn_initializer_array->isString())
776 std::string omvn_initializer_string =
777 std::string(omvn_initializer_array->getAsString());
779 LLDB_LOG(log,
"Found Objective-C selector reference \"{0}\"",
780 omvn_initializer_string);
787 bool missing_weak =
false;
794 LLDB_LOG(log,
"Found sel_registerName at {0}", sel_registerName_addr);
803 Type *sel_ptr_type = PointerType::getUnqual(
m_module->getContext());
807 type_array[0] = llvm::PointerType::getUnqual(
m_module->getContext());
809 ArrayRef<Type *> srN_arg_types(type_array, 1);
811 llvm::FunctionType *srN_type =
812 FunctionType::get(sel_ptr_type, srN_arg_types,
false);
815 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
816 Constant *srN_addr_int =
817 ConstantInt::get(
m_intptr_ty, sel_registerName_addr,
false);
819 ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty)};
824 "sel_registerName", selector_load->getIterator());
828 selector_load->replaceAllUsesWith(srN_call);
830 selector_load->eraseFromParent();
840 for (Instruction &inst : basic_block) {
841 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
843 selector_loads.push_back(&inst);
846 for (Instruction *inst : selector_loads) {
849 "static reference to an Objective-C selector to a "
850 "dynamic reference\n");
852 LLDB_LOG(log,
"Couldn't rewrite a reference to an Objective-C selector");
865 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
867 MDNode *alloc_md = alloc->getMetadata(
"clang.decl.ptr");
869 if (!alloc_md || !alloc_md->getNumOperands())
872 ConstantInt *constant_int =
873 mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0));
880 uintptr_t ptr = constant_int->getZExtValue();
882 clang::VarDecl *decl =
reinterpret_cast<clang::VarDecl *
>(ptr);
887 StringRef decl_name(decl->getName());
891 result_decl_type,
false,
false))
894 GlobalVariable *persistent_global =
new GlobalVariable(
895 (*
m_module), alloc->getType(),
false,
896 GlobalValue::ExternalLinkage,
nullptr,
897 alloc->getName().str());
902 NamedMDNode *named_metadata =
903 m_module->getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
905 llvm::Metadata *values[2];
906 values[0] = ConstantAsMetadata::get(persistent_global);
907 values[1] = ConstantAsMetadata::get(constant_int);
909 ArrayRef<llvm::Metadata *> value_ref(values, 2);
911 MDNode *persistent_global_md = MDNode::get(
m_module->getContext(), value_ref);
912 named_metadata->addOperand(persistent_global_md);
917 LoadInst *persistent_load =
918 new LoadInst(persistent_global->getValueType(), persistent_global,
"",
919 alloc->getIterator());
924 alloc->replaceAllUsesWith(persistent_load);
925 alloc->eraseFromParent();
938 for (Instruction &inst : basic_block) {
940 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) {
941 llvm::StringRef alloc_name = alloc->getName();
943 if (alloc_name.starts_with(
"$") && !alloc_name.starts_with(
"$__lldb")) {
944 if (alloc_name.find_first_of(
"0123456789") == 1) {
945 LLDB_LOG(log,
"Rejecting a numeric persistent variable.");
948 "$1, ... are reserved for use as result "
954 pvar_allocs.push_back(alloc);
959 for (Instruction *inst : pvar_allocs) {
962 "the creation of a persistent variable\n");
964 LLDB_LOG(log,
"Couldn't rewrite the creation of a persistent variable");
979 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) {
980 switch (constant_expr->getOpcode()) {
983 case Instruction::GetElementPtr:
984 case Instruction::BitCast:
985 Value *s = constant_expr->getOperand(0);
989 }
else if (GlobalVariable *global_variable =
990 dyn_cast<GlobalVariable>(llvm_value_ptr)) {
991 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
994 clang::NamedDecl *named_decl =
DeclForGlobal(global_variable);
1000 if (!global_variable->hasExternalLinkage())
1003 LLDB_LOG(log,
"Found global variable \"{0}\" without metadata",
1004 global_variable->getName());
1009 llvm::StringRef name(named_decl->getName());
1011 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1012 if (value_decl ==
nullptr)
1018 const Type *value_type =
nullptr;
1020 if (name.starts_with(
"$")) {
1032 value_type = PointerType::get(global_variable->getType(), 0);
1034 value_type = global_variable->getType();
1038 std::optional<uint64_t> value_size = compiler_type.
GetByteSize(target);
1041 std::optional<size_t> opt_alignment = compiler_type.
GetTypeBitAlign(target);
1047 "Type of \"{0}\" is [clang \"{1}\", llvm \"{2}\"] [size {3}, "
1051 PrintType(value_type), *value_size, value_alignment);
1055 llvm_value_ptr, *value_size,
1057 }
else if (isa<llvm::Function>(llvm_value_ptr)) {
1058 LLDB_LOG(log,
"Function pointers aren't handled right now");
1076 LLDB_LOG(log,
"Symbol \"{0}\" had no address", name);
1081 LLDB_LOG(log,
"Found \"{0}\" at {1}", name, symbol_addr);
1083 Type *symbol_type = symbol->getType();
1085 Constant *symbol_addr_int = ConstantInt::get(
m_intptr_ty, symbol_addr,
false);
1087 Value *symbol_addr_ptr =
1088 ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1093 symbol->replaceAllUsesWith(symbol_addr_ptr);
1103 for (
unsigned op_index = 0, num_ops = Old->arg_size();
1104 op_index < num_ops; ++op_index)
1108 "one of the arguments of a function call.\n");
1119 GlobalVariable *global_variable =
1120 dyn_cast<GlobalVariable>(classlist_reference);
1122 if (!global_variable)
1125 Constant *initializer = global_variable->getInitializer();
1130 if (!initializer->hasName())
1133 StringRef name(initializer->getName());
1138 LLDB_LOG(log,
"Found reference to Objective-C class {0} ({1})", name,
1139 (
unsigned long long)class_ptr);
1144 if (global_variable->use_empty())
1147 SmallVector<LoadInst *, 2> load_instructions;
1149 for (llvm::User *u : global_variable->users()) {
1150 if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
1151 load_instructions.push_back(load_instruction);
1154 if (load_instructions.empty())
1157 Constant *class_addr = ConstantInt::get(
m_intptr_ty, (uint64_t)class_ptr);
1159 for (LoadInst *load_instruction : load_instructions) {
1160 Constant *class_bitcast =
1161 ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1163 load_instruction->replaceAllUsesWith(class_bitcast);
1165 load_instruction->eraseFromParent();
1172 std::vector<CallInst *> calls_to_remove;
1174 for (Instruction &inst : basic_block) {
1175 CallInst *call = dyn_cast<CallInst>(&inst);
1181 bool remove =
false;
1183 llvm::Function *func = call->getCalledFunction();
1185 if (func && func->getName() ==
"__cxa_atexit")
1188 llvm::Value *val = call->getCalledOperand();
1190 if (val && val->getName() ==
"__cxa_atexit")
1194 calls_to_remove.push_back(call);
1197 for (CallInst *ci : calls_to_remove)
1198 ci->eraseFromParent();
1206 for (Instruction &inst : basic_block) {
1207 CallInst *call = dyn_cast<CallInst>(&inst);
1220 for (GlobalVariable &global_var :
m_module->globals()) {
1221 llvm::StringRef global_name = global_var.getName();
1223 LLDB_LOG(log,
"Examining {0}, DeclForGlobalValue returns {1}", global_name,
1226 if (global_name.starts_with(
"OBJC_IVAR")) {
1229 "indirect ivar symbol {0}\n",
1234 }
else if (global_name.contains(
"OBJC_CLASSLIST_REFERENCES_$")) {
1237 "for an Objective-C static method call\n");
1241 }
else if (global_name.contains(
"OBJC_CLASSLIST_SUP_REFS_$")) {
1244 "for an Objective-C static method call\n");
1251 "external variable {0}\n",
1263 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
1272 Constant *zero(Constant::getNullValue(guard_load->getType()));
1273 guard_load->replaceAllUsesWith(zero);
1274 guard_load->eraseFromParent();
1278 guard_store->eraseFromParent();
1287 for (Instruction &inst : basic_block) {
1289 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1291 guard_loads.push_back(&inst);
1293 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1295 guard_stores.push_back(&inst);
1298 for (Instruction *inst : guard_loads)
1301 for (Instruction *inst : guard_stores)
1309 llvm::Function *llvm_function,
1313 SmallVector<User *, 16> users;
1317 for (llvm::User *u : old_constant->users())
1320 for (
size_t i = 0; i < users.size(); ++i) {
1321 User *user = users[i];
1323 if (Constant *constant = dyn_cast<Constant>(user)) {
1326 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
1327 switch (constant_expr->getOpcode()) {
1329 error_stream.
Printf(
"error [IRForTarget internal]: Unhandled "
1330 "constant expression type: \"%s\"",
1333 case Instruction::BitCast: {
1335 [&value_maker, &entry_instruction_finder, old_constant,
1336 constant_expr](llvm::Function *function) -> llvm::Value * {
1340 if (constant_expr->getOperand(0) != old_constant)
1341 return constant_expr;
1343 return new BitCastInst(
1344 value_maker.
GetValue(function), constant_expr->getType(),
1346 llvm::cast<Instruction>(
1347 entry_instruction_finder.
GetValue(function))
1351 if (!
UnfoldConstant(constant_expr, llvm_function, bit_cast_maker,
1352 entry_instruction_finder, error_stream))
1355 case Instruction::GetElementPtr: {
1361 [&value_maker, &entry_instruction_finder, old_constant,
1362 constant_expr](llvm::Function *function) -> llvm::Value * {
1363 auto *gep = cast<llvm::GEPOperator>(constant_expr);
1364 Value *ptr = gep->getPointerOperand();
1366 if (ptr == old_constant)
1367 ptr = value_maker.
GetValue(function);
1369 std::vector<Value *> index_vector;
1370 for (Value *operand : gep->indices()) {
1371 if (operand == old_constant)
1372 operand = value_maker.
GetValue(function);
1374 index_vector.push_back(operand);
1377 ArrayRef<Value *> indices(index_vector);
1379 return GetElementPtrInst::Create(
1380 gep->getSourceElementType(), ptr, indices,
"",
1381 llvm::cast<Instruction>(
1382 entry_instruction_finder.
GetValue(function))
1387 get_element_pointer_maker,
1388 entry_instruction_finder, error_stream))
1394 "error [IRForTarget internal]: Unhandled constant type: \"%s\"",
1399 if (Instruction *inst = llvm::dyn_cast<Instruction>(user)) {
1400 if (llvm_function && inst->getParent()->getParent() != llvm_function) {
1401 error_stream.
PutCString(
"error: Capturing non-local variables in "
1402 "expressions is unsupported.\n");
1405 inst->replaceUsesOfWith(
1406 old_constant, value_maker.
GetValue(inst->getParent()->getParent()));
1409 "error [IRForTarget internal]: Unhandled non-constant type: \"%s\"",
1416 if (!isa<GlobalValue>(old_constant)) {
1417 old_constant->destroyConstant();
1431 LLDB_LOG(log,
"Element arrangement:");
1433 uint32_t num_elements;
1434 uint32_t element_index;
1442 Function::arg_iterator iter(llvm_function.arg_begin());
1444 if (iter == llvm_function.arg_end()) {
1446 "arguments (should take at least a struct pointer)");
1451 Argument *argument = &*iter;
1453 if (argument->getName() ==
"this") {
1456 if (iter == llvm_function.arg_end()) {
1458 "'this' argument (should take a struct pointer "
1465 }
else if (argument->getName() ==
"self") {
1468 if (iter == llvm_function.arg_end()) {
1470 "'self' argument (should take '_cmd' and a struct "
1476 if (iter->getName() !=
"_cmd") {
1478 "after 'self' argument (should take '_cmd')",
1486 if (iter == llvm_function.arg_end()) {
1488 "'self' and '_cmd' arguments (should take a struct "
1497 if (argument->getName() !=
"$__lldb_arg") {
1499 "argument named '{0}' instead of the struct pointer",
1500 argument->getName());
1507 BasicBlock &entry_block(llvm_function.getEntryBlock());
1508 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
1510 if (!FirstEntryInstruction) {
1512 "first instruction in the wrapper for use in "
1518 LLVMContext &context(
m_module->getContext());
1519 IntegerType *offset_type(Type::getInt32Ty(context));
1523 "Internal error [IRForTarget]: Couldn't produce an offset type");
1528 for (element_index = 0; element_index < num_elements; ++element_index) {
1529 const clang::NamedDecl *decl =
nullptr;
1530 Value *value =
nullptr;
1537 "Internal error [IRForTarget]: Structure information is incomplete");
1542 LLDB_LOG(log,
" \"{0}\" (\"{1}\") placed at {2}", name,
1543 decl->getNameAsString(), offset);
1549 [
this, name, offset_type, offset, argument,
1550 value](llvm::Function *function) -> llvm::Value * {
1557 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(
1560 Type *int8Ty = Type::getInt8Ty(function->getContext());
1561 ConstantInt *offset_int(
1562 ConstantInt::get(offset_type, offset,
true));
1563 GetElementPtrInst *get_element_ptr =
1564 GetElementPtrInst::Create(int8Ty, argument, offset_int,
"",
1565 entry_instruction->getIterator());
1569 new LoadInst(value->getType(), get_element_ptr,
"",
1570 entry_instruction->getIterator());
1574 return get_element_ptr;
1578 if (Constant *constant = dyn_cast<Constant>(value)) {
1583 }
else if (Instruction *instruction = dyn_cast<Instruction>(value)) {
1584 if (instruction->getParent()->getParent() != &llvm_function) {
1586 "expressions is unsupported.\n");
1589 value->replaceAllUsesWith(
1590 body_result_maker.GetValue(instruction->getParent()->getParent()));
1592 LLDB_LOG(log,
"Unhandled non-constant type: \"{0}\"",
1597 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
1598 var->eraseFromParent();
1602 LLDB_LOG(log,
"Total structure [align {0}, size {1}]", (int64_t)alignment,
1618 raw_string_ostream oss(s);
1622 LLDB_LOG(log,
"Module as passed in to IRForTarget: \n\"{0}\"", s);
1625 Function *
const main_function =
1633 "'{0}' in the module",
1639 if (main_function) {
1641 LLDB_LOG(log,
"Couldn't fix the linkage for the function");
1651 if (main_function) {
1653 LLDB_LOG(log,
"CreateResultVariable() failed");
1663 raw_string_ostream oss(s);
1667 LLDB_LOG(log,
"Module after creating the result variable: \n\"{0}\"", s);
1670 for (llvm::Function &function : *
m_module) {
1671 for (BasicBlock &bb : function) {
1673 LLDB_LOG(log,
"RemoveGuards() failed");
1681 LLDB_LOG(log,
"RewritePersistentAllocs() failed");
1690 LLDB_LOG(log,
"RemoveCXAAtExit() failed");
1704 LLDB_LOG(log,
"RewriteObjCConstStrings() failed");
1711 for (llvm::Function &function : *
m_module) {
1712 for (llvm::BasicBlock &bb : function) {
1714 LLDB_LOG(log,
"RewriteObjCSelectors() failed");
1724 for (llvm::Function &function : *
m_module) {
1725 for (BasicBlock &bb : function) {
1727 LLDB_LOG(log,
"ResolveCalls() failed");
1740 if (main_function) {
1742 LLDB_LOG(log,
"ResolveExternals() failed");
1750 LLDB_LOG(log,
"ReplaceVariables() failed");
1760 raw_string_ostream oss(s);
1764 LLDB_LOG(log,
"Module after preparing for execution: \n\"{0}\"", s);
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 std::string PrintValue(const Value *value, bool truncate=false)
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, bool truncate=false)
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.
FunctionValueCache(Maker const &maker)
llvm::Value * GetValue(llvm::Function *function)
std::function< llvm::Value *(llvm::Function *)> Maker
lldb_private::ConstString m_func_name
The name of the function to translate.
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.
IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map, bool resolve_vars, lldb_private::IRExecutionUnit &execution_unit, lldb_private::Stream &error_stream, const char *func_name="$__lldb_expr")
Constructor.
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.
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 ...
static bool 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].
TypeSystemClang * GetTypeSystem() const
Returns the TypeSystem that uses this ClangASTSource instance as it's ExternalASTSource.
"lldb/Expression/ClangExpressionDeclMap.h" Manages named entities that are defined in LLDB's debug in...
bool AddPersistentVariable(const clang::NamedDecl *decl, ConstString name, TypeFromParser type, bool is_result, bool is_lvalue)
[Used by IRForTarget] Add a variable to the list of persistent variables for the process.
bool GetStructElement(const clang::NamedDecl *&decl, llvm::Value *&value, lldb::offset_t &offset, ConstString &name, uint32_t index)
[Used by IRForTarget] Get specific information about one field of the laid-out struct after DoStructL...
bool DoStructLayout()
[Used by IRForTarget] Finalize the struct, laying out the position of each object in it.
bool AddValueToStruct(const clang::NamedDecl *decl, ConstString name, llvm::Value *value, size_t size, lldb::offset_t alignment)
[Used by IRForTarget] Add a variable to the struct that needs to be materialized each time the expres...
lldb::addr_t GetSymbolAddress(Target &target, Process *process, ConstString name, lldb::SymbolType symbol_type, Module *module=nullptr)
[Used by IRForTarget] Get the address of a symbol given nothing but its name.
bool GetStructInfo(uint32_t &num_elements, size_t &size, lldb::offset_t &alignment)
[Used by IRForTarget] Get general information about the laid-out struct after DoStructLayout() has be...
Generic representation of a type in a programming language.
std::optional< uint64_t > GetByteSize(ExecutionContextScope *exe_scope) const
Return the size of the type in bytes.
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
std::optional< size_t > GetTypeBitAlign(ExecutionContextScope *exe_scope) const
A uniqued constant string class.
bool IsEmpty() const
Test for empty string.
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const char * GetCString() const
Get the string value as a C string.
"lldb/Expression/IRExecutionUnit.h" Contains the IR and, optionally, JIT- compiled code for a module.
lldb::addr_t FindSymbol(ConstString name, bool &missing_weak)
lldb::TargetSP GetTarget()
const char * GetData() const
A stream class that can stream formatted output to a file.
void Format(const char *format, Args &&... args)
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
CompilerType GetType(clang::QualType qt)
Creates a CompilerType from the given QualType with the current TypeSystemClang instance as the Compi...
#define LLDB_INVALID_ADDRESS
TaggedASTType< 0 > TypeFromParser
std::shared_ptr< lldb_private::Target > TargetSP
static clang::QualType GetQualType(const CompilerType &ct)