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