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