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