blob: 345ae349633e0906763a9b6273c6de3951159563 [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,
35 const char *func_name) :
Sean Callanana6223432010-08-20 01:02:30 +000036 ModulePass(&ID),
Sean Callanan8bce6652010-07-13 21:41:46 +000037 m_decl_map(decl_map),
Sean Callananf5857a02010-07-31 01:32:05 +000038 m_target_data(target_data),
Sean Callanan65dafa82010-08-27 01:01:44 +000039 m_sel_registerName(NULL),
40 m_func_name(func_name)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000041{
42}
43
Sean Callanana48fe162010-08-11 03:57:18 +000044/* A handy utility function used at several places in the code */
45
46static std::string
47PrintValue(Value *V, bool truncate = false)
48{
49 std::string s;
50 raw_string_ostream rso(s);
51 V->print(rso);
52 rso.flush();
53 if (truncate)
54 s.resize(s.length() - 1);
55 return s;
56}
57
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000058IRForTarget::~IRForTarget()
59{
60}
61
Sean Callanan82b74c82010-08-12 01:56:52 +000062bool
63IRForTarget::createResultVariable(llvm::Module &M,
64 llvm::Function &F)
65{
66 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
67
68 // Find the result variable
69
70 Value *result_value = M.getNamedValue("___clang_expr_result");
71
72 if (!result_value)
73 {
74 if (log)
75 log->PutCString("Couldn't find result variable");
76 return false;
77 }
78
79 if (log)
80 log->Printf("Found result in the IR: %s", PrintValue(result_value, false).c_str());
81
82 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
83
84 if (!result_global)
85 {
86 if (log)
87 log->PutCString("Result variable isn't a GlobalVariable");
88 return false;
89 }
90
91 // Find the metadata and follow it to the VarDecl
92
93 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
94
95 if (!named_metadata)
96 {
97 if (log)
98 log->PutCString("No global metadata");
99
100 return false;
101 }
102
103 unsigned num_nodes = named_metadata->getNumOperands();
104 unsigned node_index;
105
106 MDNode *metadata_node = NULL;
107
108 for (node_index = 0;
109 node_index < num_nodes;
110 ++node_index)
111 {
112 metadata_node = named_metadata->getOperand(node_index);
113
114 if (metadata_node->getNumOperands() != 2)
115 continue;
116
117 if (metadata_node->getOperand(0) == result_global)
118 break;
119 }
120
121 if (!metadata_node)
122 {
123 if (log)
124 log->PutCString("Couldn't find result metadata");
125 return false;
126 }
127
128 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
129
130 uint64_t result_decl_intptr = constant_int->getZExtValue();
131
132 clang::VarDecl *result_decl = reinterpret_cast<clang::VarDecl *>(result_decl_intptr);
133
134 // Get the next available result name from m_decl_map and create the persistent
135 // variable for it
136
137 lldb_private::TypeFromParser result_decl_type (result_decl->getType().getAsOpaquePtr(),
138 &result_decl->getASTContext());
139 std::string new_result_name;
140
141 m_decl_map->GetPersistentResultName(new_result_name);
Sean Callanan8c127202010-08-23 23:09:38 +0000142 m_decl_map->AddPersistentVariable(result_decl, new_result_name.c_str(), result_decl_type);
Sean Callanan82b74c82010-08-12 01:56:52 +0000143
144 if (log)
145 log->Printf("Creating a new result global: %s", new_result_name.c_str());
146
147 // Construct a new result global and set up its metadata
148
149 GlobalVariable *new_result_global = new GlobalVariable(M,
150 result_global->getType()->getElementType(),
151 false, /* not constant */
152 GlobalValue::ExternalLinkage,
153 NULL, /* no initializer */
154 new_result_name.c_str());
155
156 // It's too late in compilation to create a new VarDecl for this, but we don't
157 // need to. We point the metadata at the old VarDecl. This creates an odd
158 // anomaly: a variable with a Value whose name is something like $0 and a
159 // Decl whose name is ___clang_expr_result. This condition is handled in
160 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
161 // fixed up.
162
163 ConstantInt *new_constant_int = ConstantInt::get(constant_int->getType(),
164 result_decl_intptr,
165 false);
166
167 llvm::Value* values[2];
168 values[0] = new_result_global;
169 values[1] = new_constant_int;
170
171 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
172 named_metadata->addOperand(persistent_global_md);
173
174 if (log)
Sean Callanan2e2db532010-09-07 22:43:19 +0000175 log->Printf("Replacing %s with %s",
176 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000177 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000178
179 if (result_global->hasNUses(0))
180 {
181 // We need to synthesize a store for this variable, because otherwise
182 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000183
Sean Callanan2e2db532010-09-07 22:43:19 +0000184 BasicBlock &entry_block(F.getEntryBlock());
185 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
186
187 if (!first_entry_instruction)
188 return false;
189
190 if (!result_global->hasInitializer())
191 {
192 if (log)
193 log->Printf("Couldn't find initializer for unused variable");
194 return false;
195 }
196
197 Constant *initializer = result_global->getInitializer();
198
199 StoreInst *synthesized_store = new StoreInst::StoreInst(initializer,
200 new_result_global,
201 first_entry_instruction);
202
203 if (log)
204 log->Printf("Synthesized result store %s\n", PrintValue(synthesized_store).c_str());
205 }
206 else
207 {
208 result_global->replaceAllUsesWith(new_result_global);
209 }
210
Sean Callanan82b74c82010-08-12 01:56:52 +0000211 result_global->eraseFromParent();
212
213 return true;
214}
215
Sean Callananf5857a02010-07-31 01:32:05 +0000216static bool isObjCSelectorRef(Value *V)
217{
218 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
219
220 if (!GV || !GV->hasName() || !GV->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
221 return false;
222
223 return true;
224}
225
226bool
227IRForTarget::RewriteObjCSelector(Instruction* selector_load,
228 Module &M)
229{
230 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
231
232 LoadInst *load = dyn_cast<LoadInst>(selector_load);
233
234 if (!load)
235 return false;
236
237 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
238 //
239 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
240 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
241 //
242 // where %obj is the object pointer and %tmp is the selector.
243 //
244 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_METH_VAR_NAME_".
245 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
246
247 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
248
249 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
250
251 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
252 return false;
253
254 Constant *osr_initializer = _objc_selector_references_->getInitializer();
255
256 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
257
258 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
259 return false;
260
261 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
262
263 if (!osr_initializer_base)
264 return false;
265
266 // Find the string's initializer (a ConstantArray) and get the string from it
267
268 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
269
270 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
271 return false;
272
273 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
274
275 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
276
277 if (!omvn_initializer_array->isString())
278 return false;
279
280 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
281
282 if (log)
283 log->Printf("Found Objective-C selector reference %s", omvn_initializer_string.c_str());
284
285 // Construct a call to sel_registerName
286
287 if (!m_sel_registerName)
288 {
289 uint64_t srN_addr;
290
291 if (!m_decl_map->GetFunctionAddress("sel_registerName", srN_addr))
292 return false;
293
294 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
295
296 // The below code would be "more correct," but in actuality what's required is uint8_t*
297 //Type *sel_type = StructType::get(M.getContext());
298 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
299 const Type *sel_ptr_type = Type::getInt8PtrTy(M.getContext());
300
301 std::vector <const Type *> srN_arg_types;
302 srN_arg_types.push_back(Type::getInt8PtrTy(M.getContext()));
303 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
304
305 // Build the constant containing the pointer to the function
306 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
307 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
308 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
309 Constant *srN_addr_int = ConstantInt::get(intptr_ty, srN_addr, false);
310 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
311 }
312
313 SmallVector <Value*, 1> srN_arguments;
314
315 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(M.getContext()));
316
317 srN_arguments.push_back(omvn_pointer);
318
319 CallInst *srN_call = CallInst::Create(m_sel_registerName,
320 srN_arguments.begin(),
321 srN_arguments.end(),
322 "srN",
323 selector_load);
324
325 // Replace the load with the call in all users
326
327 selector_load->replaceAllUsesWith(srN_call);
328
329 selector_load->eraseFromParent();
330
331 return true;
332}
333
334bool
335IRForTarget::rewriteObjCSelectors(Module &M,
336 BasicBlock &BB)
337{
338 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
339
340 BasicBlock::iterator ii;
341
342 typedef SmallVector <Instruction*, 2> InstrList;
343 typedef InstrList::iterator InstrIterator;
344
345 InstrList selector_loads;
346
347 for (ii = BB.begin();
348 ii != BB.end();
349 ++ii)
350 {
351 Instruction &inst = *ii;
352
353 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
354 if (isObjCSelectorRef(load->getPointerOperand()))
355 selector_loads.push_back(&inst);
356 }
357
358 InstrIterator iter;
359
360 for (iter = selector_loads.begin();
361 iter != selector_loads.end();
362 ++iter)
363 {
364 if (!RewriteObjCSelector(*iter, M))
365 {
366 if(log)
367 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
368 return false;
369 }
370 }
371
372 return true;
373}
374
Sean Callanana48fe162010-08-11 03:57:18 +0000375bool
376IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc,
377 llvm::Module &M)
378{
379 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
380
381 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
382
383 if (!alloc_md || !alloc_md->getNumOperands())
384 return false;
385
386 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
387
388 if (!constant_int)
389 return false;
390
391 // We attempt to register this as a new persistent variable with the DeclMap.
392
393 uintptr_t ptr = constant_int->getZExtValue();
394
Sean Callanan82b74c82010-08-12 01:56:52 +0000395 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +0000396
Sean Callanan82b74c82010-08-12 01:56:52 +0000397 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
398 &decl->getASTContext());
399
Sean Callanan8c127202010-08-23 23:09:38 +0000400 if (!m_decl_map->AddPersistentVariable(decl, decl->getName().str().c_str(), result_decl_type))
Sean Callanana48fe162010-08-11 03:57:18 +0000401 return false;
402
403 GlobalVariable *persistent_global = new GlobalVariable(M,
404 alloc->getType()->getElementType(),
405 false, /* not constant */
406 GlobalValue::ExternalLinkage,
407 NULL, /* no initializer */
408 alloc->getName().str().c_str());
409
410 // What we're going to do here is make believe this was a regular old external
411 // variable. That means we need to make the metadata valid.
412
413 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
414
415 llvm::Value* values[2];
416 values[0] = persistent_global;
417 values[1] = constant_int;
418
419 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
420 named_metadata->addOperand(persistent_global_md);
421
422 alloc->replaceAllUsesWith(persistent_global);
423 alloc->eraseFromParent();
424
425 return true;
426}
427
428bool
429IRForTarget::rewritePersistentAllocs(llvm::Module &M,
430 llvm::BasicBlock &BB)
431{
432 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
433
434 BasicBlock::iterator ii;
435
436 typedef SmallVector <Instruction*, 2> InstrList;
437 typedef InstrList::iterator InstrIterator;
438
439 InstrList pvar_allocs;
440
441 for (ii = BB.begin();
442 ii != BB.end();
443 ++ii)
444 {
445 Instruction &inst = *ii;
446
447 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
448 if (alloc->getName().startswith("$"))
449 pvar_allocs.push_back(alloc);
450 }
451
452 InstrIterator iter;
453
454 for (iter = pvar_allocs.begin();
455 iter != pvar_allocs.end();
456 ++iter)
457 {
458 if (!RewritePersistentAlloc(*iter, M))
459 {
460 if(log)
461 log->PutCString("Couldn't rewrite the creation of a persistent variable");
462 return false;
463 }
464 }
465
466 return true;
467}
468
Sean Callanan8bce6652010-07-13 21:41:46 +0000469static clang::NamedDecl *
Sean Callanan02fbafa2010-07-27 21:39:39 +0000470DeclForGlobalValue(Module &module,
471 GlobalValue *global_value)
Sean Callanan8bce6652010-07-13 21:41:46 +0000472{
473 NamedMDNode *named_metadata = module.getNamedMetadata("clang.global.decl.ptrs");
474
475 if (!named_metadata)
476 return NULL;
477
478 unsigned num_nodes = named_metadata->getNumOperands();
479 unsigned node_index;
480
481 for (node_index = 0;
482 node_index < num_nodes;
483 ++node_index)
484 {
485 MDNode *metadata_node = named_metadata->getOperand(node_index);
486
487 if (!metadata_node)
488 return NULL;
489
490 if (metadata_node->getNumOperands() != 2)
Sean Callanana48fe162010-08-11 03:57:18 +0000491 continue;
Sean Callanan8bce6652010-07-13 21:41:46 +0000492
493 if (metadata_node->getOperand(0) != global_value)
494 continue;
495
496 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
497
498 if (!constant_int)
499 return NULL;
500
501 uintptr_t ptr = constant_int->getZExtValue();
502
503 return reinterpret_cast<clang::NamedDecl *>(ptr);
504 }
505
506 return NULL;
507}
508
509bool
510IRForTarget::MaybeHandleVariable(Module &M,
Sean Callanan02fbafa2010-07-27 21:39:39 +0000511 Value *V,
Sean Callanan8bce6652010-07-13 21:41:46 +0000512 bool Store)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000513{
Sean Callananf5857a02010-07-31 01:32:05 +0000514 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
515
Sean Callananbc2928a2010-08-03 00:23:29 +0000516 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(V))
517 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000518 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +0000519 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000520 default:
521 break;
522 case Instruction::GetElementPtr:
523 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +0000524 Value *s = constant_expr->getOperand(0);
525 MaybeHandleVariable(M, s, Store);
526 }
527 }
Sean Callanan8bce6652010-07-13 21:41:46 +0000528 if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(V))
Sean Callananf5857a02010-07-31 01:32:05 +0000529 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000530 clang::NamedDecl *named_decl = DeclForGlobalValue(M, global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000531
Sean Callananf5857a02010-07-31 01:32:05 +0000532 if (!named_decl)
533 {
534 if (isObjCSelectorRef(V))
535 return true;
536
537 if (log)
538 log->Printf("Found global variable %s without metadata", global_variable->getName().str().c_str());
539 return false;
540 }
541
Sean Callanan810f22d2010-07-16 00:09:46 +0000542 std::string name = named_decl->getName().str();
543
544 void *qual_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +0000545 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +0000546
547 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +0000548 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000549 qual_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +0000550 ast_context = &value_decl->getASTContext();
551 }
Sean Callanan810f22d2010-07-16 00:09:46 +0000552 else
Sean Callananf328c9f2010-07-20 23:31:16 +0000553 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000554 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +0000555 }
556
Sean Callanan02fbafa2010-07-27 21:39:39 +0000557 const Type *value_type = global_variable->getType();
Sean Callanan8bce6652010-07-13 21:41:46 +0000558
559 size_t value_size = m_target_data->getTypeStoreSize(value_type);
560 off_t value_alignment = m_target_data->getPrefTypeAlignment(value_type);
561
Sean Callanan8c127202010-08-23 23:09:38 +0000562 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Sean Callanan45690fe2010-08-30 22:17:16 +0000563 name.c_str(),
Sean Callanan8c127202010-08-23 23:09:38 +0000564 V,
Sean Callananba992c52010-07-27 02:07:53 +0000565 value_size,
566 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +0000567 return false;
568 }
569
570 return true;
571}
572
573bool
Sean Callananba992c52010-07-27 02:07:53 +0000574IRForTarget::MaybeHandleCall(Module &M,
575 CallInst *C)
576{
577 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
578
Sean Callanan02fbafa2010-07-27 21:39:39 +0000579 Function *fun = C->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +0000580
581 if (fun == NULL)
582 return true;
583
584 clang::NamedDecl *fun_decl = DeclForGlobalValue(M, fun);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000585 uint64_t fun_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000586 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +0000587
Sean Callananf5857a02010-07-31 01:32:05 +0000588 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +0000589 {
Sean Callananf5857a02010-07-31 01:32:05 +0000590 if (!m_decl_map->GetFunctionInfo(fun_decl, fun_value_ptr, fun_addr))
591 {
Sean Callanan92aa6662010-09-07 21:49:41 +0000592 fun_value_ptr = NULL;
593
594 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
595 {
596 if (log)
597 log->Printf("Function %s had no address", fun->getName().str().c_str());
598
599 return false;
600 }
Sean Callananf5857a02010-07-31 01:32:05 +0000601 }
602 }
603 else
604 {
605 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
606 {
607 if (log)
608 log->Printf("Metadataless function %s had no address", fun->getName().str().c_str());
609 return false;
610 }
Sean Callananba992c52010-07-27 02:07:53 +0000611 }
612
613 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +0000614 log->Printf("Found %s at %llx", fun->getName().str().c_str(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +0000615
Sean Callananf5857a02010-07-31 01:32:05 +0000616 Value *fun_addr_ptr;
617
618 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +0000619 {
Sean Callanan02fbafa2010-07-27 21:39:39 +0000620 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
621 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan92aa6662010-09-07 21:49:41 +0000622 const FunctionType *fun_ty = fun->getFunctionType();
Sean Callanan02fbafa2010-07-27 21:39:39 +0000623 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
624 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000625 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
626
627 if (fun_value_ptr)
628 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000629 }
Sean Callananf5857a02010-07-31 01:32:05 +0000630
631 if (fun_value_ptr)
632 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000633
Sean Callananf5857a02010-07-31 01:32:05 +0000634 C->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000635
Sean Callananba992c52010-07-27 02:07:53 +0000636 return true;
637}
638
639bool
Sean Callananf5857a02010-07-31 01:32:05 +0000640IRForTarget::resolveExternals(Module &M, BasicBlock &BB)
Sean Callanan8bce6652010-07-13 21:41:46 +0000641{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000642 /////////////////////////////////////////////////////////////////////////
643 // Prepare the current basic block for execution in the remote process
644 //
645
Sean Callanan02fbafa2010-07-27 21:39:39 +0000646 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +0000647
648 for (ii = BB.begin();
649 ii != BB.end();
650 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000651 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000652 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000653
Sean Callanan8bce6652010-07-13 21:41:46 +0000654 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000655 if (!MaybeHandleVariable(M, load->getPointerOperand(), false))
Sean Callanan8bce6652010-07-13 21:41:46 +0000656 return false;
Sean Callananf5857a02010-07-31 01:32:05 +0000657
Sean Callanan8bce6652010-07-13 21:41:46 +0000658 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000659 if (!MaybeHandleVariable(M, store->getPointerOperand(), true))
660 return false;
661
662 if (CallInst *call = dyn_cast<CallInst>(&inst))
663 if (!MaybeHandleCall(M, call))
Sean Callanan8bce6652010-07-13 21:41:46 +0000664 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000665 }
666
667 return true;
668}
669
Sean Callanan02fbafa2010-07-27 21:39:39 +0000670static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +0000671{
672 ConstantExpr *C = dyn_cast<ConstantExpr>(V);
673
674 if (!C || C->getOpcode() != Instruction::BitCast)
675 return false;
676
677 GlobalVariable *GV = dyn_cast<GlobalVariable>(C->getOperand(0));
678
679 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
680 return false;
681
682 return true;
683}
684
685static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
686{
687 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
688
689 Value::use_iterator ui;
690
691 for (ui = guard_load->use_begin();
692 ui != guard_load->use_end();
693 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +0000694 {
Greg Clayton6e713402010-07-30 20:30:44 +0000695 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +0000696 {
697 // do nothing for the moment
698 }
699 else
700 {
701 ui->replaceUsesOfWith(guard_load, zero);
702 }
703 }
Sean Callanan45839272010-07-24 01:37:44 +0000704
705 guard_load->eraseFromParent();
706}
707
708static void ExciseGuardStore(Instruction* guard_store)
709{
710 guard_store->eraseFromParent();
711}
712
713bool
714IRForTarget::removeGuards(Module &M, BasicBlock &BB)
715{
716 ///////////////////////////////////////////////////////
717 // Eliminate any reference to guard variables found.
718 //
719
Sean Callanan02fbafa2010-07-27 21:39:39 +0000720 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +0000721
Sean Callanan02fbafa2010-07-27 21:39:39 +0000722 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +0000723 typedef InstrList::iterator InstrIterator;
724
725 InstrList guard_loads;
726 InstrList guard_stores;
727
728 for (ii = BB.begin();
729 ii != BB.end();
730 ++ii)
731 {
732 Instruction &inst = *ii;
733
734 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
735 if (isGuardVariableRef(load->getPointerOperand()))
736 guard_loads.push_back(&inst);
737
738 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
739 if (isGuardVariableRef(store->getPointerOperand()))
740 guard_stores.push_back(&inst);
741 }
742
743 InstrIterator iter;
744
745 for (iter = guard_loads.begin();
746 iter != guard_loads.end();
747 ++iter)
748 TurnGuardLoadIntoZero(*iter, M);
749
750 for (iter = guard_stores.begin();
751 iter != guard_stores.end();
752 ++iter)
753 ExciseGuardStore(*iter);
754
755 return true;
756}
757
Sean Callananbafd6852010-07-14 23:40:29 +0000758// UnfoldConstant operates on a constant [C] which has just been replaced with a value
759// [new_value]. We assume that new_value has been properly placed early in the function,
760// most likely somewhere in front of the first instruction in the entry basic block
761// [first_entry_instruction].
762//
763// UnfoldConstant reads through the uses of C and replaces C in those uses with new_value.
764// Where those uses are constants, the function generates new instructions to compute the
765// result of the new, non-constant expression and places them before first_entry_instruction.
766// These instructions replace the constant uses, so UnfoldConstant calls itself recursively
767// for those.
768
769static bool
Sean Callanan02fbafa2010-07-27 21:39:39 +0000770UnfoldConstant(Constant *C, Value *new_value, Instruction *first_entry_instruction)
Sean Callananbafd6852010-07-14 23:40:29 +0000771{
772 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
773
774 Value::use_iterator ui;
775
Sean Callanana48fe162010-08-11 03:57:18 +0000776 SmallVector<User*, 16> users;
777
778 // We do this because the use list might change, invalidating our iterator.
779 // Much better to keep a work list ourselves.
Sean Callananbafd6852010-07-14 23:40:29 +0000780 for (ui = C->use_begin();
781 ui != C->use_end();
782 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +0000783 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +0000784
Sean Callanana48fe162010-08-11 03:57:18 +0000785 for (int i = 0;
786 i < users.size();
787 ++i)
788 {
789 User *user = users[i];
790
Sean Callananbafd6852010-07-14 23:40:29 +0000791 if (Constant *constant = dyn_cast<Constant>(user))
792 {
793 // synthesize a new non-constant equivalent of the constant
794
795 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
796 {
797 switch (constant_expr->getOpcode())
798 {
799 default:
800 if (log)
801 log->Printf("Unhandled constant expression type: %s", PrintValue(constant_expr).c_str());
802 return false;
803 case Instruction::BitCast:
804 {
805 // UnaryExpr
806 // OperandList[0] is value
807
808 Value *s = constant_expr->getOperand(0);
809
810 if (s == C)
811 s = new_value;
812
813 BitCastInst *bit_cast(new BitCastInst(s, C->getType(), "", first_entry_instruction));
814
815 UnfoldConstant(constant_expr, bit_cast, first_entry_instruction);
816 }
817 break;
818 case Instruction::GetElementPtr:
819 {
820 // GetElementPtrConstantExpr
821 // OperandList[0] is base
822 // OperandList[1]... are indices
823
824 Value *ptr = constant_expr->getOperand(0);
825
826 if (ptr == C)
827 ptr = new_value;
828
829 SmallVector<Value*, 16> indices;
830
831 unsigned operand_index;
832 unsigned num_operands = constant_expr->getNumOperands();
833
834 for (operand_index = 1;
835 operand_index < num_operands;
836 ++operand_index)
837 {
838 Value *operand = constant_expr->getOperand(operand_index);
839
840 if (operand == C)
841 operand = new_value;
842
843 indices.push_back(operand);
844 }
845
846 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_instruction));
847
848 UnfoldConstant(constant_expr, get_element_ptr, first_entry_instruction);
849 }
850 break;
851 }
852 }
853 else
854 {
855 if (log)
856 log->Printf("Unhandled constant type: %s", PrintValue(constant).c_str());
857 return false;
858 }
859 }
860 else
861 {
862 // simple fall-through case for non-constants
863 user->replaceUsesOfWith(C, new_value);
864 }
865 }
866
867 return true;
868}
869
Sean Callanan8bce6652010-07-13 21:41:46 +0000870bool
Sean Callananf5857a02010-07-31 01:32:05 +0000871IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +0000872{
873 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
874
875 m_decl_map->DoStructLayout();
876
877 if (log)
878 log->Printf("Element arrangement:");
879
880 uint32_t num_elements;
881 uint32_t element_index;
882
883 size_t size;
884 off_t alignment;
885
886 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
887 return false;
888
Sean Callananf5857a02010-07-31 01:32:05 +0000889 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +0000890
Sean Callananf5857a02010-07-31 01:32:05 +0000891 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +0000892 return false;
893
Sean Callanan02fbafa2010-07-27 21:39:39 +0000894 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +0000895
896 if (!argument->getName().equals("___clang_arg"))
897 return false;
898
899 if (log)
900 log->Printf("Arg: %s", PrintValue(argument).c_str());
901
Sean Callananf5857a02010-07-31 01:32:05 +0000902 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan02fbafa2010-07-27 21:39:39 +0000903 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +0000904
905 if (!first_entry_instruction)
906 return false;
907
908 LLVMContext &context(M.getContext());
909 const IntegerType *offset_type(Type::getInt32Ty(context));
910
911 if (!offset_type)
912 return false;
913
914 for (element_index = 0; element_index < num_elements; ++element_index)
915 {
916 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000917 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +0000918 off_t offset;
Sean Callanan45690fe2010-08-30 22:17:16 +0000919 const char *name;
Sean Callanan8bce6652010-07-13 21:41:46 +0000920
Sean Callanan45690fe2010-08-30 22:17:16 +0000921 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan8bce6652010-07-13 21:41:46 +0000922 return false;
923
924 if (log)
Sean Callanan45690fe2010-08-30 22:17:16 +0000925 log->Printf(" %s [%s] (%s) placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +0000926 value->getName().str().c_str(),
Sean Callanan45690fe2010-08-30 22:17:16 +0000927 name,
Sean Callanan8bce6652010-07-13 21:41:46 +0000928 PrintValue(value, true).c_str(),
929 offset);
930
931 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
932 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", first_entry_instruction);
933 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", first_entry_instruction);
934
Sean Callananbafd6852010-07-14 23:40:29 +0000935 if (Constant *constant = dyn_cast<Constant>(value))
936 UnfoldConstant(constant, bit_cast, first_entry_instruction);
937 else
938 value->replaceAllUsesWith(bit_cast);
Sean Callanan8bce6652010-07-13 21:41:46 +0000939 }
940
941 if (log)
942 log->Printf("Total structure [align %d, size %d]", alignment, size);
943
944 return true;
945}
946
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000947bool
948IRForTarget::runOnModule(Module &M)
949{
950 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
951
Sean Callanan65dafa82010-08-27 01:01:44 +0000952 Function* function = M.getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000953
954 if (!function)
955 {
956 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000957 log->Printf("Couldn't find %s() in the module", m_func_name.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000958
959 return false;
960 }
961
Sean Callanan02fbafa2010-07-27 21:39:39 +0000962 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000963
Sean Callanan82b74c82010-08-12 01:56:52 +0000964 ////////////////////////////////////////////////////////////
965 // Replace __clang_expr_result with a persistent variable
966 //
967
968 if (!createResultVariable(M, *function))
969 return false;
970
Sean Callananf5857a02010-07-31 01:32:05 +0000971 //////////////////////////////////
972 // Run basic-block level passes
973 //
974
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000975 for (bbi = function->begin();
976 bbi != function->end();
977 ++bbi)
978 {
Sean Callanan8c127202010-08-23 23:09:38 +0000979 if (!removeGuards(M, *bbi))
980 return false;
981
Sean Callanana48fe162010-08-11 03:57:18 +0000982 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +0000983 return false;
984
Sean Callanana48fe162010-08-11 03:57:18 +0000985 if (!rewriteObjCSelectors(M, *bbi))
986 return false;
987
Sean Callananf5857a02010-07-31 01:32:05 +0000988 if (!resolveExternals(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +0000989 return false;
990 }
991
Sean Callanan8bce6652010-07-13 21:41:46 +0000992 if (log)
993 {
Sean Callanan321fe9e2010-07-28 01:00:59 +0000994 std::string s;
995 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +0000996
Sean Callanan321fe9e2010-07-28 01:00:59 +0000997 M.print(oss, NULL);
998
999 oss.flush();
1000
1001 log->Printf("Module after preparing for execution: \n%s", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001002 }
1003
Sean Callanana48fe162010-08-11 03:57:18 +00001004 ///////////////////////////////
1005 // Run function-level passes
1006 //
1007
1008 if (!replaceVariables(M, *function))
1009 return false;
1010
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001011 return true;
1012}
1013
1014void
1015IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +00001016 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001017{
1018}
1019
1020PassManagerType
1021IRForTarget::getPotentialPassManagerType() const
1022{
1023 return PMT_ModulePassManager;
1024}