]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Expression/IRForTarget.cpp
Merge ^/head r275749 through r275758.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Expression / IRForTarget.cpp
1 //===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "lldb/Expression/IRForTarget.h"
11
12 #include "llvm/Support/raw_ostream.h"
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/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Transforms/IPO.h"
21 #include "llvm/IR/ValueSymbolTable.h"
22
23 #include "clang/AST/ASTContext.h"
24
25 #include "lldb/Core/dwarf.h"
26 #include "lldb/Core/ConstString.h"
27 #include "lldb/Core/DataBufferHeap.h"
28 #include "lldb/Core/Log.h"
29 #include "lldb/Core/Scalar.h"
30 #include "lldb/Core/StreamString.h"
31 #include "lldb/Expression/ClangExpressionDeclMap.h"
32 #include "lldb/Expression/IRExecutionUnit.h"
33 #include "lldb/Expression/IRInterpreter.h"
34 #include "lldb/Host/Endian.h"
35 #include "lldb/Symbol/ClangASTContext.h"
36 #include "lldb/Symbol/ClangASTType.h"
37
38 #include <map>
39
40 using namespace llvm;
41
42 static char ID;
43
44 IRForTarget::StaticDataAllocator::StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit) :
45     m_execution_unit(execution_unit),
46     m_stream_string(lldb_private::Stream::eBinary, execution_unit.GetAddressByteSize(), execution_unit.GetByteOrder()),
47     m_allocation(LLDB_INVALID_ADDRESS)
48 {
49 }
50
51 IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) :
52     m_maker(maker),
53     m_values()
54 {
55 }
56
57 IRForTarget::FunctionValueCache::~FunctionValueCache()
58 {
59 }
60
61 llvm::Value *IRForTarget::FunctionValueCache::GetValue(llvm::Function *function)
62 {
63     if (!m_values.count(function))
64     {
65         llvm::Value *ret = m_maker(function);
66         m_values[function] = ret;
67         return ret;
68     }
69     return m_values[function];
70 }
71
72 lldb::addr_t IRForTarget::StaticDataAllocator::Allocate()
73 {
74     lldb_private::Error err;
75
76     if (m_allocation != LLDB_INVALID_ADDRESS)
77     {
78         m_execution_unit.FreeNow(m_allocation);
79         m_allocation = LLDB_INVALID_ADDRESS;
80     }
81
82     m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
83
84     return m_allocation;
85 }
86
87 static llvm::Value *FindEntryInstruction (llvm::Function *function)
88 {
89     if (function->empty())
90         return NULL;
91
92     return function->getEntryBlock().getFirstNonPHIOrDbg();
93 }
94
95 IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
96                           bool resolve_vars,
97                           lldb_private::IRExecutionUnit &execution_unit,
98                           lldb_private::Stream *error_stream,
99                           const char *func_name) :
100     ModulePass(ID),
101     m_resolve_vars(resolve_vars),
102     m_func_name(func_name),
103     m_module(NULL),
104     m_decl_map(decl_map),
105     m_data_allocator(execution_unit),
106     m_CFStringCreateWithBytes(NULL),
107     m_sel_registerName(NULL),
108     m_intptr_ty(NULL),
109     m_error_stream(error_stream),
110     m_result_store(NULL),
111     m_result_is_pointer(false),
112     m_reloc_placeholder(NULL),
113     m_entry_instruction_finder (FindEntryInstruction)
114 {
115 }
116
117 /* Handy utility functions used at several places in the code */
118
119 static std::string
120 PrintValue(const Value *value, bool truncate = false)
121 {
122     std::string s;
123     if (value)
124     {
125         raw_string_ostream rso(s);
126         value->print(rso);
127         rso.flush();
128         if (truncate)
129             s.resize(s.length() - 1);
130     }
131     return s;
132 }
133
134 static std::string
135 PrintType(const llvm::Type *type, bool truncate = false)
136 {
137     std::string s;
138     raw_string_ostream rso(s);
139     type->print(rso);
140     rso.flush();
141     if (truncate)
142         s.resize(s.length() - 1);
143     return s;
144 }
145
146 IRForTarget::~IRForTarget()
147 {
148 }
149
150 bool
151 IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
152 {
153     llvm_function.setLinkage(GlobalValue::ExternalLinkage);
154
155     std::string name = llvm_function.getName().str();
156
157     return true;
158 }
159
160 IRForTarget::LookupResult
161 IRForTarget::GetFunctionAddress (llvm::Function *fun,
162                                  uint64_t &fun_addr,
163                                  lldb_private::ConstString &name,
164                                  Constant **&value_ptr)
165 {
166     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
167
168     fun_addr = LLDB_INVALID_ADDRESS;
169     name.Clear();
170     value_ptr = NULL;
171
172     if (fun->isIntrinsic())
173     {
174         Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
175
176         switch (intrinsic_id)
177         {
178         default:
179             if (log)
180                 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
181
182             if (m_error_stream)
183                 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
184
185             return LookupResult::Fail;
186         case Intrinsic::memcpy:
187             {
188                 static lldb_private::ConstString g_memcpy_str ("memcpy");
189                 name = g_memcpy_str;
190             }
191             break;
192         case Intrinsic::memset:
193             {
194                 static lldb_private::ConstString g_memset_str ("memset");
195                 name = g_memset_str;
196             }
197             break;
198         case Intrinsic::dbg_declare:
199         case Intrinsic::dbg_value:
200             return LookupResult::Ignore;
201         }
202
203         if (log && name)
204             log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
205     }
206     else
207     {
208         name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
209     }
210
211     // Find the address of the function.
212
213     clang::NamedDecl *fun_decl = DeclForGlobal (fun);
214
215     if (fun_decl)
216     {
217         if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
218         {
219             lldb_private::ConstString altnernate_name;
220             bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
221             if (!found_it)
222             {
223                 // Check for an alternate mangling for "std::basic_string<char>"
224                 // that is part of the itanium C++ name mangling scheme
225                 const char *name_cstr = name.GetCString();
226                 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
227                 {
228                     std::string alternate_mangling("_ZNKSs");
229                     alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
230                     altnernate_name.SetCString(alternate_mangling.c_str());
231                     found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
232                 }
233             }
234
235             if (!found_it)
236             {
237                 lldb_private::Mangled mangled_name(name);
238                 lldb_private::Mangled alt_mangled_name(altnernate_name);
239                 if (log)
240                 {
241                     if (alt_mangled_name)
242                         log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
243                                     mangled_name.GetName().GetCString(),
244                                     alt_mangled_name.GetName().GetCString());
245                     else
246                         log->Printf("Function \"%s\" had no address",
247                                     mangled_name.GetName().GetCString());
248                 }
249
250                 if (m_error_stream)
251                 {
252                     if (alt_mangled_name)
253                         m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
254                                                mangled_name.GetName().GetCString(),
255                                                alt_mangled_name.GetName().GetCString());
256                     else if (mangled_name.GetMangledName())
257                         m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
258                                                mangled_name.GetName().GetCString(),
259                                                mangled_name.GetMangledName().GetCString());
260                     else
261                         m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
262                                                mangled_name.GetName().GetCString());
263                 }
264                 return LookupResult::Fail;
265             }
266         }
267     }
268     else
269     {
270         if (!m_decl_map->GetFunctionAddress (name, fun_addr))
271         {
272             if (log)
273                 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
274
275             if (m_error_stream)
276                 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
277
278             return LookupResult::Fail;
279         }
280     }
281
282     if (log)
283         log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
284
285     return LookupResult::Success;
286 }
287
288 llvm::Constant *
289 IRForTarget::BuildFunctionPointer (llvm::Type *type,
290                                    uint64_t ptr)
291 {
292     PointerType *fun_ptr_ty = PointerType::getUnqual(type);
293     Constant *fun_addr_int = ConstantInt::get(m_intptr_ty, ptr, false);
294     return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
295 }
296
297 void
298 IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
299                                       llvm::Value *function_ptr,
300                                       const char *name)
301 {
302     for (llvm::User *user : function_ptr->users())
303     {
304         if (Instruction *user_inst = dyn_cast<Instruction>(user))
305         {
306             MDString* md_name = MDString::get(context, StringRef(name));
307
308             MDNode *metadata = MDNode::get(context, md_name);
309
310             user_inst->setMetadata("lldb.call.realName", metadata);
311         }
312         else
313         {
314             RegisterFunctionMetadata (context, user, name);
315         }
316     }
317 }
318
319 bool
320 IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module)
321 {
322     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
323
324     for (llvm::Module::iterator fi = llvm_module.begin();
325          fi != llvm_module.end();
326          ++fi)
327     {
328         Function *fun = fi;
329
330         bool is_decl = fun->isDeclaration();
331
332         if (log)
333             log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
334
335         if (!is_decl)
336             continue;
337
338         if (fun->use_empty())
339             continue; // ignore
340
341         uint64_t addr = LLDB_INVALID_ADDRESS;
342         lldb_private::ConstString name;
343         Constant **value_ptr = NULL;
344
345         LookupResult result = GetFunctionAddress(fun,
346                                                  addr,
347                                                  name,
348                                                  value_ptr);
349
350         switch (result)
351         {
352         case LookupResult::Fail:
353             return false; // GetFunctionAddress reports its own errors
354
355         case LookupResult::Ignore:
356             break; // Nothing to do
357
358         case LookupResult::Success:
359             {
360                 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
361
362                 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
363
364                 if (value_ptr)
365                     *value_ptr = value;
366
367                 // If we are replacing a function with the nobuiltin attribute, it may
368                 // be called with the builtin attribute on call sites. Remove any such
369                 // attributes since it's illegal to have a builtin call to something
370                 // other than a nobuiltin function.
371                 if (fun->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
372                     llvm::Attribute builtin = llvm::Attribute::get(fun->getContext(), llvm::Attribute::Builtin);
373
374                     for (auto u : fun->users()) {
375                         if (auto call = dyn_cast<CallInst>(u)) {
376                             call->removeAttribute(AttributeSet::FunctionIndex, builtin);
377                         }
378                     }
379                 }
380
381                 fun->replaceAllUsesWith(value);
382             }
383             break;
384         }
385     }
386
387     return true;
388 }
389
390
391 clang::NamedDecl *
392 IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
393 {
394     NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
395
396     if (!named_metadata)
397         return NULL;
398
399     unsigned num_nodes = named_metadata->getNumOperands();
400     unsigned node_index;
401
402     for (node_index = 0;
403          node_index < num_nodes;
404          ++node_index)
405     {
406         MDNode *metadata_node = named_metadata->getOperand(node_index);
407
408         if (!metadata_node)
409             return NULL;
410
411         if (metadata_node->getNumOperands() != 2)
412             continue;
413
414         if (metadata_node->getOperand(0) != global_val)
415             continue;
416
417         ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
418
419         if (!constant_int)
420             return NULL;
421
422         uintptr_t ptr = constant_int->getZExtValue();
423
424         return reinterpret_cast<clang::NamedDecl *>(ptr);
425     }
426
427     return NULL;
428 }
429
430 clang::NamedDecl *
431 IRForTarget::DeclForGlobal (GlobalValue *global_val)
432 {
433     return DeclForGlobal(global_val, m_module);
434 }
435
436 bool
437 IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
438 {
439     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
440
441     if (!m_resolve_vars)
442         return true;
443
444     // Find the result variable.  If it doesn't exist, we can give up right here.
445
446     ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
447
448     std::string result_name_str;
449     const char *result_name = NULL;
450
451     for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
452          vi != ve;
453          ++vi)
454     {
455         result_name_str = vi->first().str();
456         const char *value_name = result_name_str.c_str();
457
458         if (strstr(value_name, "$__lldb_expr_result_ptr") &&
459             strncmp(value_name, "_ZGV", 4))
460         {
461             result_name = value_name;
462             m_result_is_pointer = true;
463             break;
464         }
465
466         if (strstr(value_name, "$__lldb_expr_result") &&
467             strncmp(value_name, "_ZGV", 4))
468         {
469             result_name = value_name;
470             m_result_is_pointer = false;
471             break;
472         }
473     }
474
475     if (!result_name)
476     {
477         if (log)
478             log->PutCString("Couldn't find result variable");
479
480         return true;
481     }
482
483     if (log)
484         log->Printf("Result name: \"%s\"", result_name);
485
486     Value *result_value = m_module->getNamedValue(result_name);
487
488     if (!result_value)
489     {
490         if (log)
491             log->PutCString("Result variable had no data");
492
493         if (m_error_stream)
494             m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
495
496         return false;
497     }
498
499     if (log)
500         log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
501
502     GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
503
504     if (!result_global)
505     {
506         if (log)
507             log->PutCString("Result variable isn't a GlobalVariable");
508
509         if (m_error_stream)
510             m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
511
512         return false;
513     }
514
515     clang::NamedDecl *result_decl = DeclForGlobal (result_global);
516     if (!result_decl)
517     {
518         if (log)
519             log->PutCString("Result variable doesn't have a corresponding Decl");
520
521         if (m_error_stream)
522             m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name);
523
524         return false;
525     }
526
527     if (log)
528     {
529         std::string decl_desc_str;
530         raw_string_ostream decl_desc_stream(decl_desc_str);
531         result_decl->print(decl_desc_stream);
532         decl_desc_stream.flush();
533
534         log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
535     }
536
537     clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
538     if (!result_var)
539     {
540         if (log)
541             log->PutCString("Result variable Decl isn't a VarDecl");
542
543         if (m_error_stream)
544             m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name);
545
546         return false;
547     }
548
549     // Get the next available result name from m_decl_map and create the persistent
550     // variable for it
551
552     // If the result is an Lvalue, it is emitted as a pointer; see
553     // ASTResultSynthesizer::SynthesizeBodyResult.
554     if (m_result_is_pointer)
555     {
556         clang::QualType pointer_qual_type = result_var->getType();
557         const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
558
559         const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
560         const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
561
562         if (pointer_pointertype)
563         {
564             clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
565
566             m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
567                                                          &result_decl->getASTContext());
568         }
569         else if (pointer_objcobjpointertype)
570         {
571             clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
572
573             m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
574                                                          &result_decl->getASTContext());
575         }
576         else
577         {
578             if (log)
579                 log->PutCString("Expected result to have pointer type, but it did not");
580
581             if (m_error_stream)
582                 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
583
584             return false;
585         }
586     }
587     else
588     {
589         m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
590                                                      &result_decl->getASTContext());
591     }
592
593     if (m_result_type.GetBitSize() == 0)
594     {
595         lldb_private::StreamString type_desc_stream;
596         m_result_type.DumpTypeDescription(&type_desc_stream);
597
598         if (log)
599             log->Printf("Result type has size 0");
600
601         if (m_error_stream)
602             m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
603                                    type_desc_stream.GetData());
604         return false;
605     }
606
607     if (log)
608     {
609         lldb_private::StreamString type_desc_stream;
610         m_result_type.DumpTypeDescription(&type_desc_stream);
611
612         log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
613     }
614
615     m_result_name = lldb_private::ConstString("$RESULT_NAME");
616
617     if (log)
618         log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
619                     m_result_name.GetCString(),
620                     m_result_type.GetByteSize());
621
622     // Construct a new result global and set up its metadata
623
624     GlobalVariable *new_result_global = new GlobalVariable((*m_module),
625                                                            result_global->getType()->getElementType(),
626                                                            false, /* not constant */
627                                                            GlobalValue::ExternalLinkage,
628                                                            NULL, /* no initializer */
629                                                            m_result_name.GetCString ());
630
631     // It's too late in compilation to create a new VarDecl for this, but we don't
632     // need to.  We point the metadata at the old VarDecl.  This creates an odd
633     // anomaly: a variable with a Value whose name is something like $0 and a
634     // Decl whose name is $__lldb_expr_result.  This condition is handled in
635     // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
636     // fixed up.
637
638     ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
639                                                      reinterpret_cast<uint64_t>(result_decl),
640                                                      false);
641
642     llvm::Value* values[2];
643     values[0] = new_result_global;
644     values[1] = new_constant_int;
645
646     ArrayRef<Value*> value_ref(values, 2);
647
648     MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
649     NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
650     named_metadata->addOperand(persistent_global_md);
651
652     if (log)
653         log->Printf("Replacing \"%s\" with \"%s\"",
654                     PrintValue(result_global).c_str(),
655                     PrintValue(new_result_global).c_str());
656
657     if (result_global->use_empty())
658     {
659         // We need to synthesize a store for this variable, because otherwise
660         // there's nothing to put into its equivalent persistent variable.
661
662         BasicBlock &entry_block(llvm_function.getEntryBlock());
663         Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
664
665         if (!first_entry_instruction)
666             return false;
667
668         if (!result_global->hasInitializer())
669         {
670             if (log)
671                 log->Printf("Couldn't find initializer for unused variable");
672
673             if (m_error_stream)
674                 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
675
676             return false;
677         }
678
679         Constant *initializer = result_global->getInitializer();
680
681         StoreInst *synthesized_store = new StoreInst(initializer,
682                                                      new_result_global,
683                                                      first_entry_instruction);
684
685         if (log)
686             log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
687     }
688     else
689     {
690         result_global->replaceAllUsesWith(new_result_global);
691     }
692
693     if (!m_decl_map->AddPersistentVariable(result_decl,
694                                            m_result_name,
695                                            m_result_type,
696                                            true,
697                                            m_result_is_pointer))
698         return false;
699
700     result_global->eraseFromParent();
701
702     return true;
703 }
704
705 bool
706 IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
707                                      llvm::GlobalVariable *cstr)
708 {
709     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
710
711     Type *ns_str_ty = ns_str->getType();
712
713     Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
714     Type *i32_ty = Type::getInt32Ty(m_module->getContext());
715     Type *i8_ty = Type::getInt8Ty(m_module->getContext());
716
717     if (!m_CFStringCreateWithBytes)
718     {
719         lldb::addr_t CFStringCreateWithBytes_addr;
720
721         static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
722
723         if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
724         {
725             if (log)
726                 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
727
728             if (m_error_stream)
729                 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
730
731             return false;
732         }
733
734         if (log)
735             log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
736
737         // Build the function type:
738         //
739         // CFStringRef CFStringCreateWithBytes (
740         //   CFAllocatorRef alloc,
741         //   const UInt8 *bytes,
742         //   CFIndex numBytes,
743         //   CFStringEncoding encoding,
744         //   Boolean isExternalRepresentation
745         // );
746         //
747         // We make the following substitutions:
748         //
749         // CFStringRef -> i8*
750         // CFAllocatorRef -> i8*
751         // UInt8 * -> i8*
752         // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
753         // CFStringEncoding -> i32
754         // Boolean -> i8
755
756         Type *arg_type_array[5];
757
758         arg_type_array[0] = i8_ptr_ty;
759         arg_type_array[1] = i8_ptr_ty;
760         arg_type_array[2] = m_intptr_ty;
761         arg_type_array[3] = i32_ty;
762         arg_type_array[4] = i8_ty;
763
764         ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
765
766         llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
767
768         // Build the constant containing the pointer to the function
769         PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
770         Constant *CFSCWB_addr_int = ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false);
771         m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
772     }
773
774     ConstantDataSequential *string_array = NULL;
775
776     if (cstr)
777         string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
778
779     Constant *alloc_arg         = Constant::getNullValue(i8_ptr_ty);
780     Constant *bytes_arg         = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
781     Constant *numBytes_arg      = ConstantInt::get(m_intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
782     Constant *encoding_arg      = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
783     Constant *isExternal_arg    = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
784
785     Value *argument_array[5];
786
787     argument_array[0] = alloc_arg;
788     argument_array[1] = bytes_arg;
789     argument_array[2] = numBytes_arg;
790     argument_array[3] = encoding_arg;
791     argument_array[4] = isExternal_arg;
792
793     ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
794
795     FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * {
796         return CallInst::Create(m_CFStringCreateWithBytes,
797                                 CFSCWB_arguments,
798                                 "CFStringCreateWithBytes",
799                                 llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)));
800     });
801
802     if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder))
803     {
804         if (log)
805             log->PutCString("Couldn't replace the NSString with the result of the call");
806
807         if (m_error_stream)
808             m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
809
810         return false;
811     }
812
813     ns_str->eraseFromParent();
814
815     return true;
816 }
817
818 bool
819 IRForTarget::RewriteObjCConstStrings()
820 {
821     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
822
823     ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
824
825     for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
826          vi != ve;
827          ++vi)
828     {
829         std::string value_name = vi->first().str();
830         const char *value_name_cstr = value_name.c_str();
831
832         if (strstr(value_name_cstr, "_unnamed_cfstring_"))
833         {
834             Value *nsstring_value = vi->second;
835
836             GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
837
838             if (!nsstring_global)
839             {
840                 if (log)
841                     log->PutCString("NSString variable is not a GlobalVariable");
842
843                 if (m_error_stream)
844                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
845
846                 return false;
847             }
848
849             if (!nsstring_global->hasInitializer())
850             {
851                 if (log)
852                     log->PutCString("NSString variable does not have an initializer");
853
854                 if (m_error_stream)
855                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
856
857                 return false;
858             }
859
860             ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
861
862             if (!nsstring_struct)
863             {
864                 if (log)
865                     log->PutCString("NSString variable's initializer is not a ConstantStruct");
866
867                 if (m_error_stream)
868                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
869
870                 return false;
871             }
872
873             // We expect the following structure:
874             //
875             // struct {
876             //   int *isa;
877             //   int flags;
878             //   char *str;
879             //   long length;
880             // };
881
882             if (nsstring_struct->getNumOperands() != 4)
883             {
884                 if (log)
885                     log->Printf("NSString variable's initializer structure has an unexpected number of members.  Should be 4, is %d", nsstring_struct->getNumOperands());
886
887                 if (m_error_stream)
888                     m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
889
890                 return false;
891             }
892
893             Constant *nsstring_member = nsstring_struct->getOperand(2);
894
895             if (!nsstring_member)
896             {
897                 if (log)
898                     log->PutCString("NSString initializer's str element was empty");
899
900                 if (m_error_stream)
901                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
902
903                 return false;
904             }
905
906             ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
907
908             if (!nsstring_expr)
909             {
910                 if (log)
911                     log->PutCString("NSString initializer's str element is not a ConstantExpr");
912
913                 if (m_error_stream)
914                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
915
916                 return false;
917             }
918
919             if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
920             {
921                 if (log)
922                     log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
923
924                 if (m_error_stream)
925                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
926
927                 return false;
928             }
929
930             Constant *nsstring_cstr = nsstring_expr->getOperand(0);
931
932             GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
933
934             if (!cstr_global)
935             {
936                 if (log)
937                     log->PutCString("NSString initializer's str element is not a GlobalVariable");
938
939                 if (m_error_stream)
940                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
941
942                 return false;
943             }
944
945             if (!cstr_global->hasInitializer())
946             {
947                 if (log)
948                     log->PutCString("NSString initializer's str element does not have an initializer");
949
950                 if (m_error_stream)
951                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
952
953                 return false;
954             }
955
956             /*
957             if (!cstr_array)
958             {
959                 if (log)
960                     log->PutCString("NSString initializer's str element is not a ConstantArray");
961
962                 if (m_error_stream)
963                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
964
965                 return false;
966             }
967
968             if (!cstr_array->isCString())
969             {
970                 if (log)
971                     log->PutCString("NSString initializer's str element is not a C string array");
972
973                 if (m_error_stream)
974                     m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
975
976                 return false;
977             }
978             */
979
980             ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
981
982             if (log)
983             {
984                 if (cstr_array)
985                     log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().str().c_str());
986                 else
987                     log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
988             }
989
990             if (!cstr_array)
991                 cstr_global = NULL;
992
993             if (!RewriteObjCConstString(nsstring_global, cstr_global))
994             {
995                 if (log)
996                     log->PutCString("Error rewriting the constant string");
997
998                 // We don't print an error message here because RewriteObjCConstString has done so for us.
999
1000                 return false;
1001             }
1002         }
1003     }
1004
1005     for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1006          vi != ve;
1007          ++vi)
1008     {
1009         std::string value_name = vi->first().str();
1010         const char *value_name_cstr = value_name.c_str();
1011
1012         if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
1013         {
1014             GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1015
1016             if (!gv)
1017             {
1018                 if (log)
1019                     log->PutCString("__CFConstantStringClassReference is not a global variable");
1020
1021                 if (m_error_stream)
1022                     m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1023
1024                 return false;
1025             }
1026
1027             gv->eraseFromParent();
1028
1029             break;
1030         }
1031     }
1032
1033     return true;
1034 }
1035
1036 static bool IsObjCSelectorRef (Value *value)
1037 {
1038     GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
1039
1040     if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
1041         return false;
1042
1043     return true;
1044 }
1045
1046 // This function does not report errors; its callers are responsible.
1047 bool
1048 IRForTarget::RewriteObjCSelector (Instruction* selector_load)
1049 {
1050     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1051
1052     LoadInst *load = dyn_cast<LoadInst>(selector_load);
1053
1054     if (!load)
1055         return false;
1056
1057     // Unpack the message name from the selector.  In LLVM IR, an objc_msgSend gets represented as
1058     //
1059     // %tmp     = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1060     // %call    = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1061     //
1062     // where %obj is the object pointer and %tmp is the selector.
1063     //
1064     // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1065     // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
1066
1067     // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1068
1069     GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1070
1071     if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1072         return false;
1073
1074     Constant *osr_initializer = _objc_selector_references_->getInitializer();
1075
1076     ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1077
1078     if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1079         return false;
1080
1081     Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1082
1083     if (!osr_initializer_base)
1084         return false;
1085
1086     // Find the string's initializer (a ConstantArray) and get the string from it
1087
1088     GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1089
1090     if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1091         return false;
1092
1093     Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1094
1095     ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
1096
1097     if (!omvn_initializer_array->isString())
1098         return false;
1099
1100     std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1101
1102     if (log)
1103         log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
1104
1105     // Construct a call to sel_registerName
1106
1107     if (!m_sel_registerName)
1108     {
1109         lldb::addr_t sel_registerName_addr;
1110
1111         static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
1112         if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
1113             return false;
1114
1115         if (log)
1116             log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
1117
1118         // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1119
1120         // The below code would be "more correct," but in actuality what's required is uint8_t*
1121         //Type *sel_type = StructType::get(m_module->getContext());
1122         //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
1123         Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
1124
1125         Type *type_array[1];
1126
1127         type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1128
1129         ArrayRef<Type *> srN_arg_types(type_array, 1);
1130
1131         llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1132
1133         // Build the constant containing the pointer to the function
1134         PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
1135         Constant *srN_addr_int = ConstantInt::get(m_intptr_ty, sel_registerName_addr, false);
1136         m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1137     }
1138
1139     Value *argument_array[1];
1140
1141     Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
1142
1143     argument_array[0] = omvn_pointer;
1144
1145     ArrayRef<Value *> srN_arguments(argument_array, 1);
1146
1147     CallInst *srN_call = CallInst::Create(m_sel_registerName,
1148                                           srN_arguments,
1149                                           "sel_registerName",
1150                                           selector_load);
1151
1152     // Replace the load with the call in all users
1153
1154     selector_load->replaceAllUsesWith(srN_call);
1155
1156     selector_load->eraseFromParent();
1157
1158     return true;
1159 }
1160
1161 bool
1162 IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
1163 {
1164     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1165
1166     BasicBlock::iterator ii;
1167
1168     typedef SmallVector <Instruction*, 2> InstrList;
1169     typedef InstrList::iterator InstrIterator;
1170
1171     InstrList selector_loads;
1172
1173     for (ii = basic_block.begin();
1174          ii != basic_block.end();
1175          ++ii)
1176     {
1177         Instruction &inst = *ii;
1178
1179         if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1180             if (IsObjCSelectorRef(load->getPointerOperand()))
1181                 selector_loads.push_back(&inst);
1182     }
1183
1184     InstrIterator iter;
1185
1186     for (iter = selector_loads.begin();
1187          iter != selector_loads.end();
1188          ++iter)
1189     {
1190         if (!RewriteObjCSelector(*iter))
1191         {
1192             if (m_error_stream)
1193                 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1194
1195             if (log)
1196                 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
1197
1198             return false;
1199         }
1200     }
1201
1202     return true;
1203 }
1204
1205 // This function does not report errors; its callers are responsible.
1206 bool
1207 IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
1208 {
1209     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1210
1211     AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1212
1213     MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1214
1215     if (!alloc_md || !alloc_md->getNumOperands())
1216         return false;
1217
1218     ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1219
1220     if (!constant_int)
1221         return false;
1222
1223     // We attempt to register this as a new persistent variable with the DeclMap.
1224
1225     uintptr_t ptr = constant_int->getZExtValue();
1226
1227     clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
1228
1229     lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1230                                                    &decl->getASTContext());
1231
1232     StringRef decl_name (decl->getName());
1233     lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
1234     if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
1235         return false;
1236
1237     GlobalVariable *persistent_global = new GlobalVariable((*m_module),
1238                                                            alloc->getType(),
1239                                                            false, /* not constant */
1240                                                            GlobalValue::ExternalLinkage,
1241                                                            NULL, /* no initializer */
1242                                                            alloc->getName().str().c_str());
1243
1244     // What we're going to do here is make believe this was a regular old external
1245     // variable.  That means we need to make the metadata valid.
1246
1247     NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
1248
1249     llvm::Value* values[2];
1250     values[0] = persistent_global;
1251     values[1] = constant_int;
1252
1253     ArrayRef<llvm::Value*> value_ref(values, 2);
1254
1255     MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
1256     named_metadata->addOperand(persistent_global_md);
1257
1258     // Now, since the variable is a pointer variable, we will drop in a load of that
1259     // pointer variable.
1260
1261     LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1262
1263     if (log)
1264         log->Printf("Replacing \"%s\" with \"%s\"",
1265                     PrintValue(alloc).c_str(),
1266                     PrintValue(persistent_load).c_str());
1267
1268     alloc->replaceAllUsesWith(persistent_load);
1269     alloc->eraseFromParent();
1270
1271     return true;
1272 }
1273
1274 bool
1275 IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
1276 {
1277     if (!m_resolve_vars)
1278         return true;
1279
1280     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1281
1282     BasicBlock::iterator ii;
1283
1284     typedef SmallVector <Instruction*, 2> InstrList;
1285     typedef InstrList::iterator InstrIterator;
1286
1287     InstrList pvar_allocs;
1288
1289     for (ii = basic_block.begin();
1290          ii != basic_block.end();
1291          ++ii)
1292     {
1293         Instruction &inst = *ii;
1294
1295         if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
1296         {
1297             llvm::StringRef alloc_name = alloc->getName();
1298
1299             if (alloc_name.startswith("$") &&
1300                 !alloc_name.startswith("$__lldb"))
1301             {
1302                 if (alloc_name.find_first_of("0123456789") == 1)
1303                 {
1304                     if (log)
1305                         log->Printf("Rejecting a numeric persistent variable.");
1306
1307                     if (m_error_stream)
1308                         m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1309
1310                     return false;
1311                 }
1312
1313                 pvar_allocs.push_back(alloc);
1314             }
1315         }
1316     }
1317
1318     InstrIterator iter;
1319
1320     for (iter = pvar_allocs.begin();
1321          iter != pvar_allocs.end();
1322          ++iter)
1323     {
1324         if (!RewritePersistentAlloc(*iter))
1325         {
1326             if (m_error_stream)
1327                 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1328
1329             if (log)
1330                 log->PutCString("Couldn't rewrite the creation of a persistent variable");
1331
1332             return false;
1333         }
1334     }
1335
1336     return true;
1337 }
1338
1339 bool
1340 IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1341 {
1342     if (!initializer)
1343         return true;
1344
1345     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1346
1347     if (log && log->GetVerbose())
1348         log->Printf("  MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1349
1350     Type *initializer_type = initializer->getType();
1351
1352     if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1353     {
1354         memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1355         return true;
1356     }
1357     else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
1358     {
1359         if (array_initializer->isString())
1360         {
1361             std::string array_initializer_string = array_initializer->getAsString();
1362             memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1363         }
1364         else
1365         {
1366             ArrayType *array_initializer_type = array_initializer->getType();
1367             Type *array_element_type = array_initializer_type->getElementType();
1368
1369             size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1370
1371             for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i)
1372             {
1373                 Value *operand_value = array_initializer->getOperand(i);
1374                 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1375
1376                 if (!operand_constant)
1377                     return false;
1378
1379                 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
1380                     return false;
1381             }
1382         }
1383         return true;
1384     }
1385     else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1386     {
1387         StructType *struct_initializer_type = struct_initializer->getType();
1388         const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1389
1390         for (unsigned i = 0;
1391              i < struct_initializer->getNumOperands();
1392              ++i)
1393         {
1394             if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1395                 return false;
1396         }
1397         return true;
1398     }
1399     else if (isa<ConstantAggregateZero>(initializer))
1400     {
1401         memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1402         return true;
1403     }
1404     return false;
1405 }
1406
1407 bool
1408 IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1409 {
1410     if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1411         return false;
1412
1413     if (global_variable == m_reloc_placeholder)
1414         return true;
1415
1416     uint64_t offset = m_data_allocator.GetStream().GetSize();
1417
1418     llvm::Type *variable_type = global_variable->getType();
1419
1420     Constant *initializer = global_variable->getInitializer();
1421
1422     llvm::Type *initializer_type = initializer->getType();
1423
1424     size_t size = m_target_data->getTypeAllocSize(initializer_type);
1425     size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1426
1427     const size_t mask = (align - 1);
1428     uint64_t aligned_offset = (offset + mask) & ~mask;
1429     m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
1430     offset = aligned_offset;
1431
1432     lldb_private::DataBufferHeap data(size, '\0');
1433
1434     if (initializer)
1435         if (!MaterializeInitializer(data.GetBytes(), initializer))
1436             return false;
1437
1438     m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
1439
1440     Constant *new_pointer = BuildRelocation(variable_type, offset);
1441
1442     global_variable->replaceAllUsesWith(new_pointer);
1443
1444     global_variable->eraseFromParent();
1445
1446     return true;
1447 }
1448
1449 // This function does not report errors; its callers are responsible.
1450 bool
1451 IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
1452 {
1453     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1454
1455     if (log)
1456         log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
1457
1458     if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
1459     {
1460         switch (constant_expr->getOpcode())
1461         {
1462         default:
1463             break;
1464         case Instruction::GetElementPtr:
1465         case Instruction::BitCast:
1466             Value *s = constant_expr->getOperand(0);
1467             if (!MaybeHandleVariable(s))
1468                 return false;
1469         }
1470     }
1471     else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
1472     {
1473         if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1474             return MaterializeInternalVariable(global_variable);
1475
1476         clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
1477
1478         if (!named_decl)
1479         {
1480             if (IsObjCSelectorRef(llvm_value_ptr))
1481                 return true;
1482
1483             if (!global_variable->hasExternalLinkage())
1484                 return true;
1485
1486             if (log)
1487                 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
1488
1489             return false;
1490         }
1491
1492         std::string name (named_decl->getName().str());
1493
1494         clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1495         if (value_decl == NULL)
1496             return false;
1497
1498         lldb_private::ClangASTType clang_type(&value_decl->getASTContext(), value_decl->getType());
1499
1500         const Type *value_type = NULL;
1501
1502         if (name[0] == '$')
1503         {
1504             // The $__lldb_expr_result name indicates the the return value has allocated as
1505             // a static variable.  Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1506             // accesses to this static variable need to be redirected to the result of dereferencing
1507             // a pointer that is passed in as one of the arguments.
1508             //
1509             // Consequently, when reporting the size of the type, we report a pointer type pointing
1510             // to the type of $__lldb_expr_result, not the type itself.
1511             //
1512             // We also do this for any user-declared persistent variables.
1513             clang_type = clang_type.GetPointerType();
1514             value_type = PointerType::get(global_variable->getType(), 0);
1515         }
1516         else
1517         {
1518             value_type = global_variable->getType();
1519         }
1520
1521         const uint64_t value_size = clang_type.GetByteSize();
1522         lldb::offset_t value_alignment = (clang_type.GetTypeBitAlign() + 7ull) / 8ull;
1523
1524         if (log)
1525         {
1526             log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRIu64 "]",
1527                         name.c_str(),
1528                         clang_type.GetQualType().getAsString().c_str(),
1529                         PrintType(value_type).c_str(),
1530                         value_size,
1531                         value_alignment);
1532         }
1533
1534
1535         if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
1536                                                         lldb_private::ConstString (name.c_str()),
1537                                                         llvm_value_ptr,
1538                                                         value_size,
1539                                                         value_alignment))
1540         {
1541             if (!global_variable->hasExternalLinkage())
1542                 return true;
1543             else if (HandleSymbol (global_variable))
1544                 return true;
1545             else
1546                 return false;
1547         }
1548     }
1549     else if (dyn_cast<llvm::Function>(llvm_value_ptr))
1550     {
1551         if (log)
1552             log->Printf("Function pointers aren't handled right now");
1553
1554         return false;
1555     }
1556
1557     return true;
1558 }
1559
1560 // This function does not report errors; its callers are responsible.
1561 bool
1562 IRForTarget::HandleSymbol (Value *symbol)
1563 {
1564     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1565
1566     lldb_private::ConstString name(symbol->getName().str().c_str());
1567
1568     lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
1569
1570     if (symbol_addr == LLDB_INVALID_ADDRESS)
1571     {
1572         if (log)
1573             log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1574
1575         return false;
1576     }
1577
1578     if (log)
1579         log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
1580
1581     Type *symbol_type = symbol->getType();
1582
1583     Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false);
1584
1585     Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1586
1587     if (log)
1588         log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1589
1590     symbol->replaceAllUsesWith(symbol_addr_ptr);
1591
1592     return true;
1593 }
1594
1595 bool
1596 IRForTarget::MaybeHandleCallArguments (CallInst *Old)
1597 {
1598     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1599
1600     if (log)
1601         log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
1602
1603     for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
1604          op_index < num_ops;
1605          ++op_index)
1606         if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
1607         {
1608             if (m_error_stream)
1609                 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1610
1611             return false;
1612         }
1613
1614     return true;
1615 }
1616
1617 bool
1618 IRForTarget::HandleObjCClass(Value *classlist_reference)
1619 {
1620     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1621
1622     GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1623
1624     if (!global_variable)
1625         return false;
1626
1627     Constant *initializer = global_variable->getInitializer();
1628
1629     if (!initializer)
1630         return false;
1631
1632     if (!initializer->hasName())
1633         return false;
1634
1635     StringRef name(initializer->getName());
1636     lldb_private::ConstString name_cstr(name.str().c_str());
1637     lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
1638
1639     if (log)
1640         log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1641
1642     if (class_ptr == LLDB_INVALID_ADDRESS)
1643         return false;
1644
1645     if (global_variable->use_empty())
1646         return false;
1647
1648     SmallVector<LoadInst *, 2> load_instructions;
1649
1650     for (llvm::User *u : global_variable->users())
1651     {
1652         if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
1653             load_instructions.push_back(load_instruction);
1654     }
1655
1656     if (load_instructions.empty())
1657         return false;
1658
1659     Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr);
1660
1661     for (LoadInst *load_instruction : load_instructions)
1662     {
1663         Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1664
1665         load_instruction->replaceAllUsesWith(class_bitcast);
1666
1667         load_instruction->eraseFromParent();
1668     }
1669
1670     return true;
1671 }
1672
1673 bool
1674 IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1675 {
1676     BasicBlock::iterator ii;
1677
1678     std::vector<CallInst *> calls_to_remove;
1679
1680     for (ii = basic_block.begin();
1681          ii != basic_block.end();
1682          ++ii)
1683     {
1684         Instruction &inst = *ii;
1685
1686         CallInst *call = dyn_cast<CallInst>(&inst);
1687
1688         // MaybeHandleCallArguments handles error reporting; we are silent here
1689         if (!call)
1690             continue;
1691
1692         bool remove = false;
1693
1694         llvm::Function *func = call->getCalledFunction();
1695
1696         if (func && func->getName() == "__cxa_atexit")
1697             remove = true;
1698
1699         llvm::Value *val = call->getCalledValue();
1700
1701         if (val && val->getName() == "__cxa_atexit")
1702             remove = true;
1703
1704         if (remove)
1705             calls_to_remove.push_back(call);
1706     }
1707
1708     for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1709          ci != ce;
1710          ++ci)
1711     {
1712         (*ci)->eraseFromParent();
1713     }
1714
1715     return true;
1716 }
1717
1718 bool
1719 IRForTarget::ResolveCalls(BasicBlock &basic_block)
1720 {
1721     /////////////////////////////////////////////////////////////////////////
1722     // Prepare the current basic block for execution in the remote process
1723     //
1724
1725     BasicBlock::iterator ii;
1726
1727     for (ii = basic_block.begin();
1728          ii != basic_block.end();
1729          ++ii)
1730     {
1731         Instruction &inst = *ii;
1732
1733         CallInst *call = dyn_cast<CallInst>(&inst);
1734
1735         // MaybeHandleCallArguments handles error reporting; we are silent here
1736         if (call && !MaybeHandleCallArguments(call))
1737             return false;
1738     }
1739
1740     return true;
1741 }
1742
1743 bool
1744 IRForTarget::ResolveExternals (Function &llvm_function)
1745 {
1746     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1747
1748     for (GlobalVariable &global_var : m_module->globals())
1749     {
1750         std::string global_name = global_var.getName().str();
1751
1752         if (log)
1753             log->Printf("Examining %s, DeclForGlobalValue returns %p",
1754                         global_name.c_str(),
1755                         static_cast<void*>(DeclForGlobal(&global_var)));
1756
1757         if (global_name.find("OBJC_IVAR") == 0)
1758         {
1759             if (!HandleSymbol(&global_var))
1760             {
1761                 if (m_error_stream)
1762                     m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", global_name.c_str());
1763
1764                 return false;
1765             }
1766         }
1767         else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1768         {
1769             if (!HandleObjCClass(&global_var))
1770             {
1771                 if (m_error_stream)
1772                     m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1773
1774                 return false;
1775             }
1776         }
1777         else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos)
1778         {
1779             if (!HandleObjCClass(&global_var))
1780             {
1781                 if (m_error_stream)
1782                     m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1783
1784                 return false;
1785             }
1786         }
1787         else if (DeclForGlobal(&global_var))
1788         {
1789             if (!MaybeHandleVariable (&global_var))
1790             {
1791                 if (m_error_stream)
1792                     m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", global_name.c_str());
1793
1794                 return false;
1795             }
1796         }
1797     }
1798
1799     return true;
1800 }
1801
1802 bool
1803 IRForTarget::ReplaceStrings ()
1804 {
1805     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1806
1807     typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1808
1809     OffsetsTy offsets;
1810
1811     for (GlobalVariable &gv : m_module->globals())
1812     {
1813         if (!gv.hasInitializer())
1814             continue;
1815
1816         Constant *gc = gv.getInitializer();
1817
1818         std::string str;
1819
1820         if (gc->isNullValue())
1821         {
1822             Type *gc_type = gc->getType();
1823
1824             ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1825
1826             if (!gc_array_type)
1827                 continue;
1828
1829             Type *gc_element_type = gc_array_type->getElementType();
1830
1831             IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1832
1833             if (gc_integer_type->getBitWidth() != 8)
1834                 continue;
1835
1836             str = "";
1837         }
1838         else
1839         {
1840             ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
1841
1842             if (!gc_array)
1843                 continue;
1844
1845             if (!gc_array->isCString())
1846                 continue;
1847
1848             if (log)
1849                 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
1850
1851             str = gc_array->getAsString();
1852         }
1853
1854         offsets[&gv] = m_data_allocator.GetStream().GetSize();
1855
1856         m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
1857     }
1858
1859     Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
1860
1861     for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1862          oi != oe;
1863          ++oi)
1864     {
1865         GlobalVariable *gv = oi->first;
1866         size_t offset = oi->second;
1867
1868         Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1869
1870         if (log)
1871             log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1872
1873         for (llvm::User *u : gv->users())
1874         {
1875             if (log)
1876                 log->Printf("Found use %s", PrintValue(u).c_str());
1877
1878             ConstantExpr *const_expr = dyn_cast<ConstantExpr>(u);
1879             StoreInst *store_inst = dyn_cast<StoreInst>(u);
1880
1881             if (const_expr)
1882             {
1883                 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1884                 {
1885                     if (log)
1886                         log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1887
1888                     return false;
1889                 }
1890
1891                 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1892                 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1893
1894                 const_expr->replaceAllUsesWith(new_gep);
1895             }
1896             else if (store_inst)
1897             {
1898                 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1899
1900                 store_inst->setOperand(0, bit_cast);
1901             }
1902             else
1903             {
1904                 if (log)
1905                     log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1906
1907                 return false;
1908             }
1909         }
1910
1911         gv->eraseFromParent();
1912     }
1913
1914     return true;
1915 }
1916
1917 bool
1918 IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1919 {
1920     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1921
1922     typedef SmallVector <Value*, 2> ConstantList;
1923     typedef SmallVector <llvm::Instruction*, 2> UserList;
1924     typedef ConstantList::iterator ConstantIterator;
1925     typedef UserList::iterator UserIterator;
1926
1927     ConstantList static_constants;
1928     UserList static_users;
1929
1930     for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1931          ii != ie;
1932          ++ii)
1933     {
1934         llvm::Instruction &inst = *ii;
1935
1936         for (Value *operand_val : inst.operand_values())
1937         {
1938             ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1939
1940             if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
1941             {
1942                 static_constants.push_back(operand_val);
1943                 static_users.push_back(ii);
1944             }
1945         }
1946     }
1947
1948     ConstantIterator constant_iter;
1949     UserIterator user_iter;
1950
1951     for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1952          constant_iter != static_constants.end();
1953          ++constant_iter, ++user_iter)
1954     {
1955         Value *operand_val = *constant_iter;
1956         llvm::Instruction *inst = *user_iter;
1957
1958         ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1959
1960         if (operand_constant_fp)
1961         {
1962             Type *operand_type = operand_constant_fp->getType();
1963
1964             APFloat operand_apfloat = operand_constant_fp->getValueAPF();
1965             APInt operand_apint = operand_apfloat.bitcastToAPInt();
1966
1967             const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
1968             size_t operand_data_size = operand_apint.getBitWidth() / 8;
1969
1970             if (log)
1971             {
1972                 std::string s;
1973                 raw_string_ostream ss(s);
1974                 for (size_t index = 0;
1975                      index < operand_data_size;
1976                      ++index)
1977                 {
1978                     ss << (uint32_t)operand_raw_data[index];
1979                     ss << " ";
1980                 }
1981                 ss.flush();
1982
1983                 log->Printf("Found ConstantFP with size %" PRIu64 " and raw data %s", (uint64_t)operand_data_size, s.c_str());
1984             }
1985
1986             lldb_private::DataBufferHeap data(operand_data_size, 0);
1987
1988             if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
1989             {
1990                 uint8_t *data_bytes = data.GetBytes();
1991
1992                 for (size_t index = 0;
1993                      index < operand_data_size;
1994                      ++index)
1995                 {
1996                     data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
1997                 }
1998             }
1999             else
2000             {
2001                 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2002             }
2003
2004             uint64_t offset = m_data_allocator.GetStream().GetSize();
2005
2006             size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2007
2008             const size_t mask = (align - 1);
2009             uint64_t aligned_offset = (offset + mask) & ~mask;
2010             m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
2011
2012             m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
2013
2014             llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
2015
2016             Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
2017
2018             llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2019
2020             operand_constant_fp->replaceAllUsesWith(fp_load);
2021         }
2022     }
2023
2024     return true;
2025 }
2026
2027 static bool isGuardVariableRef(Value *V)
2028 {
2029     Constant *Old = NULL;
2030
2031     if (!(Old = dyn_cast<Constant>(V)))
2032         return false;
2033
2034     ConstantExpr *CE = NULL;
2035
2036     if ((CE = dyn_cast<ConstantExpr>(V)))
2037     {
2038         if (CE->getOpcode() != Instruction::BitCast)
2039             return false;
2040
2041         Old = CE->getOperand(0);
2042     }
2043
2044     GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
2045
2046     if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2047         return false;
2048
2049     return true;
2050 }
2051
2052 void
2053 IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
2054 {
2055     Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
2056
2057     for (llvm::User *u : guard_load->users())
2058     {
2059         if (isa<Constant>(u))
2060         {
2061             // do nothing for the moment
2062         }
2063         else
2064         {
2065             u->replaceUsesOfWith(guard_load, zero);
2066         }
2067     }
2068
2069     guard_load->eraseFromParent();
2070 }
2071
2072 static void ExciseGuardStore(Instruction* guard_store)
2073 {
2074     guard_store->eraseFromParent();
2075 }
2076
2077 bool
2078 IRForTarget::RemoveGuards(BasicBlock &basic_block)
2079 {
2080     ///////////////////////////////////////////////////////
2081     // Eliminate any reference to guard variables found.
2082     //
2083
2084     BasicBlock::iterator ii;
2085
2086     typedef SmallVector <Instruction*, 2> InstrList;
2087     typedef InstrList::iterator InstrIterator;
2088
2089     InstrList guard_loads;
2090     InstrList guard_stores;
2091
2092     for (ii = basic_block.begin();
2093          ii != basic_block.end();
2094          ++ii)
2095     {
2096         Instruction &inst = *ii;
2097
2098         if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2099             if (isGuardVariableRef(load->getPointerOperand()))
2100                 guard_loads.push_back(&inst);
2101
2102         if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2103             if (isGuardVariableRef(store->getPointerOperand()))
2104                 guard_stores.push_back(&inst);
2105     }
2106
2107     InstrIterator iter;
2108
2109     for (iter = guard_loads.begin();
2110          iter != guard_loads.end();
2111          ++iter)
2112         TurnGuardLoadIntoZero(*iter);
2113
2114     for (iter = guard_stores.begin();
2115          iter != guard_stores.end();
2116          ++iter)
2117         ExciseGuardStore(*iter);
2118
2119     return true;
2120 }
2121
2122 // This function does not report errors; its callers are responsible.
2123 bool
2124 IRForTarget::UnfoldConstant(Constant *old_constant,
2125                             FunctionValueCache &value_maker,
2126                             FunctionValueCache &entry_instruction_finder)
2127 {
2128     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2129
2130     SmallVector<User*, 16> users;
2131
2132     // We do this because the use list might change, invalidating our iterator.
2133     // Much better to keep a work list ourselves.
2134     for (llvm::User *u : old_constant->users())
2135         users.push_back(u);
2136
2137     for (size_t i = 0;
2138          i < users.size();
2139          ++i)
2140     {
2141         User *user = users[i];
2142
2143         if (Constant *constant = dyn_cast<Constant>(user))
2144         {
2145             // synthesize a new non-constant equivalent of the constant
2146
2147             if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2148             {
2149                 switch (constant_expr->getOpcode())
2150                 {
2151                 default:
2152                     if (log)
2153                         log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
2154                     return false;
2155                 case Instruction::BitCast:
2156                     {
2157                         FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2158                             // UnaryExpr
2159                             //   OperandList[0] is value
2160
2161                             if (constant_expr->getOperand(0) != old_constant)
2162                                 return constant_expr;
2163
2164                             return new BitCastInst(value_maker.GetValue(function),
2165                                                    constant_expr->getType(),
2166                                                    "",
2167                                                    llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2168                         });
2169
2170                         if (!UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder))
2171                             return false;
2172                     }
2173                     break;
2174                 case Instruction::GetElementPtr:
2175                     {
2176                         // GetElementPtrConstantExpr
2177                         //   OperandList[0] is base
2178                         //   OperandList[1]... are indices
2179
2180                         FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2181                             Value *ptr = constant_expr->getOperand(0);
2182
2183                             if (ptr == old_constant)
2184                                 ptr = value_maker.GetValue(function);
2185
2186                             std::vector<Value*> index_vector;
2187
2188                             unsigned operand_index;
2189                             unsigned num_operands = constant_expr->getNumOperands();
2190
2191                             for (operand_index = 1;
2192                                  operand_index < num_operands;
2193                                  ++operand_index)
2194                             {
2195                                 Value *operand = constant_expr->getOperand(operand_index);
2196
2197                                 if (operand == old_constant)
2198                                     operand = value_maker.GetValue(function);
2199
2200                                 index_vector.push_back(operand);
2201                             }
2202
2203                             ArrayRef <Value*> indices(index_vector);
2204
2205                             return GetElementPtrInst::Create(ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2206                         });
2207
2208                         if (!UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder))
2209                             return false;
2210                     }
2211                     break;
2212                 }
2213             }
2214             else
2215             {
2216                 if (log)
2217                     log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
2218                 return false;
2219             }
2220         }
2221         else
2222         {
2223             if (Instruction *inst = llvm::dyn_cast<Instruction>(user))
2224             {
2225                 inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent()));
2226             }
2227             else
2228             {
2229                 if (log)
2230                     log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str());
2231                 return false;
2232             }
2233         }
2234     }
2235
2236     if (!isa<GlobalValue>(old_constant))
2237     {
2238         old_constant->destroyConstant();
2239     }
2240
2241     return true;
2242 }
2243
2244 bool
2245 IRForTarget::ReplaceVariables (Function &llvm_function)
2246 {
2247     if (!m_resolve_vars)
2248         return true;
2249
2250     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2251
2252     m_decl_map->DoStructLayout();
2253
2254     if (log)
2255         log->Printf("Element arrangement:");
2256
2257     uint32_t num_elements;
2258     uint32_t element_index;
2259
2260     size_t size;
2261     lldb::offset_t alignment;
2262
2263     if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2264         return false;
2265
2266     Function::arg_iterator iter(llvm_function.getArgumentList().begin());
2267
2268     if (iter == llvm_function.getArgumentList().end())
2269     {
2270         if (m_error_stream)
2271             m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2272
2273         return false;
2274     }
2275
2276     Argument *argument = iter;
2277
2278     if (argument->getName().equals("this"))
2279     {
2280         ++iter;
2281
2282         if (iter == llvm_function.getArgumentList().end())
2283         {
2284             if (m_error_stream)
2285                 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2286
2287             return false;
2288         }
2289
2290         argument = iter;
2291     }
2292     else if (argument->getName().equals("self"))
2293     {
2294         ++iter;
2295
2296         if (iter == llvm_function.getArgumentList().end())
2297         {
2298             if (m_error_stream)
2299                 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2300
2301             return false;
2302         }
2303
2304         if (!iter->getName().equals("_cmd"))
2305         {
2306             if (m_error_stream)
2307                 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2308
2309             return false;
2310         }
2311
2312         ++iter;
2313
2314         if (iter == llvm_function.getArgumentList().end())
2315         {
2316             if (m_error_stream)
2317                 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2318
2319             return false;
2320         }
2321
2322         argument = iter;
2323     }
2324
2325     if (!argument->getName().equals("$__lldb_arg"))
2326     {
2327         if (m_error_stream)
2328             m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2329
2330         return false;
2331     }
2332
2333     if (log)
2334         log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
2335
2336     BasicBlock &entry_block(llvm_function.getEntryBlock());
2337     Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
2338
2339     if (!FirstEntryInstruction)
2340     {
2341         if (m_error_stream)
2342             m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2343
2344         return false;
2345     }
2346
2347     LLVMContext &context(m_module->getContext());
2348     IntegerType *offset_type(Type::getInt32Ty(context));
2349
2350     if (!offset_type)
2351     {
2352         if (m_error_stream)
2353             m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2354
2355         return false;
2356     }
2357
2358     for (element_index = 0; element_index < num_elements; ++element_index)
2359     {
2360         const clang::NamedDecl *decl = NULL;
2361         Value *value = NULL;
2362         lldb::offset_t offset;
2363         lldb_private::ConstString name;
2364
2365         if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
2366         {
2367             if (m_error_stream)
2368                 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2369
2370             return false;
2371         }
2372
2373         if (log)
2374             log->Printf("  \"%s\" (\"%s\") placed at %" PRIu64,
2375                         name.GetCString(),
2376                         decl->getNameAsString().c_str(),
2377                         offset);
2378
2379         if (value)
2380         {
2381             if (log)
2382                 log->Printf("    Replacing [%s]", PrintValue(value).c_str());
2383
2384             FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * {
2385                 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2386                 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2387                 // entry in order to produce the static variable that the AST thinks it is accessing.
2388
2389                 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function));
2390
2391                 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
2392                 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument,
2393                                                                                offset_int,
2394                                                                                "",
2395                                                                                entry_instruction);
2396
2397                 if (name == m_result_name && !m_result_is_pointer)
2398                 {
2399                     BitCastInst *bit_cast = new BitCastInst(get_element_ptr,
2400                                                             value->getType()->getPointerTo(),
2401                                                             "",
2402                                                             entry_instruction);
2403
2404                     LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
2405
2406                     return load;
2407                 }
2408                 else
2409                 {
2410                     BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction);
2411
2412                     return bit_cast;
2413                 }
2414             });
2415
2416             if (Constant *constant = dyn_cast<Constant>(value))
2417             {
2418                 UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder);
2419             }
2420             else if (Instruction *instruction = dyn_cast<Instruction>(value))
2421             {
2422                 value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent()));
2423             }
2424             else
2425             {
2426                 if (log)
2427                     log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str());
2428                 return false;
2429             }
2430
2431             if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2432                 var->eraseFromParent();
2433         }
2434     }
2435
2436     if (log)
2437         log->Printf("Total structure [align %" PRId64 ", size %" PRIu64 "]", (int64_t)alignment, (uint64_t)size);
2438
2439     return true;
2440 }
2441
2442 llvm::Constant *
2443 IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
2444 {
2445     llvm::Constant *offset_int = ConstantInt::get(m_intptr_ty, offset);
2446
2447     llvm::Constant *offset_array[1];
2448
2449     offset_array[0] = offset_int;
2450
2451     llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2452
2453     llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
2454     llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2455
2456     return reloc_getbitcast;
2457 }
2458
2459 bool
2460 IRForTarget::CompleteDataAllocation ()
2461 {
2462     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2463
2464     if (!m_data_allocator.GetStream().GetSize())
2465         return true;
2466
2467     lldb::addr_t allocation = m_data_allocator.Allocate();
2468
2469     if (log)
2470     {
2471         if (allocation)
2472             log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2473         else
2474             log->Printf("Failed to allocate static data");
2475     }
2476
2477     if (!allocation || allocation == LLDB_INVALID_ADDRESS)
2478         return false;
2479
2480     Constant *relocated_addr = ConstantInt::get(m_intptr_ty, (uint64_t)allocation);
2481     Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2482
2483     m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2484
2485     m_reloc_placeholder->eraseFromParent();
2486
2487     return true;
2488 }
2489
2490 bool
2491 IRForTarget::StripAllGVs (Module &llvm_module)
2492 {
2493     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2494     std::vector<GlobalVariable *> global_vars;
2495     std::set<GlobalVariable *>erased_vars;
2496
2497     bool erased = true;
2498
2499     while (erased)
2500     {
2501         erased = false;
2502
2503         for (GlobalVariable &global_var : llvm_module.globals())
2504         {
2505             global_var.removeDeadConstantUsers();
2506
2507             if (global_var.use_empty())
2508             {
2509                 if (log)
2510                     log->Printf("Did remove %s",
2511                                 PrintValue(&global_var).c_str());
2512                 global_var.eraseFromParent();
2513                 erased = true;
2514                 break;
2515             }
2516         }
2517     }
2518
2519     for (GlobalVariable &global_var : llvm_module.globals())
2520     {
2521         GlobalValue::user_iterator ui = global_var.user_begin();
2522
2523         if (log)
2524             log->Printf("Couldn't remove %s because of %s",
2525                         PrintValue(&global_var).c_str(),
2526                         PrintValue(*ui).c_str());
2527     }
2528
2529     return true;
2530 }
2531
2532 bool
2533 IRForTarget::runOnModule (Module &llvm_module)
2534 {
2535     lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2536
2537     m_module = &llvm_module;
2538     m_target_data.reset(new DataLayout(m_module));
2539     m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(), m_target_data->getPointerSizeInBits());
2540
2541     if (log)
2542     {
2543         std::string s;
2544         raw_string_ostream oss(s);
2545
2546         m_module->print(oss, NULL);
2547
2548         oss.flush();
2549
2550         log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2551     }
2552
2553     Function* main_function = m_module->getFunction(StringRef(m_func_name.c_str()));
2554
2555     if (!main_function)
2556     {
2557         if (log)
2558             log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
2559
2560         if (m_error_stream)
2561             m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
2562
2563         return false;
2564     }
2565
2566     if (!FixFunctionLinkage (*main_function))
2567     {
2568         if (log)
2569             log->Printf("Couldn't fix the linkage for the function");
2570
2571         return false;
2572     }
2573
2574     llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext());
2575
2576     m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2577                                                    int8_ty,
2578                                                    false /* IsConstant */,
2579                                                    GlobalVariable::InternalLinkage,
2580                                                    Constant::getNullValue(int8_ty),
2581                                                    "reloc_placeholder",
2582                                                    NULL /* InsertBefore */,
2583                                                    GlobalVariable::NotThreadLocal /* ThreadLocal */,
2584                                                    0 /* AddressSpace */);
2585
2586     ////////////////////////////////////////////////////////////
2587     // Replace $__lldb_expr_result with a persistent variable
2588     //
2589
2590     if (!CreateResultVariable(*main_function))
2591     {
2592         if (log)
2593             log->Printf("CreateResultVariable() failed");
2594
2595         // CreateResultVariable() reports its own errors, so we don't do so here
2596
2597         return false;
2598     }
2599
2600     if (log && log->GetVerbose())
2601     {
2602         std::string s;
2603         raw_string_ostream oss(s);
2604
2605         m_module->print(oss, NULL);
2606
2607         oss.flush();
2608
2609         log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2610     }
2611
2612     for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2613          fi != fe;
2614          ++fi)
2615     {
2616         llvm::Function *function = fi;
2617
2618         if (function->begin() == function->end())
2619             continue;
2620
2621         Function::iterator bbi;
2622
2623         for (bbi = function->begin();
2624              bbi != function->end();
2625              ++bbi)
2626         {
2627             if (!RemoveGuards(*bbi))
2628             {
2629                 if (log)
2630                     log->Printf("RemoveGuards() failed");
2631
2632                 // RemoveGuards() reports its own errors, so we don't do so here
2633
2634                 return false;
2635             }
2636
2637             if (!RewritePersistentAllocs(*bbi))
2638             {
2639                 if (log)
2640                     log->Printf("RewritePersistentAllocs() failed");
2641
2642                 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2643
2644                 return false;
2645             }
2646
2647             if (!RemoveCXAAtExit(*bbi))
2648             {
2649                 if (log)
2650                     log->Printf("RemoveCXAAtExit() failed");
2651
2652                 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2653
2654                 return false;
2655             }
2656         }
2657     }
2658
2659     ///////////////////////////////////////////////////////////////////////////////
2660     // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2661     //
2662
2663     if (!RewriteObjCConstStrings())
2664     {
2665         if (log)
2666             log->Printf("RewriteObjCConstStrings() failed");
2667
2668         // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2669
2670         return false;
2671     }
2672
2673     ///////////////////////////////
2674     // Resolve function pointers
2675     //
2676
2677     if (!ResolveFunctionPointers(llvm_module))
2678     {
2679         if (log)
2680             log->Printf("ResolveFunctionPointers() failed");
2681
2682         // ResolveFunctionPointers() reports its own errors, so we don't do so here
2683
2684         return false;
2685     }
2686
2687     for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2688          fi != fe;
2689          ++fi)
2690     {
2691         llvm::Function *function = fi;
2692
2693         for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2694              bbi != bbe;
2695              ++bbi)
2696         {
2697             if (!RewriteObjCSelectors(*bbi))
2698             {
2699                 if (log)
2700                     log->Printf("RewriteObjCSelectors() failed");
2701
2702                 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2703
2704                 return false;
2705             }
2706         }
2707     }
2708
2709     for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2710          fi != fe;
2711          ++fi)
2712     {
2713         llvm::Function *function = fi;
2714
2715         for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2716              bbi != bbe;
2717              ++bbi)
2718         {
2719             if (!ResolveCalls(*bbi))
2720             {
2721                 if (log)
2722                     log->Printf("ResolveCalls() failed");
2723
2724                 // ResolveCalls() reports its own errors, so we don't do so here
2725
2726                 return false;
2727             }
2728
2729             if (!ReplaceStaticLiterals(*bbi))
2730             {
2731                 if (log)
2732                     log->Printf("ReplaceStaticLiterals() failed");
2733
2734                 return false;
2735             }
2736         }
2737     }
2738
2739     ////////////////////////////////////////////////////////////////////////
2740     // Run function-level passes that only make sense on the main function
2741     //
2742
2743     if (!ResolveExternals(*main_function))
2744     {
2745         if (log)
2746             log->Printf("ResolveExternals() failed");
2747
2748         // ResolveExternals() reports its own errors, so we don't do so here
2749
2750         return false;
2751     }
2752
2753     if (!ReplaceVariables(*main_function))
2754     {
2755         if (log)
2756             log->Printf("ReplaceVariables() failed");
2757
2758         // ReplaceVariables() reports its own errors, so we don't do so here
2759
2760         return false;
2761     }
2762
2763     if (!ReplaceStrings())
2764     {
2765         if (log)
2766             log->Printf("ReplaceStrings() failed");
2767
2768         return false;
2769     }
2770
2771     if (!CompleteDataAllocation())
2772     {
2773         if (log)
2774             log->Printf("CompleteDataAllocation() failed");
2775
2776         return false;
2777     }
2778
2779     if (!StripAllGVs(llvm_module))
2780     {
2781         if (log)
2782             log->Printf("StripAllGVs() failed");
2783     }
2784
2785     if (log && log->GetVerbose())
2786     {
2787         std::string s;
2788         raw_string_ostream oss(s);
2789
2790         m_module->print(oss, NULL);
2791
2792         oss.flush();
2793
2794         log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
2795     }
2796
2797     return true;
2798 }
2799
2800 void
2801 IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
2802 {
2803 }
2804
2805 PassManagerType
2806 IRForTarget::getPotentialPassManagerType() const
2807 {
2808     return PMT_ModulePassManager;
2809 }