blob: bd121d57bb7401e5ff6707ac86df610a4e0ffd0d [file] [log] [blame]
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001//===-- IRForTarget.cpp -------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Expression/IRForTarget.h"
11
12#include "llvm/Support/raw_ostream.h"
13#include "llvm/InstrTypes.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000014#include "llvm/Instructions.h"
Sean Callanan3cb1fd82010-09-28 23:55:00 +000015#include "llvm/Intrinsics.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000016#include "llvm/Module.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000017#include "llvm/Target/TargetData.h"
Sean Callanan82b74c82010-08-12 01:56:52 +000018#include "llvm/ValueSymbolTable.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000019
20#include "clang/AST/ASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000021
Greg Clayton8de27c72010-10-15 22:48:33 +000022#include "lldb/Core/ConstString.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000023#include "lldb/Core/dwarf.h"
24#include "lldb/Core/Log.h"
25#include "lldb/Core/Scalar.h"
26#include "lldb/Core/StreamString.h"
27#include "lldb/Expression/ClangExpressionDeclMap.h"
28
29#include <map>
30
31using namespace llvm;
32
Sean Callanan3351dac2010-08-18 18:50:51 +000033static char ID;
34
35IRForTarget::IRForTarget(lldb_private::ClangExpressionDeclMap *decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +000036 bool resolve_vars,
Sean Callanan65dafa82010-08-27 01:01:44 +000037 const char *func_name) :
Sean Callanan47a5c4c2010-09-23 03:01:22 +000038 ModulePass(ID),
Sean Callanan8bce6652010-07-13 21:41:46 +000039 m_decl_map(decl_map),
Sean Callanan65dafa82010-08-27 01:01:44 +000040 m_sel_registerName(NULL),
Sean Callanane8a59a82010-09-13 21:34:21 +000041 m_func_name(func_name),
42 m_resolve_vars(resolve_vars)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000043{
44}
45
Sean Callanan771131d2010-09-30 21:18:25 +000046/* Handy utility functions used at several places in the code */
Sean Callanana48fe162010-08-11 03:57:18 +000047
48static std::string
Sean Callanan771131d2010-09-30 21:18:25 +000049PrintValue(const Value *V, bool truncate = false)
Sean Callanana48fe162010-08-11 03:57:18 +000050{
51 std::string s;
52 raw_string_ostream rso(s);
53 V->print(rso);
54 rso.flush();
55 if (truncate)
56 s.resize(s.length() - 1);
57 return s;
58}
59
Sean Callanan771131d2010-09-30 21:18:25 +000060static std::string
61PrintType(const Type *T, bool truncate = false)
62{
63 std::string s;
64 raw_string_ostream rso(s);
65 T->print(rso);
66 rso.flush();
67 if (truncate)
68 s.resize(s.length() - 1);
69 return s;
70}
71
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000072IRForTarget::~IRForTarget()
73{
74}
75
Sean Callanan82b74c82010-08-12 01:56:52 +000076bool
Greg Clayton8de27c72010-10-15 22:48:33 +000077IRForTarget::createResultVariable (llvm::Module &llvm_module, llvm::Function &llvm_function)
Sean Callanan82b74c82010-08-12 01:56:52 +000078{
Greg Claytone005f2c2010-11-06 01:53:30 +000079 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan82b74c82010-08-12 01:56:52 +000080
Sean Callanane8a59a82010-09-13 21:34:21 +000081 if (!m_resolve_vars)
82 return true;
83
84 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000085
Greg Clayton8de27c72010-10-15 22:48:33 +000086 ValueSymbolTable& value_symbol_table = llvm_module.getValueSymbolTable();
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000087
88 const char *result_name = NULL;
89
90 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
91 vi != ve;
92 ++vi)
93 {
Greg Clayton8de27c72010-10-15 22:48:33 +000094 if (strstr(vi->first(), "$__lldb_expr_result") &&
Sean Callananc04743d2010-09-28 21:13:03 +000095 !strstr(vi->first(), "GV"))
96 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000097 result_name = vi->first();
Sean Callananc04743d2010-09-28 21:13:03 +000098 break;
99 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000100 }
101
102 if (!result_name)
103 {
104 if (log)
105 log->PutCString("Couldn't find result variable");
106
107 return true;
108 }
109
Sean Callananc04743d2010-09-28 21:13:03 +0000110 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000111 log->Printf("Result name: \"%s\"", result_name);
Sean Callananc04743d2010-09-28 21:13:03 +0000112
Greg Clayton8de27c72010-10-15 22:48:33 +0000113 Value *result_value = llvm_module.getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000114
115 if (!result_value)
116 {
117 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000118 log->PutCString("Result variable had no data");
Sean Callanane8a59a82010-09-13 21:34:21 +0000119
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000120 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000121 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000122
Sean Callanan82b74c82010-08-12 01:56:52 +0000123 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000124 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000125
126 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
127
128 if (!result_global)
129 {
130 if (log)
131 log->PutCString("Result variable isn't a GlobalVariable");
132 return false;
133 }
134
135 // Find the metadata and follow it to the VarDecl
136
Greg Clayton8de27c72010-10-15 22:48:33 +0000137 NamedMDNode *named_metadata = llvm_module.getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000138
139 if (!named_metadata)
140 {
141 if (log)
142 log->PutCString("No global metadata");
143
144 return false;
145 }
146
147 unsigned num_nodes = named_metadata->getNumOperands();
148 unsigned node_index;
149
150 MDNode *metadata_node = NULL;
151
152 for (node_index = 0;
153 node_index < num_nodes;
154 ++node_index)
155 {
156 metadata_node = named_metadata->getOperand(node_index);
157
158 if (metadata_node->getNumOperands() != 2)
159 continue;
160
161 if (metadata_node->getOperand(0) == result_global)
162 break;
163 }
164
165 if (!metadata_node)
166 {
167 if (log)
168 log->PutCString("Couldn't find result metadata");
169 return false;
170 }
171
172 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
173
Greg Claytonb5037af2010-11-15 01:47:11 +0000174 lldb::addr_t result_decl_intptr = constant_int->getZExtValue();
Sean Callanan82b74c82010-08-12 01:56:52 +0000175
176 clang::VarDecl *result_decl = reinterpret_cast<clang::VarDecl *>(result_decl_intptr);
177
178 // Get the next available result name from m_decl_map and create the persistent
179 // variable for it
180
181 lldb_private::TypeFromParser result_decl_type (result_decl->getType().getAsOpaquePtr(),
182 &result_decl->getASTContext());
Greg Clayton8de27c72010-10-15 22:48:33 +0000183
184 lldb_private::ConstString new_result_name (m_decl_map->GetPersistentResultName());
185 m_decl_map->AddPersistentVariable(result_decl, new_result_name, result_decl_type);
Sean Callanan82b74c82010-08-12 01:56:52 +0000186
187 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000188 log->Printf("Creating a new result global: \"%s\"", new_result_name.GetCString());
Sean Callanan82b74c82010-08-12 01:56:52 +0000189
190 // Construct a new result global and set up its metadata
191
Greg Clayton8de27c72010-10-15 22:48:33 +0000192 GlobalVariable *new_result_global = new GlobalVariable(llvm_module,
Sean Callanan82b74c82010-08-12 01:56:52 +0000193 result_global->getType()->getElementType(),
194 false, /* not constant */
195 GlobalValue::ExternalLinkage,
196 NULL, /* no initializer */
Greg Clayton8de27c72010-10-15 22:48:33 +0000197 new_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000198
199 // It's too late in compilation to create a new VarDecl for this, but we don't
200 // need to. We point the metadata at the old VarDecl. This creates an odd
201 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000202 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000203 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
204 // fixed up.
205
206 ConstantInt *new_constant_int = ConstantInt::get(constant_int->getType(),
207 result_decl_intptr,
208 false);
209
210 llvm::Value* values[2];
211 values[0] = new_result_global;
212 values[1] = new_constant_int;
213
Greg Clayton8de27c72010-10-15 22:48:33 +0000214 MDNode *persistent_global_md = MDNode::get(llvm_module.getContext(), values, 2);
Sean Callanan82b74c82010-08-12 01:56:52 +0000215 named_metadata->addOperand(persistent_global_md);
216
217 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000218 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000219 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000220 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000221
222 if (result_global->hasNUses(0))
223 {
224 // We need to synthesize a store for this variable, because otherwise
225 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000226
Greg Clayton8de27c72010-10-15 22:48:33 +0000227 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000228 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
229
230 if (!first_entry_instruction)
231 return false;
232
233 if (!result_global->hasInitializer())
234 {
235 if (log)
236 log->Printf("Couldn't find initializer for unused variable");
237 return false;
238 }
239
240 Constant *initializer = result_global->getInitializer();
241
242 StoreInst *synthesized_store = new StoreInst::StoreInst(initializer,
243 new_result_global,
244 first_entry_instruction);
245
246 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000247 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000248 }
249 else
250 {
251 result_global->replaceAllUsesWith(new_result_global);
252 }
253
Sean Callanan82b74c82010-08-12 01:56:52 +0000254 result_global->eraseFromParent();
255
256 return true;
257}
258
Sean Callananf5857a02010-07-31 01:32:05 +0000259static bool isObjCSelectorRef(Value *V)
260{
261 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
262
263 if (!GV || !GV->hasName() || !GV->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
264 return false;
265
266 return true;
267}
268
269bool
270IRForTarget::RewriteObjCSelector(Instruction* selector_load,
271 Module &M)
272{
Greg Claytone005f2c2010-11-06 01:53:30 +0000273 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +0000274
275 LoadInst *load = dyn_cast<LoadInst>(selector_load);
276
277 if (!load)
278 return false;
279
280 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
281 //
282 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
283 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
284 //
285 // where %obj is the object pointer and %tmp is the selector.
286 //
287 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_METH_VAR_NAME_".
288 // @"\01L_OBJC_METH_VAR_NAME_" contains the string.
289
290 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
291
292 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
293
294 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
295 return false;
296
297 Constant *osr_initializer = _objc_selector_references_->getInitializer();
298
299 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
300
301 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
302 return false;
303
304 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
305
306 if (!osr_initializer_base)
307 return false;
308
309 // Find the string's initializer (a ConstantArray) and get the string from it
310
311 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
312
313 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
314 return false;
315
316 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
317
318 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
319
320 if (!omvn_initializer_array->isString())
321 return false;
322
323 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
324
325 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000326 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +0000327
328 // Construct a call to sel_registerName
329
330 if (!m_sel_registerName)
331 {
Greg Claytonb5037af2010-11-15 01:47:11 +0000332 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +0000333
Greg Clayton8de27c72010-10-15 22:48:33 +0000334 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +0000335 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +0000336 return false;
337
Sean Callananc2c6f772010-10-26 00:31:56 +0000338 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000339 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +0000340
Sean Callananf5857a02010-07-31 01:32:05 +0000341 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
342
343 // The below code would be "more correct," but in actuality what's required is uint8_t*
344 //Type *sel_type = StructType::get(M.getContext());
345 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
346 const Type *sel_ptr_type = Type::getInt8PtrTy(M.getContext());
347
348 std::vector <const Type *> srN_arg_types;
349 srN_arg_types.push_back(Type::getInt8PtrTy(M.getContext()));
350 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
351
352 // Build the constant containing the pointer to the function
353 const IntegerType *intptr_ty = Type::getIntNTy(M.getContext(),
354 (M.getPointerSize() == Module::Pointer64) ? 64 : 32);
355 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +0000356 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000357 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
358 }
359
360 SmallVector <Value*, 1> srN_arguments;
361
362 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(M.getContext()));
363
364 srN_arguments.push_back(omvn_pointer);
365
366 CallInst *srN_call = CallInst::Create(m_sel_registerName,
367 srN_arguments.begin(),
368 srN_arguments.end(),
369 "srN",
370 selector_load);
371
372 // Replace the load with the call in all users
373
374 selector_load->replaceAllUsesWith(srN_call);
375
376 selector_load->eraseFromParent();
377
378 return true;
379}
380
381bool
382IRForTarget::rewriteObjCSelectors(Module &M,
383 BasicBlock &BB)
384{
Greg Claytone005f2c2010-11-06 01:53:30 +0000385 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +0000386
387 BasicBlock::iterator ii;
388
389 typedef SmallVector <Instruction*, 2> InstrList;
390 typedef InstrList::iterator InstrIterator;
391
392 InstrList selector_loads;
393
394 for (ii = BB.begin();
395 ii != BB.end();
396 ++ii)
397 {
398 Instruction &inst = *ii;
399
400 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
401 if (isObjCSelectorRef(load->getPointerOperand()))
402 selector_loads.push_back(&inst);
403 }
404
405 InstrIterator iter;
406
407 for (iter = selector_loads.begin();
408 iter != selector_loads.end();
409 ++iter)
410 {
411 if (!RewriteObjCSelector(*iter, M))
412 {
413 if(log)
414 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
415 return false;
416 }
417 }
418
419 return true;
420}
421
Sean Callanana48fe162010-08-11 03:57:18 +0000422bool
423IRForTarget::RewritePersistentAlloc(llvm::Instruction *persistent_alloc,
Greg Clayton8de27c72010-10-15 22:48:33 +0000424 llvm::Module &llvm_module)
Sean Callanana48fe162010-08-11 03:57:18 +0000425{
426 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
427
428 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
429
430 if (!alloc_md || !alloc_md->getNumOperands())
431 return false;
432
433 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
434
435 if (!constant_int)
436 return false;
437
438 // We attempt to register this as a new persistent variable with the DeclMap.
439
440 uintptr_t ptr = constant_int->getZExtValue();
441
Sean Callanan82b74c82010-08-12 01:56:52 +0000442 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +0000443
Sean Callanan82b74c82010-08-12 01:56:52 +0000444 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
445 &decl->getASTContext());
446
Greg Clayton8de27c72010-10-15 22:48:33 +0000447 StringRef decl_name (decl->getName());
448 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
449 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type))
Sean Callanana48fe162010-08-11 03:57:18 +0000450 return false;
451
Greg Clayton8de27c72010-10-15 22:48:33 +0000452 GlobalVariable *persistent_global = new GlobalVariable(llvm_module,
Sean Callanana48fe162010-08-11 03:57:18 +0000453 alloc->getType()->getElementType(),
454 false, /* not constant */
455 GlobalValue::ExternalLinkage,
456 NULL, /* no initializer */
457 alloc->getName().str().c_str());
458
459 // What we're going to do here is make believe this was a regular old external
460 // variable. That means we need to make the metadata valid.
461
Greg Clayton8de27c72010-10-15 22:48:33 +0000462 NamedMDNode *named_metadata = llvm_module.getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +0000463
464 llvm::Value* values[2];
465 values[0] = persistent_global;
466 values[1] = constant_int;
467
Greg Clayton8de27c72010-10-15 22:48:33 +0000468 MDNode *persistent_global_md = MDNode::get(llvm_module.getContext(), values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +0000469 named_metadata->addOperand(persistent_global_md);
470
471 alloc->replaceAllUsesWith(persistent_global);
472 alloc->eraseFromParent();
473
474 return true;
475}
476
477bool
478IRForTarget::rewritePersistentAllocs(llvm::Module &M,
479 llvm::BasicBlock &BB)
480{
Sean Callanane8a59a82010-09-13 21:34:21 +0000481 if (!m_resolve_vars)
482 return true;
483
Greg Claytone005f2c2010-11-06 01:53:30 +0000484 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +0000485
486 BasicBlock::iterator ii;
487
488 typedef SmallVector <Instruction*, 2> InstrList;
489 typedef InstrList::iterator InstrIterator;
490
491 InstrList pvar_allocs;
492
493 for (ii = BB.begin();
494 ii != BB.end();
495 ++ii)
496 {
497 Instruction &inst = *ii;
498
499 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan03c997b2010-10-21 22:41:32 +0000500 if (alloc->getName().startswith("$") &&
501 !alloc->getName().startswith("$__lldb"))
Sean Callanana48fe162010-08-11 03:57:18 +0000502 pvar_allocs.push_back(alloc);
503 }
504
505 InstrIterator iter;
506
507 for (iter = pvar_allocs.begin();
508 iter != pvar_allocs.end();
509 ++iter)
510 {
511 if (!RewritePersistentAlloc(*iter, M))
512 {
513 if(log)
514 log->PutCString("Couldn't rewrite the creation of a persistent variable");
515 return false;
516 }
517 }
518
519 return true;
520}
521
Sean Callanan8bce6652010-07-13 21:41:46 +0000522static clang::NamedDecl *
Sean Callanan02fbafa2010-07-27 21:39:39 +0000523DeclForGlobalValue(Module &module,
524 GlobalValue *global_value)
Sean Callanan8bce6652010-07-13 21:41:46 +0000525{
526 NamedMDNode *named_metadata = module.getNamedMetadata("clang.global.decl.ptrs");
527
528 if (!named_metadata)
529 return NULL;
530
531 unsigned num_nodes = named_metadata->getNumOperands();
532 unsigned node_index;
533
534 for (node_index = 0;
535 node_index < num_nodes;
536 ++node_index)
537 {
538 MDNode *metadata_node = named_metadata->getOperand(node_index);
539
540 if (!metadata_node)
541 return NULL;
542
543 if (metadata_node->getNumOperands() != 2)
Sean Callanana48fe162010-08-11 03:57:18 +0000544 continue;
Sean Callanan8bce6652010-07-13 21:41:46 +0000545
546 if (metadata_node->getOperand(0) != global_value)
547 continue;
548
549 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
550
551 if (!constant_int)
552 return NULL;
553
554 uintptr_t ptr = constant_int->getZExtValue();
555
556 return reinterpret_cast<clang::NamedDecl *>(ptr);
557 }
558
559 return NULL;
560}
561
562bool
Greg Clayton8de27c72010-10-15 22:48:33 +0000563IRForTarget::MaybeHandleVariable
564(
565 Module &llvm_module,
Sean Callanan1d1b39c2010-11-08 00:31:32 +0000566 Value *llvm_value_ptr
Greg Clayton8de27c72010-10-15 22:48:33 +0000567)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000568{
Greg Claytone005f2c2010-11-06 01:53:30 +0000569 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +0000570
Greg Clayton8de27c72010-10-15 22:48:33 +0000571 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +0000572 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000573 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +0000574 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +0000575 default:
576 break;
577 case Instruction::GetElementPtr:
578 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +0000579 Value *s = constant_expr->getOperand(0);
Sean Callanan1d1b39c2010-11-08 00:31:32 +0000580 MaybeHandleVariable(llvm_module, s);
Sean Callananbc2928a2010-08-03 00:23:29 +0000581 }
582 }
Greg Clayton8de27c72010-10-15 22:48:33 +0000583 if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +0000584 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000585 clang::NamedDecl *named_decl = DeclForGlobalValue(llvm_module, global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000586
Sean Callananf5857a02010-07-31 01:32:05 +0000587 if (!named_decl)
588 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000589 if (isObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +0000590 return true;
591
592 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000593 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callananf5857a02010-07-31 01:32:05 +0000594 return false;
595 }
596
Greg Clayton8de27c72010-10-15 22:48:33 +0000597 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +0000598
Sean Callanan771131d2010-09-30 21:18:25 +0000599 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +0000600 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +0000601
602 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +0000603 {
Sean Callanan771131d2010-09-30 21:18:25 +0000604 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +0000605 ast_context = &value_decl->getASTContext();
606 }
Sean Callanan810f22d2010-07-16 00:09:46 +0000607 else
Sean Callananf328c9f2010-07-20 23:31:16 +0000608 {
Sean Callanan810f22d2010-07-16 00:09:46 +0000609 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +0000610 }
Sean Callanan771131d2010-09-30 21:18:25 +0000611
612 clang::QualType qual_type(clang::QualType::getFromOpaquePtr(opaque_type));
Sean Callananf328c9f2010-07-20 23:31:16 +0000613
Sean Callanan02fbafa2010-07-27 21:39:39 +0000614 const Type *value_type = global_variable->getType();
Sean Callanan771131d2010-09-30 21:18:25 +0000615
616 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
617 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
618
619 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000620 log->Printf("Type of \"%s\" is [clang \"%s\", lldb \"%s\"] [size %d, align %d]",
Sean Callanan771131d2010-09-30 21:18:25 +0000621 name.c_str(),
622 qual_type.getAsString().c_str(),
623 PrintType(value_type).c_str(),
624 value_size,
625 value_alignment);
626
Sean Callanan8bce6652010-07-13 21:41:46 +0000627
Sean Callanan8c127202010-08-23 23:09:38 +0000628 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +0000629 lldb_private::ConstString (name.c_str()),
630 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +0000631 value_size,
632 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +0000633 return false;
634 }
635
636 return true;
637}
638
639bool
Sean Callanandc27aba2010-10-05 22:26:43 +0000640IRForTarget::MaybeHandleCallArguments(Module &M,
641 CallInst *C)
642{
Greg Claytone005f2c2010-11-06 01:53:30 +0000643 // lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanandc27aba2010-10-05 22:26:43 +0000644
645 for (unsigned op_index = 0, num_ops = C->getNumArgOperands();
646 op_index < num_ops;
647 ++op_index)
Sean Callanan1d1b39c2010-11-08 00:31:32 +0000648 if (!MaybeHandleVariable(M, C->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanandc27aba2010-10-05 22:26:43 +0000649 return false;
650
651 return true;
652}
653
654bool
Greg Clayton8de27c72010-10-15 22:48:33 +0000655IRForTarget::MaybeHandleCall(Module &llvm_module,
656 CallInst *llvm_call_inst)
Sean Callananba992c52010-07-27 02:07:53 +0000657{
Greg Claytone005f2c2010-11-06 01:53:30 +0000658 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananba992c52010-07-27 02:07:53 +0000659
Greg Clayton8de27c72010-10-15 22:48:33 +0000660 Function *fun = llvm_call_inst->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +0000661
662 if (fun == NULL)
Sean Callanan65af7342010-09-08 20:04:08 +0000663 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000664 Value *val = llvm_call_inst->getCalledValue();
Sean Callanan65af7342010-09-08 20:04:08 +0000665
666 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(val);
667
668 if (const_expr && const_expr->getOpcode() == Instruction::BitCast)
669 {
670 fun = dyn_cast<Function>(const_expr->getOperand(0));
671
672 if (!fun)
673 return true;
674 }
675 else
676 {
677 return true;
678 }
679 }
Sean Callananba992c52010-07-27 02:07:53 +0000680
Greg Clayton8de27c72010-10-15 22:48:33 +0000681 lldb_private::ConstString str;
Sean Callananc04743d2010-09-28 21:13:03 +0000682
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000683 if (fun->isIntrinsic())
Sean Callananc04743d2010-09-28 21:13:03 +0000684 {
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000685 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
Sean Callananc04743d2010-09-28 21:13:03 +0000686
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000687 switch (intrinsic_id)
688 {
689 default:
690 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000691 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000692 return false;
693 case Intrinsic::memcpy:
Greg Clayton8de27c72010-10-15 22:48:33 +0000694 {
695 static lldb_private::ConstString g_memcpy_str ("memcpy");
696 str = g_memcpy_str;
697 }
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000698 break;
699 }
Sean Callananc04743d2010-09-28 21:13:03 +0000700
Greg Clayton8de27c72010-10-15 22:48:33 +0000701 if (log && str)
Greg Claytonb5037af2010-11-15 01:47:11 +0000702 log->Printf("Resolved intrinsic name \"%s\"", str.GetCString());
Sean Callanan3cb1fd82010-09-28 23:55:00 +0000703 }
704 else
705 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000706 str.SetCStringWithLength (fun->getName().data(), fun->getName().size());
Sean Callananc04743d2010-09-28 21:13:03 +0000707 }
708
Greg Clayton8de27c72010-10-15 22:48:33 +0000709 clang::NamedDecl *fun_decl = DeclForGlobalValue (llvm_module, fun);
Greg Claytonb5037af2010-11-15 01:47:11 +0000710 lldb::addr_t fun_addr = LLDB_INVALID_ADDRESS;
Sean Callananf5857a02010-07-31 01:32:05 +0000711 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +0000712
Sean Callananf5857a02010-07-31 01:32:05 +0000713 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +0000714 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000715 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_value_ptr, fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +0000716 {
Sean Callanan92aa6662010-09-07 21:49:41 +0000717 fun_value_ptr = NULL;
718
Greg Clayton8de27c72010-10-15 22:48:33 +0000719 if (!m_decl_map->GetFunctionAddress (str, fun_addr))
Sean Callanan92aa6662010-09-07 21:49:41 +0000720 {
721 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000722 log->Printf("Function \"%s\" had no address", str.GetCString());
Sean Callanan92aa6662010-09-07 21:49:41 +0000723
724 return false;
725 }
Sean Callananf5857a02010-07-31 01:32:05 +0000726 }
727 }
728 else
729 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000730 if (!m_decl_map->GetFunctionAddress (str, fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +0000731 {
732 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000733 log->Printf ("Metadataless function \"%s\" had no address", str.GetCString());
Sean Callananf5857a02010-07-31 01:32:05 +0000734 }
Sean Callananba992c52010-07-27 02:07:53 +0000735 }
736
737 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000738 log->Printf("Found \"%s\" at 0x%llx", str.GetCString(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +0000739
Sean Callananf5857a02010-07-31 01:32:05 +0000740 Value *fun_addr_ptr;
741
742 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +0000743 {
Greg Clayton8de27c72010-10-15 22:48:33 +0000744 const IntegerType *intptr_ty = Type::getIntNTy(llvm_module.getContext(),
745 (llvm_module.getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan92aa6662010-09-07 21:49:41 +0000746 const FunctionType *fun_ty = fun->getFunctionType();
Sean Callanan02fbafa2010-07-27 21:39:39 +0000747 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
748 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +0000749 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
750
751 if (fun_value_ptr)
752 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000753 }
Sean Callananf5857a02010-07-31 01:32:05 +0000754
755 if (fun_value_ptr)
756 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +0000757
Greg Clayton8de27c72010-10-15 22:48:33 +0000758 llvm_call_inst->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +0000759
Greg Clayton8de27c72010-10-15 22:48:33 +0000760 ConstantArray *func_name = (ConstantArray*)ConstantArray::get(llvm_module.getContext(), str.GetCString());
Sean Callanane8a59a82010-09-13 21:34:21 +0000761
762 Value *values[1];
763 values[0] = func_name;
Greg Clayton8de27c72010-10-15 22:48:33 +0000764 MDNode *func_metadata = MDNode::get(llvm_module.getContext(), values, 1);
Sean Callanane8a59a82010-09-13 21:34:21 +0000765
Greg Clayton8de27c72010-10-15 22:48:33 +0000766 llvm_call_inst->setMetadata("lldb.call.realName", func_metadata);
Sean Callanane8a59a82010-09-13 21:34:21 +0000767
768 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000769 log->Printf("Set metadata for %p [%d, \"%s\"]", llvm_call_inst, func_name->isString(), func_name->getAsString().c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000770
Sean Callananba992c52010-07-27 02:07:53 +0000771 return true;
772}
773
774bool
Sean Callanan1d1b39c2010-11-08 00:31:32 +0000775IRForTarget::resolveCalls(Module &M, BasicBlock &BB)
Sean Callanan8bce6652010-07-13 21:41:46 +0000776{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000777 /////////////////////////////////////////////////////////////////////////
778 // Prepare the current basic block for execution in the remote process
779 //
780
Sean Callanan02fbafa2010-07-27 21:39:39 +0000781 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +0000782
783 for (ii = BB.begin();
784 ii != BB.end();
785 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000786 {
Sean Callanan8bce6652010-07-13 21:41:46 +0000787 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000788
Sean Callanan1d1b39c2010-11-08 00:31:32 +0000789 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +0000790
Sean Callanan1d1b39c2010-11-08 00:31:32 +0000791 if (call && !MaybeHandleCall(M, call))
792 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000793 }
794
795 return true;
796}
797
Sean Callanan1d1b39c2010-11-08 00:31:32 +0000798bool
799IRForTarget::resolveExternals(Module &M,
800 Function &F)
801{
802 for (Module::global_iterator global = M.global_begin(), end = M.global_end();
803 global != end;
804 ++global)
805 {
806 if ((*global).hasExternalLinkage() &&
807 !MaybeHandleVariable (M, global))
808 return false;
809 }
810
811 return true;
812}
813
Sean Callanan02fbafa2010-07-27 21:39:39 +0000814static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +0000815{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000816 Constant *C;
Sean Callanan45839272010-07-24 01:37:44 +0000817
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000818 if (!(C = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +0000819 return false;
820
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000821 ConstantExpr *CE;
822
823 if ((CE = dyn_cast<ConstantExpr>(V)))
824 {
825 if (CE->getOpcode() != Instruction::BitCast)
826 return false;
827
828 C = CE->getOperand(0);
829 }
830
831 GlobalVariable *GV = dyn_cast<GlobalVariable>(C);
Sean Callanan45839272010-07-24 01:37:44 +0000832
833 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
834 return false;
835
836 return true;
837}
838
839static void TurnGuardLoadIntoZero(Instruction* guard_load, Module &M)
840{
841 Constant* zero(ConstantInt::get(Type::getInt8Ty(M.getContext()), 0, true));
842
843 Value::use_iterator ui;
844
845 for (ui = guard_load->use_begin();
846 ui != guard_load->use_end();
847 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +0000848 {
Greg Clayton6e713402010-07-30 20:30:44 +0000849 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +0000850 {
851 // do nothing for the moment
852 }
853 else
854 {
855 ui->replaceUsesOfWith(guard_load, zero);
856 }
857 }
Sean Callanan45839272010-07-24 01:37:44 +0000858
859 guard_load->eraseFromParent();
860}
861
862static void ExciseGuardStore(Instruction* guard_store)
863{
864 guard_store->eraseFromParent();
865}
866
867bool
868IRForTarget::removeGuards(Module &M, BasicBlock &BB)
869{
870 ///////////////////////////////////////////////////////
871 // Eliminate any reference to guard variables found.
872 //
873
Sean Callanan02fbafa2010-07-27 21:39:39 +0000874 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +0000875
Sean Callanan02fbafa2010-07-27 21:39:39 +0000876 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +0000877 typedef InstrList::iterator InstrIterator;
878
879 InstrList guard_loads;
880 InstrList guard_stores;
881
882 for (ii = BB.begin();
883 ii != BB.end();
884 ++ii)
885 {
886 Instruction &inst = *ii;
887
888 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
889 if (isGuardVariableRef(load->getPointerOperand()))
890 guard_loads.push_back(&inst);
891
892 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
893 if (isGuardVariableRef(store->getPointerOperand()))
894 guard_stores.push_back(&inst);
895 }
896
897 InstrIterator iter;
898
899 for (iter = guard_loads.begin();
900 iter != guard_loads.end();
901 ++iter)
902 TurnGuardLoadIntoZero(*iter, M);
903
904 for (iter = guard_stores.begin();
905 iter != guard_stores.end();
906 ++iter)
907 ExciseGuardStore(*iter);
908
909 return true;
910}
911
Sean Callananbafd6852010-07-14 23:40:29 +0000912// UnfoldConstant operates on a constant [C] which has just been replaced with a value
913// [new_value]. We assume that new_value has been properly placed early in the function,
914// most likely somewhere in front of the first instruction in the entry basic block
915// [first_entry_instruction].
916//
917// UnfoldConstant reads through the uses of C and replaces C in those uses with new_value.
918// Where those uses are constants, the function generates new instructions to compute the
919// result of the new, non-constant expression and places them before first_entry_instruction.
920// These instructions replace the constant uses, so UnfoldConstant calls itself recursively
921// for those.
922
923static bool
Sean Callanan02fbafa2010-07-27 21:39:39 +0000924UnfoldConstant(Constant *C, Value *new_value, Instruction *first_entry_instruction)
Sean Callananbafd6852010-07-14 23:40:29 +0000925{
Greg Claytone005f2c2010-11-06 01:53:30 +0000926 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +0000927
928 Value::use_iterator ui;
929
Sean Callanana48fe162010-08-11 03:57:18 +0000930 SmallVector<User*, 16> users;
931
932 // We do this because the use list might change, invalidating our iterator.
933 // Much better to keep a work list ourselves.
Sean Callananbafd6852010-07-14 23:40:29 +0000934 for (ui = C->use_begin();
935 ui != C->use_end();
936 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +0000937 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +0000938
Sean Callanana48fe162010-08-11 03:57:18 +0000939 for (int i = 0;
940 i < users.size();
941 ++i)
942 {
943 User *user = users[i];
944
Sean Callananbafd6852010-07-14 23:40:29 +0000945 if (Constant *constant = dyn_cast<Constant>(user))
946 {
947 // synthesize a new non-constant equivalent of the constant
948
949 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
950 {
951 switch (constant_expr->getOpcode())
952 {
953 default:
954 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000955 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +0000956 return false;
957 case Instruction::BitCast:
958 {
959 // UnaryExpr
960 // OperandList[0] is value
961
962 Value *s = constant_expr->getOperand(0);
963
964 if (s == C)
965 s = new_value;
966
967 BitCastInst *bit_cast(new BitCastInst(s, C->getType(), "", first_entry_instruction));
968
969 UnfoldConstant(constant_expr, bit_cast, first_entry_instruction);
970 }
971 break;
972 case Instruction::GetElementPtr:
973 {
974 // GetElementPtrConstantExpr
975 // OperandList[0] is base
976 // OperandList[1]... are indices
977
978 Value *ptr = constant_expr->getOperand(0);
979
980 if (ptr == C)
981 ptr = new_value;
982
983 SmallVector<Value*, 16> indices;
984
985 unsigned operand_index;
986 unsigned num_operands = constant_expr->getNumOperands();
987
988 for (operand_index = 1;
989 operand_index < num_operands;
990 ++operand_index)
991 {
992 Value *operand = constant_expr->getOperand(operand_index);
993
994 if (operand == C)
995 operand = new_value;
996
997 indices.push_back(operand);
998 }
999
1000 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices.begin(), indices.end(), "", first_entry_instruction));
1001
1002 UnfoldConstant(constant_expr, get_element_ptr, first_entry_instruction);
1003 }
1004 break;
1005 }
1006 }
1007 else
1008 {
1009 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001010 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00001011 return false;
1012 }
1013 }
1014 else
1015 {
1016 // simple fall-through case for non-constants
1017 user->replaceUsesOfWith(C, new_value);
1018 }
1019 }
1020
1021 return true;
1022}
1023
Sean Callanan8bce6652010-07-13 21:41:46 +00001024bool
Sean Callananf5857a02010-07-31 01:32:05 +00001025IRForTarget::replaceVariables(Module &M, Function &F)
Sean Callanan8bce6652010-07-13 21:41:46 +00001026{
Sean Callanane8a59a82010-09-13 21:34:21 +00001027 if (!m_resolve_vars)
1028 return true;
1029
Greg Claytone005f2c2010-11-06 01:53:30 +00001030 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00001031
1032 m_decl_map->DoStructLayout();
1033
1034 if (log)
1035 log->Printf("Element arrangement:");
1036
1037 uint32_t num_elements;
1038 uint32_t element_index;
1039
1040 size_t size;
1041 off_t alignment;
1042
1043 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
1044 return false;
1045
Sean Callananf5857a02010-07-31 01:32:05 +00001046 Function::arg_iterator iter(F.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00001047
Sean Callananf5857a02010-07-31 01:32:05 +00001048 if (iter == F.getArgumentList().end())
Sean Callanan8bce6652010-07-13 21:41:46 +00001049 return false;
1050
Sean Callanan02fbafa2010-07-27 21:39:39 +00001051 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00001052
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00001053 if (argument->getName().equals("this"))
1054 {
1055 ++iter;
1056
1057 if (iter == F.getArgumentList().end())
1058 return false;
1059
1060 argument = iter;
1061 }
1062
Greg Clayton8de27c72010-10-15 22:48:33 +00001063 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan8bce6652010-07-13 21:41:46 +00001064 return false;
1065
1066 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001067 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00001068
Sean Callananf5857a02010-07-31 01:32:05 +00001069 BasicBlock &entry_block(F.getEntryBlock());
Sean Callanan02fbafa2010-07-27 21:39:39 +00001070 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00001071
1072 if (!first_entry_instruction)
1073 return false;
1074
1075 LLVMContext &context(M.getContext());
1076 const IntegerType *offset_type(Type::getInt32Ty(context));
1077
1078 if (!offset_type)
1079 return false;
1080
1081 for (element_index = 0; element_index < num_elements; ++element_index)
1082 {
1083 const clang::NamedDecl *decl;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001084 Value *value;
Sean Callanan8bce6652010-07-13 21:41:46 +00001085 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00001086 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00001087
Sean Callanan45690fe2010-08-30 22:17:16 +00001088 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan8bce6652010-07-13 21:41:46 +00001089 return false;
1090
1091 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001092 log->Printf(" \"%s\" [\"%s\"] (\"%s\") placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +00001093 value->getName().str().c_str(),
Greg Clayton8de27c72010-10-15 22:48:33 +00001094 name.GetCString(),
Sean Callanan8bce6652010-07-13 21:41:46 +00001095 PrintValue(value, true).c_str(),
1096 offset);
1097
1098 ConstantInt *offset_int(ConstantInt::getSigned(offset_type, offset));
1099 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", first_entry_instruction);
1100 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", first_entry_instruction);
1101
Sean Callananbafd6852010-07-14 23:40:29 +00001102 if (Constant *constant = dyn_cast<Constant>(value))
1103 UnfoldConstant(constant, bit_cast, first_entry_instruction);
1104 else
1105 value->replaceAllUsesWith(bit_cast);
Sean Callananb51ee982010-11-02 23:51:17 +00001106
1107 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
1108 var->eraseFromParent();
Sean Callanan8bce6652010-07-13 21:41:46 +00001109 }
1110
1111 if (log)
1112 log->Printf("Total structure [align %d, size %d]", alignment, size);
1113
1114 return true;
1115}
1116
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001117bool
1118IRForTarget::runOnModule(Module &M)
1119{
Greg Claytone005f2c2010-11-06 01:53:30 +00001120 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001121
Sean Callanan65dafa82010-08-27 01:01:44 +00001122 Function* function = M.getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001123
1124 if (!function)
1125 {
1126 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001127 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001128
1129 return false;
1130 }
1131
Sean Callanan02fbafa2010-07-27 21:39:39 +00001132 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001133
Sean Callanan82b74c82010-08-12 01:56:52 +00001134 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00001135 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00001136 //
1137
1138 if (!createResultVariable(M, *function))
1139 return false;
1140
Sean Callananf5857a02010-07-31 01:32:05 +00001141 //////////////////////////////////
1142 // Run basic-block level passes
1143 //
1144
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001145 for (bbi = function->begin();
1146 bbi != function->end();
1147 ++bbi)
1148 {
Sean Callanan8c127202010-08-23 23:09:38 +00001149 if (!removeGuards(M, *bbi))
1150 return false;
1151
Sean Callanana48fe162010-08-11 03:57:18 +00001152 if (!rewritePersistentAllocs(M, *bbi))
Sean Callananf5857a02010-07-31 01:32:05 +00001153 return false;
1154
Sean Callanana48fe162010-08-11 03:57:18 +00001155 if (!rewriteObjCSelectors(M, *bbi))
1156 return false;
1157
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001158 if (!resolveCalls(M, *bbi))
Sean Callanan8bce6652010-07-13 21:41:46 +00001159 return false;
1160 }
1161
Sean Callanan771131d2010-09-30 21:18:25 +00001162 ///////////////////////////////
1163 // Run function-level passes
1164 //
1165
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001166 if (!resolveExternals(M, *function))
1167 return false;
1168
Sean Callanan771131d2010-09-30 21:18:25 +00001169 if (!replaceVariables(M, *function))
1170 return false;
1171
Sean Callanan8bce6652010-07-13 21:41:46 +00001172 if (log)
1173 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00001174 std::string s;
1175 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00001176
Sean Callanan321fe9e2010-07-28 01:00:59 +00001177 M.print(oss, NULL);
1178
1179 oss.flush();
1180
Greg Claytonb5037af2010-11-15 01:47:11 +00001181 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001182 }
1183
1184 return true;
1185}
1186
1187void
1188IRForTarget::assignPassManager(PMStack &PMS,
Sean Callanan8bce6652010-07-13 21:41:46 +00001189 PassManagerType T)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001190{
1191}
1192
1193PassManagerType
1194IRForTarget::getPotentialPassManagerType() const
1195{
1196 return PMT_ModulePassManager;
1197}