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