blob: c14891b160c623ce6d346cfc23eaa653dd345208 [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 Callanan02fbafa2010-07-27 21:39:39 +000034 const TargetData *target_data) :
Sean Callanana6223432010-08-20 01:02:30 +000035 ModulePass(&ID),
Sean Callanan8bce6652010-07-13 21:41:46 +000036 m_decl_map(decl_map),
Sean Callananf5857a02010-07-31 01:32:05 +000037 m_target_data(target_data),
38 m_sel_registerName(NULL)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000039{
40}
41
Sean Callanana48fe162010-08-11 03:57:18 +000042/* A handy utility function used at several places in the code */
43
44static std::string
45PrintValue(Value *V, bool truncate = false)
46{
47 std::string s;
48 raw_string_ostream rso(s);
49 V->print(rso);
50 rso.flush();
51 if (truncate)
52 s.resize(s.length() - 1);
53 return s;
54}
55
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000056IRForTarget::~IRForTarget()
57{
58}
59
Sean Callanan82b74c82010-08-12 01:56:52 +000060bool
61IRForTarget::createResultVariable(llvm::Module &M,
62 llvm::Function &F)
63{
64 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
65
66 // Find the result variable
67
68 Value *result_value = M.getNamedValue("___clang_expr_result");
69
70 if (!result_value)
71 {
72 if (log)
73 log->PutCString("Couldn't find result variable");
74 return false;
75 }
76
77 if (log)
78 log->Printf("Found result in the IR: %s", PrintValue(result_value, false).c_str());
79
80 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
81
82 if (!result_global)
83 {
84 if (log)
85 log->PutCString("Result variable isn't a GlobalVariable");
86 return false;
87 }
88
89 // Find the metadata and follow it to the VarDecl
90
91 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
92
93 if (!named_metadata)
94 {
95 if (log)
96 log->PutCString("No global metadata");
97
98 return false;
99 }
100
101 unsigned num_nodes = named_metadata->getNumOperands();
102 unsigned node_index;
103
104 MDNode *metadata_node = NULL;
105
106 for (node_index = 0;
107 node_index < num_nodes;
108 ++node_index)
109 {
110 metadata_node = named_metadata->getOperand(node_index);
111
112 if (metadata_node->getNumOperands() != 2)
113 continue;
114
115 if (metadata_node->getOperand(0) == result_global)
116 break;
117 }
118
119 if (!metadata_node)
120 {
121 if (log)
122 log->PutCString("Couldn't find result metadata");
123 return false;
124 }
125
126 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
127
128 uint64_t result_decl_intptr = constant_int->getZExtValue();
129
130 clang::VarDecl *result_decl = reinterpret_cast<clang::VarDecl *>(result_decl_intptr);
131
132 // Get the next available result name from m_decl_map and create the persistent
133 // variable for it
134
135 lldb_private::TypeFromParser result_decl_type (result_decl->getType().getAsOpaquePtr(),
136 &result_decl->getASTContext());
137 std::string new_result_name;
138
139 m_decl_map->GetPersistentResultName(new_result_name);
Sean Callanan8c127202010-08-23 23:09:38 +0000140 m_decl_map->AddPersistentVariable(result_decl, new_result_name.c_str(), result_decl_type);
Sean Callanan82b74c82010-08-12 01:56:52 +0000141
142 if (log)
143 log->Printf("Creating a new result global: %s", new_result_name.c_str());
144
145 // Construct a new result global and set up its metadata
146
147 GlobalVariable *new_result_global = new GlobalVariable(M,
148 result_global->getType()->getElementType(),
149 false, /* not constant */
150 GlobalValue::ExternalLinkage,
151 NULL, /* no initializer */
152 new_result_name.c_str());
153
154 // It's too late in compilation to create a new VarDecl for this, but we don't
155 // need to. We point the metadata at the old VarDecl. This creates an odd
156 // anomaly: a variable with a Value whose name is something like $0 and a
157 // Decl whose name is ___clang_expr_result. This condition is handled in
158 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
159 // fixed up.
160
161 ConstantInt *new_constant_int = ConstantInt::get(constant_int->getType(),
162 result_decl_intptr,
163 false);
164
165 llvm::Value* values[2];
166 values[0] = new_result_global;
167 values[1] = new_constant_int;
168
169 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
170 named_metadata->addOperand(persistent_global_md);
171
172 if (log)
173 log->Printf("Replacing %s with %s",
174 PrintValue(result_global).c_str(),
175 PrintValue(new_result_global).c_str());
176
177 result_global->replaceAllUsesWith(new_result_global);
178 result_global->eraseFromParent();
179
180 return true;
181}
182
Sean Callananf5857a02010-07-31 01:32:05 +0000183static bool isObjCSelectorRef(Value *V)
184{
185 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
186
187 if (!GV || !GV->hasName() || !GV->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
188 return false;
189
190 return true;
191}
192
193bool
194IRForTarget::RewriteObjCSelector(Instruction* selector_load,
195 Module &M)
196{
197 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
198
199 LoadInst *load = dyn_cast<LoadInst>(selector_load);
200
201 if (!load)
202 return false;
203
204 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
205 //
206 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
207 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
208 //
209 // where %obj is the object pointer and %tmp is the selector.
210 //
211 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_METH_VAR_NAME_".
212 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
213
214 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
215
216 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
217
218 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
219 return false;
220
221 Constant *osr_initializer = _objc_selector_references_->getInitializer();
222
223 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
224
225 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
226 return false;
227
228 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
229
230 if (!osr_initializer_base)
231 return false;
232
233 // Find the string's initializer (a ConstantArray) and get the string from it
234
235 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
236
237 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
238 return false;
239
240 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
241
242 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
243
244 if (!omvn_initializer_array->isString())
245 return false;
246
247 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
248
249 if (log)
250 log->Printf("Found Objective-C selector reference %s", omvn_initializer_string.c_str());
251
252 // Construct a call to sel_registerName
253
254 if (!m_sel_registerName)
255 {
256 uint64_t srN_addr;
257
258 if (!m_decl_map->GetFunctionAddress("sel_registerName", srN_addr))
259 return false;
260
261 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
262
263 // The below code would be "more correct," but in actuality what's required is uint8_t*
264 //Type *sel_type = StructType::get(M.getContext());
265 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
266 const Type *sel_ptr_type = Type::getInt8PtrTy(M.getContext());
267
268 std::vector <const Type *> srN_arg_types;
269 srN_arg_types.push_back(Type::getInt8PtrTy(M.getContext()));
270 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
271
272 // Build the constant containing the pointer to the function
273 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
274 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
275 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
276 Constant *srN_addr_int = ConstantInt::get(intptr_ty, srN_addr, false);
277 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
278 }
279
280 SmallVector <Value*, 1> srN_arguments;
281
282 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(M.getContext()));
283
284 srN_arguments.push_back(omvn_pointer);
285
286 CallInst *srN_call = CallInst::Create(m_sel_registerName,
287 srN_arguments.begin(),
288 srN_arguments.end(),
289 "srN",
290 selector_load);
291
292 // Replace the load with the call in all users
293
294 selector_load->replaceAllUsesWith(srN_call);
295
296 selector_load->eraseFromParent();
297
298 return true;
299}
300
301bool
302IRForTarget::rewriteObjCSelectors(Module &M,
303 BasicBlock &BB)
304{
305 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
306
307 BasicBlock::iterator ii;
308
309 typedef SmallVector <Instruction*, 2> InstrList;
310 typedef InstrList::iterator InstrIterator;
311
312 InstrList selector_loads;
313
314 for (ii = BB.begin();
315 ii != BB.end();
316 ++ii)
317 {
318 Instruction &inst = *ii;
319
320 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
321 if (isObjCSelectorRef(load->getPointerOperand()))
322 selector_loads.push_back(&inst);
323 }
324
325 InstrIterator iter;
326
327 for (iter = selector_loads.begin();
328 iter != selector_loads.end();
329 ++iter)
330 {
331 if (!RewriteObjCSelector(*iter, M))
332 {
333 if(log)
334 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
335 return false;
336 }
337 }
338
339 return true;
340}
341
Sean Callanana48fe162010-08-11 03:57:18 +0000342bool
343IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc,
344 llvm::Module &M)
345{
346 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
347
348 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
349
350 if (!alloc_md || !alloc_md->getNumOperands())
351 return false;
352
353 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
354
355 if (!constant_int)
356 return false;
357
358 // We attempt to register this as a new persistent variable with the DeclMap.
359
360 uintptr_t ptr = constant_int->getZExtValue();
361
Sean Callanan82b74c82010-08-12 01:56:52 +0000362 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +0000363
Sean Callanan82b74c82010-08-12 01:56:52 +0000364 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
365 &decl->getASTContext());
366
Sean Callanan8c127202010-08-23 23:09:38 +0000367 if (!m_decl_map->AddPersistentVariable(decl, decl->getName().str().c_str(), result_decl_type))
Sean Callanana48fe162010-08-11 03:57:18 +0000368 return false;
369
370 GlobalVariable *persistent_global = new GlobalVariable(M,
371 alloc->getType()->getElementType(),
372 false, /* not constant */
373 GlobalValue::ExternalLinkage,
374 NULL, /* no initializer */
375 alloc->getName().str().c_str());
376
377 // What we're going to do here is make believe this was a regular old external
378 // variable. That means we need to make the metadata valid.
379
380 NamedMDNode *named_metadata = M.getNamedMetadata("clang.global.decl.ptrs");
381
382 llvm::Value* values[2];
383 values[0] = persistent_global;
384 values[1] = constant_int;
385
386 MDNode *persistent_global_md = MDNode::get(M.getContext(), values, 2);
387 named_metadata->addOperand(persistent_global_md);
388
389 alloc->replaceAllUsesWith(persistent_global);
390 alloc->eraseFromParent();
391
392 return true;
393}
394
395bool
396IRForTarget::rewritePersistentAllocs(llvm::Module &M,
397 llvm::BasicBlock &BB)
398{
399 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
400
401 BasicBlock::iterator ii;
402
403 typedef SmallVector <Instruction*, 2> InstrList;
404 typedef InstrList::iterator InstrIterator;
405
406 InstrList pvar_allocs;
407
408 for (ii = BB.begin();
409 ii != BB.end();
410 ++ii)
411 {
412 Instruction &inst = *ii;
413
414 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
415 if (alloc->getName().startswith("$"))
416 pvar_allocs.push_back(alloc);
417 }
418
419 InstrIterator iter;
420
421 for (iter = pvar_allocs.begin();
422 iter != pvar_allocs.end();
423 ++iter)
424 {
425 if (!RewritePersistentAlloc(*iter, M))
426 {
427 if(log)
428 log->PutCString("Couldn't rewrite the creation of a persistent variable");
429 return false;
430 }
431 }
432
433 return true;
434}
435
Sean Callanan8bce6652010-07-13 21:41:46 +0000436static clang::NamedDecl *
Sean Callanan02fbafa2010-07-27 21:39:39 +0000437DeclForGlobalValue(Module &module,
438 GlobalValue *global_value)
Sean Callanan8bce6652010-07-13 21:41:46 +0000439{
440 NamedMDNode *named_metadata = module.getNamedMetadata("clang.global.decl.ptrs");
441
442 if (!named_metadata)
443 return NULL;
444
445 unsigned num_nodes = named_metadata->getNumOperands();
446 unsigned node_index;
447
448 for (node_index = 0;
449 node_index < num_nodes;
450 ++node_index)
451 {
452 MDNode *metadata_node = named_metadata->getOperand(node_index);
453
454 if (!metadata_node)
455 return NULL;
456
457 if (metadata_node->getNumOperands() != 2)
Sean Callanana48fe162010-08-11 03:57:18 +0000458 continue;
Sean Callanan8bce6652010-07-13 21:41:46 +0000459
460 if (metadata_node->getOperand(0) != global_value)
461 continue;
462
463 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
464
465 if (!constant_int)
466 return NULL;
467
468 uintptr_t ptr = constant_int->getZExtValue();
469
470 return reinterpret_cast<clang::NamedDecl *>(ptr);
471 }
472
473 return NULL;
474}
475
476bool
477IRForTarget::MaybeHandleVariable(Module &M,
Sean Callanan02fbafa2010-07-27 21:39:39 +0000478 Value *V,
Sean Callanan8bce6652010-07-13 21:41:46 +0000479 bool Store)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000480{
Sean Callananf5857a02010-07-31 01:32:05 +0000481 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
482
Sean Callananbc2928a2010-08-03 00:23:29 +0000483 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(V))
484 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000485 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +0000486 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000487 default:
488 break;
489 case Instruction::GetElementPtr:
490 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +0000491 Value *s = constant_expr->getOperand(0);
492 MaybeHandleVariable(M, s, Store);
493 }
494 }
Sean Callanan8bce6652010-07-13 21:41:46 +0000495 if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(V))
Sean Callananf5857a02010-07-31 01:32:05 +0000496 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000497 clang::NamedDecl *named_decl = DeclForGlobalValue(M, global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000498
Sean Callananf5857a02010-07-31 01:32:05 +0000499 if (!named_decl)
500 {
501 if (isObjCSelectorRef(V))
502 return true;
503
504 if (log)
505 log->Printf("Found global variable %s without metadata", global_variable->getName().str().c_str());
506 return false;
507 }
508
Sean Callanan810f22d2010-07-16 00:09:46 +0000509 std::string name = named_decl->getName().str();
510
511 void *qual_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +0000512 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +0000513
514 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +0000515 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000516 qual_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +0000517 ast_context = &value_decl->getASTContext();
518 }
Sean Callanan810f22d2010-07-16 00:09:46 +0000519 else
Sean Callananf328c9f2010-07-20 23:31:16 +0000520 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000521 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +0000522 }
523
Sean Callanan02fbafa2010-07-27 21:39:39 +0000524 const Type *value_type = global_variable->getType();
Sean Callanan8bce6652010-07-13 21:41:46 +0000525
526 size_t value_size = m_target_data->getTypeStoreSize(value_type);
527 off_t value_alignment = m_target_data->getPrefTypeAlignment(value_type);
528
Sean Callanan8c127202010-08-23 23:09:38 +0000529 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
530 V,
Sean Callananba992c52010-07-27 02:07:53 +0000531 value_size,
532 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +0000533 return false;
534 }
535
536 return true;
537}
538
539bool
Sean Callananba992c52010-07-27 02:07:53 +0000540IRForTarget::MaybeHandleCall(Module &M,
541 CallInst *C)
542{
543 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
544
Sean Callanan02fbafa2010-07-27 21:39:39 +0000545 Function *fun = C->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +0000546
547 if (fun == NULL)
548 return true;
549
550 clang::NamedDecl *fun_decl = DeclForGlobalValue(M, fun);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000551 uint64_t fun_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000552 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +0000553
Sean Callananf5857a02010-07-31 01:32:05 +0000554 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +0000555 {
Sean Callananf5857a02010-07-31 01:32:05 +0000556 if (!m_decl_map->GetFunctionInfo(fun_decl, fun_value_ptr, fun_addr))
557 {
558 if (log)
559 log->Printf("Function %s had no address", fun_decl->getNameAsCString());
560 return false;
561 }
562 }
563 else
564 {
565 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
566 {
567 if (log)
568 log->Printf("Metadataless function %s had no address", fun->getName().str().c_str());
569 return false;
570 }
Sean Callananba992c52010-07-27 02:07:53 +0000571 }
572
573 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +0000574 log->Printf("Found %s at %llx", fun->getName().str().c_str(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +0000575
Sean Callananf5857a02010-07-31 01:32:05 +0000576 Value *fun_addr_ptr;
577
578 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +0000579 {
580 std::vector<const Type*> params;
581
582 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
583 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
584
585 FunctionType *fun_ty = FunctionType::get(intptr_ty, params, true);
586 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
587 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000588 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
589
590 if (fun_value_ptr)
591 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000592 }
Sean Callananf5857a02010-07-31 01:32:05 +0000593
594 if (fun_value_ptr)
595 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000596
Sean Callananf5857a02010-07-31 01:32:05 +0000597 C->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000598
Sean Callananba992c52010-07-27 02:07:53 +0000599 return true;
600}
601
602bool
Sean Callananf5857a02010-07-31 01:32:05 +0000603IRForTarget::resolveExternals(Module &M, BasicBlock &BB)
Sean Callanan8bce6652010-07-13 21:41:46 +0000604{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000605 /////////////////////////////////////////////////////////////////////////
606 // Prepare the current basic block for execution in the remote process
607 //
608
Sean Callanan02fbafa2010-07-27 21:39:39 +0000609 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +0000610
611 for (ii = BB.begin();
612 ii != BB.end();
613 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000614 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000615 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000616
Sean Callanan8bce6652010-07-13 21:41:46 +0000617 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000618 if (!MaybeHandleVariable(M, load->getPointerOperand(), false))
Sean Callanan8bce6652010-07-13 21:41:46 +0000619 return false;
Sean Callananf5857a02010-07-31 01:32:05 +0000620
Sean Callanan8bce6652010-07-13 21:41:46 +0000621 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000622 if (!MaybeHandleVariable(M, store->getPointerOperand(), true))
623 return false;
624
625 if (CallInst *call = dyn_cast<CallInst>(&inst))
626 if (!MaybeHandleCall(M, call))
Sean Callanan8bce6652010-07-13 21:41:46 +0000627 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000628 }
629
630 return true;
631}
632
Sean Callanan02fbafa2010-07-27 21:39:39 +0000633static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +0000634{
635 ConstantExpr *C = dyn_cast<ConstantExpr>(V);
636
637 if (!C || C->getOpcode() != Instruction::BitCast)
638 return false;
639
640 GlobalVariable *GV = dyn_cast<GlobalVariable>(C->getOperand(0));
641
642 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
643 return false;
644
645 return true;
646}
647
648static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
649{
650 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
651
652 Value::use_iterator ui;
653
654 for (ui = guard_load->use_begin();
655 ui != guard_load->use_end();
656 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +0000657 {
Greg Clayton6e713402010-07-30 20:30:44 +0000658 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +0000659 {
660 // do nothing for the moment
661 }
662 else
663 {
664 ui->replaceUsesOfWith(guard_load, zero);
665 }
666 }
Sean Callanan45839272010-07-24 01:37:44 +0000667
668 guard_load->eraseFromParent();
669}
670
671static void ExciseGuardStore(Instruction* guard_store)
672{
673 guard_store->eraseFromParent();
674}
675
676bool
677IRForTarget::removeGuards(Module &M, BasicBlock &BB)
678{
679 ///////////////////////////////////////////////////////
680 // Eliminate any reference to guard variables found.
681 //
682
Sean Callanan02fbafa2010-07-27 21:39:39 +0000683 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +0000684
Sean Callanan02fbafa2010-07-27 21:39:39 +0000685 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +0000686 typedef InstrList::iterator InstrIterator;
687
688 InstrList guard_loads;
689 InstrList guard_stores;
690
691 for (ii = BB.begin();
692 ii != BB.end();
693 ++ii)
694 {
695 Instruction &inst = *ii;
696
697 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
698 if (isGuardVariableRef(load->getPointerOperand()))
699 guard_loads.push_back(&inst);
700
701 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
702 if (isGuardVariableRef(store->getPointerOperand()))
703 guard_stores.push_back(&inst);
704 }
705
706 InstrIterator iter;
707
708 for (iter = guard_loads.begin();
709 iter != guard_loads.end();
710 ++iter)
711 TurnGuardLoadIntoZero(*iter, M);
712
713 for (iter = guard_stores.begin();
714 iter != guard_stores.end();
715 ++iter)
716 ExciseGuardStore(*iter);
717
718 return true;
719}
720
Sean Callananbafd6852010-07-14 23:40:29 +0000721// UnfoldConstant operates on a constant [C] which has just been replaced with a value
722// [new_value]. We assume that new_value has been properly placed early in the function,
723// most likely somewhere in front of the first instruction in the entry basic block
724// [first_entry_instruction].
725//
726// UnfoldConstant reads through the uses of C and replaces C in those uses with new_value.
727// Where those uses are constants, the function generates new instructions to compute the
728// result of the new, non-constant expression and places them before first_entry_instruction.
729// These instructions replace the constant uses, so UnfoldConstant calls itself recursively
730// for those.
731
732static bool
Sean Callanan02fbafa2010-07-27 21:39:39 +0000733UnfoldConstant(Constant *C, Value *new_value, Instruction *first_entry_instruction)
Sean Callananbafd6852010-07-14 23:40:29 +0000734{
735 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
736
737 Value::use_iterator ui;
738
Sean Callanana48fe162010-08-11 03:57:18 +0000739 SmallVector<User*, 16> users;
740
741 // We do this because the use list might change, invalidating our iterator.
742 // Much better to keep a work list ourselves.
Sean Callananbafd6852010-07-14 23:40:29 +0000743 for (ui = C->use_begin();
744 ui != C->use_end();
745 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +0000746 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +0000747
Sean Callanana48fe162010-08-11 03:57:18 +0000748 for (int i = 0;
749 i < users.size();
750 ++i)
751 {
752 User *user = users[i];
753
Sean Callananbafd6852010-07-14 23:40:29 +0000754 if (Constant *constant = dyn_cast<Constant>(user))
755 {
756 // synthesize a new non-constant equivalent of the constant
757
758 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
759 {
760 switch (constant_expr->getOpcode())
761 {
762 default:
763 if (log)
764 log->Printf("Unhandled constant expression type: %s", PrintValue(constant_expr).c_str());
765 return false;
766 case Instruction::BitCast:
767 {
768 // UnaryExpr
769 // OperandList[0] is value
770
771 Value *s = constant_expr->getOperand(0);
772
773 if (s == C)
774 s = new_value;
775
776 BitCastInst *bit_cast(new BitCastInst(s, C->getType(), "", first_entry_instruction));
777
778 UnfoldConstant(constant_expr, bit_cast, first_entry_instruction);
779 }
780 break;
781 case Instruction::GetElementPtr:
782 {
783 // GetElementPtrConstantExpr
784 // OperandList[0] is base
785 // OperandList[1]... are indices
786
787 Value *ptr = constant_expr->getOperand(0);
788
789 if (ptr == C)
790 ptr = new_value;
791
792 SmallVector<Value*, 16> indices;
793
794 unsigned operand_index;
795 unsigned num_operands = constant_expr->getNumOperands();
796
797 for (operand_index = 1;
798 operand_index < num_operands;
799 ++operand_index)
800 {
801 Value *operand = constant_expr->getOperand(operand_index);
802
803 if (operand == C)
804 operand = new_value;
805
806 indices.push_back(operand);
807 }
808
809 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_instruction));
810
811 UnfoldConstant(constant_expr, get_element_ptr, first_entry_instruction);
812 }
813 break;
814 }
815 }
816 else
817 {
818 if (log)
819 log->Printf("Unhandled constant type: %s", PrintValue(constant).c_str());
820 return false;
821 }
822 }
823 else
824 {
825 // simple fall-through case for non-constants
826 user->replaceUsesOfWith(C, new_value);
827 }
828 }
829
830 return true;
831}
832
Sean Callanan8bce6652010-07-13 21:41:46 +0000833bool
Sean Callananf5857a02010-07-31 01:32:05 +0000834IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +0000835{
836 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
837
838 m_decl_map->DoStructLayout();
839
840 if (log)
841 log->Printf("Element arrangement:");
842
843 uint32_t num_elements;
844 uint32_t element_index;
845
846 size_t size;
847 off_t alignment;
848
849 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
850 return false;
851
Sean Callananf5857a02010-07-31 01:32:05 +0000852 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +0000853
Sean Callananf5857a02010-07-31 01:32:05 +0000854 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +0000855 return false;
856
Sean Callanan02fbafa2010-07-27 21:39:39 +0000857 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +0000858
859 if (!argument->getName().equals("___clang_arg"))
860 return false;
861
862 if (log)
863 log->Printf("Arg: %s", PrintValue(argument).c_str());
864
Sean Callananf5857a02010-07-31 01:32:05 +0000865 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan02fbafa2010-07-27 21:39:39 +0000866 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +0000867
868 if (!first_entry_instruction)
869 return false;
870
871 LLVMContext &context(M.getContext());
872 const IntegerType *offset_type(Type::getInt32Ty(context));
873
874 if (!offset_type)
875 return false;
876
877 for (element_index = 0; element_index < num_elements; ++element_index)
878 {
879 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000880 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +0000881 off_t offset;
882
883 if (!m_decl_map->GetStructElement (decl, value, offset, element_index))
884 return false;
885
886 if (log)
887 log->Printf(" %s (%s) placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +0000888 value->getName().str().c_str(),
Sean Callanan8bce6652010-07-13 21:41:46 +0000889 PrintValue(value, true).c_str(),
890 offset);
891
892 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
893 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", first_entry_instruction);
894 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", first_entry_instruction);
895
Sean Callananbafd6852010-07-14 23:40:29 +0000896 if (Constant *constant = dyn_cast<Constant>(value))
897 UnfoldConstant(constant, bit_cast, first_entry_instruction);
898 else
899 value->replaceAllUsesWith(bit_cast);
Sean Callanan8bce6652010-07-13 21:41:46 +0000900 }
901
902 if (log)
903 log->Printf("Total structure [align %d, size %d]", alignment, size);
904
905 return true;
906}
907
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000908bool
909IRForTarget::runOnModule(Module &M)
910{
911 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
912
Sean Callanan02fbafa2010-07-27 21:39:39 +0000913 Function* function = M.getFunction(StringRef("___clang_expr"));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000914
915 if (!function)
916 {
917 if (log)
918 log->Printf("Couldn't find ___clang_expr() in the module");
919
920 return false;
921 }
922
Sean Callanan02fbafa2010-07-27 21:39:39 +0000923 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000924
Sean Callanan82b74c82010-08-12 01:56:52 +0000925 ////////////////////////////////////////////////////////////
926 // Replace __clang_expr_result with a persistent variable
927 //
928
929 if (!createResultVariable(M, *function))
930 return false;
931
Sean Callananf5857a02010-07-31 01:32:05 +0000932 //////////////////////////////////
933 // Run basic-block level passes
934 //
935
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000936 for (bbi = function->begin();
937 bbi != function->end();
938 ++bbi)
939 {
Sean Callanan8c127202010-08-23 23:09:38 +0000940 if (!removeGuards(M, *bbi))
941 return false;
942
Sean Callanana48fe162010-08-11 03:57:18 +0000943 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +0000944 return false;
945
Sean Callanana48fe162010-08-11 03:57:18 +0000946 if (!rewriteObjCSelectors(M, *bbi))
947 return false;
948
Sean Callananf5857a02010-07-31 01:32:05 +0000949 if (!resolveExternals(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +0000950 return false;
951 }
952
Sean Callanan8bce6652010-07-13 21:41:46 +0000953 if (log)
954 {
Sean Callanan321fe9e2010-07-28 01:00:59 +0000955 std::string s;
956 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +0000957
Sean Callanan321fe9e2010-07-28 01:00:59 +0000958 M.print(oss, NULL);
959
960 oss.flush();
961
962 log->Printf("Module after preparing for execution: \n%s", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000963 }
964
Sean Callanana48fe162010-08-11 03:57:18 +0000965 ///////////////////////////////
966 // Run function-level passes
967 //
968
969 if (!replaceVariables(M, *function))
970 return false;
971
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000972 return true;
973}
974
975void
976IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +0000977 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000978{
979}
980
981PassManagerType
982IRForTarget::getPotentialPassManagerType() const
983{
984 return PMT_ModulePassManager;
985}