blob: 2c0f86c412024f3fd9734e5fc317574277950fc9 [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);
140 m_decl_map->AddPersistentVariable(new_result_name.c_str(), result_decl_type);
141
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
367 if (!m_decl_map->AddPersistentVariable(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 Callananba992c52010-07-27 02:07:53 +0000529 if (named_decl && !m_decl_map->AddValueToStruct(V,
530 named_decl,
531 name,
Sean Callanana386e052010-08-13 22:29:54 +0000532 lldb_private::TypeFromParser(qual_type, ast_context),
Sean Callananba992c52010-07-27 02:07:53 +0000533 value_size,
534 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +0000535 return false;
536 }
537
538 return true;
539}
540
541bool
Sean Callananba992c52010-07-27 02:07:53 +0000542IRForTarget::MaybeHandleCall(Module &M,
543 CallInst *C)
544{
545 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
546
Sean Callanan02fbafa2010-07-27 21:39:39 +0000547 Function *fun = C->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +0000548
549 if (fun == NULL)
550 return true;
551
552 clang::NamedDecl *fun_decl = DeclForGlobalValue(M, fun);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000553 uint64_t fun_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000554 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +0000555
Sean Callananf5857a02010-07-31 01:32:05 +0000556 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +0000557 {
Sean Callananf5857a02010-07-31 01:32:05 +0000558 if (!m_decl_map->GetFunctionInfo(fun_decl, fun_value_ptr, fun_addr))
559 {
560 if (log)
561 log->Printf("Function %s had no address", fun_decl->getNameAsCString());
562 return false;
563 }
564 }
565 else
566 {
567 if (!m_decl_map->GetFunctionAddress(fun->getName().str().c_str(), fun_addr))
568 {
569 if (log)
570 log->Printf("Metadataless function %s had no address", fun->getName().str().c_str());
571 return false;
572 }
Sean Callananba992c52010-07-27 02:07:53 +0000573 }
574
575 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +0000576 log->Printf("Found %s at %llx", fun->getName().str().c_str(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +0000577
Sean Callananf5857a02010-07-31 01:32:05 +0000578 Value *fun_addr_ptr;
579
580 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +0000581 {
582 std::vector<const Type*> params;
583
584 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
585 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
586
587 FunctionType *fun_ty = FunctionType::get(intptr_ty, params, true);
588 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
589 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000590 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
591
592 if (fun_value_ptr)
593 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000594 }
Sean Callananf5857a02010-07-31 01:32:05 +0000595
596 if (fun_value_ptr)
597 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000598
Sean Callananf5857a02010-07-31 01:32:05 +0000599 C->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000600
Sean Callananba992c52010-07-27 02:07:53 +0000601 return true;
602}
603
604bool
Sean Callananf5857a02010-07-31 01:32:05 +0000605IRForTarget::resolveExternals(Module &M, BasicBlock &BB)
Sean Callanan8bce6652010-07-13 21:41:46 +0000606{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000607 /////////////////////////////////////////////////////////////////////////
608 // Prepare the current basic block for execution in the remote process
609 //
610
Sean Callanan02fbafa2010-07-27 21:39:39 +0000611 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +0000612
613 for (ii = BB.begin();
614 ii != BB.end();
615 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000616 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000617 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000618
Sean Callanan8bce6652010-07-13 21:41:46 +0000619 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000620 if (!MaybeHandleVariable(M, load->getPointerOperand(), false))
Sean Callanan8bce6652010-07-13 21:41:46 +0000621 return false;
Sean Callananf5857a02010-07-31 01:32:05 +0000622
Sean Callanan8bce6652010-07-13 21:41:46 +0000623 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
Sean Callananba992c52010-07-27 02:07:53 +0000624 if (!MaybeHandleVariable(M, store->getPointerOperand(), true))
625 return false;
626
627 if (CallInst *call = dyn_cast<CallInst>(&inst))
628 if (!MaybeHandleCall(M, call))
Sean Callanan8bce6652010-07-13 21:41:46 +0000629 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000630 }
631
632 return true;
633}
634
Sean Callanan02fbafa2010-07-27 21:39:39 +0000635static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +0000636{
637 ConstantExpr *C = dyn_cast<ConstantExpr>(V);
638
639 if (!C || C->getOpcode() != Instruction::BitCast)
640 return false;
641
642 GlobalVariable *GV = dyn_cast<GlobalVariable>(C->getOperand(0));
643
644 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
645 return false;
646
647 return true;
648}
649
650static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
651{
652 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
653
654 Value::use_iterator ui;
655
656 for (ui = guard_load->use_begin();
657 ui != guard_load->use_end();
658 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +0000659 {
Greg Clayton6e713402010-07-30 20:30:44 +0000660 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +0000661 {
662 // do nothing for the moment
663 }
664 else
665 {
666 ui->replaceUsesOfWith(guard_load, zero);
667 }
668 }
Sean Callanan45839272010-07-24 01:37:44 +0000669
670 guard_load->eraseFromParent();
671}
672
673static void ExciseGuardStore(Instruction* guard_store)
674{
675 guard_store->eraseFromParent();
676}
677
678bool
679IRForTarget::removeGuards(Module &M, BasicBlock &BB)
680{
681 ///////////////////////////////////////////////////////
682 // Eliminate any reference to guard variables found.
683 //
684
Sean Callanan02fbafa2010-07-27 21:39:39 +0000685 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +0000686
Sean Callanan02fbafa2010-07-27 21:39:39 +0000687 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +0000688 typedef InstrList::iterator InstrIterator;
689
690 InstrList guard_loads;
691 InstrList guard_stores;
692
693 for (ii = BB.begin();
694 ii != BB.end();
695 ++ii)
696 {
697 Instruction &inst = *ii;
698
699 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
700 if (isGuardVariableRef(load->getPointerOperand()))
701 guard_loads.push_back(&inst);
702
703 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
704 if (isGuardVariableRef(store->getPointerOperand()))
705 guard_stores.push_back(&inst);
706 }
707
708 InstrIterator iter;
709
710 for (iter = guard_loads.begin();
711 iter != guard_loads.end();
712 ++iter)
713 TurnGuardLoadIntoZero(*iter, M);
714
715 for (iter = guard_stores.begin();
716 iter != guard_stores.end();
717 ++iter)
718 ExciseGuardStore(*iter);
719
720 return true;
721}
722
Sean Callananbafd6852010-07-14 23:40:29 +0000723// UnfoldConstant operates on a constant [C] which has just been replaced with a value
724// [new_value]. We assume that new_value has been properly placed early in the function,
725// most likely somewhere in front of the first instruction in the entry basic block
726// [first_entry_instruction].
727//
728// UnfoldConstant reads through the uses of C and replaces C in those uses with new_value.
729// Where those uses are constants, the function generates new instructions to compute the
730// result of the new, non-constant expression and places them before first_entry_instruction.
731// These instructions replace the constant uses, so UnfoldConstant calls itself recursively
732// for those.
733
734static bool
Sean Callanan02fbafa2010-07-27 21:39:39 +0000735UnfoldConstant(Constant *C, Value *new_value, Instruction *first_entry_instruction)
Sean Callananbafd6852010-07-14 23:40:29 +0000736{
737 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
738
739 Value::use_iterator ui;
740
Sean Callanana48fe162010-08-11 03:57:18 +0000741 SmallVector<User*, 16> users;
742
743 // We do this because the use list might change, invalidating our iterator.
744 // Much better to keep a work list ourselves.
Sean Callananbafd6852010-07-14 23:40:29 +0000745 for (ui = C->use_begin();
746 ui != C->use_end();
747 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +0000748 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +0000749
Sean Callanana48fe162010-08-11 03:57:18 +0000750 for (int i = 0;
751 i < users.size();
752 ++i)
753 {
754 User *user = users[i];
755
Sean Callananbafd6852010-07-14 23:40:29 +0000756 if (Constant *constant = dyn_cast<Constant>(user))
757 {
758 // synthesize a new non-constant equivalent of the constant
759
760 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
761 {
762 switch (constant_expr->getOpcode())
763 {
764 default:
765 if (log)
766 log->Printf("Unhandled constant expression type: %s", PrintValue(constant_expr).c_str());
767 return false;
768 case Instruction::BitCast:
769 {
770 // UnaryExpr
771 // OperandList[0] is value
772
773 Value *s = constant_expr->getOperand(0);
774
775 if (s == C)
776 s = new_value;
777
778 BitCastInst *bit_cast(new BitCastInst(s, C->getType(), "", first_entry_instruction));
779
780 UnfoldConstant(constant_expr, bit_cast, first_entry_instruction);
781 }
782 break;
783 case Instruction::GetElementPtr:
784 {
785 // GetElementPtrConstantExpr
786 // OperandList[0] is base
787 // OperandList[1]... are indices
788
789 Value *ptr = constant_expr->getOperand(0);
790
791 if (ptr == C)
792 ptr = new_value;
793
794 SmallVector<Value*, 16> indices;
795
796 unsigned operand_index;
797 unsigned num_operands = constant_expr->getNumOperands();
798
799 for (operand_index = 1;
800 operand_index < num_operands;
801 ++operand_index)
802 {
803 Value *operand = constant_expr->getOperand(operand_index);
804
805 if (operand == C)
806 operand = new_value;
807
808 indices.push_back(operand);
809 }
810
811 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_instruction));
812
813 UnfoldConstant(constant_expr, get_element_ptr, first_entry_instruction);
814 }
815 break;
816 }
817 }
818 else
819 {
820 if (log)
821 log->Printf("Unhandled constant type: %s", PrintValue(constant).c_str());
822 return false;
823 }
824 }
825 else
826 {
827 // simple fall-through case for non-constants
828 user->replaceUsesOfWith(C, new_value);
829 }
830 }
831
832 return true;
833}
834
Sean Callanan8bce6652010-07-13 21:41:46 +0000835bool
Sean Callananf5857a02010-07-31 01:32:05 +0000836IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +0000837{
838 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
839
840 m_decl_map->DoStructLayout();
841
842 if (log)
843 log->Printf("Element arrangement:");
844
845 uint32_t num_elements;
846 uint32_t element_index;
847
848 size_t size;
849 off_t alignment;
850
851 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
852 return false;
853
Sean Callananf5857a02010-07-31 01:32:05 +0000854 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +0000855
Sean Callananf5857a02010-07-31 01:32:05 +0000856 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +0000857 return false;
858
Sean Callanan02fbafa2010-07-27 21:39:39 +0000859 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +0000860
861 if (!argument->getName().equals("___clang_arg"))
862 return false;
863
864 if (log)
865 log->Printf("Arg: %s", PrintValue(argument).c_str());
866
Sean Callananf5857a02010-07-31 01:32:05 +0000867 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan02fbafa2010-07-27 21:39:39 +0000868 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +0000869
870 if (!first_entry_instruction)
871 return false;
872
873 LLVMContext &context(M.getContext());
874 const IntegerType *offset_type(Type::getInt32Ty(context));
875
876 if (!offset_type)
877 return false;
878
879 for (element_index = 0; element_index < num_elements; ++element_index)
880 {
881 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000882 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +0000883 off_t offset;
884
885 if (!m_decl_map->GetStructElement (decl, value, offset, element_index))
886 return false;
887
888 if (log)
889 log->Printf(" %s (%s) placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +0000890 value->getName().str().c_str(),
Sean Callanan8bce6652010-07-13 21:41:46 +0000891 PrintValue(value, true).c_str(),
892 offset);
893
894 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
895 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", first_entry_instruction);
896 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", first_entry_instruction);
897
Sean Callananbafd6852010-07-14 23:40:29 +0000898 if (Constant *constant = dyn_cast<Constant>(value))
899 UnfoldConstant(constant, bit_cast, first_entry_instruction);
900 else
901 value->replaceAllUsesWith(bit_cast);
Sean Callanan8bce6652010-07-13 21:41:46 +0000902 }
903
904 if (log)
905 log->Printf("Total structure [align %d, size %d]", alignment, size);
906
907 return true;
908}
909
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000910bool
911IRForTarget::runOnModule(Module &M)
912{
913 lldb_private::Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
914
Sean Callanan02fbafa2010-07-27 21:39:39 +0000915 Function* function = M.getFunction(StringRef("___clang_expr"));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000916
917 if (!function)
918 {
919 if (log)
920 log->Printf("Couldn't find ___clang_expr() in the module");
921
922 return false;
923 }
924
Sean Callanan02fbafa2010-07-27 21:39:39 +0000925 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000926
Sean Callanan82b74c82010-08-12 01:56:52 +0000927 ////////////////////////////////////////////////////////////
928 // Replace __clang_expr_result with a persistent variable
929 //
930
931 if (!createResultVariable(M, *function))
932 return false;
933
Sean Callananf5857a02010-07-31 01:32:05 +0000934 //////////////////////////////////
935 // Run basic-block level passes
936 //
937
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000938 for (bbi = function->begin();
939 bbi != function->end();
940 ++bbi)
941 {
Sean Callanana48fe162010-08-11 03:57:18 +0000942 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +0000943 return false;
944
Sean Callanana48fe162010-08-11 03:57:18 +0000945 if (!rewriteObjCSelectors(M, *bbi))
946 return false;
947
Sean Callananf5857a02010-07-31 01:32:05 +0000948 if (!resolveExternals(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +0000949 return false;
Sean Callanan45839272010-07-24 01:37:44 +0000950
951 if (!removeGuards(M, *bbi))
952 return false;
Sean Callanan8bce6652010-07-13 21:41:46 +0000953 }
954
Sean Callanan8bce6652010-07-13 21:41:46 +0000955 if (log)
956 {
Sean Callanan321fe9e2010-07-28 01:00:59 +0000957 std::string s;
958 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +0000959
Sean Callanan321fe9e2010-07-28 01:00:59 +0000960 M.print(oss, NULL);
961
962 oss.flush();
963
964 log->Printf("Module after preparing for execution: \n%s", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000965 }
966
Sean Callanana48fe162010-08-11 03:57:18 +0000967 ///////////////////////////////
968 // Run function-level passes
969 //
970
971 if (!replaceVariables(M, *function))
972 return false;
973
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000974 return true;
975}
976
977void
978IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +0000979 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000980{
981}
982
983PassManagerType
984IRForTarget::getPotentialPassManagerType() const
985{
986 return PMT_ModulePassManager;
987}