blob: f368b8dc0277665e3882f573d806876d3501e6fd [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 Callanan5cf4a1c2010-07-03 01:35:46 +000015#include "llvm/Module.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000016#include "llvm/Target/TargetData.h"
Sean Callanan82b74c82010-08-12 01:56:52 +000017#include "llvm/ValueSymbolTable.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000018
19#include "clang/AST/ASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000020
21#include "lldb/Core/dwarf.h"
22#include "lldb/Core/Log.h"
23#include "lldb/Core/Scalar.h"
24#include "lldb/Core/StreamString.h"
25#include "lldb/Expression/ClangExpressionDeclMap.h"
26
27#include <map>
28
29using namespace llvm;
30
Sean Callanan3351dac2010-08-18 18:50:51 +000031static char ID;
32
33IRForTarget::IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map,
Sean Callanan65dafa82010-08-27 01:01:44 +000034 const TargetData *target_data,
Sean Callanane8a59a82010-09-13 21:34:21 +000035 bool resolve_vars,
Sean Callanan65dafa82010-08-27 01:01:44 +000036 const char *func_name) :
Sean Callanana6223432010-08-20 01:02:30 +000037 ModulePass(&ID),
Sean Callanan8bce6652010-07-13 21:41:46 +000038 m_decl_map(decl_map),
Sean Callananf5857a02010-07-31 01:32:05 +000039 m_target_data(target_data),
Sean Callanan65dafa82010-08-27 01:01:44 +000040 m_sel_registerName(NULL),
Sean Callanane8a59a82010-09-13 21:34:21 +000041 m_func_name(func_name),
42 m_resolve_vars(resolve_vars)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000043{
44}
45
Sean Callanana48fe162010-08-11 03:57:18 +000046/* A handy utility function used at several places in the code */
47
48static std::string
49PrintValue(Value *V, bool truncate = false)
50{
51 std::string s;
52 raw_string_ostream rso(s);
53 V->print(rso);
54 rso.flush();
55 if (truncate)
56 s.resize(s.length() - 1);
57 return s;
58}
59
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000060IRForTarget::~IRForTarget()
61{
62}
63
Sean Callanan82b74c82010-08-12 01:56:52 +000064bool
65IRForTarget::createResultVariable(llvm::Module &M,
66 llvm::Function &F)
67{
68 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
69
Sean Callanane8a59a82010-09-13 21:34:21 +000070 if (!m_resolve_vars)
71 return true;
72
73 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan82b74c82010-08-12 01:56:52 +000074
75 Value *result_value = M.getNamedValue("___clang_expr_result");
76
77 if (!result_value)
78 {
79 if (log)
80 log->PutCString("Couldn't find result variable");
Sean Callanane8a59a82010-09-13 21:34:21 +000081
82 return true;
Sean Callanan82b74c82010-08-12 01:56:52 +000083 }
Sean Callanane8a59a82010-09-13 21:34:21 +000084
Sean Callanan82b74c82010-08-12 01:56:52 +000085 if (log)
86 log->Printf("Found result in the IR: %s", PrintValue(result_value, false).c_str());
87
88 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
89
90 if (!result_global)
91 {
92 if (log)
93 log->PutCString("Result variable isn't a GlobalVariable");
94 return false;
95 }
96
97 // Find the metadata and follow it to the VarDecl
98
99 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
100
101 if (!named_metadata)
102 {
103 if (log)
104 log->PutCString("No global metadata");
105
106 return false;
107 }
108
109 unsigned num_nodes = named_metadata->getNumOperands();
110 unsigned node_index;
111
112 MDNode *metadata_node = NULL;
113
114 for (node_index = 0;
115 node_index < num_nodes;
116 ++node_index)
117 {
118 metadata_node = named_metadata->getOperand(node_index);
119
120 if (metadata_node->getNumOperands() != 2)
121 continue;
122
123 if (metadata_node->getOperand(0) == result_global)
124 break;
125 }
126
127 if (!metadata_node)
128 {
129 if (log)
130 log->PutCString("Couldn't find result metadata");
131 return false;
132 }
133
134 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
135
136 uint64_t result_decl_intptr = constant_int->getZExtValue();
137
138 clang::VarDecl *result_decl = reinterpret_cast<clang::VarDecl *>(result_decl_intptr);
139
140 // Get the next available result name from m_decl_map and create the persistent
141 // variable for it
142
143 lldb_private::TypeFromParser result_decl_type (result_decl->getType().getAsOpaquePtr(),
144 &result_decl->getASTContext());
145 std::string new_result_name;
146
147 m_decl_map->GetPersistentResultName(new_result_name);
Sean Callanan8c127202010-08-23 23:09:38 +0000148 m_decl_map->AddPersistentVariable(result_decl, new_result_name.c_str(), result_decl_type);
Sean Callanan82b74c82010-08-12 01:56:52 +0000149
150 if (log)
151 log->Printf("Creating a new result global: %s", new_result_name.c_str());
152
153 // Construct a new result global and set up its metadata
154
155 GlobalVariable *new_result_global = new GlobalVariable(M,
156 result_global->getType()->getElementType(),
157 false, /* not constant */
158 GlobalValue::ExternalLinkage,
159 NULL, /* no initializer */
160 new_result_name.c_str());
161
162 // It's too late in compilation to create a new VarDecl for this, but we don't
163 // need to. We point the metadata at the old VarDecl. This creates an odd
164 // anomaly: a variable with a Value whose name is something like $0 and a
165 // Decl whose name is ___clang_expr_result. This condition is handled in
166 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
167 // fixed up.
168
169 ConstantInt *new_constant_int = ConstantInt::get(constant_int->getType(),
170 result_decl_intptr,
171 false);
172
173 llvm::Value* values[2];
174 values[0] = new_result_global;
175 values[1] = new_constant_int;
176
177 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
178 named_metadata->addOperand(persistent_global_md);
179
180 if (log)
Sean Callanan2e2db532010-09-07 22:43:19 +0000181 log->Printf("Replacing %s with %s",
182 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000183 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000184
185 if (result_global->hasNUses(0))
186 {
187 // We need to synthesize a store for this variable, because otherwise
188 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000189
Sean Callanan2e2db532010-09-07 22:43:19 +0000190 BasicBlock &entry_block(F.getEntryBlock());
191 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
192
193 if (!first_entry_instruction)
194 return false;
195
196 if (!result_global->hasInitializer())
197 {
198 if (log)
199 log->Printf("Couldn't find initializer for unused variable");
200 return false;
201 }
202
203 Constant *initializer = result_global->getInitializer();
204
205 StoreInst *synthesized_store = new StoreInst::StoreInst(initializer,
206 new_result_global,
207 first_entry_instruction);
208
209 if (log)
210 log->Printf("Synthesized result store %s\n", PrintValue(synthesized_store).c_str());
211 }
212 else
213 {
214 result_global->replaceAllUsesWith(new_result_global);
215 }
216
Sean Callanan82b74c82010-08-12 01:56:52 +0000217 result_global->eraseFromParent();
218
219 return true;
220}
221
Sean Callananf5857a02010-07-31 01:32:05 +0000222static bool isObjCSelectorRef(Value *V)
223{
224 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
225
226 if (!GV || !GV->hasName() || !GV->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
227 return false;
228
229 return true;
230}
231
232bool
233IRForTarget::RewriteObjCSelector(Instruction* selector_load,
234 Module &M)
235{
236 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
237
238 LoadInst *load = dyn_cast<LoadInst>(selector_load);
239
240 if (!load)
241 return false;
242
243 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
244 //
245 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
246 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
247 //
248 // where %obj is the object pointer and %tmp is the selector.
249 //
250 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_METH_VAR_NAME_".
251 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
252
253 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
254
255 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
256
257 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
258 return false;
259
260 Constant *osr_initializer = _objc_selector_references_->getInitializer();
261
262 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
263
264 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
265 return false;
266
267 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
268
269 if (!osr_initializer_base)
270 return false;
271
272 // Find the string's initializer (a ConstantArray) and get the string from it
273
274 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
275
276 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
277 return false;
278
279 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
280
281 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
282
283 if (!omvn_initializer_array->isString())
284 return false;
285
286 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
287
288 if (log)
289 log->Printf("Found Objective-C selector reference %s", omvn_initializer_string.c_str());
290
291 // Construct a call to sel_registerName
292
293 if (!m_sel_registerName)
294 {
295 uint64_t srN_addr;
296
297 if (!m_decl_map->GetFunctionAddress("sel_registerName", srN_addr))
298 return false;
299
300 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
301
302 // The below code would be "more correct," but in actuality what's required is uint8_t*
303 //Type *sel_type = StructType::get(M.getContext());
304 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
305 const Type *sel_ptr_type = Type::getInt8PtrTy(M.getContext());
306
307 std::vector <const Type *> srN_arg_types;
308 srN_arg_types.push_back(Type::getInt8PtrTy(M.getContext()));
309 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
310
311 // Build the constant containing the pointer to the function
312 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
313 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
314 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
315 Constant *srN_addr_int = ConstantInt::get(intptr_ty, srN_addr, false);
316 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
317 }
318
319 SmallVector <Value*, 1> srN_arguments;
320
321 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(M.getContext()));
322
323 srN_arguments.push_back(omvn_pointer);
324
325 CallInst *srN_call = CallInst::Create(m_sel_registerName,
326 srN_arguments.begin(),
327 srN_arguments.end(),
328 "srN",
329 selector_load);
330
331 // Replace the load with the call in all users
332
333 selector_load->replaceAllUsesWith(srN_call);
334
335 selector_load->eraseFromParent();
336
337 return true;
338}
339
340bool
341IRForTarget::rewriteObjCSelectors(Module &M,
342 BasicBlock &BB)
343{
344 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
345
346 BasicBlock::iterator ii;
347
348 typedef SmallVector <Instruction*, 2> InstrList;
349 typedef InstrList::iterator InstrIterator;
350
351 InstrList selector_loads;
352
353 for (ii = BB.begin();
354 ii != BB.end();
355 ++ii)
356 {
357 Instruction &inst = *ii;
358
359 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
360 if (isObjCSelectorRef(load->getPointerOperand()))
361 selector_loads.push_back(&inst);
362 }
363
364 InstrIterator iter;
365
366 for (iter = selector_loads.begin();
367 iter != selector_loads.end();
368 ++iter)
369 {
370 if (!RewriteObjCSelector(*iter, M))
371 {
372 if(log)
373 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
374 return false;
375 }
376 }
377
378 return true;
379}
380
Sean Callanana48fe162010-08-11 03:57:18 +0000381bool
382IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc,
383 llvm::Module &M)
384{
385 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
386
387 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
388
389 if (!alloc_md || !alloc_md->getNumOperands())
390 return false;
391
392 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
393
394 if (!constant_int)
395 return false;
396
397 // We attempt to register this as a new persistent variable with the DeclMap.
398
399 uintptr_t ptr = constant_int->getZExtValue();
400
Sean Callanan82b74c82010-08-12 01:56:52 +0000401 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +0000402
Sean Callanan82b74c82010-08-12 01:56:52 +0000403 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
404 &decl->getASTContext());
405
Sean Callanan8c127202010-08-23 23:09:38 +0000406 if (!m_decl_map->AddPersistentVariable(decl, decl->getName().str().c_str(), result_decl_type))
Sean Callanana48fe162010-08-11 03:57:18 +0000407 return false;
408
409 GlobalVariable *persistent_global = new GlobalVariable(M,
410 alloc->getType()->getElementType(),
411 false, /* not constant */
412 GlobalValue::ExternalLinkage,
413 NULL, /* no initializer */
414 alloc->getName().str().c_str());
415
416 // What we're going to do here is make believe this was a regular old external
417 // variable. That means we need to make the metadata valid.
418
419 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
420
421 llvm::Value* values[2];
422 values[0] = persistent_global;
423 values[1] = constant_int;
424
425 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
426 named_metadata->addOperand(persistent_global_md);
427
428 alloc->replaceAllUsesWith(persistent_global);
429 alloc->eraseFromParent();
430
431 return true;
432}
433
434bool
435IRForTarget::rewritePersistentAllocs(llvm::Module &M,
436 llvm::BasicBlock &BB)
437{
Sean Callanane8a59a82010-09-13 21:34:21 +0000438 if (!m_resolve_vars)
439 return true;
440
Sean Callanana48fe162010-08-11 03:57:18 +0000441 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
442
443 BasicBlock::iterator ii;
444
445 typedef SmallVector <Instruction*, 2> InstrList;
446 typedef InstrList::iterator InstrIterator;
447
448 InstrList pvar_allocs;
449
450 for (ii = BB.begin();
451 ii != BB.end();
452 ++ii)
453 {
454 Instruction &inst = *ii;
455
456 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
457 if (alloc->getName().startswith("$"))
458 pvar_allocs.push_back(alloc);
459 }
460
461 InstrIterator iter;
462
463 for (iter = pvar_allocs.begin();
464 iter != pvar_allocs.end();
465 ++iter)
466 {
467 if (!RewritePersistentAlloc(*iter, M))
468 {
469 if(log)
470 log->PutCString("Couldn't rewrite the creation of a persistent variable");
471 return false;
472 }
473 }
474
475 return true;
476}
477
Sean Callanan8bce6652010-07-13 21:41:46 +0000478static clang::NamedDecl *
Sean Callanan02fbafa2010-07-27 21:39:39 +0000479DeclForGlobalValue(Module &module,
480 GlobalValue *global_value)
Sean Callanan8bce6652010-07-13 21:41:46 +0000481{
482 NamedMDNode *named_metadata = module.getNamedMetadata("clang.global.decl.ptrs");
483
484 if (!named_metadata)
485 return NULL;
486
487 unsigned num_nodes = named_metadata->getNumOperands();
488 unsigned node_index;
489
490 for (node_index = 0;
491 node_index < num_nodes;
492 ++node_index)
493 {
494 MDNode *metadata_node = named_metadata->getOperand(node_index);
495
496 if (!metadata_node)
497 return NULL;
498
499 if (metadata_node->getNumOperands() != 2)
Sean Callanana48fe162010-08-11 03:57:18 +0000500 continue;
Sean Callanan8bce6652010-07-13 21:41:46 +0000501
502 if (metadata_node->getOperand(0) != global_value)
503 continue;
504
505 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
506
507 if (!constant_int)
508 return NULL;
509
510 uintptr_t ptr = constant_int->getZExtValue();
511
512 return reinterpret_cast<clang::NamedDecl *>(ptr);
513 }
514
515 return NULL;
516}
517
518bool
519IRForTarget::MaybeHandleVariable(Module &M,
Sean Callanan02fbafa2010-07-27 21:39:39 +0000520 Value *V,
Sean Callanan8bce6652010-07-13 21:41:46 +0000521 bool Store)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000522{
Sean Callananf5857a02010-07-31 01:32:05 +0000523 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
524
Sean Callananbc2928a2010-08-03 00:23:29 +0000525 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(V))
526 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000527 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +0000528 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000529 default:
530 break;
531 case Instruction::GetElementPtr:
532 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +0000533 Value *s = constant_expr->getOperand(0);
534 MaybeHandleVariable(M, s, Store);
535 }
536 }
Sean Callanan8bce6652010-07-13 21:41:46 +0000537 if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(V))
Sean Callananf5857a02010-07-31 01:32:05 +0000538 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000539 clang::NamedDecl *named_decl = DeclForGlobalValue(M, global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000540
Sean Callananf5857a02010-07-31 01:32:05 +0000541 if (!named_decl)
542 {
543 if (isObjCSelectorRef(V))
544 return true;
545
546 if (log)
547 log->Printf("Found global variable %s without metadata", global_variable->getName().str().c_str());
548 return false;
549 }
550
Sean Callanan810f22d2010-07-16 00:09:46 +0000551 std::string name = named_decl->getName().str();
552
553 void *qual_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +0000554 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +0000555
556 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +0000557 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000558 qual_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +0000559 ast_context = &value_decl->getASTContext();
560 }
Sean Callanan810f22d2010-07-16 00:09:46 +0000561 else
Sean Callananf328c9f2010-07-20 23:31:16 +0000562 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000563 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +0000564 }
565
Sean Callanan02fbafa2010-07-27 21:39:39 +0000566 const Type *value_type = global_variable->getType();
Sean Callanan8bce6652010-07-13 21:41:46 +0000567
568 size_t value_size = m_target_data->getTypeStoreSize(value_type);
569 off_t value_alignment = m_target_data->getPrefTypeAlignment(value_type);
570
Sean Callanan8c127202010-08-23 23:09:38 +0000571 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Sean Callanan45690fe2010-08-30 22:17:16 +0000572 name.c_str(),
Sean Callanan8c127202010-08-23 23:09:38 +0000573 V,
Sean Callananba992c52010-07-27 02:07:53 +0000574 value_size,
575 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +0000576 return false;
577 }
578
579 return true;
580}
581
582bool
Sean Callananba992c52010-07-27 02:07:53 +0000583IRForTarget::MaybeHandleCall(Module &M,
584 CallInst *C)
585{
586 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
587
Sean Callanan02fbafa2010-07-27 21:39:39 +0000588 Function *fun = C->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +0000589
590 if (fun == NULL)
Sean Callanan65af7342010-09-08 20:04:08 +0000591 {
592 Value *val = C->getCalledValue();
593
594 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(val);
595
596 if (const_expr && const_expr->getOpcode() == Instruction::BitCast)
597 {
598 fun = dyn_cast<Function>(const_expr->getOperand(0));
599
600 if (!fun)
601 return true;
602 }
603 else
604 {
605 return true;
606 }
607 }
Sean Callananba992c52010-07-27 02:07:53 +0000608
609 clang::NamedDecl *fun_decl = DeclForGlobalValue(M, fun);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000610 uint64_t fun_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000611 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +0000612
Sean Callananf5857a02010-07-31 01:32:05 +0000613 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +0000614 {
Sean Callananf5857a02010-07-31 01:32:05 +0000615 if (!m_decl_map->GetFunctionInfo(fun_decl, fun_value_ptr, fun_addr))
616 {
Sean Callanan92aa6662010-09-07 21:49:41 +0000617 fun_value_ptr = NULL;
618
619 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
620 {
621 if (log)
622 log->Printf("Function %s had no address", fun->getName().str().c_str());
623
624 return false;
625 }
Sean Callananf5857a02010-07-31 01:32:05 +0000626 }
627 }
628 else
629 {
630 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
631 {
632 if (log)
633 log->Printf("Metadataless function %s had no address", fun->getName().str().c_str());
634 return false;
635 }
Sean Callananba992c52010-07-27 02:07:53 +0000636 }
637
638 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +0000639 log->Printf("Found %s at %llx", fun->getName().str().c_str(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +0000640
Sean Callananf5857a02010-07-31 01:32:05 +0000641 Value *fun_addr_ptr;
642
643 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +0000644 {
Sean Callanan02fbafa2010-07-27 21:39:39 +0000645 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
646 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan92aa6662010-09-07 21:49:41 +0000647 const FunctionType *fun_ty = fun->getFunctionType();
Sean Callanan02fbafa2010-07-27 21:39:39 +0000648 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
649 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000650 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
651
652 if (fun_value_ptr)
653 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000654 }
Sean Callananf5857a02010-07-31 01:32:05 +0000655
656 if (fun_value_ptr)
657 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000658
Sean Callananf5857a02010-07-31 01:32:05 +0000659 C->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000660
Sean Callanane8a59a82010-09-13 21:34:21 +0000661 ConstantArray *func_name = (ConstantArray*)ConstantArray::get(M.getContext(), fun->getName());
662
663 Value *values[1];
664 values[0] = func_name;
665 MDNode *func_metadata = MDNode::get(M.getContext(), values, 1);
666
667 C->setMetadata("lldb.call.realName", func_metadata);
668
669 if (log)
670 log->Printf("Set metadata for %p [%d, %s]", C, func_name->isString(), func_name->getAsString().c_str());
671
Sean Callananba992c52010-07-27 02:07:53 +0000672 return true;
673}
674
675bool
Sean Callananf5857a02010-07-31 01:32:05 +0000676IRForTarget::resolveExternals(Module &M, BasicBlock &BB)
Sean Callanan8bce6652010-07-13 21:41:46 +0000677{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000678 /////////////////////////////////////////////////////////////////////////
679 // Prepare the current basic block for execution in the remote process
680 //
681
Sean Callanan02fbafa2010-07-27 21:39:39 +0000682 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +0000683
684 for (ii = BB.begin();
685 ii != BB.end();
686 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000687 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000688 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000689
Sean Callanane8a59a82010-09-13 21:34:21 +0000690 if (m_resolve_vars)
691 {
692 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
693 if (!MaybeHandleVariable(M, load->getPointerOperand(), false))
694 return false;
Sean Callananf5857a02010-07-31 01:32:05 +0000695
Sean Callanane8a59a82010-09-13 21:34:21 +0000696 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
697 if (!MaybeHandleVariable(M, store->getPointerOperand(), true))
698 return false;
699 }
Sean Callananba992c52010-07-27 02:07:53 +0000700
701 if (CallInst *call = dyn_cast<CallInst>(&inst))
702 if (!MaybeHandleCall(M, call))
Sean Callanan8bce6652010-07-13 21:41:46 +0000703 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000704 }
705
706 return true;
707}
708
Sean Callanan02fbafa2010-07-27 21:39:39 +0000709static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +0000710{
711 ConstantExpr *C = dyn_cast<ConstantExpr>(V);
712
713 if (!C || C->getOpcode() != Instruction::BitCast)
714 return false;
715
716 GlobalVariable *GV = dyn_cast<GlobalVariable>(C->getOperand(0));
717
718 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
719 return false;
720
721 return true;
722}
723
724static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
725{
726 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
727
728 Value::use_iterator ui;
729
730 for (ui = guard_load->use_begin();
731 ui != guard_load->use_end();
732 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +0000733 {
Greg Clayton6e713402010-07-30 20:30:44 +0000734 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +0000735 {
736 // do nothing for the moment
737 }
738 else
739 {
740 ui->replaceUsesOfWith(guard_load, zero);
741 }
742 }
Sean Callanan45839272010-07-24 01:37:44 +0000743
744 guard_load->eraseFromParent();
745}
746
747static void ExciseGuardStore(Instruction* guard_store)
748{
749 guard_store->eraseFromParent();
750}
751
752bool
753IRForTarget::removeGuards(Module &M, BasicBlock &BB)
754{
755 ///////////////////////////////////////////////////////
756 // Eliminate any reference to guard variables found.
757 //
758
Sean Callanan02fbafa2010-07-27 21:39:39 +0000759 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +0000760
Sean Callanan02fbafa2010-07-27 21:39:39 +0000761 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +0000762 typedef InstrList::iterator InstrIterator;
763
764 InstrList guard_loads;
765 InstrList guard_stores;
766
767 for (ii = BB.begin();
768 ii != BB.end();
769 ++ii)
770 {
771 Instruction &inst = *ii;
772
773 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
774 if (isGuardVariableRef(load->getPointerOperand()))
775 guard_loads.push_back(&inst);
776
777 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
778 if (isGuardVariableRef(store->getPointerOperand()))
779 guard_stores.push_back(&inst);
780 }
781
782 InstrIterator iter;
783
784 for (iter = guard_loads.begin();
785 iter != guard_loads.end();
786 ++iter)
787 TurnGuardLoadIntoZero(*iter, M);
788
789 for (iter = guard_stores.begin();
790 iter != guard_stores.end();
791 ++iter)
792 ExciseGuardStore(*iter);
793
794 return true;
795}
796
Sean Callananbafd6852010-07-14 23:40:29 +0000797// UnfoldConstant operates on a constant [C] which has just been replaced with a value
798// [new_value]. We assume that new_value has been properly placed early in the function,
799// most likely somewhere in front of the first instruction in the entry basic block
800// [first_entry_instruction].
801//
802// UnfoldConstant reads through the uses of C and replaces C in those uses with new_value.
803// Where those uses are constants, the function generates new instructions to compute the
804// result of the new, non-constant expression and places them before first_entry_instruction.
805// These instructions replace the constant uses, so UnfoldConstant calls itself recursively
806// for those.
807
808static bool
Sean Callanan02fbafa2010-07-27 21:39:39 +0000809UnfoldConstant(Constant *C, Value *new_value, Instruction *first_entry_instruction)
Sean Callananbafd6852010-07-14 23:40:29 +0000810{
811 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
812
813 Value::use_iterator ui;
814
Sean Callanana48fe162010-08-11 03:57:18 +0000815 SmallVector<User*, 16> users;
816
817 // We do this because the use list might change, invalidating our iterator.
818 // Much better to keep a work list ourselves.
Sean Callananbafd6852010-07-14 23:40:29 +0000819 for (ui = C->use_begin();
820 ui != C->use_end();
821 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +0000822 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +0000823
Sean Callanana48fe162010-08-11 03:57:18 +0000824 for (int i = 0;
825 i < users.size();
826 ++i)
827 {
828 User *user = users[i];
829
Sean Callananbafd6852010-07-14 23:40:29 +0000830 if (Constant *constant = dyn_cast<Constant>(user))
831 {
832 // synthesize a new non-constant equivalent of the constant
833
834 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
835 {
836 switch (constant_expr->getOpcode())
837 {
838 default:
839 if (log)
840 log->Printf("Unhandled constant expression type: %s", PrintValue(constant_expr).c_str());
841 return false;
842 case Instruction::BitCast:
843 {
844 // UnaryExpr
845 // OperandList[0] is value
846
847 Value *s = constant_expr->getOperand(0);
848
849 if (s == C)
850 s = new_value;
851
852 BitCastInst *bit_cast(new BitCastInst(s, C->getType(), "", first_entry_instruction));
853
854 UnfoldConstant(constant_expr, bit_cast, first_entry_instruction);
855 }
856 break;
857 case Instruction::GetElementPtr:
858 {
859 // GetElementPtrConstantExpr
860 // OperandList[0] is base
861 // OperandList[1]... are indices
862
863 Value *ptr = constant_expr->getOperand(0);
864
865 if (ptr == C)
866 ptr = new_value;
867
868 SmallVector<Value*, 16> indices;
869
870 unsigned operand_index;
871 unsigned num_operands = constant_expr->getNumOperands();
872
873 for (operand_index = 1;
874 operand_index < num_operands;
875 ++operand_index)
876 {
877 Value *operand = constant_expr->getOperand(operand_index);
878
879 if (operand == C)
880 operand = new_value;
881
882 indices.push_back(operand);
883 }
884
885 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_instruction));
886
887 UnfoldConstant(constant_expr, get_element_ptr, first_entry_instruction);
888 }
889 break;
890 }
891 }
892 else
893 {
894 if (log)
895 log->Printf("Unhandled constant type: %s", PrintValue(constant).c_str());
896 return false;
897 }
898 }
899 else
900 {
901 // simple fall-through case for non-constants
902 user->replaceUsesOfWith(C, new_value);
903 }
904 }
905
906 return true;
907}
908
Sean Callanan8bce6652010-07-13 21:41:46 +0000909bool
Sean Callananf5857a02010-07-31 01:32:05 +0000910IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +0000911{
Sean Callanane8a59a82010-09-13 21:34:21 +0000912 if (!m_resolve_vars)
913 return true;
914
Sean Callanan8bce6652010-07-13 21:41:46 +0000915 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
916
917 m_decl_map->DoStructLayout();
918
919 if (log)
920 log->Printf("Element arrangement:");
921
922 uint32_t num_elements;
923 uint32_t element_index;
924
925 size_t size;
926 off_t alignment;
927
928 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
929 return false;
930
Sean Callananf5857a02010-07-31 01:32:05 +0000931 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +0000932
Sean Callananf5857a02010-07-31 01:32:05 +0000933 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +0000934 return false;
935
Sean Callanan02fbafa2010-07-27 21:39:39 +0000936 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +0000937
938 if (!argument->getName().equals("___clang_arg"))
939 return false;
940
941 if (log)
942 log->Printf("Arg: %s", PrintValue(argument).c_str());
943
Sean Callananf5857a02010-07-31 01:32:05 +0000944 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan02fbafa2010-07-27 21:39:39 +0000945 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +0000946
947 if (!first_entry_instruction)
948 return false;
949
950 LLVMContext &context(M.getContext());
951 const IntegerType *offset_type(Type::getInt32Ty(context));
952
953 if (!offset_type)
954 return false;
955
956 for (element_index = 0; element_index < num_elements; ++element_index)
957 {
958 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000959 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +0000960 off_t offset;
Sean Callanan45690fe2010-08-30 22:17:16 +0000961 const char *name;
Sean Callanan8bce6652010-07-13 21:41:46 +0000962
Sean Callanan45690fe2010-08-30 22:17:16 +0000963 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan8bce6652010-07-13 21:41:46 +0000964 return false;
965
966 if (log)
Sean Callanan45690fe2010-08-30 22:17:16 +0000967 log->Printf(" %s [%s] (%s) placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +0000968 value->getName().str().c_str(),
Sean Callanan45690fe2010-08-30 22:17:16 +0000969 name,
Sean Callanan8bce6652010-07-13 21:41:46 +0000970 PrintValue(value, true).c_str(),
971 offset);
972
973 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
974 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", first_entry_instruction);
975 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", first_entry_instruction);
976
Sean Callananbafd6852010-07-14 23:40:29 +0000977 if (Constant *constant = dyn_cast<Constant>(value))
978 UnfoldConstant(constant, bit_cast, first_entry_instruction);
979 else
980 value->replaceAllUsesWith(bit_cast);
Sean Callanan8bce6652010-07-13 21:41:46 +0000981 }
982
983 if (log)
984 log->Printf("Total structure [align %d, size %d]", alignment, size);
985
986 return true;
987}
988
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000989bool
990IRForTarget::runOnModule(Module &M)
991{
992 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
993
Sean Callanan65dafa82010-08-27 01:01:44 +0000994 Function* function = M.getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000995
996 if (!function)
997 {
998 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000999 log->Printf("Couldn't find %s() in the module", m_func_name.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001000
1001 return false;
1002 }
1003
Sean Callanan02fbafa2010-07-27 21:39:39 +00001004 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001005
Sean Callanan82b74c82010-08-12 01:56:52 +00001006 ////////////////////////////////////////////////////////////
1007 // Replace __clang_expr_result with a persistent variable
1008 //
1009
1010 if (!createResultVariable(M, *function))
1011 return false;
1012
Sean Callananf5857a02010-07-31 01:32:05 +00001013 //////////////////////////////////
1014 // Run basic-block level passes
1015 //
1016
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001017 for (bbi = function->begin();
1018 bbi != function->end();
1019 ++bbi)
1020 {
Sean Callanan8c127202010-08-23 23:09:38 +00001021 if (!removeGuards(M, *bbi))
1022 return false;
1023
Sean Callanana48fe162010-08-11 03:57:18 +00001024 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +00001025 return false;
1026
Sean Callanana48fe162010-08-11 03:57:18 +00001027 if (!rewriteObjCSelectors(M, *bbi))
1028 return false;
1029
Sean Callananf5857a02010-07-31 01:32:05 +00001030 if (!resolveExternals(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +00001031 return false;
1032 }
1033
Sean Callanan8bce6652010-07-13 21:41:46 +00001034 if (log)
1035 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00001036 std::string s;
1037 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00001038
Sean Callanan321fe9e2010-07-28 01:00:59 +00001039 M.print(oss, NULL);
1040
1041 oss.flush();
1042
1043 log->Printf("Module after preparing for execution: \n%s", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001044 }
1045
Sean Callanana48fe162010-08-11 03:57:18 +00001046 ///////////////////////////////
1047 // Run function-level passes
1048 //
1049
1050 if (!replaceVariables(M, *function))
1051 return false;
1052
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001053 return true;
1054}
1055
1056void
1057IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +00001058 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001059{
1060}
1061
1062PassManagerType
1063IRForTarget::getPotentialPassManagerType() const
1064{
1065 return PMT_ModulePassManager;
1066}