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