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