LLDB mainline
IRForTarget.cpp
Go to the documentation of this file.
1//===-- IRForTarget.cpp ---------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "IRForTarget.h"
11
13#include "ClangUtil.h"
14
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"
29
30#include "clang/AST/ASTContext.h"
31
32#include "lldb/Core/dwarf.h"
38#include "lldb/Utility/Endian.h"
40#include "lldb/Utility/Log.h"
41#include "lldb/Utility/Scalar.h"
43
44#include <map>
45#include <optional>
46
47using namespace llvm;
49
50typedef SmallVector<Instruction *, 2> InstrList;
51
54
56
57llvm::Value *
59 if (!m_values.count(function)) {
60 llvm::Value *ret = m_maker(function);
61 m_values[function] = ret;
62 return ret;
63 }
64 return m_values[function];
65}
66
67static llvm::Value *FindEntryInstruction(llvm::Function *function) {
68 if (function->empty())
69 return nullptr;
70
71 return &*function->getEntryBlock().getFirstNonPHIOrDbg();
72}
73
75 bool resolve_vars,
76 lldb_private::IRExecutionUnit &execution_unit,
77 lldb_private::Stream &error_stream,
78 lldb_private::ExecutionPolicy execution_policy,
79 const char *func_name)
80 : m_resolve_vars(resolve_vars), m_func_name(func_name),
81 m_decl_map(decl_map), m_error_stream(error_stream),
82 m_execution_unit(execution_unit), m_policy(execution_policy),
84
85/* Handy utility functions used at several places in the code */
86
87static std::string PrintValue(const Value *value) {
88 if (!value)
89 return {};
90 std::string s;
91 raw_string_ostream rso(s);
92 value->print(rso);
93 return s;
94}
95
96static std::string PrintType(const llvm::Type *type) {
97 if (!type)
98 return {};
99 std::string s;
100 raw_string_ostream rso(s);
101 type->print(rso);
102 return s;
103}
104
105bool IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function) {
106 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
107
108 return true;
109}
110
111clang::NamedDecl *IRForTarget::DeclForGlobal(const GlobalValue *global_val,
112 Module *module) {
113 NamedMDNode *named_metadata =
114 module->getNamedMetadata("clang.global.decl.ptrs");
115
116 if (!named_metadata)
117 return nullptr;
118
119 unsigned num_nodes = named_metadata->getNumOperands();
120 unsigned node_index;
121
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));
125 if (!metadata_node)
126 return nullptr;
127
128 if (metadata_node->getNumOperands() != 2)
129 continue;
130
131 if (mdconst::dyn_extract_or_null<GlobalValue>(
132 metadata_node->getOperand(0)) != global_val)
133 continue;
134
135 ConstantInt *constant_int =
136 mdconst::dyn_extract<ConstantInt>(metadata_node->getOperand(1));
137
138 if (!constant_int)
139 return nullptr;
140
141 uintptr_t ptr = constant_int->getZExtValue();
142
143 return reinterpret_cast<clang::NamedDecl *>(ptr);
144 }
145
146 return nullptr;
147}
148
149clang::NamedDecl *IRForTarget::DeclForGlobal(GlobalValue *global_val) {
150 return DeclForGlobal(global_val, m_module);
151}
152
153/// Returns true iff the mangled symbol is for a static guard variable.
154static bool isGuardVariableSymbol(llvm::StringRef mangled_symbol,
155 bool check_ms_abi = true) {
156 bool result =
157 mangled_symbol.starts_with("_ZGV"); // Itanium ABI guard variable
158 if (check_ms_abi)
159 result |= mangled_symbol.ends_with("@4IA"); // Microsoft ABI
160 return result;
161}
162
163bool IRForTarget::CreateResultVariable(llvm::Function &llvm_function) {
164 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
165
166 if (!m_resolve_vars)
167 return true;
168
169 // Find the result variable. If it doesn't exist, we can give up right here.
170
171 ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable();
172
173 llvm::StringRef result_name;
174 bool found_result = false;
175
176 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
177 result_name = value_symbol.first();
178
179 // Check if this is a guard variable. It seems this causes some hiccups
180 // on Windows, so let's only check for Itanium guard variables.
181 bool is_guard_var = isGuardVariableSymbol(result_name, /*MS ABI*/ false);
182
183 // Skip non-globals, e.g. the MS ABI dynamic initializer function that
184 // shares a mangled name with the result variable.
185 if (!isa<GlobalVariable>(value_symbol.second))
186 continue;
187
188 if (result_name.contains("$__lldb_expr_result_ptr") && !is_guard_var) {
189 found_result = true;
190 m_result_is_pointer = true;
191 break;
192 }
193
194 if (result_name.contains("$__lldb_expr_result") && !is_guard_var) {
195 found_result = true;
196 m_result_is_pointer = false;
197 break;
198 }
199 }
200
201 if (!found_result) {
202 LLDB_LOG(log, "Couldn't find result variable");
203
204 return true;
205 }
206
207 LLDB_LOG(log, "Result name: \"{0}\"", result_name);
208
209 Value *result_value = m_module->getNamedValue(result_name);
210
211 if (!result_value) {
212 LLDB_LOG(log, "Result variable had no data");
213
214 m_error_stream.Format("Internal error [IRForTarget]: Result variable's "
215 "name ({0}) exists, but not its definition\n",
216 result_name);
217
218 return false;
219 }
220
221 LLDB_LOG(log, "Found result in the IR: \"{0}\"", PrintValue(result_value));
222
223 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
224
225 if (!result_global) {
226 LLDB_LOG(log, "Result variable isn't a GlobalVariable");
227
228 m_error_stream.Format("Internal error [IRForTarget]: Result variable ({0}) "
229 "is defined, but is not a global variable\n",
230 result_name);
231
232 return false;
233 }
234
235 clang::NamedDecl *result_decl = DeclForGlobal(result_global);
236 if (!result_decl) {
237 LLDB_LOG(log, "Result variable doesn't have a corresponding Decl");
238
239 m_error_stream.Format("Internal error [IRForTarget]: Result variable ({0}) "
240 "does not have a corresponding Clang entity\n",
241 result_name);
242
243 return false;
244 }
245
246 if (log) {
247 std::string decl_desc_str;
248 raw_string_ostream decl_desc_stream(decl_desc_str);
249 result_decl->print(decl_desc_stream);
250
251 LLDB_LOG(log, "Found result decl: \"{0}\"", decl_desc_str);
252 }
253
254 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
255 if (!result_var) {
256 LLDB_LOG(log, "Result variable Decl isn't a VarDecl");
257
258 m_error_stream.Format("Internal error [IRForTarget]: Result variable "
259 "({0})'s corresponding Clang entity isn't a "
260 "variable\n",
261 result_name);
262
263 return false;
264 }
265
266 // Get the next available result name from m_decl_map and create the
267 // persistent variable for it
268
269 // If the result is an Lvalue, it is emitted as a pointer; see
270 // ASTResultSynthesizer::SynthesizeBodyResult.
272 clang::QualType pointer_qual_type = result_var->getType();
273 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
274
275 const clang::PointerType *pointer_pointertype =
276 pointer_type->getAs<clang::PointerType>();
277 const clang::ObjCObjectPointerType *pointer_objcobjpointertype =
278 pointer_type->getAs<clang::ObjCObjectPointerType>();
279
280 if (pointer_pointertype) {
281 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
282
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);
288
290 m_decl_map->GetTypeSystem()->GetType(element_qual_type));
291 } else {
292 LLDB_LOG(log, "Expected result to have pointer type, but it did not");
293
294 m_error_stream.Format("Internal error [IRForTarget]: Lvalue result ({0}) "
295 "is not a pointer variable\n",
296 result_name);
297
298 return false;
299 }
300 } else {
302 m_decl_map->GetTypeSystem()->GetType(result_var->getType()));
303 }
304
305 lldb::TargetSP target_sp(m_execution_unit.GetTarget());
306 auto bit_size_or_err = m_result_type.GetBitSize(target_sp.get());
307 if (!bit_size_or_err) {
308 lldb_private::StreamString type_desc_stream;
309 m_result_type.DumpTypeDescription(&type_desc_stream);
310
311 LLDB_LOG(log, "Result type has unknown size");
312
313 m_error_stream.Printf("Error [IRForTarget]: Size of result type '%s' "
314 "couldn't be determined\n%s",
315 type_desc_stream.GetData(),
316 llvm::toString(bit_size_or_err.takeError()).c_str());
317 return false;
318 }
319
320 if (log) {
321 lldb_private::StreamString type_desc_stream;
322 m_result_type.DumpTypeDescription(&type_desc_stream);
323
324 LLDB_LOG(log, "Result decl type: \"{0}\"", type_desc_stream.GetData());
325 }
326
328
329 LLDB_LOG(log, "Creating a new result global: \"{0}\" with size {1}",
331 llvm::expectedToOptional(m_result_type.GetByteSize(target_sp.get()))
332 .value_or(0));
333
334 // Construct a new result global and set up its metadata
335
336 GlobalVariable *new_result_global = new GlobalVariable(
337 (*m_module), result_global->getValueType(), false, /* not constant */
338 GlobalValue::ExternalLinkage, nullptr, /* no initializer */
339 m_result_name.GetCString());
340
341 // It's too late in compilation to create a new VarDecl for this, but we
342 // don't need to. We point the metadata at the old VarDecl. This creates an
343 // odd anomaly: a variable with a Value whose name is something like $0 and a
344 // Decl whose name is $__lldb_expr_result. This condition is handled in
345 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
346 // fixed up.
347
348 ConstantInt *new_constant_int =
349 ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
350 reinterpret_cast<uintptr_t>(result_decl), false);
351
352 llvm::Metadata *values[2];
353 values[0] = ConstantAsMetadata::get(new_result_global);
354 values[1] = ConstantAsMetadata::get(new_constant_int);
355
356 ArrayRef<Metadata *> value_ref(values, 2);
357
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);
362
363 LLDB_LOG(log, "Replacing \"{0}\" with \"{1}\"", PrintValue(result_global),
364 PrintValue(new_result_global));
365
366 if (result_global->use_empty()) {
367 // We need to synthesize a store for this variable, because otherwise
368 // there's nothing to put into its equivalent persistent variable.
369
370 BasicBlock &entry_block(llvm_function.getEntryBlock());
371 Instruction *first_entry_instruction(&*entry_block.getFirstNonPHIOrDbg());
372
373 if (!first_entry_instruction)
374 return false;
375
376 if (!result_global->hasInitializer()) {
377 LLDB_LOG(log, "Couldn't find initializer for unused variable");
378
379 m_error_stream.Format("Internal error [IRForTarget]: Result variable "
380 "({0}) has no writes and no initializer\n",
381 result_name);
382
383 return false;
384 }
385
386 Constant *initializer = result_global->getInitializer();
387
388 StoreInst *synthesized_store = new StoreInst(
389 initializer, new_result_global, first_entry_instruction->getIterator());
390
391 LLDB_LOG(log, "Synthesized result store \"{0}\"\n",
392 PrintValue(synthesized_store));
393 } else {
394 result_global->replaceAllUsesWith(new_result_global);
395 }
396
397 if (!m_decl_map->AddPersistentVariable(
398 result_decl, m_result_name, m_result_type, true, m_result_is_pointer))
399 return false;
400
401 result_global->eraseFromParent();
402
403 return true;
404}
405
406bool IRForTarget::RewriteObjCConstString(llvm::GlobalVariable *ns_str,
407 llvm::GlobalVariable *cstr) {
408 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
409
410 Type *ns_str_ty = ns_str->getType();
411
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());
415
417 lldb::addr_t CFStringCreateWithBytes_addr;
418
419 static lldb_private::ConstString g_CFStringCreateWithBytes_str(
420 "CFStringCreateWithBytes");
421
422 bool missing_weak = false;
423 CFStringCreateWithBytes_addr = m_execution_unit.FindSymbol(
424 g_CFStringCreateWithBytes_str, missing_weak);
425 if (CFStringCreateWithBytes_addr == LLDB_INVALID_ADDRESS || missing_weak) {
426 LLDB_LOG(log, "Couldn't find CFStringCreateWithBytes in the target");
427
428 m_error_stream.Printf("Error [IRForTarget]: Rewriting an Objective-C "
429 "constant string requires "
430 "CFStringCreateWithBytes\n");
431
432 return false;
433 }
434
435 LLDB_LOG(log, "Found CFStringCreateWithBytes at {0:x}",
436 CFStringCreateWithBytes_addr);
437
438 // Build the function type:
439 //
440 // CFStringRef CFStringCreateWithBytes (
441 // CFAllocatorRef alloc,
442 // const UInt8 *bytes,
443 // CFIndex numBytes,
444 // CFStringEncoding encoding,
445 // Boolean isExternalRepresentation
446 // );
447 //
448 // We make the following substitutions:
449 //
450 // CFStringRef -> i8*
451 // CFAllocatorRef -> i8*
452 // UInt8 * -> i8*
453 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its
454 // pointer size for now) CFStringEncoding -> i32 Boolean -> i8
455
456 Type *arg_type_array[5];
457
458 arg_type_array[0] = i8_ptr_ty;
459 arg_type_array[1] = i8_ptr_ty;
460 arg_type_array[2] = m_intptr_ty;
461 arg_type_array[3] = i32_ty;
462 arg_type_array[4] = i8_ty;
463
464 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
465
466 llvm::FunctionType *CFSCWB_ty =
467 FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
468
469 // Build the constant containing the pointer to the function
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)};
475 }
476
477 ConstantDataSequential *string_array = nullptr;
478
479 if (cstr)
480 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
481
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) {
488 case 1:
489 encoding_flags = 0x08000100; /* 0x08000100 is kCFStringEncodingUTF8 */
490 break;
491 case 2:
492 encoding_flags = 0x0100; /* 0x0100 is kCFStringEncodingUTF16 */
493 break;
494 case 4:
495 encoding_flags = 0x0c000100; /* 0x0c000100 is kCFStringEncodingUTF32 */
496 break;
497 default:
498 encoding_flags = 0x0600; /* fall back to 0x0600, kCFStringEncodingASCII */
499 LLDB_LOG(log, "Encountered an Objective-C constant string with unusual "
500 "element size {0}",
501 string_array->getElementByteSize());
502 }
503 Constant *encoding_arg = ConstantInt::get(i32_ty, encoding_flags, false);
504 Constant *isExternal_arg =
505 ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
506
507 Value *argument_array[5];
508
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;
514
515 ArrayRef<Value *> CFSCWB_arguments(argument_array, 5);
516
517 FunctionValueCache CFSCWB_Caller(
518 [this, &CFSCWB_arguments](llvm::Function *function) -> llvm::Value * {
519 return CallInst::Create(
520 m_CFStringCreateWithBytes, CFSCWB_arguments,
521 "CFStringCreateWithBytes",
522 llvm::cast<Instruction>(
523 m_entry_instruction_finder.GetValue(function))
524 ->getIterator());
525 });
526
527 if (auto err = UnfoldConstant(ns_str, nullptr, CFSCWB_Caller,
529 std::string error_msg = llvm::toString(std::move(err));
530 LLDB_LOG(log,
531 "Couldn't replace the NSString with the result of the call: {0}",
532 error_msg);
533
534 m_error_stream.Format("error [IRForTarget internal]: Couldn't replace an "
535 "Objective-C constant string with a dynamic "
536 "string\n{0}",
537 error_msg);
538
539 return false;
540 }
541
542 ns_str->eraseFromParent();
543
544 return true;
545}
546
548 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
549
550 ValueSymbolTable &value_symbol_table = m_module->getValueSymbolTable();
551
552 std::vector<std::pair<GlobalVariable *, GlobalVariable *>>
553 nsstring_to_cstr_list;
554
555 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
556 llvm::StringRef value_name = value_symbol.first();
557
558 if (value_name.contains("_unnamed_cfstring_")) {
559 Value *nsstring_value = value_symbol.second;
560
561 GlobalVariable *nsstring_global =
562 dyn_cast<GlobalVariable>(nsstring_value);
563
564 if (!nsstring_global) {
565 LLDB_LOG(log, "NSString variable is not a GlobalVariable");
566
567 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
568 "constant string is not a global variable\n");
569
570 return false;
571 }
572
573 if (!nsstring_global->hasInitializer()) {
574 LLDB_LOG(log, "NSString variable does not have an initializer");
575
576 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
577 "constant string does not have an initializer\n");
578
579 return false;
580 }
581
582 ConstantStruct *nsstring_struct =
583 dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
584
585 if (!nsstring_struct) {
586 LLDB_LOG(log,
587 "NSString variable's initializer is not a ConstantStruct");
588
589 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
590 "constant string is not a structure constant\n");
591
592 return false;
593 }
594
595 // We expect the following structure:
596 //
597 // struct {
598 // int *isa;
599 // int flags;
600 // char *str;
601 // long length;
602 // };
603
604 if (nsstring_struct->getNumOperands() != 4) {
605
606 LLDB_LOG(log,
607 "NSString variable's initializer structure has an "
608 "unexpected number of members. Should be 4, is {0}",
609 nsstring_struct->getNumOperands());
610
611 m_error_stream.Printf("Internal error [IRForTarget]: The struct for an "
612 "Objective-C constant string is not as "
613 "expected\n");
614
615 return false;
616 }
617
618 Constant *nsstring_member = nsstring_struct->getOperand(2);
619
620 if (!nsstring_member) {
621 LLDB_LOG(log, "NSString initializer's str element was empty");
622
623 m_error_stream.Printf("Internal error [IRForTarget]: An Objective-C "
624 "constant string does not have a string "
625 "initializer\n");
626
627 return false;
628 }
629
630 auto *cstr_global = dyn_cast<GlobalVariable>(nsstring_member);
631 if (!cstr_global) {
632 LLDB_LOG(log,
633 "NSString initializer's str element is not a GlobalVariable");
634
635 m_error_stream.Printf("Internal error [IRForTarget]: Unhandled"
636 "constant string initializer\n");
637
638 return false;
639 }
640
641 if (!cstr_global->hasInitializer()) {
642 LLDB_LOG(log, "NSString initializer's str element does not have an "
643 "initializer");
644
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");
648
649 return false;
650 }
651
652 /*
653 if (!cstr_array)
654 {
655 if (log)
656 log->PutCString("NSString initializer's str element is not a
657 ConstantArray");
658
659 if (m_error_stream)
660 m_error_stream.Printf("Internal error [IRForTarget]: An
661 Objective-C constant string's string initializer doesn't point to an
662 array\n");
663
664 return false;
665 }
666
667 if (!cstr_array->isCString())
668 {
669 if (log)
670 log->PutCString("NSString initializer's str element is not a C
671 string array");
672
673 if (m_error_stream)
674 m_error_stream.Printf("Internal error [IRForTarget]: An
675 Objective-C constant string's string initializer doesn't point to a C
676 string\n");
677
678 return false;
679 }
680 */
681
682 ConstantDataArray *cstr_array =
683 dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
684
685 if (cstr_array)
686 LLDB_LOG(log, "Found NSString constant {0}, which contains \"{1}\"",
687 value_name, cstr_array->getAsString());
688 else
689 LLDB_LOG(log, "Found NSString constant {0}, which contains \"\"",
690 value_name);
691
692 if (!cstr_array)
693 cstr_global = nullptr;
694
695 // Queue up replacing the string as we are currently iterating
696 // over the module.
697 nsstring_to_cstr_list.emplace_back(nsstring_global, cstr_global);
698 }
699 }
700
701 for (auto [nsstring_global, cstr_global] : nsstring_to_cstr_list) {
702 if (!RewriteObjCConstString(nsstring_global, cstr_global)) {
703 LLDB_LOG(log, "Error rewriting the constant string");
704 return false;
705 }
706 }
707
708 for (StringMapEntry<llvm::Value *> &value_symbol : value_symbol_table) {
709 llvm::StringRef value_name = value_symbol.first();
710
711 if (value_name == "__CFConstantStringClassReference") {
712 GlobalVariable *gv = dyn_cast<GlobalVariable>(value_symbol.second);
713
714 if (!gv) {
715 LLDB_LOG(log,
716 "__CFConstantStringClassReference is not a global variable");
717
718 m_error_stream.Printf("Internal error [IRForTarget]: Found a "
719 "CFConstantStringClassReference, but it is not a "
720 "global object\n");
721
722 return false;
723 }
724
725 gv->eraseFromParent();
726
727 break;
728 }
729 }
730
731 return true;
732}
733
734static bool IsObjCSelectorRef(Value *value) {
735 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
736
737 return !(
738 !global_variable || !global_variable->hasName() ||
739 !global_variable->getName().starts_with("OBJC_SELECTOR_REFERENCES_"));
740}
741
742// This function does not report errors; its callers are responsible.
743bool IRForTarget::RewriteObjCSelector(Instruction *selector_load) {
744 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
745
746 LoadInst *load = dyn_cast<LoadInst>(selector_load);
747
748 if (!load)
749 return false;
750
751 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend
752 // gets represented as
753 //
754 // %sel = load ptr, ptr @OBJC_SELECTOR_REFERENCES_, align 8
755 // call i8 @objc_msgSend(ptr %obj, ptr %sel, ...)
756 //
757 // where %obj is the object pointer and %sel is the selector.
758 //
759 // @"OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called
760 // @"\01L_OBJC_METH_VAR_NAME_".
761 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
762
763 // Find the pointer's initializer and get the string from its target.
764
765 GlobalVariable *_objc_selector_references_ =
766 dyn_cast<GlobalVariable>(load->getPointerOperand());
767
768 if (!_objc_selector_references_ ||
769 !_objc_selector_references_->hasInitializer())
770 return false;
771
772 Constant *osr_initializer = _objc_selector_references_->getInitializer();
773 if (!osr_initializer)
774 return false;
775
776 // Find the string's initializer (a ConstantArray) and get the string from it
777
778 GlobalVariable *_objc_meth_var_name_ =
779 dyn_cast<GlobalVariable>(osr_initializer);
780
781 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
782 return false;
783
784 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
785
786 ConstantDataArray *omvn_initializer_array =
787 dyn_cast<ConstantDataArray>(omvn_initializer);
788
789 if (!omvn_initializer_array->isString())
790 return false;
791
792 std::string omvn_initializer_string =
793 std::string(omvn_initializer_array->getAsString());
794
795 LLDB_LOG(log, "Found Objective-C selector reference \"{0}\"",
796 omvn_initializer_string);
797
798 // Construct a call to sel_registerName
799
800 if (!m_sel_registerName) {
801 lldb::addr_t sel_registerName_addr;
802
803 bool missing_weak = false;
804 static lldb_private::ConstString g_sel_registerName_str("sel_registerName");
805 sel_registerName_addr = m_execution_unit.FindSymbol(g_sel_registerName_str,
806 missing_weak);
807 if (sel_registerName_addr == LLDB_INVALID_ADDRESS || missing_weak)
808 return false;
809
810 LLDB_LOG(log, "Found sel_registerName at {0:x}", sel_registerName_addr);
811
812 // Build the function type: struct objc_selector
813 // *sel_registerName(uint8_t*)
814
815 // The below code would be "more correct," but in actuality what's required
816 // is uint8_t*
817 // Type *sel_type = StructType::get(m_module->getContext());
818 // Type *sel_ptr_type = PointerType::getUnqual(sel_type);
819 Type *sel_ptr_type = PointerType::getUnqual(m_module->getContext());
820
821 Type *type_array[1];
822
823 type_array[0] = llvm::PointerType::getUnqual(m_module->getContext());
824
825 ArrayRef<Type *> srN_arg_types(type_array, 1);
826
827 llvm::FunctionType *srN_type =
828 FunctionType::get(sel_ptr_type, srN_arg_types, false);
829
830 // Build the constant containing the pointer to the function
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);
834 m_sel_registerName = {srN_type,
835 ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty)};
836 }
837
838 CallInst *srN_call =
839 CallInst::Create(m_sel_registerName, _objc_meth_var_name_,
840 "sel_registerName", selector_load->getIterator());
841
842 // Replace the load with the call in all users
843
844 selector_load->replaceAllUsesWith(srN_call);
845
846 selector_load->eraseFromParent();
847
848 return true;
849}
850
851bool IRForTarget::RewriteObjCSelectors(BasicBlock &basic_block) {
852 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
853
854 InstrList selector_loads;
855
856 for (Instruction &inst : basic_block) {
857 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
858 if (IsObjCSelectorRef(load->getPointerOperand()))
859 selector_loads.push_back(&inst);
860 }
861
862 for (Instruction *inst : selector_loads) {
863 if (!RewriteObjCSelector(inst)) {
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");
867
868 LLDB_LOG(log, "Couldn't rewrite a reference to an Objective-C selector");
869
870 return false;
871 }
872 }
873
874 return true;
875}
876
877// This function does not report errors; its callers are responsible.
878bool IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc) {
879 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
880
881 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
882
883 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
884
885 if (!alloc_md || !alloc_md->getNumOperands())
886 return false;
887
888 ConstantInt *constant_int =
889 mdconst::dyn_extract<ConstantInt>(alloc_md->getOperand(0));
890
891 if (!constant_int)
892 return false;
893
894 // We attempt to register this as a new persistent variable with the DeclMap.
895
896 uintptr_t ptr = constant_int->getZExtValue();
897
898 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
899
900 lldb_private::TypeFromParser result_decl_type(
901 m_decl_map->GetTypeSystem()->GetType(decl->getType()));
902
903 StringRef decl_name(decl->getName());
904 lldb_private::ConstString persistent_variable_name(decl_name);
905 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name,
906 result_decl_type, false, false))
907 return false;
908
909 GlobalVariable *persistent_global = new GlobalVariable(
910 (*m_module), alloc->getType(), false, /* not constant */
911 GlobalValue::ExternalLinkage, nullptr, /* no initializer */
912 alloc->getName().str());
913
914 // What we're going to do here is make believe this was a regular old
915 // external variable. That means we need to make the metadata valid.
916
917 NamedMDNode *named_metadata =
918 m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
919
920 llvm::Metadata *values[2];
921 values[0] = ConstantAsMetadata::get(persistent_global);
922 values[1] = ConstantAsMetadata::get(constant_int);
923
924 ArrayRef<llvm::Metadata *> value_ref(values, 2);
925
926 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
927 named_metadata->addOperand(persistent_global_md);
928
929 // Now, since the variable is a pointer variable, we will drop in a load of
930 // that pointer variable.
931
932 LoadInst *persistent_load =
933 new LoadInst(persistent_global->getValueType(), persistent_global, "",
934 alloc->getIterator());
935
936 LLDB_LOG(log, "Replacing \"{0}\" with \"{1}\"", PrintValue(alloc),
937 PrintValue(persistent_load));
938
939 alloc->replaceAllUsesWith(persistent_load);
940 alloc->eraseFromParent();
941
942 return true;
943}
944
945bool IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block) {
946 if (!m_resolve_vars)
947 return true;
948
949 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
950
951 InstrList pvar_allocs;
952
953 for (Instruction &inst : basic_block) {
954
955 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst)) {
956 llvm::StringRef alloc_name = alloc->getName();
957
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.");
961
962 m_error_stream.Printf("Error [IRForTarget]: Names starting with $0, "
963 "$1, ... are reserved for use as result "
964 "names\n");
965
966 return false;
967 }
968
969 pvar_allocs.push_back(alloc);
970 }
971 }
972 }
973
974 for (Instruction *inst : pvar_allocs) {
975 if (!RewritePersistentAlloc(inst)) {
976 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
977 "the creation of a persistent variable\n");
978
979 LLDB_LOG(log, "Couldn't rewrite the creation of a persistent variable");
980
981 return false;
982 }
983 }
984
985 return true;
986}
987
988// This function does not report errors; its callers are responsible.
989bool IRForTarget::MaybeHandleVariable(Value *llvm_value_ptr) {
990 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
991
992 LLDB_LOG(log, "MaybeHandleVariable ({0})", PrintValue(llvm_value_ptr));
993
994 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr)) {
995 switch (constant_expr->getOpcode()) {
996 default:
997 break;
998 case Instruction::GetElementPtr:
999 case Instruction::BitCast:
1000 Value *s = constant_expr->getOperand(0);
1001 if (!MaybeHandleVariable(s))
1002 return false;
1003 }
1004 } else if (GlobalVariable *global_variable =
1005 dyn_cast<GlobalVariable>(llvm_value_ptr)) {
1006 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1007 return true;
1008
1009 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
1010
1011 if (!named_decl) {
1012 if (IsObjCSelectorRef(llvm_value_ptr))
1013 return true;
1014
1015 if (!global_variable->hasExternalLinkage())
1016 return true;
1017
1018 LLDB_LOG(log, "Found global variable \"{0}\" without metadata",
1019 global_variable->getName());
1020
1021 return false;
1022 }
1023
1024 llvm::StringRef name(named_decl->getName());
1025
1026 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1027 if (value_decl == nullptr)
1028 return false;
1029
1030 lldb_private::CompilerType compiler_type =
1031 m_decl_map->GetTypeSystem()->GetType(value_decl->getType());
1032
1033 const Type *value_type = nullptr;
1034
1035 if (name.starts_with("$")) {
1036 // The $__lldb_expr_result name indicates the return value has allocated
1037 // as a static variable. Per the comment at
1038 // ASTResultSynthesizer::SynthesizeBodyResult, accesses to this static
1039 // variable need to be redirected to the result of dereferencing a
1040 // pointer that is passed in as one of the arguments.
1041 //
1042 // Consequently, when reporting the size of the type, we report a pointer
1043 // type pointing to the type of $__lldb_expr_result, not the type itself.
1044 //
1045 // We also do this for any user-declared persistent variables.
1046 compiler_type = compiler_type.GetPointerType();
1047 value_type = PointerType::getUnqual(global_variable->getContext());
1048 } else {
1049 value_type = global_variable->getType();
1050 }
1051
1052 auto *target = m_execution_unit.GetTarget().get();
1053 std::optional<uint64_t> value_size =
1054 llvm::expectedToOptional(compiler_type.GetByteSize(target));
1055 if (!value_size)
1056 return false;
1057 std::optional<size_t> opt_alignment = compiler_type.GetTypeBitAlign(target);
1058 if (!opt_alignment)
1059 return false;
1060 lldb::offset_t value_alignment = (*opt_alignment + 7ull) / 8ull;
1061
1062 LLDB_LOG(log,
1063 "Type of \"{0}\" is [clang \"{1}\", llvm \"{2}\"] [size {3}, "
1064 "align {4}]",
1065 name,
1066 lldb_private::ClangUtil::GetQualType(compiler_type).getAsString(),
1067 PrintType(value_type), *value_size, value_alignment);
1068
1069 if (named_decl)
1070 m_decl_map->AddValueToStruct(named_decl, lldb_private::ConstString(name),
1071 llvm_value_ptr, *value_size,
1072 value_alignment);
1073 } else if (isa<llvm::Function>(llvm_value_ptr)) {
1074 LLDB_LOG(log, "Function pointers aren't handled right now");
1075
1076 return false;
1077 }
1078
1079 return true;
1080}
1081
1082// This function does not report errors; its callers are responsible.
1083bool IRForTarget::HandleSymbol(Value *symbol) {
1084 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1085
1086 lldb_private::ConstString name(symbol->getName());
1087
1088 lldb::addr_t symbol_addr =
1089 m_decl_map->GetSymbolAddress(name, lldb::eSymbolTypeAny);
1090
1091 if (symbol_addr == LLDB_INVALID_ADDRESS) {
1092 LLDB_LOG(log, "Symbol \"{0}\" had no address", name);
1093
1094 return false;
1095 }
1096
1097 LLDB_LOG(log, "Found \"{0}\" at {1:x}", name, symbol_addr);
1098
1099 Type *symbol_type = symbol->getType();
1100
1101 Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false);
1102
1103 Value *symbol_addr_ptr =
1104 ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1105
1106 LLDB_LOG(log, "Replacing {0} with {1}", PrintValue(symbol),
1107 PrintValue(symbol_addr_ptr));
1108
1109 symbol->replaceAllUsesWith(symbol_addr_ptr);
1110
1111 return true;
1112}
1113
1115 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1116
1117 LLDB_LOG(log, "MaybeHandleCallArguments({0})", PrintValue(Old));
1118
1119 for (unsigned op_index = 0, num_ops = Old->arg_size();
1120 op_index < num_ops; ++op_index)
1121 // conservatively believe that this is a store
1122 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) {
1123 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't rewrite "
1124 "one of the arguments of a function call.\n");
1125
1126 return false;
1127 }
1128
1129 return true;
1130}
1131
1132bool IRForTarget::HandleObjCClass(Value *classlist_reference) {
1133 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1134
1135 GlobalVariable *global_variable =
1136 dyn_cast<GlobalVariable>(classlist_reference);
1137
1138 if (!global_variable)
1139 return false;
1140
1141 Constant *initializer = global_variable->getInitializer();
1142
1143 if (!initializer)
1144 return false;
1145
1146 if (!initializer->hasName())
1147 return false;
1148
1149 StringRef name(initializer->getName());
1150 lldb_private::ConstString name_cstr(name);
1151 lldb::addr_t class_ptr =
1152 m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
1153
1154 LLDB_LOG(log, "Found reference to Objective-C class {0} ({1:x})", name,
1155 (unsigned long long)class_ptr);
1156
1157 if (class_ptr == LLDB_INVALID_ADDRESS)
1158 return false;
1159
1160 if (global_variable->use_empty())
1161 return false;
1162
1163 SmallVector<LoadInst *, 2> load_instructions;
1164
1165 for (llvm::User *u : global_variable->users()) {
1166 if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
1167 load_instructions.push_back(load_instruction);
1168 }
1169
1170 if (load_instructions.empty())
1171 return false;
1172
1173 Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr);
1174
1175 for (LoadInst *load_instruction : load_instructions) {
1176 Constant *class_bitcast =
1177 ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1178
1179 load_instruction->replaceAllUsesWith(class_bitcast);
1180
1181 load_instruction->eraseFromParent();
1182 }
1183
1184 return true;
1185}
1186
1187bool IRForTarget::RemoveCXAAtExit(BasicBlock &basic_block) {
1188 std::vector<CallInst *> calls_to_remove;
1189 llvm::SmallVector<llvm::Function *, 2> dead_atexit_callbacks;
1190
1191 for (Instruction &inst : basic_block) {
1192 CallInst *call = dyn_cast<CallInst>(&inst);
1193
1194 // MaybeHandleCallArguments handles error reporting; we are silent here
1195 if (!call)
1196 continue;
1197
1198 bool remove = false;
1199
1200 llvm::Function *func = call->getCalledFunction();
1201
1202 // Itanium ABI uses __cxa_atexit; MS ABI uses plain atexit.
1203 if (func &&
1204 (func->getName() == "__cxa_atexit" || func->getName() == "atexit"))
1205 remove = true;
1206
1207 llvm::Value *val = call->getCalledOperand();
1208
1209 if (val && (val->getName() == "__cxa_atexit" || val->getName() == "atexit"))
1210 remove = true;
1211
1212 if (remove) {
1213 // MS ABI destructor thunks (mangled "??__F...") reference the static
1214 // they destroy; track them to clear once the call is gone.
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);
1221 }
1222 }
1223
1224 for (CallInst *ci : calls_to_remove)
1225 ci->eraseFromParent();
1226
1227 // Clear the body of any orphaned atexit-destructor thunk so it no longer
1228 // references the statics it used to destroy.
1229 for (llvm::Function *cb : dead_atexit_callbacks) {
1230 if (!cb->use_empty())
1231 continue;
1232 cb->deleteBody();
1233 llvm::BasicBlock *entry =
1234 llvm::BasicBlock::Create(cb->getContext(), "", cb);
1235 llvm::ReturnInst::Create(cb->getContext(), entry);
1236 }
1237
1238 return true;
1239}
1240
1241bool IRForTarget::ResolveCalls(BasicBlock &basic_block) {
1242 // Prepare the current basic block for execution in the remote process
1243
1244 for (Instruction &inst : basic_block) {
1245 CallInst *call = dyn_cast<CallInst>(&inst);
1246
1247 // MaybeHandleCallArguments handles error reporting; we are silent here
1248 if (call && !MaybeHandleCallArguments(call))
1249 return false;
1250 }
1251
1252 return true;
1253}
1254
1255bool IRForTarget::ResolveExternals(Function &llvm_function) {
1256 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1257
1258 for (GlobalVariable &global_var : m_module->globals()) {
1259 llvm::StringRef global_name = global_var.getName();
1260
1261 LLDB_LOG(log, "Examining {0}, DeclForGlobalValue returns {1}", global_name,
1262 static_cast<void *>(DeclForGlobal(&global_var)));
1263
1264 if (global_name.starts_with("OBJC_IVAR")) {
1265 if (!HandleSymbol(&global_var)) {
1266 m_error_stream.Format("Error [IRForTarget]: Couldn't find Objective-C "
1267 "indirect ivar symbol {0}\n",
1268 global_name);
1269
1270 return false;
1271 }
1272 } else if (global_name.contains("OBJC_CLASSLIST_REFERENCES_$")) {
1273 if (!HandleObjCClass(&global_var)) {
1274 m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class "
1275 "for an Objective-C static method call\n");
1276
1277 return false;
1278 }
1279 } else if (global_name.contains("OBJC_CLASSLIST_SUP_REFS_$")) {
1280 if (!HandleObjCClass(&global_var)) {
1281 m_error_stream.Printf("Error [IRForTarget]: Couldn't resolve the class "
1282 "for an Objective-C static method call\n");
1283
1284 return false;
1285 }
1286 } else if (DeclForGlobal(&global_var)) {
1287 if (!MaybeHandleVariable(&global_var)) {
1288 m_error_stream.Format("Internal error [IRForTarget]: Couldn't rewrite "
1289 "external variable {0}\n",
1290 global_name);
1291
1292 return false;
1293 }
1294 }
1295 }
1296
1297 return true;
1298}
1299
1300static bool isGuardVariableRef(Value *V) {
1301 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
1302
1303 if (!GV || !GV->hasName() || !isGuardVariableSymbol(GV->getName()))
1304 return false;
1305
1306 return true;
1307}
1308
1309void IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction *guard_load) {
1310 Constant *zero(Constant::getNullValue(guard_load->getType()));
1311 guard_load->replaceAllUsesWith(zero);
1312 guard_load->eraseFromParent();
1313}
1314
1315static void ExciseGuardStore(Instruction *guard_store) {
1316 guard_store->eraseFromParent();
1317}
1318
1319bool IRForTarget::RemoveGuards(BasicBlock &basic_block) {
1320 // Eliminate any reference to guard variables found.
1321
1322 InstrList guard_loads;
1323 InstrList guard_stores;
1324
1325 for (Instruction &inst : basic_block) {
1326
1327 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1328 if (isGuardVariableRef(load->getPointerOperand()))
1329 guard_loads.push_back(&inst);
1330
1331 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1332 if (isGuardVariableRef(store->getPointerOperand()))
1333 guard_stores.push_back(&inst);
1334 }
1335
1336 for (Instruction *inst : guard_loads)
1338
1339 for (Instruction *inst : guard_stores)
1340 ExciseGuardStore(inst);
1341
1342 return true;
1343}
1344
1345llvm::Error
1346IRForTarget::UnfoldConstant(Constant *old_constant,
1347 llvm::Function *llvm_function,
1348 FunctionValueCache &value_maker,
1349 FunctionValueCache &entry_instruction_finder,
1350 lldb_private::Stream &error_stream) {
1351 SmallVector<User *, 16> users;
1352
1353 // We do this because the use list might change, invalidating our iterator.
1354 // Much better to keep a work list ourselves.
1355 for (llvm::User *u : old_constant->users())
1356 users.push_back(u);
1357
1358 for (User *user : users) {
1359 if (Constant *constant = dyn_cast<Constant>(user)) {
1360 // synthesize a new non-constant equivalent of the constant
1361
1362 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant)) {
1363 switch (constant_expr->getOpcode()) {
1364 default:
1365 return llvm::createStringErrorV(
1366 "unhandled constant expression type: \"{0}\".",
1367 PrintValue(constant_expr));
1368
1369 case Instruction::BitCast: {
1370 FunctionValueCache bit_cast_maker(
1371 [&value_maker, &entry_instruction_finder, old_constant,
1372 constant_expr](llvm::Function *function) -> llvm::Value * {
1373 // UnaryExpr
1374 // OperandList[0] is value
1375
1376 if (constant_expr->getOperand(0) != old_constant)
1377 return constant_expr;
1378
1379 return new BitCastInst(
1380 value_maker.GetValue(function), constant_expr->getType(),
1381 "",
1382 llvm::cast<Instruction>(
1383 entry_instruction_finder.GetValue(function))
1384 ->getIterator());
1385 });
1386
1387 if (auto err =
1388 UnfoldConstant(constant_expr, llvm_function, bit_cast_maker,
1389 entry_instruction_finder, error_stream))
1390 return err;
1391 } break;
1392 case Instruction::GetElementPtr: {
1393 // GetElementPtrConstantExpr
1394 // OperandList[0] is base
1395 // OperandList[1]... are indices
1396
1397 FunctionValueCache get_element_pointer_maker(
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();
1402
1403 if (ptr == old_constant)
1404 ptr = value_maker.GetValue(function);
1405
1406 std::vector<Value *> index_vector;
1407 for (Value *operand : gep->indices()) {
1408 if (operand == old_constant)
1409 operand = value_maker.GetValue(function);
1410
1411 index_vector.push_back(operand);
1412 }
1413
1414 ArrayRef<Value *> indices(index_vector);
1415
1416 return GetElementPtrInst::Create(
1417 gep->getSourceElementType(), ptr, indices, "",
1418 llvm::cast<Instruction>(
1419 entry_instruction_finder.GetValue(function))
1420 ->getIterator());
1421 });
1422
1423 if (auto err = UnfoldConstant(constant_expr, llvm_function,
1424 get_element_pointer_maker,
1425 entry_instruction_finder, error_stream))
1426 return err;
1427 } break;
1428 }
1429 } else if (ConstantPtrAuth *constant_ptr_auth =
1430 dyn_cast<ConstantPtrAuth>(constant)) {
1431 // No need to handle ConstantPtrAuth users if old_constant is an address
1432 // discriminator.
1433 if (constant_ptr_auth->hasAddressDiscriminator() &&
1434 constant_ptr_auth->getAddrDiscriminator() == old_constant)
1435 continue;
1436
1437 return llvm::createStringErrorV("unhandled constant type \"{0}\".",
1438 PrintValue(constant_ptr_auth));
1439 } else {
1440 return llvm::createStringErrorV("unhandled constant type \"{0}\".",
1441 PrintValue(constant));
1442 }
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.");
1447
1448 inst->replaceUsesOfWith(
1449 old_constant, value_maker.GetValue(inst->getParent()->getParent()));
1450 } else {
1451 return llvm::createStringErrorV("unhandled non-constant type: \"{0}\".",
1452 PrintValue(user));
1453 }
1454 }
1455
1456 if (!isa<GlobalValue>(old_constant)) {
1457 old_constant->destroyConstant();
1458 }
1459
1460 return llvm::Error::success();
1461}
1462
1463bool IRForTarget::ReplaceVariables(Function &llvm_function) {
1464 if (!m_resolve_vars)
1465 return true;
1466
1467 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1468
1469 m_decl_map->DoStructLayout();
1470
1471 LLDB_LOG(log, "Element arrangement:");
1472
1473 uint32_t num_elements;
1474 uint32_t element_index;
1475
1476 size_t size;
1477 lldb::offset_t alignment;
1478
1479 if (!m_decl_map->GetStructInfo(num_elements, size, alignment))
1480 return false;
1481
1482 Function::arg_iterator iter(llvm_function.arg_begin());
1483
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)");
1487
1488 return false;
1489 }
1490
1491 Argument *argument = &*iter;
1492
1493 if (argument->getName() == "this") {
1494 ++iter;
1495
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 "
1499 "too)");
1500
1501 return false;
1502 }
1503
1504 argument = &*iter;
1505 } else if (argument->getName() == "self") {
1506 ++iter;
1507
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 "
1511 "pointer too)");
1512
1513 return false;
1514 }
1515
1516 if (iter->getName() != "_cmd") {
1517 m_error_stream.Format("Internal error [IRForTarget]: Wrapper takes '{0}' "
1518 "after 'self' argument (should take '_cmd')",
1519 iter->getName());
1520
1521 return false;
1522 }
1523
1524 ++iter;
1525
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 "
1529 "pointer too)");
1530
1531 return false;
1532 }
1533
1534 argument = &*iter;
1535 }
1536
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());
1541
1542 return false;
1543 }
1544
1545 LLDB_LOG(log, "Arg: \"{0}\"", PrintValue(argument));
1546
1547 BasicBlock &entry_block(llvm_function.getEntryBlock());
1548 Instruction *FirstEntryInstruction(&*entry_block.getFirstNonPHIOrDbg());
1549
1550 if (!FirstEntryInstruction) {
1551 m_error_stream.Printf("Internal error [IRForTarget]: Couldn't find the "
1552 "first instruction in the wrapper for use in "
1553 "rewriting");
1554
1555 return false;
1556 }
1557
1558 LLVMContext &context(m_module->getContext());
1559 IntegerType *offset_type(Type::getInt32Ty(context));
1560
1561 if (!offset_type) {
1562 m_error_stream.Printf(
1563 "Internal error [IRForTarget]: Couldn't produce an offset type");
1564
1565 return false;
1566 }
1567
1568 for (element_index = 0; element_index < num_elements; ++element_index) {
1569 const clang::NamedDecl *decl = nullptr;
1570 Value *value = nullptr;
1571 lldb::offset_t offset;
1573
1574 if (!m_decl_map->GetStructElement(decl, value, offset, name,
1575 element_index)) {
1576 m_error_stream.Printf(
1577 "Internal error [IRForTarget]: Structure information is incomplete");
1578
1579 return false;
1580 }
1581
1582 LLDB_LOG(log, " \"{0}\" (\"{1}\") placed at {2}", name,
1583 decl->getNameAsString(), offset);
1584
1585 if (value) {
1586 LLDB_LOG(log, " Replacing [{0}]", PrintValue(value));
1587
1588 FunctionValueCache body_result_maker(
1589 [this, name, offset_type, offset, argument,
1590 value](llvm::Function *function) -> llvm::Value * {
1591 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1592 // in cases where the result variable is an rvalue, we have to
1593 // synthesize a dereference of the appropriate structure entry in
1594 // order to produce the static variable that the AST thinks it is
1595 // accessing.
1596
1597 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(
1598 m_entry_instruction_finder.GetValue(function));
1599
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());
1606
1607 if (name == m_result_name && !m_result_is_pointer) {
1608 LoadInst *load =
1609 new LoadInst(value->getType(), get_element_ptr, "",
1610 entry_instruction->getIterator());
1611
1612 return load;
1613 } else {
1614 return get_element_ptr;
1615 }
1616 });
1617
1618 if (Constant *constant = dyn_cast<Constant>(value)) {
1619 if (auto err =
1620 UnfoldConstant(constant, &llvm_function, body_result_maker,
1622 m_error_stream.Format("{0}", llvm::toString(std::move(err)));
1623 return false;
1624 }
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");
1629 return false;
1630 }
1631 value->replaceAllUsesWith(
1632 body_result_maker.GetValue(instruction->getParent()->getParent()));
1633 } else {
1634 LLDB_LOG(log, "Unhandled non-constant type: \"{0}\"",
1635 PrintValue(value));
1636 return false;
1637 }
1638
1639 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
1640 var->eraseFromParent();
1641 }
1642 }
1643
1644 LLDB_LOG(log, "Total structure [align {0}, size {1}]", (int64_t)alignment,
1645 (uint64_t)size);
1646
1647 return true;
1648}
1649
1650bool IRForTarget::runOnModule(Module &llvm_module) {
1651 lldb_private::Log *log(GetLog(LLDBLog::Expressions));
1652
1653 m_module = &llvm_module;
1654 m_target_data = &m_module->getDataLayout();
1655 m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(),
1656 m_target_data->getPointerSizeInBits());
1657
1658 if (log) {
1659 std::string s;
1660 raw_string_ostream oss(s);
1661
1662 m_module->print(oss, nullptr);
1663
1664 LLDB_LOG(log, "Module as passed in to IRForTarget: \n\"{0}\"", s);
1665 }
1666
1667 Function *const main_function =
1668 m_func_name.IsEmpty() ? nullptr
1669 : m_module->getFunction(m_func_name.GetStringRef());
1670
1671 if (!m_func_name.IsEmpty() && !main_function) {
1672 LLDB_LOG(log, "Couldn't find \"{0}()\" in the module", m_func_name);
1673
1674 m_error_stream.Format("Internal error [IRForTarget]: Couldn't find wrapper "
1675 "'{0}' in the module",
1676 m_func_name);
1677
1678 return false;
1679 }
1680
1681 if (main_function) {
1682 if (!FixFunctionLinkage(*main_function)) {
1683 LLDB_LOG(log, "Couldn't fix the linkage for the function");
1684
1685 return false;
1686 }
1687 }
1688
1689 // Replace $__lldb_expr_result with a persistent variable.
1690 if (main_function) {
1691 if (!CreateResultVariable(*main_function)) {
1692 LLDB_LOG(log, "CreateResultVariable() failed");
1693
1694 // CreateResultVariable() reports its own errors, so we don't do so here
1695
1696 return false;
1697 }
1698 }
1699
1700 if (log && log->GetVerbose()) {
1701 std::string s;
1702 raw_string_ostream oss(s);
1703
1704 m_module->print(oss, nullptr);
1705
1706 LLDB_LOG(log, "Module after creating the result variable: \n\"{0}\"", s);
1707 }
1708
1709 for (llvm::Function &function : *m_module) {
1710 for (BasicBlock &bb : function) {
1711 if (!RemoveGuards(bb)) {
1712 LLDB_LOG(log, "RemoveGuards() failed");
1713
1714 // RemoveGuards() reports its own errors, so we don't do so here
1715
1716 return false;
1717 }
1718
1719 if (!RewritePersistentAllocs(bb)) {
1720 LLDB_LOG(log, "RewritePersistentAllocs() failed");
1721
1722 // RewritePersistentAllocs() reports its own errors, so we don't do so
1723 // here
1724
1725 return false;
1726 }
1727
1728 if (!RemoveCXAAtExit(bb)) {
1729 LLDB_LOG(log, "RemoveCXAAtExit() failed");
1730
1731 // RemoveCXAAtExit() reports its own errors, so we don't do so here
1732
1733 return false;
1734 }
1735 }
1736 }
1737
1738 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
1739 if (!RewriteObjCConstStrings()) {
1740 LLDB_LOG(log, "RewriteObjCConstStrings() failed");
1741
1742 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
1743
1744 return false;
1745 }
1746
1747 for (llvm::Function &function : *m_module) {
1748 for (llvm::BasicBlock &bb : function) {
1749 if (!RewriteObjCSelectors(bb)) {
1750 LLDB_LOG(log, "RewriteObjCSelectors() failed");
1751
1752 // RewriteObjCSelectors() reports its own errors, so we don't do so
1753 // here
1754
1755 return false;
1756 }
1757 }
1758 }
1759
1760 for (llvm::Function &function : *m_module) {
1761 for (BasicBlock &bb : function) {
1762 if (!ResolveCalls(bb)) {
1763 LLDB_LOG(log, "ResolveCalls() failed");
1764
1765 // ResolveCalls() reports its own errors, so we don't do so here
1766
1767 return false;
1768 }
1769 }
1770 }
1771
1772 // Run function-level passes that only make sense on the main function.
1773 if (main_function) {
1774 if (!ResolveExternals(*main_function)) {
1775 LLDB_LOG(log, "ResolveExternals() failed");
1776
1777 // ResolveExternals() reports its own errors, so we don't do so here
1778
1779 return false;
1780 }
1781
1782 if (!ReplaceVariables(*main_function)) {
1783 LLDB_LOG(log, "ReplaceVariables() failed");
1784
1785 // ReplaceVariables() reports its own errors, so we don't do so here
1786
1787 return false;
1788 }
1789 }
1790
1791 // Run architecture specific module-level passes.
1792 if (llvm::Error error =
1794 LLDB_LOG_ERROR(log, std::move(error),
1795 "InsertPointerSigningFixups() failed: {0}");
1796 return false;
1797 }
1798
1799 if (log && log->GetVerbose()) {
1800 std::string s;
1801 raw_string_ostream oss(s);
1802
1803 m_module->print(oss, nullptr);
1804
1805 LLDB_LOG(log, "Module after preparing for execution: \n\"{0}\"", s);
1806 }
1807
1808 return true;
1809}
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.
Definition Log.h:375
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
FunctionValueCache(Maker const &maker)
llvm::Value * GetValue(llvm::Function *function)
std::function< llvm::Value *(llvm::Function *)> Maker
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.
Definition ConstString.h:40
"lldb/Expression/IRExecutionUnit.h" Contains the IR and, optionally, JIT- compiled code for a module.
bool GetVerbose() const
Definition Log.cpp:329
const char * GetData() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
#define LLDB_INVALID_ADDRESS
Error InjectPointerSigningFixupCode(llvm::Module &M, ExecutionPolicy execution_policy)
TaggedASTType< 0 > TypeFromParser
ExecutionPolicy
Expression execution policies.
uint64_t offset_t
Definition lldb-types.h:86
@ eSymbolTypeObjCClass
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
static clang::QualType GetQualType(const CompilerType &ct)
Definition ClangUtil.cpp:36