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