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