blob: c3379a12b3b810131c75858d2c8e89671ec28e86 [file] [log] [blame]
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001//===-- IRForTarget.cpp -------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Expression/IRForTarget.h"
11
12#include "llvm/Support/raw_ostream.h"
13#include "llvm/InstrTypes.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000014#include "llvm/Instructions.h"
Sean Callanan3cb1fd82010-09-28 23:55:00 +000015#include "llvm/Intrinsics.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000016#include "llvm/Module.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000017#include "llvm/Target/TargetData.h"
Sean Callanan82b74c82010-08-12 01:56:52 +000018#include "llvm/ValueSymbolTable.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000019
20#include "clang/AST/ASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000021
Greg Clayton8de27c72010-10-15 22:48:33 +000022#include "lldb/Core/ConstString.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000023#include "lldb/Core/dwarf.h"
24#include "lldb/Core/Log.h"
25#include "lldb/Core/Scalar.h"
26#include "lldb/Core/StreamString.h"
27#include "lldb/Expression/ClangExpressionDeclMap.h"
28
29#include <map>
30
31using namespace llvm;
32
Sean Callanan3351dac2010-08-18 18:50:51 +000033static char ID;
34
35IRForTarget::IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +000036 bool resolve_vars,
Sean Callanan65dafa82010-08-27 01:01:44 +000037 const char *func_name) :
Sean Callanan47a5c4c2010-09-23 03:01:22 +000038 ModulePass(ID),
Sean Callanan8bce6652010-07-13 21:41:46 +000039 m_decl_map(decl_map),
Sean Callanan6ba533e2010-11-17 23:00:36 +000040 m_CFStringCreateWithBytes(NULL),
Sean Callanan65dafa82010-08-27 01:01:44 +000041 m_sel_registerName(NULL),
Sean Callanane8a59a82010-09-13 21:34:21 +000042 m_func_name(func_name),
43 m_resolve_vars(resolve_vars)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000044{
45}
46
Sean Callanan771131d2010-09-30 21:18:25 +000047/* Handy utility functions used at several places in the code */
Sean Callanana48fe162010-08-11 03:57:18 +000048
49static std::string
Sean Callanan771131d2010-09-30 21:18:25 +000050PrintValue(const Value *V, bool truncate = false)
Sean Callanana48fe162010-08-11 03:57:18 +000051{
52 std::string s;
53 raw_string_ostream rso(s);
54 V->print(rso);
55 rso.flush();
56 if (truncate)
57 s.resize(s.length() - 1);
58 return s;
59}
60
Sean Callanan771131d2010-09-30 21:18:25 +000061static std::string
62PrintType(const Type *T, bool truncate = false)
63{
64 std::string s;
65 raw_string_ostream rso(s);
66 T->print(rso);
67 rso.flush();
68 if (truncate)
69 s.resize(s.length() - 1);
70 return s;
71}
72
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000073IRForTarget::~IRForTarget()
74{
75}
76
Sean Callanan82b74c82010-08-12 01:56:52 +000077bool
Greg Clayton8de27c72010-10-15 22:48:33 +000078IRForTarget::createResultVariable (llvm::Module &llvm_module, llvm::Function &llvm_function)
Sean Callanan82b74c82010-08-12 01:56:52 +000079{
Greg Claytone005f2c2010-11-06 01:53:30 +000080 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan82b74c82010-08-12 01:56:52 +000081
Sean Callanane8a59a82010-09-13 21:34:21 +000082 if (!m_resolve_vars)
83 return true;
84
85 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000086
Greg Clayton8de27c72010-10-15 22:48:33 +000087 ValueSymbolTable& value_symbol_table = llvm_module.getValueSymbolTable();
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000088
89 const char *result_name = NULL;
90
91 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
92 vi != ve;
93 ++vi)
94 {
Greg Clayton8de27c72010-10-15 22:48:33 +000095 if (strstr(vi->first(), "$__lldb_expr_result") &&
Sean Callananc04743d2010-09-28 21:13:03 +000096 !strstr(vi->first(), "GV"))
97 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000098 result_name = vi->first();
Sean Callananc04743d2010-09-28 21:13:03 +000099 break;
100 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000101 }
102
103 if (!result_name)
104 {
105 if (log)
106 log->PutCString("Couldn't find result variable");
107
108 return true;
109 }
110
Sean Callananc04743d2010-09-28 21:13:03 +0000111 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000112 log->Printf("Result name: \"%s\"", result_name);
Sean Callananc04743d2010-09-28 21:13:03 +0000113
Greg Clayton8de27c72010-10-15 22:48:33 +0000114 Value *result_value = llvm_module.getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000115
116 if (!result_value)
117 {
118 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000119 log->PutCString("Result variable had no data");
Sean Callanane8a59a82010-09-13 21:34:21 +0000120
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000121 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000122 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000123
Sean Callanan82b74c82010-08-12 01:56:52 +0000124 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000125 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000126
127 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
128
129 if (!result_global)
130 {
131 if (log)
132 log->PutCString("Result variable isn't a GlobalVariable");
133 return false;
134 }
135
136 // Find the metadata and follow it to the VarDecl
137
Greg Clayton8de27c72010-10-15 22:48:33 +0000138 NamedMDNode *named_metadata = llvm_module.getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000139
140 if (!named_metadata)
141 {
142 if (log)
143 log->PutCString("No global metadata");
144
145 return false;
146 }
147
148 unsigned num_nodes = named_metadata->getNumOperands();
149 unsigned node_index;
150
151 MDNode *metadata_node = NULL;
152
153 for (node_index = 0;
154 node_index < num_nodes;
155 ++node_index)
156 {
157 metadata_node = named_metadata->getOperand(node_index);
158
159 if (metadata_node->getNumOperands() != 2)
160 continue;
161
162 if (metadata_node->getOperand(0) == result_global)
163 break;
164 }
165
166 if (!metadata_node)
167 {
168 if (log)
169 log->PutCString("Couldn't find result metadata");
170 return false;
171 }
172
173 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
174
Greg Claytonb5037af2010-11-15 01:47:11 +0000175 lldb::addr_t result_decl_intptr = constant_int->getZExtValue();
Sean Callanan82b74c82010-08-12 01:56:52 +0000176
177 clang::VarDecl *result_decl = reinterpret_cast<clang::VarDecl *>(result_decl_intptr);
178
179 // Get the next available result name from m_decl_map and create the persistent
180 // variable for it
181
182 lldb_private::TypeFromParser result_decl_type (result_decl->getType().getAsOpaquePtr(),
183 &result_decl->getASTContext());
Greg Clayton8de27c72010-10-15 22:48:33 +0000184
185 lldb_private::ConstString new_result_name (m_decl_map->GetPersistentResultName());
186 m_decl_map->AddPersistentVariable(result_decl, new_result_name, result_decl_type);
Sean Callanan82b74c82010-08-12 01:56:52 +0000187
188 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000189 log->Printf("Creating a new result global: \"%s\"", new_result_name.GetCString());
Sean Callanan82b74c82010-08-12 01:56:52 +0000190
191 // Construct a new result global and set up its metadata
192
Greg Clayton8de27c72010-10-15 22:48:33 +0000193 GlobalVariable *new_result_global = new GlobalVariable(llvm_module,
Sean Callanan82b74c82010-08-12 01:56:52 +0000194 result_global->getType()->getElementType(),
195 false, /* not constant */
196 GlobalValue::ExternalLinkage,
197 NULL, /* no initializer */
Greg Clayton8de27c72010-10-15 22:48:33 +0000198 new_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000199
200 // It's too late in compilation to create a new VarDecl for this, but we don't
201 // need to. We point the metadata at the old VarDecl. This creates an odd
202 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000203 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000204 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
205 // fixed up.
206
207 ConstantInt *new_constant_int = ConstantInt::get(constant_int->getType(),
208 result_decl_intptr,
209 false);
210
211 llvm::Value* values[2];
212 values[0] = new_result_global;
213 values[1] = new_constant_int;
214
Greg Clayton8de27c72010-10-15 22:48:33 +0000215 MDNode *persistent_global_md = MDNode::get(llvm_module.getContext(), values, 2);
Sean Callanan82b74c82010-08-12 01:56:52 +0000216 named_metadata->addOperand(persistent_global_md);
217
218 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000219 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000220 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000221 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000222
223 if (result_global->hasNUses(0))
224 {
225 // We need to synthesize a store for this variable, because otherwise
226 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000227
Greg Clayton8de27c72010-10-15 22:48:33 +0000228 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000229 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
230
231 if (!first_entry_instruction)
232 return false;
233
234 if (!result_global->hasInitializer())
235 {
236 if (log)
237 log->Printf("Couldn't find initializer for unused variable");
238 return false;
239 }
240
241 Constant *initializer = result_global->getInitializer();
242
243 StoreInst *synthesized_store = new StoreInst::StoreInst(initializer,
244 new_result_global,
245 first_entry_instruction);
246
247 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000248 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000249 }
250 else
251 {
252 result_global->replaceAllUsesWith(new_result_global);
253 }
254
Sean Callanan82b74c82010-08-12 01:56:52 +0000255 result_global->eraseFromParent();
256
257 return true;
258}
259
Sean Callanan6ba533e2010-11-17 23:00:36 +0000260static void DebugUsers(lldb::LogSP &log, Value *V, uint8_t depth)
261{
262 if (!depth)
263 return;
264
265 depth--;
266
267 log->Printf(" <Begin %d users>", V->getNumUses());
268
269 for (Value::use_iterator ui = V->use_begin(), ue = V->use_end();
270 ui != ue;
271 ++ui)
272 {
273 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
274 DebugUsers(log, *ui, depth);
275 }
276
277 log->Printf(" <End uses>");
278}
279
280bool
281IRForTarget::rewriteObjCConstString(llvm::Module &M,
282 llvm::GlobalVariable *NSStr,
283 llvm::GlobalVariable *CStr,
284 Instruction *FirstEntryInstruction)
285{
286 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
287
288 const Type *i8_ptr_ty = Type::getInt8PtrTy(M.getContext());
289 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
290 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
291 const Type *i32_ty = Type::getInt32Ty(M.getContext());
292 const Type *i8_ty = Type::getInt8Ty(M.getContext());
293
294 if (!m_CFStringCreateWithBytes)
295 {
296 lldb::addr_t CFStringCreateWithBytes_addr;
297
298 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
299
300 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
301 {
302 if (log)
303 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
304
305 return false;
306 }
307
308 if (log)
309 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr);
310
311 // Build the function type:
312 //
313 // CFStringRef CFStringCreateWithBytes (
314 // CFAllocatorRef alloc,
315 // const UInt8 *bytes,
316 // CFIndex numBytes,
317 // CFStringEncoding encoding,
318 // Boolean isExternalRepresentation
319 // );
320 //
321 // We make the following substitutions:
322 //
323 // CFStringRef -> i8*
324 // CFAllocatorRef -> i8*
325 // UInt8 * -> i8*
326 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
327 // CFStringEncoding -> i32
328 // Boolean -> i8
329
330 std::vector <const Type *> CFSCWB_arg_types;
331 CFSCWB_arg_types.push_back(i8_ptr_ty);
332 CFSCWB_arg_types.push_back(i8_ptr_ty);
333 CFSCWB_arg_types.push_back(intptr_ty);
334 CFSCWB_arg_types.push_back(i32_ty);
335 CFSCWB_arg_types.push_back(i8_ty);
336 llvm::Type *CFSCWB_ty = FunctionType::get(i8_ptr_ty, CFSCWB_arg_types, false);
337
338 // Build the constant containing the pointer to the function
339 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
340 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
341 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
342 }
343
344 ConstantArray *string_array = dyn_cast<ConstantArray>(CStr->getInitializer());
345
346 SmallVector <Value*, 5> CFSCWB_arguments;
347
348 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
349 Constant *bytes_arg = ConstantExpr::getBitCast(CStr, i8_ptr_ty);
350 Constant *numBytes_arg = ConstantInt::get(intptr_ty, string_array->getType()->getNumElements(), false);
351 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
352 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
353
354 CFSCWB_arguments.push_back(alloc_arg);
355 CFSCWB_arguments.push_back(bytes_arg);
356 CFSCWB_arguments.push_back(numBytes_arg);
357 CFSCWB_arguments.push_back(encoding_arg);
358 CFSCWB_arguments.push_back(isExternal_arg);
359
360 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
361 CFSCWB_arguments.begin(),
362 CFSCWB_arguments.end(),
363 "CFStringCreateWithBytes",
364 FirstEntryInstruction);
365
366 Constant *initializer = NSStr->getInitializer();
367
368 if (!UnfoldConstant(NSStr, CFSCWB_call, FirstEntryInstruction))
369 {
370 if (log)
371 log->PutCString("Couldn't replace the NSString with the result of the call");
372
373 return false;
374 }
375
376 NSStr->eraseFromParent();
377
378 return true;
379}
380
381bool
382IRForTarget::rewriteObjCConstStrings(Module &M,
383 Function &F)
384{
385 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
386
387 ValueSymbolTable& value_symbol_table = M.getValueSymbolTable();
388
389 BasicBlock &entry_block(F.getEntryBlock());
390 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
391
392 if (!FirstEntryInstruction)
393 {
394 if (log)
395 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
396
397 return false;
398 }
399
400 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
401 vi != ve;
402 ++vi)
403 {
404 if (strstr(vi->first(), "_unnamed_cfstring_"))
405 {
406 Value *nsstring_value = vi->second;
407
408 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
409
410 if (!nsstring_global)
411 {
412 if (log)
413 log->PutCString("NSString variable is not a GlobalVariable");
414 return false;
415 }
416
417 if (!nsstring_global->hasInitializer())
418 {
419 if (log)
420 log->PutCString("NSString variable does not have an initializer");
421 return false;
422 }
423
424 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
425
426 if (!nsstring_struct)
427 {
428 if (log)
429 log->PutCString("NSString variable's initializer is not a ConstantStruct");
430 return false;
431 }
432
433 // We expect the following structure:
434 //
435 // struct {
436 // int *isa;
437 // int flags;
438 // char *str;
439 // long length;
440 // };
441
442 if (nsstring_struct->getNumOperands() != 4)
443 {
444 if (log)
445 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands());
446 return false;
447 }
448
449 Constant *nsstring_member = nsstring_struct->getOperand(2);
450
451 if (!nsstring_member)
452 {
453 if (log)
454 log->PutCString("NSString initializer's str element was empty");
455 return false;
456 }
457
458 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
459
460 if (!nsstring_expr)
461 {
462 if (log)
463 log->PutCString("NSString initializer's str element is not a ConstantExpr");
464 return false;
465 }
466
467 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
468 {
469 if (log)
470 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
471 return false;
472 }
473
474 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
475
476 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
477
478 if (!cstr_global)
479 {
480 if (log)
481 log->PutCString("NSString initializer's str element is not a GlobalVariable");
482
483 nsstring_cstr->dump();
484
485 return false;
486 }
487
488 if (!cstr_global->hasInitializer())
489 {
490 if (log)
491 log->PutCString("NSString initializer's str element does not have an initializer");
492 return false;
493 }
494
495 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer());
496
497 if (!cstr_array)
498 {
499 if (log)
500 log->PutCString("NSString initializer's str element is not a ConstantArray");
501 return false;
502 }
503
504 if (!cstr_array->isCString())
505 {
506 if (log)
507 log->PutCString("NSString initializer's str element is not a C string array");
508 return false;
509 }
510
511 if (log)
512 log->Printf("Found NSString constant %s, which contains \"%s\"", vi->first(), cstr_array->getAsString().c_str());
513
514 if (!rewriteObjCConstString(M, nsstring_global, cstr_global, FirstEntryInstruction))
515 {
516 if (log)
517 log->PutCString("Error rewriting the constant string");
518 return false;
519 }
520
521
522 }
523 }
524
525 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
526 vi != ve;
527 ++vi)
528 {
529 if (!strcmp(vi->first(), "__CFConstantStringClassReference"))
530 {
531 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
532
533 if (!gv)
534 {
535 if (log)
536 log->PutCString("__CFConstantStringClassReference is not a global variable");
537 return false;
538 }
539
540 gv->eraseFromParent();
541
542 break;
543 }
544 }
545
546 return true;
547}
548
Sean Callananf5857a02010-07-31 01:32:05 +0000549static bool isObjCSelectorRef(Value *V)
550{
551 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
552
553 if (!GV || !GV->hasName() || !GV->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
554 return false;
555
556 return true;
557}
558
559bool
560IRForTarget::RewriteObjCSelector(Instruction* selector_load,
561 Module &M)
562{
Greg Claytone005f2c2010-11-06 01:53:30 +0000563 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +0000564
565 LoadInst *load = dyn_cast<LoadInst>(selector_load);
566
567 if (!load)
568 return false;
569
570 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
571 //
572 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
573 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
574 //
575 // where %obj is the object pointer and %tmp is the selector.
576 //
577 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_METH_VAR_NAME_".
578 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
579
580 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
581
582 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
583
584 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
585 return false;
586
587 Constant *osr_initializer = _objc_selector_references_->getInitializer();
588
589 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
590
591 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
592 return false;
593
594 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
595
596 if (!osr_initializer_base)
597 return false;
598
599 // Find the string's initializer (a ConstantArray) and get the string from it
600
601 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
602
603 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
604 return false;
605
606 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
607
608 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
609
610 if (!omvn_initializer_array->isString())
611 return false;
612
613 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
614
615 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000616 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +0000617
618 // Construct a call to sel_registerName
619
620 if (!m_sel_registerName)
621 {
Greg Claytonb5037af2010-11-15 01:47:11 +0000622 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000623
Greg Clayton8de27c72010-10-15 22:48:33 +0000624 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +0000625 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +0000626 return false;
627
Sean Callananc2c6f772010-10-26 00:31:56 +0000628 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000629 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +0000630
Sean Callananf5857a02010-07-31 01:32:05 +0000631 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
632
633 // The below code would be "more correct," but in actuality what's required is uint8_t*
634 //Type *sel_type = StructType::get(M.getContext());
635 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
636 const Type *sel_ptr_type = Type::getInt8PtrTy(M.getContext());
637
638 std::vector <const Type *> srN_arg_types;
639 srN_arg_types.push_back(Type::getInt8PtrTy(M.getContext()));
640 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
641
642 // Build the constant containing the pointer to the function
643 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
644 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
645 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +0000646 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000647 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
648 }
649
650 SmallVector <Value*, 1> srN_arguments;
651
652 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(M.getContext()));
653
654 srN_arguments.push_back(omvn_pointer);
655
656 CallInst *srN_call = CallInst::Create(m_sel_registerName,
657 srN_arguments.begin(),
658 srN_arguments.end(),
Sean Callanan6ba533e2010-11-17 23:00:36 +0000659 "sel_registerName",
Sean Callananf5857a02010-07-31 01:32:05 +0000660 selector_load);
661
662 // Replace the load with the call in all users
663
664 selector_load->replaceAllUsesWith(srN_call);
665
666 selector_load->eraseFromParent();
667
668 return true;
669}
670
671bool
672IRForTarget::rewriteObjCSelectors(Module &M,
673 BasicBlock &BB)
674{
Greg Claytone005f2c2010-11-06 01:53:30 +0000675 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +0000676
677 BasicBlock::iterator ii;
678
679 typedef SmallVector <Instruction*, 2> InstrList;
680 typedef InstrList::iterator InstrIterator;
681
682 InstrList selector_loads;
683
684 for (ii = BB.begin();
685 ii != BB.end();
686 ++ii)
687 {
688 Instruction &inst = *ii;
689
690 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
691 if (isObjCSelectorRef(load->getPointerOperand()))
692 selector_loads.push_back(&inst);
693 }
694
695 InstrIterator iter;
696
697 for (iter = selector_loads.begin();
698 iter != selector_loads.end();
699 ++iter)
700 {
701 if (!RewriteObjCSelector(*iter, M))
702 {
703 if(log)
704 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
705 return false;
706 }
707 }
708
709 return true;
710}
711
Sean Callanana48fe162010-08-11 03:57:18 +0000712bool
713IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc,
Greg Clayton8de27c72010-10-15 22:48:33 +0000714 llvm::Module &llvm_module)
Sean Callanana48fe162010-08-11 03:57:18 +0000715{
716 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
717
718 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
719
720 if (!alloc_md || !alloc_md->getNumOperands())
721 return false;
722
723 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
724
725 if (!constant_int)
726 return false;
727
728 // We attempt to register this as a new persistent variable with the DeclMap.
729
730 uintptr_t ptr = constant_int->getZExtValue();
731
Sean Callanan82b74c82010-08-12 01:56:52 +0000732 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +0000733
Sean Callanan82b74c82010-08-12 01:56:52 +0000734 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
735 &decl->getASTContext());
736
Greg Clayton8de27c72010-10-15 22:48:33 +0000737 StringRef decl_name (decl->getName());
738 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
739 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type))
Sean Callanana48fe162010-08-11 03:57:18 +0000740 return false;
741
Greg Clayton8de27c72010-10-15 22:48:33 +0000742 GlobalVariable *persistent_global = new GlobalVariable(llvm_module,
Sean Callanana48fe162010-08-11 03:57:18 +0000743 alloc->getType()->getElementType(),
744 false, /* not constant */
745 GlobalValue::ExternalLinkage,
746 NULL, /* no initializer */
747 alloc->getName().str().c_str());
748
749 // What we're going to do here is make believe this was a regular old external
750 // variable. That means we need to make the metadata valid.
751
Greg Clayton8de27c72010-10-15 22:48:33 +0000752 NamedMDNode *named_metadata = llvm_module.getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +0000753
754 llvm::Value* values[2];
755 values[0] = persistent_global;
756 values[1] = constant_int;
757
Greg Clayton8de27c72010-10-15 22:48:33 +0000758 MDNode *persistent_global_md = MDNode::get(llvm_module.getContext(), values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +0000759 named_metadata->addOperand(persistent_global_md);
760
761 alloc->replaceAllUsesWith(persistent_global);
762 alloc->eraseFromParent();
763
764 return true;
765}
766
767bool
768IRForTarget::rewritePersistentAllocs(llvm::Module &M,
769 llvm::BasicBlock &BB)
770{
Sean Callanane8a59a82010-09-13 21:34:21 +0000771 if (!m_resolve_vars)
772 return true;
773
Greg Claytone005f2c2010-11-06 01:53:30 +0000774 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +0000775
776 BasicBlock::iterator ii;
777
778 typedef SmallVector <Instruction*, 2> InstrList;
779 typedef InstrList::iterator InstrIterator;
780
781 InstrList pvar_allocs;
782
783 for (ii = BB.begin();
784 ii != BB.end();
785 ++ii)
786 {
787 Instruction &inst = *ii;
788
789 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan03c997b2010-10-21 22:41:32 +0000790 if (alloc->getName().startswith("$") &&
791 !alloc->getName().startswith("$__lldb"))
Sean Callanana48fe162010-08-11 03:57:18 +0000792 pvar_allocs.push_back(alloc);
793 }
794
795 InstrIterator iter;
796
797 for (iter = pvar_allocs.begin();
798 iter != pvar_allocs.end();
799 ++iter)
800 {
801 if (!RewritePersistentAlloc(*iter, M))
802 {
803 if(log)
804 log->PutCString("Couldn't rewrite the creation of a persistent variable");
805 return false;
806 }
807 }
808
809 return true;
810}
811
Sean Callanan8bce6652010-07-13 21:41:46 +0000812static clang::NamedDecl *
Sean Callanan02fbafa2010-07-27 21:39:39 +0000813DeclForGlobalValue(Module &module,
814 GlobalValue *global_value)
Sean Callanan8bce6652010-07-13 21:41:46 +0000815{
816 NamedMDNode *named_metadata = module.getNamedMetadata("clang.global.decl.ptrs");
817
818 if (!named_metadata)
819 return NULL;
820
821 unsigned num_nodes = named_metadata->getNumOperands();
822 unsigned node_index;
823
824 for (node_index = 0;
825 node_index < num_nodes;
826 ++node_index)
827 {
828 MDNode *metadata_node = named_metadata->getOperand(node_index);
829
830 if (!metadata_node)
831 return NULL;
832
833 if (metadata_node->getNumOperands() != 2)
Sean Callanana48fe162010-08-11 03:57:18 +0000834 continue;
Sean Callanan8bce6652010-07-13 21:41:46 +0000835
836 if (metadata_node->getOperand(0) != global_value)
837 continue;
838
839 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
840
841 if (!constant_int)
842 return NULL;
843
844 uintptr_t ptr = constant_int->getZExtValue();
845
846 return reinterpret_cast<clang::NamedDecl *>(ptr);
847 }
848
849 return NULL;
850}
851
852bool
Greg Clayton8de27c72010-10-15 22:48:33 +0000853IRForTarget::MaybeHandleVariable
854(
855 Module &llvm_module,
Sean Callanan1d1b39c2010-11-08 00:31:32 +0000856 Value *llvm_value_ptr
Greg Clayton8de27c72010-10-15 22:48:33 +0000857)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000858{
Greg Claytone005f2c2010-11-06 01:53:30 +0000859 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +0000860
Greg Clayton8de27c72010-10-15 22:48:33 +0000861 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +0000862 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000863 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +0000864 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000865 default:
866 break;
867 case Instruction::GetElementPtr:
868 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +0000869 Value *s = constant_expr->getOperand(0);
Sean Callanan1d1b39c2010-11-08 00:31:32 +0000870 MaybeHandleVariable(llvm_module, s);
Sean Callananbc2928a2010-08-03 00:23:29 +0000871 }
872 }
Greg Clayton8de27c72010-10-15 22:48:33 +0000873 if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +0000874 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000875 clang::NamedDecl *named_decl = DeclForGlobalValue(llvm_module, global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000876
Sean Callananf5857a02010-07-31 01:32:05 +0000877 if (!named_decl)
878 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000879 if (isObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +0000880 return true;
881
882 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000883 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callananf5857a02010-07-31 01:32:05 +0000884 return false;
885 }
886
Greg Clayton8de27c72010-10-15 22:48:33 +0000887 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +0000888
Sean Callanan771131d2010-09-30 21:18:25 +0000889 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +0000890 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +0000891
892 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +0000893 {
Sean Callanan771131d2010-09-30 21:18:25 +0000894 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +0000895 ast_context = &value_decl->getASTContext();
896 }
Sean Callanan810f22d2010-07-16 00:09:46 +0000897 else
Sean Callananf328c9f2010-07-20 23:31:16 +0000898 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000899 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +0000900 }
Sean Callanan771131d2010-09-30 21:18:25 +0000901
902 clang::QualType qual_type(clang::QualType::getFromOpaquePtr(opaque_type));
Sean Callananf328c9f2010-07-20 23:31:16 +0000903
Sean Callanan02fbafa2010-07-27 21:39:39 +0000904 const Type *value_type = global_variable->getType();
Sean Callanan771131d2010-09-30 21:18:25 +0000905
906 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
907 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
908
909 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000910 log->Printf("Type of \"%s\" is [clang \"%s\", lldb \"%s\"] [size %d, align %d]",
Sean Callanan771131d2010-09-30 21:18:25 +0000911 name.c_str(),
912 qual_type.getAsString().c_str(),
913 PrintType(value_type).c_str(),
914 value_size,
915 value_alignment);
916
Sean Callanan8bce6652010-07-13 21:41:46 +0000917
Sean Callanan8c127202010-08-23 23:09:38 +0000918 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +0000919 lldb_private::ConstString (name.c_str()),
920 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +0000921 value_size,
922 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +0000923 return false;
924 }
925
926 return true;
927}
928
929bool
Sean Callanandc27aba2010-10-05 22:26:43 +0000930IRForTarget::MaybeHandleCallArguments(Module &M,
Sean Callanan6ba533e2010-11-17 23:00:36 +0000931 CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +0000932{
Greg Claytone005f2c2010-11-06 01:53:30 +0000933 // lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanandc27aba2010-10-05 22:26:43 +0000934
Sean Callanan6ba533e2010-11-17 23:00:36 +0000935 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +0000936 op_index < num_ops;
937 ++op_index)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000938 if (!MaybeHandleVariable(M, Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanandc27aba2010-10-05 22:26:43 +0000939 return false;
940
941 return true;
942}
943
944bool
Greg Clayton8de27c72010-10-15 22:48:33 +0000945IRForTarget::MaybeHandleCall(Module &llvm_module,
946 CallInst *llvm_call_inst)
Sean Callananba992c52010-07-27 02:07:53 +0000947{
Greg Claytone005f2c2010-11-06 01:53:30 +0000948 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananba992c52010-07-27 02:07:53 +0000949
Greg Clayton8de27c72010-10-15 22:48:33 +0000950 Function *fun = llvm_call_inst->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +0000951
952 if (fun == NULL)
Sean Callanan65af7342010-09-08 20:04:08 +0000953 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000954 Value *val = llvm_call_inst->getCalledValue();
Sean Callanan65af7342010-09-08 20:04:08 +0000955
956 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(val);
957
958 if (const_expr && const_expr->getOpcode() == Instruction::BitCast)
959 {
960 fun = dyn_cast<Function>(const_expr->getOperand(0));
961
962 if (!fun)
963 return true;
964 }
965 else
966 {
967 return true;
968 }
969 }
Sean Callananba992c52010-07-27 02:07:53 +0000970
Greg Clayton8de27c72010-10-15 22:48:33 +0000971 lldb_private::ConstString str;
Sean Callananc04743d2010-09-28 21:13:03 +0000972
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000973 if (fun->isIntrinsic())
Sean Callananc04743d2010-09-28 21:13:03 +0000974 {
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000975 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
Sean Callananc04743d2010-09-28 21:13:03 +0000976
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000977 switch (intrinsic_id)
978 {
979 default:
980 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000981 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000982 return false;
983 case Intrinsic::memcpy:
Greg Clayton8de27c72010-10-15 22:48:33 +0000984 {
985 static lldb_private::ConstString g_memcpy_str ("memcpy");
986 str = g_memcpy_str;
987 }
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000988 break;
989 }
Sean Callananc04743d2010-09-28 21:13:03 +0000990
Greg Clayton8de27c72010-10-15 22:48:33 +0000991 if (log && str)
Greg Claytonb5037af2010-11-15 01:47:11 +0000992 log->Printf("Resolved intrinsic name \"%s\"", str.GetCString());
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000993 }
994 else
995 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000996 str.SetCStringWithLength (fun->getName().data(), fun->getName().size());
Sean Callananc04743d2010-09-28 21:13:03 +0000997 }
998
Greg Clayton8de27c72010-10-15 22:48:33 +0000999 clang::NamedDecl *fun_decl = DeclForGlobalValue (llvm_module, fun);
Greg Claytonb5037af2010-11-15 01:47:11 +00001000 lldb::addr_t fun_addr = LLDB_INVALID_ADDRESS;
Sean Callananf5857a02010-07-31 01:32:05 +00001001 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +00001002
Sean Callananf5857a02010-07-31 01:32:05 +00001003 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +00001004 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001005 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_value_ptr, fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001006 {
Sean Callanan92aa6662010-09-07 21:49:41 +00001007 fun_value_ptr = NULL;
1008
Greg Clayton8de27c72010-10-15 22:48:33 +00001009 if (!m_decl_map->GetFunctionAddress (str, fun_addr))
Sean Callanan92aa6662010-09-07 21:49:41 +00001010 {
1011 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001012 log->Printf("Function \"%s\" had no address", str.GetCString());
Sean Callanan92aa6662010-09-07 21:49:41 +00001013
1014 return false;
1015 }
Sean Callananf5857a02010-07-31 01:32:05 +00001016 }
1017 }
1018 else
1019 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001020 if (!m_decl_map->GetFunctionAddress (str, fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001021 {
1022 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001023 log->Printf ("Metadataless function \"%s\" had no address", str.GetCString());
Sean Callananf5857a02010-07-31 01:32:05 +00001024 }
Sean Callananba992c52010-07-27 02:07:53 +00001025 }
1026
1027 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001028 log->Printf("Found \"%s\" at 0x%llx", str.GetCString(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +00001029
Sean Callananf5857a02010-07-31 01:32:05 +00001030 Value *fun_addr_ptr;
1031
1032 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +00001033 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001034 const IntegerType *intptr_ty = Type::getIntNTy(llvm_module.getContext(),
1035 (llvm_module.getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan92aa6662010-09-07 21:49:41 +00001036 const FunctionType *fun_ty = fun->getFunctionType();
Sean Callanan02fbafa2010-07-27 21:39:39 +00001037 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
1038 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001039 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
1040
1041 if (fun_value_ptr)
1042 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001043 }
Sean Callananf5857a02010-07-31 01:32:05 +00001044
1045 if (fun_value_ptr)
1046 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001047
Greg Clayton8de27c72010-10-15 22:48:33 +00001048 llvm_call_inst->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +00001049
Greg Clayton8de27c72010-10-15 22:48:33 +00001050 ConstantArray *func_name = (ConstantArray*)ConstantArray::get(llvm_module.getContext(), str.GetCString());
Sean Callanane8a59a82010-09-13 21:34:21 +00001051
1052 Value *values[1];
1053 values[0] = func_name;
Greg Clayton8de27c72010-10-15 22:48:33 +00001054 MDNode *func_metadata = MDNode::get(llvm_module.getContext(), values, 1);
Sean Callanane8a59a82010-09-13 21:34:21 +00001055
Greg Clayton8de27c72010-10-15 22:48:33 +00001056 llvm_call_inst->setMetadata("lldb.call.realName", func_metadata);
Sean Callanane8a59a82010-09-13 21:34:21 +00001057
1058 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001059 log->Printf("Set metadata for %p [%d, \"%s\"]", llvm_call_inst, func_name->isString(), func_name->getAsString().c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +00001060
Sean Callananba992c52010-07-27 02:07:53 +00001061 return true;
1062}
1063
1064bool
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001065IRForTarget::resolveCalls(Module &M, BasicBlock &BB)
Sean Callanan8bce6652010-07-13 21:41:46 +00001066{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001067 /////////////////////////////////////////////////////////////////////////
1068 // Prepare the current basic block for execution in the remote process
1069 //
1070
Sean Callanan02fbafa2010-07-27 21:39:39 +00001071 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001072
1073 for (ii = BB.begin();
1074 ii != BB.end();
1075 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001076 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001077 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001078
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001079 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001080
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001081 if (call && !MaybeHandleCall(M, call))
1082 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001083 }
1084
1085 return true;
1086}
1087
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001088bool
1089IRForTarget::resolveExternals(Module &M,
1090 Function &F)
1091{
1092 for (Module::global_iterator global = M.global_begin(), end = M.global_end();
1093 global != end;
1094 ++global)
1095 {
1096 if ((*global).hasExternalLinkage() &&
1097 !MaybeHandleVariable (M, global))
1098 return false;
1099 }
1100
1101 return true;
1102}
1103
Sean Callanan02fbafa2010-07-27 21:39:39 +00001104static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00001105{
Sean Callanan6ba533e2010-11-17 23:00:36 +00001106 Constant *Old;
Sean Callanan45839272010-07-24 01:37:44 +00001107
Sean Callanan6ba533e2010-11-17 23:00:36 +00001108 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00001109 return false;
1110
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001111 ConstantExpr *CE;
1112
1113 if ((CE = dyn_cast<ConstantExpr>(V)))
1114 {
1115 if (CE->getOpcode() != Instruction::BitCast)
1116 return false;
1117
Sean Callanan6ba533e2010-11-17 23:00:36 +00001118 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001119 }
1120
Sean Callanan6ba533e2010-11-17 23:00:36 +00001121 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00001122
1123 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
1124 return false;
1125
1126 return true;
1127}
1128
1129static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
1130{
1131 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
1132
1133 Value::use_iterator ui;
1134
1135 for (ui = guard_load->use_begin();
1136 ui != guard_load->use_end();
1137 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00001138 {
Greg Clayton6e713402010-07-30 20:30:44 +00001139 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00001140 {
1141 // do nothing for the moment
1142 }
1143 else
1144 {
1145 ui->replaceUsesOfWith(guard_load, zero);
1146 }
1147 }
Sean Callanan45839272010-07-24 01:37:44 +00001148
1149 guard_load->eraseFromParent();
1150}
1151
1152static void ExciseGuardStore(Instruction* guard_store)
1153{
1154 guard_store->eraseFromParent();
1155}
1156
1157bool
1158IRForTarget::removeGuards(Module &M, BasicBlock &BB)
1159{
1160 ///////////////////////////////////////////////////////
1161 // Eliminate any reference to guard variables found.
1162 //
1163
Sean Callanan02fbafa2010-07-27 21:39:39 +00001164 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00001165
Sean Callanan02fbafa2010-07-27 21:39:39 +00001166 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00001167 typedef InstrList::iterator InstrIterator;
1168
1169 InstrList guard_loads;
1170 InstrList guard_stores;
1171
1172 for (ii = BB.begin();
1173 ii != BB.end();
1174 ++ii)
1175 {
1176 Instruction &inst = *ii;
1177
1178 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1179 if (isGuardVariableRef(load->getPointerOperand()))
1180 guard_loads.push_back(&inst);
1181
1182 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1183 if (isGuardVariableRef(store->getPointerOperand()))
1184 guard_stores.push_back(&inst);
1185 }
1186
1187 InstrIterator iter;
1188
1189 for (iter = guard_loads.begin();
1190 iter != guard_loads.end();
1191 ++iter)
1192 TurnGuardLoadIntoZero(*iter, M);
1193
1194 for (iter = guard_stores.begin();
1195 iter != guard_stores.end();
1196 ++iter)
1197 ExciseGuardStore(*iter);
1198
1199 return true;
1200}
1201
Sean Callanan6ba533e2010-11-17 23:00:36 +00001202bool
1203IRForTarget::UnfoldConstant(Constant *Old, Value *New, Instruction *FirstEntryInstruction)
Sean Callananbafd6852010-07-14 23:40:29 +00001204{
Greg Claytone005f2c2010-11-06 01:53:30 +00001205 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00001206
1207 Value::use_iterator ui;
1208
Sean Callanana48fe162010-08-11 03:57:18 +00001209 SmallVector<User*, 16> users;
1210
1211 // We do this because the use list might change, invalidating our iterator.
1212 // Much better to keep a work list ourselves.
Sean Callanan6ba533e2010-11-17 23:00:36 +00001213 for (ui = Old->use_begin();
1214 ui != Old->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00001215 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00001216 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00001217
Sean Callanana48fe162010-08-11 03:57:18 +00001218 for (int i = 0;
1219 i < users.size();
1220 ++i)
1221 {
1222 User *user = users[i];
1223
Sean Callananbafd6852010-07-14 23:40:29 +00001224 if (Constant *constant = dyn_cast<Constant>(user))
1225 {
1226 // synthesize a new non-constant equivalent of the constant
1227
1228 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
1229 {
1230 switch (constant_expr->getOpcode())
1231 {
1232 default:
1233 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001234 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00001235 return false;
1236 case Instruction::BitCast:
1237 {
1238 // UnaryExpr
1239 // OperandList[0] is value
1240
1241 Value *s = constant_expr->getOperand(0);
1242
Sean Callanan6ba533e2010-11-17 23:00:36 +00001243 if (s == Old)
1244 s = New;
Sean Callananbafd6852010-07-14 23:40:29 +00001245
Sean Callanan6ba533e2010-11-17 23:00:36 +00001246 BitCastInst *bit_cast(new BitCastInst(s, Old->getType(), "", FirstEntryInstruction));
Sean Callananbafd6852010-07-14 23:40:29 +00001247
Sean Callanan6ba533e2010-11-17 23:00:36 +00001248 UnfoldConstant(constant_expr, bit_cast, FirstEntryInstruction);
Sean Callananbafd6852010-07-14 23:40:29 +00001249 }
1250 break;
1251 case Instruction::GetElementPtr:
1252 {
1253 // GetElementPtrConstantExpr
1254 // OperandList[0] is base
1255 // OperandList[1]... are indices
1256
1257 Value *ptr = constant_expr->getOperand(0);
1258
Sean Callanan6ba533e2010-11-17 23:00:36 +00001259 if (ptr == Old)
1260 ptr = New;
Sean Callananbafd6852010-07-14 23:40:29 +00001261
1262 SmallVector<Value*, 16> indices;
1263
1264 unsigned operand_index;
1265 unsigned num_operands = constant_expr->getNumOperands();
1266
1267 for (operand_index = 1;
1268 operand_index < num_operands;
1269 ++operand_index)
1270 {
1271 Value *operand = constant_expr->getOperand(operand_index);
1272
Sean Callanan6ba533e2010-11-17 23:00:36 +00001273 if (operand == Old)
1274 operand = New;
Sean Callananbafd6852010-07-14 23:40:29 +00001275
1276 indices.push_back(operand);
1277 }
1278
Sean Callanan6ba533e2010-11-17 23:00:36 +00001279 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", FirstEntryInstruction));
Sean Callananbafd6852010-07-14 23:40:29 +00001280
Sean Callanan6ba533e2010-11-17 23:00:36 +00001281 UnfoldConstant(constant_expr, get_element_ptr, FirstEntryInstruction);
Sean Callananbafd6852010-07-14 23:40:29 +00001282 }
1283 break;
1284 }
1285 }
1286 else
1287 {
1288 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001289 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00001290 return false;
1291 }
1292 }
1293 else
1294 {
1295 // simple fall-through case for non-constants
Sean Callanan6ba533e2010-11-17 23:00:36 +00001296 user->replaceUsesOfWith(Old, New);
Sean Callananbafd6852010-07-14 23:40:29 +00001297 }
1298 }
1299
1300 return true;
1301}
1302
Sean Callanan8bce6652010-07-13 21:41:46 +00001303bool
Sean Callananf5857a02010-07-31 01:32:05 +00001304IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +00001305{
Sean Callanane8a59a82010-09-13 21:34:21 +00001306 if (!m_resolve_vars)
1307 return true;
1308
Greg Claytone005f2c2010-11-06 01:53:30 +00001309 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00001310
1311 m_decl_map->DoStructLayout();
1312
1313 if (log)
1314 log->Printf("Element arrangement:");
1315
1316 uint32_t num_elements;
1317 uint32_t element_index;
1318
1319 size_t size;
1320 off_t alignment;
1321
1322 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
1323 return false;
1324
Sean Callananf5857a02010-07-31 01:32:05 +00001325 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00001326
Sean Callananf5857a02010-07-31 01:32:05 +00001327 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +00001328 return false;
1329
Sean Callanan02fbafa2010-07-27 21:39:39 +00001330 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00001331
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00001332 if (argument->getName().equals("this"))
1333 {
1334 ++iter;
1335
1336 if (iter == F.getArgumentList().end())
1337 return false;
1338
1339 argument = iter;
1340 }
1341
Greg Clayton8de27c72010-10-15 22:48:33 +00001342 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan8bce6652010-07-13 21:41:46 +00001343 return false;
1344
1345 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001346 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00001347
Sean Callananf5857a02010-07-31 01:32:05 +00001348 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00001349 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00001350
Sean Callanan6ba533e2010-11-17 23:00:36 +00001351 if (!FirstEntryInstruction)
Sean Callanan8bce6652010-07-13 21:41:46 +00001352 return false;
1353
1354 LLVMContext &context(M.getContext());
1355 const IntegerType *offset_type(Type::getInt32Ty(context));
1356
1357 if (!offset_type)
1358 return false;
1359
1360 for (element_index = 0; element_index < num_elements; ++element_index)
1361 {
1362 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001363 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +00001364 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00001365 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00001366
Sean Callanan45690fe2010-08-30 22:17:16 +00001367 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan8bce6652010-07-13 21:41:46 +00001368 return false;
1369
1370 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001371 log->Printf(" \"%s\" [\"%s\"] (\"%s\") placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +00001372 value->getName().str().c_str(),
Greg Clayton8de27c72010-10-15 22:48:33 +00001373 name.GetCString(),
Sean Callanan8bce6652010-07-13 21:41:46 +00001374 PrintValue(value, true).c_str(),
1375 offset);
1376
1377 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
Sean Callanan6ba533e2010-11-17 23:00:36 +00001378 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
1379 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
Sean Callanan8bce6652010-07-13 21:41:46 +00001380
Sean Callananbafd6852010-07-14 23:40:29 +00001381 if (Constant *constant = dyn_cast<Constant>(value))
Sean Callanan6ba533e2010-11-17 23:00:36 +00001382 UnfoldConstant(constant, bit_cast, FirstEntryInstruction);
Sean Callananbafd6852010-07-14 23:40:29 +00001383 else
1384 value->replaceAllUsesWith(bit_cast);
Sean Callananb51ee982010-11-02 23:51:17 +00001385
1386 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
1387 var->eraseFromParent();
Sean Callanan8bce6652010-07-13 21:41:46 +00001388 }
1389
1390 if (log)
1391 log->Printf("Total structure [align %d, size %d]", alignment, size);
1392
1393 return true;
1394}
1395
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001396bool
1397IRForTarget::runOnModule(Module &M)
1398{
Greg Claytone005f2c2010-11-06 01:53:30 +00001399 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001400
Sean Callanan65dafa82010-08-27 01:01:44 +00001401 Function* function = M.getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001402
1403 if (!function)
1404 {
1405 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001406 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001407
1408 return false;
1409 }
1410
Sean Callanan02fbafa2010-07-27 21:39:39 +00001411 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001412
Sean Callanan82b74c82010-08-12 01:56:52 +00001413 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00001414 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00001415 //
1416
1417 if (!createResultVariable(M, *function))
1418 return false;
1419
Sean Callanan6ba533e2010-11-17 23:00:36 +00001420 ///////////////////////////////////////////////////////////////////////////////
1421 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
1422 //
1423
1424 if (log)
1425 {
1426 std::string s;
1427 raw_string_ostream oss(s);
1428
1429 M.print(oss, NULL);
1430
1431 oss.flush();
1432
1433 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
1434 }
1435
1436 if (!rewriteObjCConstStrings(M, *function))
1437 return false;
1438
1439 if (log)
1440 {
1441 std::string s;
1442 raw_string_ostream oss(s);
1443
1444 M.print(oss, NULL);
1445
1446 oss.flush();
1447
1448 log->Printf("Module after rewriting Objective-C const strings: \n\"%s\"", s.c_str());
1449 }
1450
Sean Callananf5857a02010-07-31 01:32:05 +00001451 //////////////////////////////////
1452 // Run basic-block level passes
1453 //
1454
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001455 for (bbi = function->begin();
1456 bbi != function->end();
1457 ++bbi)
1458 {
Sean Callanan8c127202010-08-23 23:09:38 +00001459 if (!removeGuards(M, *bbi))
1460 return false;
1461
Sean Callanana48fe162010-08-11 03:57:18 +00001462 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +00001463 return false;
1464
Sean Callanana48fe162010-08-11 03:57:18 +00001465 if (!rewriteObjCSelectors(M, *bbi))
1466 return false;
1467
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001468 if (!resolveCalls(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +00001469 return false;
1470 }
1471
Sean Callanan771131d2010-09-30 21:18:25 +00001472 ///////////////////////////////
1473 // Run function-level passes
1474 //
1475
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001476 if (!resolveExternals(M, *function))
1477 return false;
1478
Sean Callanan771131d2010-09-30 21:18:25 +00001479 if (!replaceVariables(M, *function))
1480 return false;
1481
Sean Callanan8bce6652010-07-13 21:41:46 +00001482 if (log)
1483 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00001484 std::string s;
1485 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00001486
Sean Callanan321fe9e2010-07-28 01:00:59 +00001487 M.print(oss, NULL);
1488
1489 oss.flush();
1490
Greg Claytonb5037af2010-11-15 01:47:11 +00001491 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001492 }
1493
1494 return true;
1495}
1496
1497void
1498IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +00001499 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001500{
1501}
1502
1503PassManagerType
1504IRForTarget::getPotentialPassManagerType() const
1505{
1506 return PMT_ModulePassManager;
1507}