blob: ba8df1432464a6267db21589d55bce84f8b151fa [file] [log] [blame]
Sean Callanan47dc4572011-09-15 02:13:07 +00001//===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===//
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002//
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"
Sean Callanan2a8c3382011-04-14 02:01:31 +000013#include "llvm/Constants.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000014#include "llvm/InstrTypes.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000015#include "llvm/Instructions.h"
Sean Callanan3cb1fd82010-09-28 23:55:00 +000016#include "llvm/Intrinsics.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000017#include "llvm/Module.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000018#include "llvm/Target/TargetData.h"
Sean Callanan82b74c82010-08-12 01:56:52 +000019#include "llvm/ValueSymbolTable.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000020
21#include "clang/AST/ASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000022
Greg Clayton8de27c72010-10-15 22:48:33 +000023#include "lldb/Core/ConstString.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000024#include "lldb/Core/dwarf.h"
25#include "lldb/Core/Log.h"
26#include "lldb/Core/Scalar.h"
27#include "lldb/Core/StreamString.h"
28#include "lldb/Expression/ClangExpressionDeclMap.h"
Sean Callanan47dc4572011-09-15 02:13:07 +000029#include "lldb/Expression/IRInterpreter.h"
Sean Callananc0492742011-05-23 21:40:23 +000030#include "lldb/Host/Endian.h"
Sean Callanan696cf5f2011-05-07 01:06:41 +000031#include "lldb/Symbol/ClangASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000032
33#include <map>
34
35using namespace llvm;
36
Sean Callanan3351dac2010-08-18 18:50:51 +000037static char ID;
38
Sean Callananc0492742011-05-23 21:40:23 +000039IRForTarget::StaticDataAllocator::StaticDataAllocator()
40{
41}
42
43IRForTarget::StaticDataAllocator::~StaticDataAllocator()
44{
45}
46
Greg Clayton3c7feb42010-11-19 01:05:25 +000047IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
48 bool resolve_vars,
Sean Callanan47dc4572011-09-15 02:13:07 +000049 lldb_private::ExecutionPolicy execution_policy,
Sean Callanan696cf5f2011-05-07 01:06:41 +000050 lldb::ClangExpressionVariableSP &const_result,
Sean Callananc0492742011-05-23 21:40:23 +000051 StaticDataAllocator *data_allocator,
Sean Callanan97c924e2011-01-27 01:07:04 +000052 lldb_private::Stream *error_stream,
Greg Clayton3c7feb42010-11-19 01:05:25 +000053 const char *func_name) :
Sean Callanan47a5c4c2010-09-23 03:01:22 +000054 ModulePass(ID),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000055 m_resolve_vars(resolve_vars),
Sean Callanan47dc4572011-09-15 02:13:07 +000056 m_execution_policy(execution_policy),
57 m_interpret_success(false),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000058 m_func_name(func_name),
Sean Callananc0492742011-05-23 21:40:23 +000059 m_module(NULL),
Johnny Chen2bc9eb32011-07-19 19:48:13 +000060 m_decl_map(decl_map),
61 m_data_allocator(data_allocator),
Sean Callanan6ba533e2010-11-17 23:00:36 +000062 m_CFStringCreateWithBytes(NULL),
Sean Callanan65dafa82010-08-27 01:01:44 +000063 m_sel_registerName(NULL),
Johnny Chen2bc9eb32011-07-19 19:48:13 +000064 m_const_result(const_result),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000065 m_error_stream(error_stream),
Sean Callanan6a925532011-01-13 08:53:35 +000066 m_has_side_effects(false),
Sean Callanan696cf5f2011-05-07 01:06:41 +000067 m_result_store(NULL),
68 m_result_is_pointer(false),
Sean Callananc0492742011-05-23 21:40:23 +000069 m_reloc_placeholder(NULL)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000070{
71}
72
Sean Callanan771131d2010-09-30 21:18:25 +000073/* Handy utility functions used at several places in the code */
Sean Callanana48fe162010-08-11 03:57:18 +000074
75static std::string
Greg Clayton3c7feb42010-11-19 01:05:25 +000076PrintValue(const Value *value, bool truncate = false)
Sean Callanana48fe162010-08-11 03:57:18 +000077{
78 std::string s;
79 raw_string_ostream rso(s);
Greg Clayton3c7feb42010-11-19 01:05:25 +000080 value->print(rso);
Sean Callanana48fe162010-08-11 03:57:18 +000081 rso.flush();
82 if (truncate)
83 s.resize(s.length() - 1);
84 return s;
85}
86
Sean Callanan771131d2010-09-30 21:18:25 +000087static std::string
Greg Clayton3c7feb42010-11-19 01:05:25 +000088PrintType(const Type *type, bool truncate = false)
Sean Callanan771131d2010-09-30 21:18:25 +000089{
90 std::string s;
91 raw_string_ostream rso(s);
Greg Clayton3c7feb42010-11-19 01:05:25 +000092 type->print(rso);
Sean Callanan771131d2010-09-30 21:18:25 +000093 rso.flush();
94 if (truncate)
95 s.resize(s.length() - 1);
96 return s;
97}
98
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000099IRForTarget::~IRForTarget()
100{
101}
102
Sean Callananc0492742011-05-23 21:40:23 +0000103bool
104IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
105{
106 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
107
108 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
109
110 std::string name = llvm_function.getNameStr();
111
112 return true;
113}
114
Sean Callanan82b74c82010-08-12 01:56:52 +0000115bool
Sean Callananc0492742011-05-23 21:40:23 +0000116IRForTarget::HasSideEffects (llvm::Function &llvm_function)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000117{
118 llvm::Function::iterator bbi;
119 BasicBlock::iterator ii;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000120
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000121 for (bbi = llvm_function.begin();
122 bbi != llvm_function.end();
123 ++bbi)
124 {
125 BasicBlock &basic_block = *bbi;
126
127 for (ii = basic_block.begin();
128 ii != basic_block.end();
129 ++ii)
130 {
131 switch (ii->getOpcode())
132 {
133 default:
134 return true;
135 case Instruction::Store:
136 {
137 StoreInst *store_inst = dyn_cast<StoreInst>(ii);
138
139 Value *store_ptr = store_inst->getPointerOperand();
140
Sean Callanan696cf5f2011-05-07 01:06:41 +0000141 std::string ptr_name;
142
143 if (store_ptr->hasName())
144 ptr_name = store_ptr->getNameStr();
145
146 if (isa <AllocaInst> (store_ptr))
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000147 break;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000148
149 if (ptr_name.find("$__lldb_expr_result") != std::string::npos)
150 {
151 if (ptr_name.find("GV") == std::string::npos)
152 m_result_store = store_inst;
153 }
154 else
155 {
156 return true;
157 }
158
159 break;
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000160 }
161 case Instruction::Load:
162 case Instruction::Alloca:
163 case Instruction::GetElementPtr:
Sean Callanan696cf5f2011-05-07 01:06:41 +0000164 case Instruction::BitCast:
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000165 case Instruction::Ret:
Sean Callanan696cf5f2011-05-07 01:06:41 +0000166 case Instruction::ICmp:
167 case Instruction::Br:
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000168 break;
169 }
170 }
171 }
172
173 return false;
174}
175
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000176bool
177IRForTarget::GetFunctionAddress (llvm::Function *fun,
178 uint64_t &fun_addr,
179 lldb_private::ConstString &name,
180 Constant **&value_ptr)
181{
182 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
183
184 fun_addr = LLDB_INVALID_ADDRESS;
185 name.Clear();
186 value_ptr = NULL;
187
188 if (fun->isIntrinsic())
189 {
190 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
191
192 switch (intrinsic_id)
193 {
194 default:
195 if (log)
196 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
197
198 if (m_error_stream)
199 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
200
201 return false;
202 case Intrinsic::memcpy:
203 {
204 static lldb_private::ConstString g_memcpy_str ("memcpy");
205 name = g_memcpy_str;
206 }
207 break;
Sean Callanan7befa302011-11-16 00:20:50 +0000208 case Intrinsic::memset:
209 {
210 static lldb_private::ConstString g_memset_str ("memset");
211 name = g_memset_str;
212 }
213 break;
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000214 }
215
216 if (log && name)
217 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
218 }
219 else
220 {
221 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
222 }
223
224 // Find the address of the function.
225
226 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000227
228 if (fun_decl)
229 {
Sean Callananc7ca4662011-10-25 18:36:40 +0000230 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000231 {
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000232 lldb_private::ConstString alternate_mangling_const_str;
233 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
234 if (!found_it)
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000235 {
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000236 // Check for an alternate mangling for "std::basic_string<char>"
237 // that is part of the itanium C++ name mangling scheme
238 const char *name_cstr = name.GetCString();
239 if (strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
240 {
241 std::string alternate_mangling("_ZNKSs");
242 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
243 alternate_mangling_const_str.SetCString(alternate_mangling.c_str());
244 found_it = m_decl_map->GetFunctionAddress (alternate_mangling_const_str, fun_addr);
245 }
246 }
247
248 if (!found_it)
249 {
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000250 if (log)
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000251 {
252 if (alternate_mangling_const_str)
253 log->Printf("Function \"%s\" (alternate name \"%s\") has no address", name.GetCString(), alternate_mangling_const_str.GetCString());
254 else
255 log->Printf("Function \"%s\" had no address", name.GetCString());
256 }
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000257
258 if (m_error_stream)
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000259 {
260 if (alternate_mangling_const_str)
261 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n", name.GetCString(), alternate_mangling_const_str.GetCString());
262 else
263 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n", name.GetCString());
264 }
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000265 return false;
266 }
267 }
268 }
269 else
270 {
271 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
272 {
273 if (log)
274 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
275
276 if (m_error_stream)
277 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
278
279 return false;
280 }
281 }
282
283 if (log)
284 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), fun_addr);
285
286 return true;
287}
288
289llvm::Constant *
290IRForTarget::BuildFunctionPointer (llvm::Type *type,
291 uint64_t ptr)
292{
293 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
294 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
295 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
296 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
297 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
298}
299
Sean Callanan715f6b02011-10-31 22:11:40 +0000300void
301IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
302 llvm::Value *function_ptr,
303 const char *name)
304{
305 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
306
307 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
308 i != e;
309 ++i)
310 {
311 Value *user = *i;
312
313 if (Instruction *user_inst = dyn_cast<Instruction>(user))
314 {
315 Constant *name_array = ConstantArray::get(context, StringRef(name));
316
317 ArrayRef<Value *> md_values(name_array);
318
319 MDNode *metadata = MDNode::get(context, md_values);
320
321 user_inst->setMetadata("lldb.call.realName", metadata);
322 }
323 else
324 {
325 RegisterFunctionMetadata (context, user, name);
326 }
327 }
328}
329
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000330bool
331IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module,
332 llvm::Function &llvm_function)
333{
334 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
335
336 for (llvm::Module::iterator fi = llvm_module.begin();
337 fi != llvm_module.end();
338 ++fi)
339 {
340 Function *fun = fi;
341
342 bool is_decl = fun->isDeclaration();
343
344 if (log)
345 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getNameStr().c_str());
346
347 if (!is_decl)
348 continue;
349
350 if (fun->hasNUses(0))
351 continue; // ignore
352
353 uint64_t addr = LLDB_INVALID_ADDRESS;
354 lldb_private::ConstString name;
355 Constant **value_ptr = NULL;
356
357 if (!GetFunctionAddress(fun,
358 addr,
359 name,
360 value_ptr))
361 return false; // GetFunctionAddress reports its own errors
362
363 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
364
Sean Callanan715f6b02011-10-31 22:11:40 +0000365 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
366
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000367 if (value_ptr)
368 *value_ptr = value;
369
370 fun->replaceAllUsesWith(value);
371 }
372
373 return true;
374}
375
Sean Callanan47dc4572011-09-15 02:13:07 +0000376
Sean Callanan696cf5f2011-05-07 01:06:41 +0000377clang::NamedDecl *
Sean Callanan47dc4572011-09-15 02:13:07 +0000378IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000379{
380 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
381
Sean Callanan47dc4572011-09-15 02:13:07 +0000382 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan696cf5f2011-05-07 01:06:41 +0000383
384 if (!named_metadata)
385 return NULL;
386
387 unsigned num_nodes = named_metadata->getNumOperands();
388 unsigned node_index;
389
390 for (node_index = 0;
391 node_index < num_nodes;
392 ++node_index)
393 {
394 MDNode *metadata_node = named_metadata->getOperand(node_index);
395
396 if (!metadata_node)
397 return NULL;
398
399 if (metadata_node->getNumOperands() != 2)
400 continue;
401
402 if (metadata_node->getOperand(0) != global_val)
403 continue;
404
405 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
406
407 if (!constant_int)
408 return NULL;
409
410 uintptr_t ptr = constant_int->getZExtValue();
411
412 return reinterpret_cast<clang::NamedDecl *>(ptr);
413 }
414
415 return NULL;
416}
417
Sean Callanan47dc4572011-09-15 02:13:07 +0000418clang::NamedDecl *
419IRForTarget::DeclForGlobal (GlobalValue *global_val)
420{
421 return DeclForGlobal(global_val, m_module);
422}
423
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000424void
425IRForTarget::MaybeSetConstantResult (llvm::Constant *initializer,
426 const lldb_private::ConstString &name,
427 lldb_private::TypeFromParser type)
428{
Sean Callanan696cf5f2011-05-07 01:06:41 +0000429 if (llvm::ConstantExpr *init_expr = dyn_cast<llvm::ConstantExpr>(initializer))
430 {
431 switch (init_expr->getOpcode())
432 {
433 default:
434 return;
435 case Instruction::IntToPtr:
436 MaybeSetConstantResult (init_expr->getOperand(0), name, type);
437 return;
438 }
439 }
440 else if (llvm::ConstantInt *init_int = dyn_cast<llvm::ConstantInt>(initializer))
441 {
442 m_const_result = m_decl_map->BuildIntegerVariable(name, type, init_int->getValue());
443 }
444}
445
446void
Sean Callananc0492742011-05-23 21:40:23 +0000447IRForTarget::MaybeSetCastResult (lldb_private::TypeFromParser type)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000448{
449 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
450
451 if (!m_result_store)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000452 return;
453
Sean Callanan696cf5f2011-05-07 01:06:41 +0000454 LoadInst *original_load = NULL;
455
456 for (llvm::Value *current_value = m_result_store->getValueOperand(), *next_value;
457 current_value != NULL;
458 current_value = next_value)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000459 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000460 CastInst *cast_inst = dyn_cast<CastInst>(current_value);
461 LoadInst *load_inst = dyn_cast<LoadInst>(current_value);
462
463 if (cast_inst)
464 {
465 next_value = cast_inst->getOperand(0);
466 }
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000467 else if (load_inst)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000468 {
469 if (isa<LoadInst>(load_inst->getPointerOperand()))
470 {
471 next_value = load_inst->getPointerOperand();
472 }
473 else
474 {
475 original_load = load_inst;
476 break;
477 }
478 }
479 else
480 {
481 return;
482 }
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000483 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000484
485 Value *loaded_value = original_load->getPointerOperand();
486 GlobalVariable *loaded_global = dyn_cast<GlobalVariable>(loaded_value);
487
488 if (!loaded_global)
489 return;
490
Sean Callananc0492742011-05-23 21:40:23 +0000491 clang::NamedDecl *loaded_decl = DeclForGlobal(loaded_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000492
493 if (!loaded_decl)
494 return;
495
496 clang::VarDecl *loaded_var = dyn_cast<clang::VarDecl>(loaded_decl);
497
498 if (!loaded_var)
499 return;
500
501 if (log)
502 {
503 lldb_private::StreamString type_desc_stream;
504 type.DumpTypeDescription(&type_desc_stream);
505
506 log->Printf("Type to cast variable to: \"%s\"", type_desc_stream.GetString().c_str());
507 }
508
509 m_const_result = m_decl_map->BuildCastVariable(m_result_name, loaded_var, type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000510}
511
512bool
Sean Callananc0492742011-05-23 21:40:23 +0000513IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanan82b74c82010-08-12 01:56:52 +0000514{
Greg Claytone005f2c2010-11-06 01:53:30 +0000515 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan82b74c82010-08-12 01:56:52 +0000516
Sean Callanane8a59a82010-09-13 21:34:21 +0000517 if (!m_resolve_vars)
518 return true;
519
520 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000521
Sean Callananc0492742011-05-23 21:40:23 +0000522 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000523
Sean Callanan9b6898f2011-07-30 02:42:06 +0000524 std::string result_name_str;
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000525 const char *result_name = NULL;
526
527 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
528 vi != ve;
529 ++vi)
530 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000531 result_name_str = vi->first().str();
532 const char *value_name = result_name_str.c_str();
533
534 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
535 !strstr(value_name, "GV"))
Sean Callanan6a925532011-01-13 08:53:35 +0000536 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000537 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000538 m_result_is_pointer = true;
539 break;
540 }
541
Sean Callanan9b6898f2011-07-30 02:42:06 +0000542 if (strstr(value_name, "$__lldb_expr_result") &&
543 !strstr(value_name, "GV"))
Sean Callananc04743d2010-09-28 21:13:03 +0000544 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000545 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000546 m_result_is_pointer = false;
Sean Callananc04743d2010-09-28 21:13:03 +0000547 break;
548 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000549 }
550
551 if (!result_name)
552 {
553 if (log)
554 log->PutCString("Couldn't find result variable");
555
556 return true;
557 }
558
Sean Callananc04743d2010-09-28 21:13:03 +0000559 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000560 log->Printf("Result name: \"%s\"", result_name);
Sean Callananc04743d2010-09-28 21:13:03 +0000561
Sean Callananc0492742011-05-23 21:40:23 +0000562 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000563
564 if (!result_value)
565 {
566 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000567 log->PutCString("Result variable had no data");
Sean Callanan6a925532011-01-13 08:53:35 +0000568
Sean Callanan97c924e2011-01-27 01:07:04 +0000569 if (m_error_stream)
570 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
571
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000572 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000573 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000574
Sean Callanan82b74c82010-08-12 01:56:52 +0000575 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000576 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000577
578 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
579
580 if (!result_global)
581 {
582 if (log)
583 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000584
585 if (m_error_stream)
586 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
587
Sean Callanan82b74c82010-08-12 01:56:52 +0000588 return false;
589 }
590
Sean Callananc0492742011-05-23 21:40:23 +0000591 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000592 if (!result_decl)
Sean Callanan82b74c82010-08-12 01:56:52 +0000593 {
594 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000595 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanan82b74c82010-08-12 01:56:52 +0000596
Sean Callanan97c924e2011-01-27 01:07:04 +0000597 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000598 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name);
Sean Callanan97c924e2011-01-27 01:07:04 +0000599
Sean Callanan82b74c82010-08-12 01:56:52 +0000600 return false;
601 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000602
Sean Callanan696cf5f2011-05-07 01:06:41 +0000603 if (log)
Sean Callanan82b74c82010-08-12 01:56:52 +0000604 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000605 std::string decl_desc_str;
606 raw_string_ostream decl_desc_stream(decl_desc_str);
607 result_decl->print(decl_desc_stream);
608 decl_desc_stream.flush();
Sean Callanan82b74c82010-08-12 01:56:52 +0000609
Sean Callanan696cf5f2011-05-07 01:06:41 +0000610 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000611 }
612
Sean Callanan696cf5f2011-05-07 01:06:41 +0000613 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
614 if (!result_var)
Sean Callanan82b74c82010-08-12 01:56:52 +0000615 {
616 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000617 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan97c924e2011-01-27 01:07:04 +0000618
619 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000620 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name);
Sean Callanan97c924e2011-01-27 01:07:04 +0000621
Sean Callanan82b74c82010-08-12 01:56:52 +0000622 return false;
623 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000624
Sean Callanan82b74c82010-08-12 01:56:52 +0000625 // Get the next available result name from m_decl_map and create the persistent
626 // variable for it
Sean Callanan47dc4572011-09-15 02:13:07 +0000627
Sean Callanan696cf5f2011-05-07 01:06:41 +0000628 // If the result is an Lvalue, it is emitted as a pointer; see
629 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan6a925532011-01-13 08:53:35 +0000630 if (m_result_is_pointer)
631 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000632 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanand5b3c352011-01-27 04:42:51 +0000633 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
634 const clang::PointerType *pointer_pointertype = dyn_cast<clang::PointerType>(pointer_type);
Sean Callanan6a925532011-01-13 08:53:35 +0000635
636 if (!pointer_pointertype)
637 {
638 if (log)
639 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan97c924e2011-01-27 01:07:04 +0000640
641 if (m_error_stream)
642 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
643
Sean Callanan6a925532011-01-13 08:53:35 +0000644 return false;
645 }
646
647 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
648
Sean Callanan47dc4572011-09-15 02:13:07 +0000649 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
Sean Callanan6a925532011-01-13 08:53:35 +0000650 &result_decl->getASTContext());
651 }
652 else
653 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000654 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan6a925532011-01-13 08:53:35 +0000655 &result_decl->getASTContext());
656 }
657
Sean Callanan696cf5f2011-05-07 01:06:41 +0000658 if (log)
659 {
660 lldb_private::StreamString type_desc_stream;
Sean Callanan47dc4572011-09-15 02:13:07 +0000661 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000662
663 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetString().c_str());
664 }
665
Sean Callanan6a925532011-01-13 08:53:35 +0000666 m_result_name = m_decl_map->GetPersistentResultName();
Sean Callanan82b74c82010-08-12 01:56:52 +0000667
668 if (log)
Sean Callanan6a925532011-01-13 08:53:35 +0000669 log->Printf("Creating a new result global: \"%s\"", m_result_name.GetCString());
Sean Callanan82b74c82010-08-12 01:56:52 +0000670
671 // Construct a new result global and set up its metadata
672
Sean Callananc0492742011-05-23 21:40:23 +0000673 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanan82b74c82010-08-12 01:56:52 +0000674 result_global->getType()->getElementType(),
675 false, /* not constant */
676 GlobalValue::ExternalLinkage,
677 NULL, /* no initializer */
Sean Callanan6a925532011-01-13 08:53:35 +0000678 m_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000679
680 // It's too late in compilation to create a new VarDecl for this, but we don't
681 // need to. We point the metadata at the old VarDecl. This creates an odd
682 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000683 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000684 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
685 // fixed up.
686
Sean Callananc0492742011-05-23 21:40:23 +0000687 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan696cf5f2011-05-07 01:06:41 +0000688 reinterpret_cast<uint64_t>(result_decl),
Sean Callanan82b74c82010-08-12 01:56:52 +0000689 false);
690
691 llvm::Value* values[2];
692 values[0] = new_result_global;
693 values[1] = new_constant_int;
694
Sean Callanan0de254a2011-05-15 22:34:38 +0000695 ArrayRef<Value*> value_ref(values, 2);
696
Sean Callananc0492742011-05-23 21:40:23 +0000697 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
698 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000699 named_metadata->addOperand(persistent_global_md);
700
701 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000702 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000703 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000704 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000705
706 if (result_global->hasNUses(0))
707 {
708 // We need to synthesize a store for this variable, because otherwise
709 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000710
Greg Clayton8de27c72010-10-15 22:48:33 +0000711 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000712 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
713
714 if (!first_entry_instruction)
715 return false;
716
717 if (!result_global->hasInitializer())
718 {
719 if (log)
720 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000721
722 if (m_error_stream)
723 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
724
Sean Callanan2e2db532010-09-07 22:43:19 +0000725 return false;
726 }
727
728 Constant *initializer = result_global->getInitializer();
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000729
730 // Here we write the initializer into a result variable assuming it
731 // can be computed statically.
732
733 if (!m_has_side_effects)
734 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000735 //MaybeSetConstantResult (initializer,
736 // m_result_name,
737 // m_result_type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000738 }
Sean Callanan2e2db532010-09-07 22:43:19 +0000739
Greg Clayton2c344ca2011-02-05 02:28:58 +0000740 StoreInst *synthesized_store = new StoreInst(initializer,
741 new_result_global,
742 first_entry_instruction);
Sean Callanan2e2db532010-09-07 22:43:19 +0000743
744 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000745 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000746 }
747 else
748 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000749 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (m_result_type.GetOpaqueQualType()))
Sean Callanan696cf5f2011-05-07 01:06:41 +0000750 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000751 //MaybeSetCastResult (m_result_type);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000752 }
753
Sean Callanan2e2db532010-09-07 22:43:19 +0000754 result_global->replaceAllUsesWith(new_result_global);
755 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000756
757 if (!m_const_result)
758 m_decl_map->AddPersistentVariable(result_decl,
759 m_result_name,
Sean Callanan47dc4572011-09-15 02:13:07 +0000760 m_result_type,
Sean Callanan696cf5f2011-05-07 01:06:41 +0000761 true,
762 m_result_is_pointer);
Sean Callanan2e2db532010-09-07 22:43:19 +0000763
Sean Callanan82b74c82010-08-12 01:56:52 +0000764 result_global->eraseFromParent();
765
766 return true;
767}
768
Johnny Chen58021cc2011-08-09 23:10:20 +0000769#if 0
Greg Clayton3c7feb42010-11-19 01:05:25 +0000770static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000771{
772 if (!depth)
773 return;
774
775 depth--;
776
Johnny Chen58021cc2011-08-09 23:10:20 +0000777 if (log)
778 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000779
Greg Clayton3c7feb42010-11-19 01:05:25 +0000780 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000781 ui != ue;
782 ++ui)
783 {
Johnny Chen58021cc2011-08-09 23:10:20 +0000784 if (log)
785 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000786 DebugUsers(log, *ui, depth);
787 }
788
Johnny Chen58021cc2011-08-09 23:10:20 +0000789 if (log)
790 log->Printf(" <End uses>");
Sean Callanan6ba533e2010-11-17 23:00:36 +0000791}
Johnny Chen58021cc2011-08-09 23:10:20 +0000792#endif
Sean Callanan6ba533e2010-11-17 23:00:36 +0000793
794bool
Sean Callananc0492742011-05-23 21:40:23 +0000795IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton3c7feb42010-11-19 01:05:25 +0000796 llvm::GlobalVariable *cstr,
797 Instruction *FirstEntryInstruction)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000798{
799 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
800
Sean Callanan9b6898f2011-07-30 02:42:06 +0000801 Type *ns_str_ty = ns_str->getType();
Sean Callananc0492742011-05-23 21:40:23 +0000802
Sean Callanan9b6898f2011-07-30 02:42:06 +0000803 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
804 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callananc0492742011-05-23 21:40:23 +0000805 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan9b6898f2011-07-30 02:42:06 +0000806 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
807 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000808
809 if (!m_CFStringCreateWithBytes)
810 {
811 lldb::addr_t CFStringCreateWithBytes_addr;
812
813 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
814
815 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
816 {
817 if (log)
818 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
819
Sean Callanan97c924e2011-01-27 01:07:04 +0000820 if (m_error_stream)
821 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
822
Sean Callanan6ba533e2010-11-17 23:00:36 +0000823 return false;
824 }
825
826 if (log)
827 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr);
828
829 // Build the function type:
830 //
831 // CFStringRef CFStringCreateWithBytes (
832 // CFAllocatorRef alloc,
833 // const UInt8 *bytes,
834 // CFIndex numBytes,
835 // CFStringEncoding encoding,
836 // Boolean isExternalRepresentation
837 // );
838 //
839 // We make the following substitutions:
840 //
841 // CFStringRef -> i8*
842 // CFAllocatorRef -> i8*
843 // UInt8 * -> i8*
844 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
845 // CFStringEncoding -> i32
846 // Boolean -> i8
847
Sean Callanan9b6898f2011-07-30 02:42:06 +0000848 Type *arg_type_array[5];
849
850 arg_type_array[0] = i8_ptr_ty;
851 arg_type_array[1] = i8_ptr_ty;
852 arg_type_array[2] = intptr_ty;
853 arg_type_array[3] = i32_ty;
854 arg_type_array[4] = i8_ty;
855
856 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
857
Sean Callananc0492742011-05-23 21:40:23 +0000858 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000859
860 // Build the constant containing the pointer to the function
861 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
862 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
863 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
864 }
865
Sean Callanan58baaad2011-07-08 00:39:14 +0000866 ConstantArray *string_array = NULL;
Sean Callanan0ece5262011-02-10 22:17:53 +0000867
868 if (cstr)
869 string_array = dyn_cast<ConstantArray>(cstr->getInitializer());
Sean Callanan9b6898f2011-07-30 02:42:06 +0000870
Sean Callanan6ba533e2010-11-17 23:00:36 +0000871 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan0ece5262011-02-10 22:17:53 +0000872 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
873 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getType()->getNumElements() - 1 : 0, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000874 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
875 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
876
Sean Callanan9b6898f2011-07-30 02:42:06 +0000877 Value *argument_array[5];
878
879 argument_array[0] = alloc_arg;
880 argument_array[1] = bytes_arg;
881 argument_array[2] = numBytes_arg;
882 argument_array[3] = encoding_arg;
883 argument_array[4] = isExternal_arg;
884
885 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000886
887 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanan9b6898f2011-07-30 02:42:06 +0000888 CFSCWB_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +0000889 "CFStringCreateWithBytes",
890 FirstEntryInstruction);
Sean Callananae71e302010-11-18 22:21:58 +0000891
Greg Clayton3c7feb42010-11-19 01:05:25 +0000892 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000893 {
894 if (log)
895 log->PutCString("Couldn't replace the NSString with the result of the call");
896
Sean Callanan97c924e2011-01-27 01:07:04 +0000897 if (m_error_stream)
898 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
899
Sean Callanan6ba533e2010-11-17 23:00:36 +0000900 return false;
901 }
902
Greg Clayton3c7feb42010-11-19 01:05:25 +0000903 ns_str->eraseFromParent();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000904
905 return true;
906}
907
908bool
Sean Callananc0492742011-05-23 21:40:23 +0000909IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000910{
911 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
912
Sean Callananc0492742011-05-23 21:40:23 +0000913 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000914
Greg Clayton3c7feb42010-11-19 01:05:25 +0000915 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000916 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
917
918 if (!FirstEntryInstruction)
919 {
920 if (log)
921 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
922
Sean Callanan97c924e2011-01-27 01:07:04 +0000923 if (m_error_stream)
924 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
925
Sean Callanan6ba533e2010-11-17 23:00:36 +0000926 return false;
927 }
928
929 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
930 vi != ve;
931 ++vi)
932 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000933 std::string value_name = vi->first().str();
934 const char *value_name_cstr = value_name.c_str();
935
936 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000937 {
938 Value *nsstring_value = vi->second;
939
940 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
941
942 if (!nsstring_global)
943 {
944 if (log)
945 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000946
947 if (m_error_stream)
948 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
949
Sean Callanan6ba533e2010-11-17 23:00:36 +0000950 return false;
951 }
952
953 if (!nsstring_global->hasInitializer())
954 {
955 if (log)
956 log->PutCString("NSString variable does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000957
958 if (m_error_stream)
959 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
960
Sean Callanan6ba533e2010-11-17 23:00:36 +0000961 return false;
962 }
963
964 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
965
966 if (!nsstring_struct)
967 {
968 if (log)
969 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan97c924e2011-01-27 01:07:04 +0000970
971 if (m_error_stream)
972 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
973
Sean Callanan6ba533e2010-11-17 23:00:36 +0000974 return false;
975 }
976
977 // We expect the following structure:
978 //
979 // struct {
980 // int *isa;
981 // int flags;
982 // char *str;
983 // long length;
984 // };
985
986 if (nsstring_struct->getNumOperands() != 4)
987 {
988 if (log)
989 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands());
Sean Callanan97c924e2011-01-27 01:07:04 +0000990
991 if (m_error_stream)
992 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
993
Sean Callanan6ba533e2010-11-17 23:00:36 +0000994 return false;
995 }
996
997 Constant *nsstring_member = nsstring_struct->getOperand(2);
998
999 if (!nsstring_member)
1000 {
1001 if (log)
1002 log->PutCString("NSString initializer's str element was empty");
Sean Callanan97c924e2011-01-27 01:07:04 +00001003
1004 if (m_error_stream)
1005 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
1006
Sean Callanan6ba533e2010-11-17 23:00:36 +00001007 return false;
1008 }
1009
1010 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
1011
1012 if (!nsstring_expr)
1013 {
1014 if (log)
1015 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan97c924e2011-01-27 01:07:04 +00001016
1017 if (m_error_stream)
1018 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
1019
Sean Callanan6ba533e2010-11-17 23:00:36 +00001020 return false;
1021 }
1022
1023 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
1024 {
1025 if (log)
1026 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
Sean Callanan97c924e2011-01-27 01:07:04 +00001027
1028 if (m_error_stream)
1029 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
1030
Sean Callanan6ba533e2010-11-17 23:00:36 +00001031 return false;
1032 }
1033
1034 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
1035
1036 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
1037
1038 if (!cstr_global)
1039 {
1040 if (log)
1041 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001042
1043 if (m_error_stream)
1044 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
Sean Callanan65e2aee2010-11-20 02:06:01 +00001045
Sean Callanan6ba533e2010-11-17 23:00:36 +00001046 return false;
1047 }
1048
1049 if (!cstr_global->hasInitializer())
1050 {
1051 if (log)
1052 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +00001053
1054 if (m_error_stream)
1055 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
1056
Sean Callanan6ba533e2010-11-17 23:00:36 +00001057 return false;
1058 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001059
1060 /*
Sean Callanan6ba533e2010-11-17 23:00:36 +00001061 if (!cstr_array)
1062 {
1063 if (log)
1064 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan97c924e2011-01-27 01:07:04 +00001065
1066 if (m_error_stream)
1067 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
1068
Sean Callanan6ba533e2010-11-17 23:00:36 +00001069 return false;
1070 }
1071
1072 if (!cstr_array->isCString())
1073 {
1074 if (log)
1075 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan97c924e2011-01-27 01:07:04 +00001076
1077 if (m_error_stream)
1078 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
1079
Sean Callanan6ba533e2010-11-17 23:00:36 +00001080 return false;
1081 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001082 */
1083
1084 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer());
Sean Callanan6ba533e2010-11-17 23:00:36 +00001085
1086 if (log)
Sean Callanan0ece5262011-02-10 22:17:53 +00001087 {
1088 if (cstr_array)
Sean Callanan9b6898f2011-07-30 02:42:06 +00001089 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().c_str());
Sean Callanan0ece5262011-02-10 22:17:53 +00001090 else
Sean Callanan9b6898f2011-07-30 02:42:06 +00001091 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan0ece5262011-02-10 22:17:53 +00001092 }
1093
1094 if (!cstr_array)
1095 cstr_global = NULL;
Sean Callanan6ba533e2010-11-17 23:00:36 +00001096
Sean Callananc0492742011-05-23 21:40:23 +00001097 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan97c924e2011-01-27 01:07:04 +00001098 {
Sean Callanan6ba533e2010-11-17 23:00:36 +00001099 if (log)
1100 log->PutCString("Error rewriting the constant string");
Sean Callanan97c924e2011-01-27 01:07:04 +00001101
1102 // We don't print an error message here because RewriteObjCConstString has done so for us.
1103
Sean Callanan6ba533e2010-11-17 23:00:36 +00001104 return false;
1105 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00001106 }
1107 }
1108
1109 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1110 vi != ve;
1111 ++vi)
1112 {
Sean Callanan9b6898f2011-07-30 02:42:06 +00001113 std::string value_name = vi->first().str();
1114 const char *value_name_cstr = value_name.c_str();
1115
1116 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callanan6ba533e2010-11-17 23:00:36 +00001117 {
1118 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1119
1120 if (!gv)
1121 {
1122 if (log)
1123 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001124
1125 if (m_error_stream)
1126 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1127
Sean Callanan6ba533e2010-11-17 23:00:36 +00001128 return false;
1129 }
1130
1131 gv->eraseFromParent();
1132
1133 break;
1134 }
1135 }
1136
1137 return true;
1138}
1139
Greg Clayton3c7feb42010-11-19 01:05:25 +00001140static bool IsObjCSelectorRef (Value *value)
Sean Callananf5857a02010-07-31 01:32:05 +00001141{
Greg Clayton3c7feb42010-11-19 01:05:25 +00001142 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callananf5857a02010-07-31 01:32:05 +00001143
Greg Clayton3c7feb42010-11-19 01:05:25 +00001144 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callananf5857a02010-07-31 01:32:05 +00001145 return false;
1146
1147 return true;
1148}
1149
Sean Callanan97c924e2011-01-27 01:07:04 +00001150// This function does not report errors; its callers are responsible.
Sean Callananf5857a02010-07-31 01:32:05 +00001151bool
Sean Callananc0492742011-05-23 21:40:23 +00001152IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callananf5857a02010-07-31 01:32:05 +00001153{
Greg Claytone005f2c2010-11-06 01:53:30 +00001154 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001155
1156 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1157
1158 if (!load)
1159 return false;
1160
1161 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1162 //
1163 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1164 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1165 //
1166 // where %obj is the object pointer and %tmp is the selector.
1167 //
Greg Clayton3c7feb42010-11-19 01:05:25 +00001168 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1169 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callananf5857a02010-07-31 01:32:05 +00001170
1171 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1172
1173 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1174
1175 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1176 return false;
1177
1178 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1179
1180 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1181
1182 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1183 return false;
1184
1185 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1186
1187 if (!osr_initializer_base)
1188 return false;
1189
1190 // Find the string's initializer (a ConstantArray) and get the string from it
1191
1192 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1193
1194 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1195 return false;
1196
1197 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1198
1199 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
1200
1201 if (!omvn_initializer_array->isString())
1202 return false;
1203
1204 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1205
1206 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001207 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +00001208
1209 // Construct a call to sel_registerName
1210
1211 if (!m_sel_registerName)
1212 {
Greg Claytonb5037af2010-11-15 01:47:11 +00001213 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +00001214
Greg Clayton8de27c72010-10-15 22:48:33 +00001215 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +00001216 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001217 return false;
1218
Sean Callananc2c6f772010-10-26 00:31:56 +00001219 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001220 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +00001221
Sean Callananf5857a02010-07-31 01:32:05 +00001222 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1223
1224 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callananc0492742011-05-23 21:40:23 +00001225 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001226 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanan9b6898f2011-07-30 02:42:06 +00001227 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001228
Sean Callanan9b6898f2011-07-30 02:42:06 +00001229 Type *type_array[1];
1230
1231 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1232
1233 ArrayRef<Type *> srN_arg_types(type_array, 1);
1234
Sean Callananf5857a02010-07-31 01:32:05 +00001235 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1236
1237 // Build the constant containing the pointer to the function
Sean Callanan9b6898f2011-07-30 02:42:06 +00001238 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1239 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananf5857a02010-07-31 01:32:05 +00001240 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +00001241 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001242 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1243 }
1244
Sean Callanan9b6898f2011-07-30 02:42:06 +00001245 Value *argument_array[1];
1246
Sean Callananc0492742011-05-23 21:40:23 +00001247 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callananf5857a02010-07-31 01:32:05 +00001248
Sean Callanan9b6898f2011-07-30 02:42:06 +00001249 argument_array[0] = omvn_pointer;
Sean Callananf5857a02010-07-31 01:32:05 +00001250
Sean Callanan9b6898f2011-07-30 02:42:06 +00001251 ArrayRef<Value *> srN_arguments(argument_array, 1);
1252
Sean Callananf5857a02010-07-31 01:32:05 +00001253 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanan9b6898f2011-07-30 02:42:06 +00001254 srN_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +00001255 "sel_registerName",
Sean Callananf5857a02010-07-31 01:32:05 +00001256 selector_load);
1257
1258 // Replace the load with the call in all users
1259
1260 selector_load->replaceAllUsesWith(srN_call);
1261
1262 selector_load->eraseFromParent();
1263
1264 return true;
1265}
1266
1267bool
Sean Callananc0492742011-05-23 21:40:23 +00001268IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callananf5857a02010-07-31 01:32:05 +00001269{
Greg Claytone005f2c2010-11-06 01:53:30 +00001270 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001271
1272 BasicBlock::iterator ii;
1273
1274 typedef SmallVector <Instruction*, 2> InstrList;
1275 typedef InstrList::iterator InstrIterator;
1276
1277 InstrList selector_loads;
1278
Greg Clayton3c7feb42010-11-19 01:05:25 +00001279 for (ii = basic_block.begin();
1280 ii != basic_block.end();
Sean Callananf5857a02010-07-31 01:32:05 +00001281 ++ii)
1282 {
1283 Instruction &inst = *ii;
1284
1285 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton3c7feb42010-11-19 01:05:25 +00001286 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callananf5857a02010-07-31 01:32:05 +00001287 selector_loads.push_back(&inst);
1288 }
1289
1290 InstrIterator iter;
1291
1292 for (iter = selector_loads.begin();
1293 iter != selector_loads.end();
1294 ++iter)
1295 {
Sean Callananc0492742011-05-23 21:40:23 +00001296 if (!RewriteObjCSelector(*iter))
Sean Callananf5857a02010-07-31 01:32:05 +00001297 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001298 if (m_error_stream)
1299 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1300
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001301 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +00001302 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan97c924e2011-01-27 01:07:04 +00001303
Sean Callananf5857a02010-07-31 01:32:05 +00001304 return false;
1305 }
1306 }
1307
1308 return true;
1309}
1310
Sean Callanan97c924e2011-01-27 01:07:04 +00001311// This function does not report errors; its callers are responsible.
Sean Callanana48fe162010-08-11 03:57:18 +00001312bool
Sean Callananc0492742011-05-23 21:40:23 +00001313IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanana48fe162010-08-11 03:57:18 +00001314{
Sean Callanan97678d12011-01-13 21:23:32 +00001315 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1316
Sean Callanana48fe162010-08-11 03:57:18 +00001317 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1318
1319 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1320
1321 if (!alloc_md || !alloc_md->getNumOperands())
1322 return false;
1323
1324 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1325
1326 if (!constant_int)
1327 return false;
1328
1329 // We attempt to register this as a new persistent variable with the DeclMap.
1330
1331 uintptr_t ptr = constant_int->getZExtValue();
1332
Sean Callanan82b74c82010-08-12 01:56:52 +00001333 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +00001334
Sean Callanan82b74c82010-08-12 01:56:52 +00001335 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1336 &decl->getASTContext());
1337
Greg Clayton8de27c72010-10-15 22:48:33 +00001338 StringRef decl_name (decl->getName());
1339 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan6a925532011-01-13 08:53:35 +00001340 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanana48fe162010-08-11 03:57:18 +00001341 return false;
1342
Sean Callananc0492742011-05-23 21:40:23 +00001343 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanan97678d12011-01-13 21:23:32 +00001344 alloc->getType(),
Sean Callanana48fe162010-08-11 03:57:18 +00001345 false, /* not constant */
1346 GlobalValue::ExternalLinkage,
1347 NULL, /* no initializer */
1348 alloc->getName().str().c_str());
1349
1350 // What we're going to do here is make believe this was a regular old external
1351 // variable. That means we need to make the metadata valid.
1352
Sean Callananc0492742011-05-23 21:40:23 +00001353 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +00001354
1355 llvm::Value* values[2];
1356 values[0] = persistent_global;
1357 values[1] = constant_int;
Sean Callanan0de254a2011-05-15 22:34:38 +00001358
1359 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +00001360
Sean Callananc0492742011-05-23 21:40:23 +00001361 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanana48fe162010-08-11 03:57:18 +00001362 named_metadata->addOperand(persistent_global_md);
1363
Sean Callanan97678d12011-01-13 21:23:32 +00001364 // Now, since the variable is a pointer variable, we will drop in a load of that
1365 // pointer variable.
1366
1367 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1368
1369 if (log)
1370 log->Printf("Replacing \"%s\" with \"%s\"",
1371 PrintValue(alloc).c_str(),
1372 PrintValue(persistent_load).c_str());
1373
1374 alloc->replaceAllUsesWith(persistent_load);
Sean Callanana48fe162010-08-11 03:57:18 +00001375 alloc->eraseFromParent();
1376
1377 return true;
1378}
1379
1380bool
Sean Callananc0492742011-05-23 21:40:23 +00001381IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanana48fe162010-08-11 03:57:18 +00001382{
Sean Callanane8a59a82010-09-13 21:34:21 +00001383 if (!m_resolve_vars)
1384 return true;
1385
Greg Claytone005f2c2010-11-06 01:53:30 +00001386 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +00001387
1388 BasicBlock::iterator ii;
1389
1390 typedef SmallVector <Instruction*, 2> InstrList;
1391 typedef InstrList::iterator InstrIterator;
1392
1393 InstrList pvar_allocs;
1394
Greg Clayton3c7feb42010-11-19 01:05:25 +00001395 for (ii = basic_block.begin();
1396 ii != basic_block.end();
Sean Callanana48fe162010-08-11 03:57:18 +00001397 ++ii)
1398 {
1399 Instruction &inst = *ii;
1400
1401 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan237e4742011-01-21 22:30:25 +00001402 {
1403 llvm::StringRef alloc_name = alloc->getName();
1404
1405 if (alloc_name.startswith("$") &&
1406 !alloc_name.startswith("$__lldb"))
1407 {
1408 if (alloc_name.find_first_of("0123456789") == 1)
1409 {
1410 if (log)
1411 log->Printf("Rejecting a numeric persistent variable.");
1412
Sean Callanan97c924e2011-01-27 01:07:04 +00001413 if (m_error_stream)
1414 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1415
Sean Callanan237e4742011-01-21 22:30:25 +00001416 return false;
1417 }
1418
Sean Callanana48fe162010-08-11 03:57:18 +00001419 pvar_allocs.push_back(alloc);
Sean Callanan237e4742011-01-21 22:30:25 +00001420 }
1421 }
Sean Callanana48fe162010-08-11 03:57:18 +00001422 }
1423
1424 InstrIterator iter;
1425
1426 for (iter = pvar_allocs.begin();
1427 iter != pvar_allocs.end();
1428 ++iter)
1429 {
Sean Callananc0492742011-05-23 21:40:23 +00001430 if (!RewritePersistentAlloc(*iter))
Sean Callanana48fe162010-08-11 03:57:18 +00001431 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001432 if (m_error_stream)
1433 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1434
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001435 if (log)
Sean Callanana48fe162010-08-11 03:57:18 +00001436 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001437
Sean Callanana48fe162010-08-11 03:57:18 +00001438 return false;
1439 }
1440 }
1441
1442 return true;
1443}
1444
Sean Callananc7ca4662011-10-25 18:36:40 +00001445bool
1446IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1447{
1448 if (!initializer)
1449 return true;
1450
1451 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1452
1453 if (log && log->GetVerbose())
1454 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1455
1456 Type *initializer_type = initializer->getType();
1457
1458 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1459 {
1460 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1461 return true;
1462 }
1463 else if (ConstantArray *array_initializer = dyn_cast<ConstantArray>(initializer))
1464 {
1465 if (array_initializer->isString())
1466 {
1467 std::string array_initializer_string = array_initializer->getAsString();
1468 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1469 }
1470 else
1471 {
1472 ArrayType *array_initializer_type = array_initializer->getType();
1473 Type *array_element_type = array_initializer_type->getElementType();
1474
1475 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1476
1477 for (int i = 0; i < array_initializer->getNumOperands(); ++i)
1478 {
1479 if (!MaterializeInitializer(data + (i * element_size), array_initializer->getOperand(i)))
1480 return false;
1481 }
1482 }
1483 return true;
1484 }
1485 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1486 {
1487 StructType *struct_initializer_type = struct_initializer->getType();
1488 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1489
1490 for (int i = 0;
1491 i < struct_initializer->getNumOperands();
1492 ++i)
1493 {
1494 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1495 return false;
1496 }
1497 return true;
1498 }
1499 return false;
1500}
1501
1502bool
1503IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1504{
1505 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1506 return false;
1507
Sean Callananc41606f2011-11-15 19:13:54 +00001508 if (global_variable == m_reloc_placeholder)
1509 return true;
1510
Sean Callananc7ca4662011-10-25 18:36:40 +00001511 uint64_t offset = m_data_allocator->GetStream().GetSize();
1512
1513 llvm::Type *variable_type = global_variable->getType();
1514
1515 Constant *initializer = global_variable->getInitializer();
1516
1517 llvm::Type *initializer_type = initializer->getType();
1518
1519 size_t size = m_target_data->getTypeAllocSize(initializer_type);
1520
1521 lldb_private::DataBufferHeap data(size, '\0');
1522
1523 if (initializer)
1524 if (!MaterializeInitializer(data.GetBytes(), initializer))
1525 return false;
1526
1527 m_data_allocator->GetStream().Write(data.GetBytes(), data.GetByteSize());
1528
1529 Constant *new_pointer = BuildRelocation(variable_type, offset);
1530
1531 global_variable->replaceAllUsesWith(new_pointer);
1532
1533 global_variable->eraseFromParent();
1534
1535 return true;
1536}
1537
Sean Callanan97c924e2011-01-27 01:07:04 +00001538// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001539bool
Sean Callananc0492742011-05-23 21:40:23 +00001540IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001541{
Greg Claytone005f2c2010-11-06 01:53:30 +00001542 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan48443652010-12-02 19:47:57 +00001543
1544 if (log)
Sean Callananb9f09a62010-12-06 22:16:55 +00001545 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callanan9a877432011-08-01 17:41:38 +00001546
Greg Clayton8de27c72010-10-15 22:48:33 +00001547 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +00001548 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001549 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +00001550 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001551 default:
1552 break;
1553 case Instruction::GetElementPtr:
1554 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +00001555 Value *s = constant_expr->getOperand(0);
Sean Callananc0492742011-05-23 21:40:23 +00001556 if (!MaybeHandleVariable(s))
Sean Callanan48443652010-12-02 19:47:57 +00001557 return false;
Sean Callananbc2928a2010-08-03 00:23:29 +00001558 }
1559 }
Sean Callananf921cf52010-12-03 19:51:05 +00001560 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001561 {
Sean Callananc7ca4662011-10-25 18:36:40 +00001562 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1563 return MaterializeInternalVariable(global_variable);
1564
Sean Callananc0492742011-05-23 21:40:23 +00001565 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001566
Sean Callananf5857a02010-07-31 01:32:05 +00001567 if (!named_decl)
1568 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001569 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001570 return true;
1571
Sean Callanan7cd46742010-12-06 00:56:39 +00001572 if (!global_variable->hasExternalLinkage())
1573 return true;
1574
Sean Callananf5857a02010-07-31 01:32:05 +00001575 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001576 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001577
Sean Callananf5857a02010-07-31 01:32:05 +00001578 return false;
1579 }
1580
Greg Clayton8de27c72010-10-15 22:48:33 +00001581 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +00001582
Sean Callanan771131d2010-09-30 21:18:25 +00001583 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +00001584 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +00001585
1586 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +00001587 {
Sean Callanan771131d2010-09-30 21:18:25 +00001588 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +00001589 ast_context = &value_decl->getASTContext();
1590 }
Sean Callanan810f22d2010-07-16 00:09:46 +00001591 else
Sean Callananf328c9f2010-07-20 23:31:16 +00001592 {
Sean Callanan810f22d2010-07-16 00:09:46 +00001593 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +00001594 }
Sean Callanan771131d2010-09-30 21:18:25 +00001595
Sean Callanan6a925532011-01-13 08:53:35 +00001596 clang::QualType qual_type;
Sean Callanan58baaad2011-07-08 00:39:14 +00001597 const Type *value_type = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00001598
Sean Callanan97678d12011-01-13 21:23:32 +00001599 if (name[0] == '$')
Sean Callanan6a925532011-01-13 08:53:35 +00001600 {
1601 // The $__lldb_expr_result name indicates the the return value has allocated as
1602 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1603 // accesses to this static variable need to be redirected to the result of dereferencing
1604 // a pointer that is passed in as one of the arguments.
1605 //
1606 // Consequently, when reporting the size of the type, we report a pointer type pointing
1607 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanan97678d12011-01-13 21:23:32 +00001608 //
1609 // We also do this for any user-declared persistent variables.
Sean Callananf328c9f2010-07-20 23:31:16 +00001610
Sean Callanan6a925532011-01-13 08:53:35 +00001611 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1612 value_type = PointerType::get(global_variable->getType(), 0);
1613 }
1614 else
1615 {
1616 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1617 value_type = global_variable->getType();
1618 }
Sean Callanan771131d2010-09-30 21:18:25 +00001619
1620 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
1621 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001622
Sean Callanan771131d2010-09-30 21:18:25 +00001623 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001624 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %lu, align %lld]",
Sean Callanan771131d2010-09-30 21:18:25 +00001625 name.c_str(),
1626 qual_type.getAsString().c_str(),
1627 PrintType(value_type).c_str(),
1628 value_size,
1629 value_alignment);
Sean Callanan3aa7da52010-12-13 22:46:15 +00001630
Sean Callanan8bce6652010-07-13 21:41:46 +00001631
Sean Callanan8c127202010-08-23 23:09:38 +00001632 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +00001633 lldb_private::ConstString (name.c_str()),
1634 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +00001635 value_size,
1636 value_alignment))
Sean Callanan9a877432011-08-01 17:41:38 +00001637 {
1638 if (!global_variable->hasExternalLinkage())
1639 return true;
1640 else
1641 return false;
1642 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001643 }
Sean Callananf3143b72010-12-03 03:02:31 +00001644 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanan48443652010-12-02 19:47:57 +00001645 {
1646 if (log)
1647 log->Printf("Function pointers aren't handled right now");
1648
1649 return false;
1650 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001651
1652 return true;
1653}
1654
Sean Callanan97c924e2011-01-27 01:07:04 +00001655// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001656bool
Sean Callananc0492742011-05-23 21:40:23 +00001657IRForTarget::HandleSymbol (Value *symbol)
Sean Callanan81974962011-05-08 02:21:26 +00001658{
Sean Callananc7674af2011-01-17 23:42:46 +00001659 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1660
1661 lldb_private::ConstString name(symbol->getName().str().c_str());
1662
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001663 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name);
Sean Callananc7674af2011-01-17 23:42:46 +00001664
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001665 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc7674af2011-01-17 23:42:46 +00001666 {
1667 if (log)
1668 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1669
1670 return false;
1671 }
1672
1673 if (log)
1674 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), symbol_addr);
1675
Sean Callanan9b6898f2011-07-30 02:42:06 +00001676 Type *symbol_type = symbol->getType();
Sean Callananc7674af2011-01-17 23:42:46 +00001677
Sean Callanan9b6898f2011-07-30 02:42:06 +00001678 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1679 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc7674af2011-01-17 23:42:46 +00001680
1681 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1682
1683 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1684
1685 if (log)
1686 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1687
1688 symbol->replaceAllUsesWith(symbol_addr_ptr);
1689
1690 return true;
1691}
1692
1693bool
Sean Callananc0492742011-05-23 21:40:23 +00001694IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +00001695{
Sean Callanan48443652010-12-02 19:47:57 +00001696 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1697
1698 if (log)
1699 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanandc27aba2010-10-05 22:26:43 +00001700
Sean Callanan6ba533e2010-11-17 23:00:36 +00001701 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +00001702 op_index < num_ops;
1703 ++op_index)
Sean Callananc0492742011-05-23 21:40:23 +00001704 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan97c924e2011-01-27 01:07:04 +00001705 {
1706 if (m_error_stream)
1707 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1708
Sean Callanandc27aba2010-10-05 22:26:43 +00001709 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001710 }
1711
Sean Callanandc27aba2010-10-05 22:26:43 +00001712 return true;
1713}
1714
1715bool
Sean Callanan9911d2f2011-11-01 23:38:03 +00001716IRForTarget::HandleObjCClass(Value *classlist_reference)
1717{
1718 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1719
1720 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1721
1722 if (!global_variable)
1723 return false;
1724
1725 Constant *initializer = global_variable->getInitializer();
1726
1727 if (!initializer)
1728 return false;
1729
1730 if (!initializer->hasName())
1731 return false;
1732
1733 StringRef name(initializer->getName());
1734 lldb_private::ConstString name_cstr(name.str().c_str());
1735 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr);
1736
1737 if (log)
1738 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1739
1740 if (class_ptr == LLDB_INVALID_ADDRESS)
1741 return false;
1742
1743 if (global_variable->use_begin() == global_variable->use_end())
1744 return false;
1745
1746 LoadInst *load_instruction = NULL;
1747
1748 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1749 i != e;
1750 ++i)
1751 {
1752 if ((load_instruction = dyn_cast<LoadInst>(*i)))
1753 break;
1754 }
1755
1756 if (!load_instruction)
1757 return false;
1758
1759 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1760 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1761
1762 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
1763 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
1764
1765 load_instruction->replaceAllUsesWith(class_bitcast);
1766
1767 load_instruction->eraseFromParent();
1768
1769 return true;
1770}
1771
1772bool
Sean Callananc0492742011-05-23 21:40:23 +00001773IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan8bce6652010-07-13 21:41:46 +00001774{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001775 /////////////////////////////////////////////////////////////////////////
1776 // Prepare the current basic block for execution in the remote process
1777 //
1778
Sean Callanan02fbafa2010-07-27 21:39:39 +00001779 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001780
Greg Clayton3c7feb42010-11-19 01:05:25 +00001781 for (ii = basic_block.begin();
1782 ii != basic_block.end();
Sean Callanan8bce6652010-07-13 21:41:46 +00001783 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001784 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001785 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001786
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001787 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001788
Sean Callanan97c924e2011-01-27 01:07:04 +00001789 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001790 if (call && !MaybeHandleCallArguments(call))
Sean Callanan48443652010-12-02 19:47:57 +00001791 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001792 }
1793
1794 return true;
1795}
1796
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001797bool
Sean Callananc0492742011-05-23 21:40:23 +00001798IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001799{
Sean Callananae71e302010-11-18 22:21:58 +00001800 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1801
Sean Callananc0492742011-05-23 21:40:23 +00001802 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001803 global != end;
1804 ++global)
1805 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001806 if (log)
1807 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1808 (*global).getName().str().c_str(),
Sean Callananc0492742011-05-23 21:40:23 +00001809 DeclForGlobal(global));
Greg Clayton3c7feb42010-11-19 01:05:25 +00001810
Sean Callanan9911d2f2011-11-01 23:38:03 +00001811 std::string global_name = (*global).getName().str();
1812
1813 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc7674af2011-01-17 23:42:46 +00001814 {
Sean Callananc0492742011-05-23 21:40:23 +00001815 if (!HandleSymbol(global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001816 {
1817 if (m_error_stream)
1818 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str());
1819
Sean Callananc7674af2011-01-17 23:42:46 +00001820 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001821 }
Sean Callananc7674af2011-01-17 23:42:46 +00001822 }
Sean Callanan9911d2f2011-11-01 23:38:03 +00001823 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1824 {
1825 if (!HandleObjCClass(global))
1826 {
1827 if (m_error_stream)
1828 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1829
1830 return false;
1831 }
1832 }
Sean Callananc0492742011-05-23 21:40:23 +00001833 else if (DeclForGlobal(global))
Sean Callananc7674af2011-01-17 23:42:46 +00001834 {
Sean Callananc0492742011-05-23 21:40:23 +00001835 if (!MaybeHandleVariable (global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001836 {
1837 if (m_error_stream)
1838 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str());
1839
Sean Callananc7674af2011-01-17 23:42:46 +00001840 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001841 }
Sean Callananc7674af2011-01-17 23:42:46 +00001842 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001843 }
1844
1845 return true;
1846}
1847
Sean Callananc0492742011-05-23 21:40:23 +00001848bool
1849IRForTarget::ReplaceStrings ()
1850{
1851 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1852
1853 if (!m_data_allocator)
1854 return true; // hope for the best; some clients may not want static allocation!
1855
1856 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1857
1858 OffsetsTy offsets;
1859
1860 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1861 gi != ge;
1862 ++gi)
1863 {
1864 GlobalVariable *gv = gi;
1865
1866 if (!gv->hasInitializer())
1867 continue;
1868
1869 Constant *gc = gv->getInitializer();
1870
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001871 std::string str;
Sean Callananc0492742011-05-23 21:40:23 +00001872
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001873 if (gc->isNullValue())
1874 {
1875 Type *gc_type = gc->getType();
1876
1877 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1878
1879 if (!gc_array_type)
1880 continue;
1881
1882 Type *gc_element_type = gc_array_type->getElementType();
1883
1884 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1885
1886 if (gc_integer_type->getBitWidth() != 8)
1887 continue;
1888
1889 str = "";
1890 }
1891 else
1892 {
1893 ConstantArray *gc_array = dyn_cast<ConstantArray>(gc);
1894
1895 if (!gc_array)
1896 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001897
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001898 if (!gc_array->isCString())
1899 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001900
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001901 if (log)
1902 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callananc0492742011-05-23 21:40:23 +00001903
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001904 str = gc_array->getAsString();
1905 }
1906
Sean Callananc0492742011-05-23 21:40:23 +00001907 offsets[gv] = m_data_allocator->GetStream().GetSize();
1908
1909 m_data_allocator->GetStream().Write(str.c_str(), str.length() + 1);
1910 }
1911
Sean Callanan9b6898f2011-07-30 02:42:06 +00001912 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00001913
1914 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1915 oi != oe;
1916 ++oi)
1917 {
1918 GlobalVariable *gv = oi->first;
1919 size_t offset = oi->second;
1920
1921 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1922
1923 if (log)
1924 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1925
1926 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1927 ui != ue;
1928 ++ui)
1929 {
1930 if (log)
1931 log->Printf("Found use %s", PrintValue(*ui).c_str());
1932
1933 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1934 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1935
1936 if (const_expr)
1937 {
1938 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1939 {
1940 if (log)
1941 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1942
1943 return false;
1944 }
1945
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001946 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1947 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1948
1949 const_expr->replaceAllUsesWith(new_gep);
Sean Callananc0492742011-05-23 21:40:23 +00001950 }
1951 else if (store_inst)
1952 {
1953 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1954
1955 store_inst->setOperand(0, bit_cast);
1956 }
1957 else
1958 {
1959 if (log)
1960 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1961
1962 return false;
1963 }
1964 }
1965
1966 gv->eraseFromParent();
1967 }
1968
1969 return true;
1970}
1971
1972bool
1973IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1974{
1975 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1976
1977 if (!m_data_allocator)
1978 return true;
1979
1980 typedef SmallVector <Value*, 2> ConstantList;
1981 typedef SmallVector <llvm::Instruction*, 2> UserList;
1982 typedef ConstantList::iterator ConstantIterator;
1983 typedef UserList::iterator UserIterator;
1984
1985 ConstantList static_constants;
1986 UserList static_users;
1987
1988 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1989 ii != ie;
1990 ++ii)
1991 {
1992 llvm::Instruction &inst = *ii;
1993
1994 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1995 oi != oe;
1996 ++oi)
1997 {
1998 Value *operand_val = oi->get();
1999
2000 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2001
2002 if (operand_constant_fp && operand_constant_fp->getType()->isX86_FP80Ty())
2003 {
2004 static_constants.push_back(operand_val);
2005 static_users.push_back(ii);
2006 }
2007 }
2008 }
2009
2010 ConstantIterator constant_iter;
2011 UserIterator user_iter;
Greg Clayton54b38412011-05-24 23:06:02 +00002012
Sean Callananc0492742011-05-23 21:40:23 +00002013 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
2014 constant_iter != static_constants.end();
2015 ++constant_iter, ++user_iter)
2016 {
2017 Value *operand_val = *constant_iter;
2018 llvm::Instruction *inst = *user_iter;
2019
2020 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2021
2022 if (operand_constant_fp)
2023 {
2024 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2025 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2026
2027 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2028 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2029
2030 if (log)
2031 {
2032 std::string s;
2033 raw_string_ostream ss(s);
2034 for (size_t index = 0;
2035 index < operand_data_size;
2036 ++index)
2037 {
2038 ss << (uint32_t)operand_raw_data[index];
2039 ss << " ";
2040 }
2041 ss.flush();
2042
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002043 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callananc0492742011-05-23 21:40:23 +00002044 }
2045
2046 lldb_private::DataBufferHeap data(operand_data_size, 0);
2047
2048 if (lldb::endian::InlHostByteOrder() != m_data_allocator->GetStream().GetByteOrder())
2049 {
2050 uint8_t *data_bytes = data.GetBytes();
2051
2052 for (size_t index = 0;
2053 index < operand_data_size;
2054 ++index)
2055 {
2056 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2057 }
2058 }
2059 else
2060 {
2061 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2062 }
2063
2064 uint64_t offset = m_data_allocator->GetStream().GetSize();
2065
2066 m_data_allocator->GetStream().Write(data.GetBytes(), operand_data_size);
2067
Sean Callanan9b6898f2011-07-30 02:42:06 +00002068 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callananc0492742011-05-23 21:40:23 +00002069
2070 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
2071
2072 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2073
2074 operand_constant_fp->replaceAllUsesWith(fp_load);
2075 }
2076 }
2077
2078 return true;
2079}
2080
Sean Callanan02fbafa2010-07-27 21:39:39 +00002081static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00002082{
Sean Callanan58baaad2011-07-08 00:39:14 +00002083 Constant *Old = NULL;
Sean Callanan45839272010-07-24 01:37:44 +00002084
Sean Callanan6ba533e2010-11-17 23:00:36 +00002085 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00002086 return false;
2087
Sean Callanan58baaad2011-07-08 00:39:14 +00002088 ConstantExpr *CE = NULL;
Sean Callanan47a5c4c2010-09-23 03:01:22 +00002089
2090 if ((CE = dyn_cast<ConstantExpr>(V)))
2091 {
2092 if (CE->getOpcode() != Instruction::BitCast)
2093 return false;
2094
Sean Callanan6ba533e2010-11-17 23:00:36 +00002095 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00002096 }
2097
Sean Callanan6ba533e2010-11-17 23:00:36 +00002098 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00002099
2100 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2101 return false;
2102
2103 return true;
2104}
2105
Sean Callananc0492742011-05-23 21:40:23 +00002106void
2107IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callanan45839272010-07-24 01:37:44 +00002108{
Sean Callananc0492742011-05-23 21:40:23 +00002109 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callanan45839272010-07-24 01:37:44 +00002110
2111 Value::use_iterator ui;
2112
2113 for (ui = guard_load->use_begin();
2114 ui != guard_load->use_end();
2115 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00002116 {
Greg Clayton6e713402010-07-30 20:30:44 +00002117 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00002118 {
2119 // do nothing for the moment
2120 }
2121 else
2122 {
2123 ui->replaceUsesOfWith(guard_load, zero);
2124 }
2125 }
Sean Callanan45839272010-07-24 01:37:44 +00002126
2127 guard_load->eraseFromParent();
2128}
2129
2130static void ExciseGuardStore(Instruction* guard_store)
2131{
2132 guard_store->eraseFromParent();
2133}
2134
2135bool
Sean Callananc0492742011-05-23 21:40:23 +00002136IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callanan45839272010-07-24 01:37:44 +00002137{
2138 ///////////////////////////////////////////////////////
2139 // Eliminate any reference to guard variables found.
2140 //
2141
Sean Callanan02fbafa2010-07-27 21:39:39 +00002142 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00002143
Sean Callanan02fbafa2010-07-27 21:39:39 +00002144 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00002145 typedef InstrList::iterator InstrIterator;
2146
2147 InstrList guard_loads;
2148 InstrList guard_stores;
2149
Greg Clayton3c7feb42010-11-19 01:05:25 +00002150 for (ii = basic_block.begin();
2151 ii != basic_block.end();
Sean Callanan45839272010-07-24 01:37:44 +00002152 ++ii)
2153 {
2154 Instruction &inst = *ii;
2155
2156 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2157 if (isGuardVariableRef(load->getPointerOperand()))
2158 guard_loads.push_back(&inst);
2159
2160 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2161 if (isGuardVariableRef(store->getPointerOperand()))
2162 guard_stores.push_back(&inst);
2163 }
2164
2165 InstrIterator iter;
2166
2167 for (iter = guard_loads.begin();
2168 iter != guard_loads.end();
2169 ++iter)
Sean Callananc0492742011-05-23 21:40:23 +00002170 TurnGuardLoadIntoZero(*iter);
Sean Callanan45839272010-07-24 01:37:44 +00002171
2172 for (iter = guard_stores.begin();
2173 iter != guard_stores.end();
2174 ++iter)
2175 ExciseGuardStore(*iter);
2176
2177 return true;
2178}
2179
Sean Callanan97c924e2011-01-27 01:07:04 +00002180// This function does not report errors; its callers are responsible.
Sean Callanan6ba533e2010-11-17 23:00:36 +00002181bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002182IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callananbafd6852010-07-14 23:40:29 +00002183{
Greg Claytone005f2c2010-11-06 01:53:30 +00002184 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00002185
2186 Value::use_iterator ui;
2187
Sean Callanana48fe162010-08-11 03:57:18 +00002188 SmallVector<User*, 16> users;
2189
2190 // We do this because the use list might change, invalidating our iterator.
2191 // Much better to keep a work list ourselves.
Greg Clayton3c7feb42010-11-19 01:05:25 +00002192 for (ui = old_constant->use_begin();
2193 ui != old_constant->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00002194 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00002195 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00002196
Johnny Chen2bc9eb32011-07-19 19:48:13 +00002197 for (size_t i = 0;
Sean Callanana48fe162010-08-11 03:57:18 +00002198 i < users.size();
2199 ++i)
2200 {
2201 User *user = users[i];
2202
Sean Callananbafd6852010-07-14 23:40:29 +00002203 if (Constant *constant = dyn_cast<Constant>(user))
2204 {
2205 // synthesize a new non-constant equivalent of the constant
2206
2207 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2208 {
2209 switch (constant_expr->getOpcode())
2210 {
2211 default:
2212 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002213 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002214 return false;
2215 case Instruction::BitCast:
2216 {
2217 // UnaryExpr
2218 // OperandList[0] is value
2219
2220 Value *s = constant_expr->getOperand(0);
2221
Greg Clayton3c7feb42010-11-19 01:05:25 +00002222 if (s == old_constant)
2223 s = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002224
Sean Callananc0492742011-05-23 21:40:23 +00002225 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002226
Greg Clayton3c7feb42010-11-19 01:05:25 +00002227 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002228 }
2229 break;
2230 case Instruction::GetElementPtr:
2231 {
2232 // GetElementPtrConstantExpr
2233 // OperandList[0] is base
2234 // OperandList[1]... are indices
2235
2236 Value *ptr = constant_expr->getOperand(0);
2237
Greg Clayton3c7feb42010-11-19 01:05:25 +00002238 if (ptr == old_constant)
2239 ptr = new_constant;
Sean Callanan9b6898f2011-07-30 02:42:06 +00002240
2241 std::vector<Value*> index_vector;
Sean Callananbafd6852010-07-14 23:40:29 +00002242
2243 unsigned operand_index;
2244 unsigned num_operands = constant_expr->getNumOperands();
2245
2246 for (operand_index = 1;
2247 operand_index < num_operands;
2248 ++operand_index)
2249 {
2250 Value *operand = constant_expr->getOperand(operand_index);
2251
Greg Clayton3c7feb42010-11-19 01:05:25 +00002252 if (operand == old_constant)
2253 operand = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002254
Sean Callanan9b6898f2011-07-30 02:42:06 +00002255 index_vector.push_back(operand);
Sean Callananbafd6852010-07-14 23:40:29 +00002256 }
2257
Sean Callanan9b6898f2011-07-30 02:42:06 +00002258 ArrayRef <Value*> indices(index_vector);
2259
2260 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002261
Greg Clayton3c7feb42010-11-19 01:05:25 +00002262 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002263 }
2264 break;
2265 }
2266 }
2267 else
2268 {
2269 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002270 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002271 return false;
2272 }
2273 }
2274 else
2275 {
2276 // simple fall-through case for non-constants
Greg Clayton3c7feb42010-11-19 01:05:25 +00002277 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callananbafd6852010-07-14 23:40:29 +00002278 }
2279 }
2280
2281 return true;
2282}
2283
Sean Callanan8bce6652010-07-13 21:41:46 +00002284bool
Sean Callananc0492742011-05-23 21:40:23 +00002285IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan8bce6652010-07-13 21:41:46 +00002286{
Sean Callanane8a59a82010-09-13 21:34:21 +00002287 if (!m_resolve_vars)
2288 return true;
2289
Greg Claytone005f2c2010-11-06 01:53:30 +00002290 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00002291
2292 m_decl_map->DoStructLayout();
2293
2294 if (log)
2295 log->Printf("Element arrangement:");
2296
2297 uint32_t num_elements;
2298 uint32_t element_index;
2299
2300 size_t size;
2301 off_t alignment;
2302
2303 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2304 return false;
2305
Greg Clayton3c7feb42010-11-19 01:05:25 +00002306 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00002307
Greg Clayton3c7feb42010-11-19 01:05:25 +00002308 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002309 {
2310 if (m_error_stream)
2311 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2312
Sean Callanan8bce6652010-07-13 21:41:46 +00002313 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002314 }
2315
Sean Callanan02fbafa2010-07-27 21:39:39 +00002316 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00002317
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002318 if (argument->getName().equals("this"))
2319 {
2320 ++iter;
2321
Greg Clayton3c7feb42010-11-19 01:05:25 +00002322 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002323 {
2324 if (m_error_stream)
2325 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2326
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002327 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002328 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002329
2330 argument = iter;
2331 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002332 else if (argument->getName().equals("self"))
2333 {
2334 ++iter;
2335
2336 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002337 {
2338 if (m_error_stream)
2339 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2340
Sean Callanan3aa7da52010-12-13 22:46:15 +00002341 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002342 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002343
2344 if (!iter->getName().equals("_cmd"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002345 {
2346 if (m_error_stream)
2347 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2348
Sean Callanan3aa7da52010-12-13 22:46:15 +00002349 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002350 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002351
2352 ++iter;
2353
2354 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002355 {
2356 if (m_error_stream)
2357 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2358
Sean Callanan3aa7da52010-12-13 22:46:15 +00002359 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002360 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002361
2362 argument = iter;
2363 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002364
Greg Clayton8de27c72010-10-15 22:48:33 +00002365 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002366 {
2367 if (m_error_stream)
2368 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2369
Sean Callanan8bce6652010-07-13 21:41:46 +00002370 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002371 }
2372
Sean Callanan8bce6652010-07-13 21:41:46 +00002373 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002374 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00002375
Greg Clayton3c7feb42010-11-19 01:05:25 +00002376 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00002377 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00002378
Sean Callanan6ba533e2010-11-17 23:00:36 +00002379 if (!FirstEntryInstruction)
Sean Callanan97c924e2011-01-27 01:07:04 +00002380 {
2381 if (m_error_stream)
2382 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2383
Sean Callanan8bce6652010-07-13 21:41:46 +00002384 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002385 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002386
Sean Callananc0492742011-05-23 21:40:23 +00002387 LLVMContext &context(m_module->getContext());
Sean Callanan9b6898f2011-07-30 02:42:06 +00002388 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan8bce6652010-07-13 21:41:46 +00002389
2390 if (!offset_type)
Sean Callanan97c924e2011-01-27 01:07:04 +00002391 {
2392 if (m_error_stream)
2393 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2394
Sean Callanan8bce6652010-07-13 21:41:46 +00002395 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002396 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002397
2398 for (element_index = 0; element_index < num_elements; ++element_index)
2399 {
Sean Callanan58baaad2011-07-08 00:39:14 +00002400 const clang::NamedDecl *decl = NULL;
2401 Value *value = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002402 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00002403 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00002404
Sean Callanan45690fe2010-08-30 22:17:16 +00002405 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan97c924e2011-01-27 01:07:04 +00002406 {
2407 if (m_error_stream)
2408 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2409
Sean Callanan8bce6652010-07-13 21:41:46 +00002410 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002411 }
2412
Sean Callanan8bce6652010-07-13 21:41:46 +00002413 if (log)
Sean Callananc7ca4662011-10-25 18:36:40 +00002414 log->Printf(" \"%s\" (\"%s\") placed at %lld",
Greg Clayton8de27c72010-10-15 22:48:33 +00002415 name.GetCString(),
Sean Callananc7ca4662011-10-25 18:36:40 +00002416 decl->getNameAsString().c_str(),
Sean Callanan8bce6652010-07-13 21:41:46 +00002417 offset);
2418
Sean Callanan9b6898f2011-07-30 02:42:06 +00002419 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callanan6ba533e2010-11-17 23:00:36 +00002420 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan6a925532011-01-13 08:53:35 +00002421
Sean Callananc7ca4662011-10-25 18:36:40 +00002422 if (value)
Sean Callanan6a925532011-01-13 08:53:35 +00002423 {
Sean Callananc7ca4662011-10-25 18:36:40 +00002424 Value *replacement = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00002425
Sean Callananc7ca4662011-10-25 18:36:40 +00002426 if (log)
2427 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan6a925532011-01-13 08:53:35 +00002428
Sean Callananc7ca4662011-10-25 18:36:40 +00002429 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2430 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2431 // entry in order to produce the static variable that the AST thinks it is accessing.
2432 if (name == m_result_name && !m_result_is_pointer)
2433 {
2434 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2435
2436 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2437
2438 replacement = load;
2439 }
2440 else
2441 {
2442 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2443
2444 replacement = bit_cast;
2445 }
2446
2447 if (Constant *constant = dyn_cast<Constant>(value))
2448 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2449 else
2450 value->replaceAllUsesWith(replacement);
2451
2452 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2453 var->eraseFromParent();
2454 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002455 }
2456
2457 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002458 log->Printf("Total structure [align %lld, size %lu]", alignment, size);
Sean Callanan8bce6652010-07-13 21:41:46 +00002459
2460 return true;
2461}
2462
Sean Callananc0492742011-05-23 21:40:23 +00002463llvm::Constant *
Sean Callanan9b6898f2011-07-30 02:42:06 +00002464IRForTarget::BuildRelocation(llvm::Type *type,
Sean Callananc0492742011-05-23 21:40:23 +00002465 uint64_t offset)
2466{
2467 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2468
Sean Callanan9b6898f2011-07-30 02:42:06 +00002469 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2470 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002471
2472 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanan9b6898f2011-07-30 02:42:06 +00002473
2474 llvm::Constant *offset_array[1];
2475
2476 offset_array[0] = offset_int;
2477
2478 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2479
2480 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callananc0492742011-05-23 21:40:23 +00002481 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2482
2483 return reloc_getbitcast;
2484}
2485
2486bool
2487IRForTarget::CompleteDataAllocation ()
2488{
Sean Callanan47dc4572011-09-15 02:13:07 +00002489 if (!m_data_allocator)
2490 return true;
2491
Sean Callananc0492742011-05-23 21:40:23 +00002492 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2493
2494 if (!m_data_allocator->GetStream().GetSize())
2495 return true;
2496
2497 lldb::addr_t allocation = m_data_allocator->Allocate();
2498
2499 if (log)
2500 {
2501 if (allocation)
2502 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2503 else
2504 log->Printf("Failed to allocate static data");
2505 }
2506
2507 if (!allocation)
2508 return false;
2509
Sean Callanan9b6898f2011-07-30 02:42:06 +00002510 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2511 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002512
2513 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2514 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2515
2516 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2517
2518 m_reloc_placeholder->eraseFromParent();
2519
2520 return true;
2521}
2522
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002523bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002524IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002525{
Greg Claytone005f2c2010-11-06 01:53:30 +00002526 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002527
Sean Callananc0492742011-05-23 21:40:23 +00002528 m_module = &llvm_module;
Sean Callananc7ca4662011-10-25 18:36:40 +00002529 m_target_data.reset(new TargetData(m_module));
Sean Callananc0492742011-05-23 21:40:23 +00002530
2531 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002532
2533 if (!function)
2534 {
2535 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002536 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00002537
2538 if (m_error_stream)
Sean Callananc0492742011-05-23 21:40:23 +00002539 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
Sean Callanan6a925532011-01-13 08:53:35 +00002540
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002541 return false;
2542 }
Sean Callananc0492742011-05-23 21:40:23 +00002543
2544 if (!FixFunctionLinkage (*function))
2545 {
2546 if (log)
2547 log->Printf("Couldn't fix the linkage for the function");
2548
2549 return false;
2550 }
2551
Sean Callananc7ca4662011-10-25 18:36:40 +00002552 if (log)
2553 {
2554 std::string s;
2555 raw_string_ostream oss(s);
2556
2557 m_module->print(oss, NULL);
2558
2559 oss.flush();
2560
2561 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2562 }
2563
Sean Callanan9b6898f2011-07-30 02:42:06 +00002564 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00002565
2566 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2567 intptr_ty,
2568 false /* isConstant */,
2569 GlobalVariable::InternalLinkage,
2570 Constant::getNullValue(intptr_ty),
2571 "reloc_placeholder",
2572 NULL /* InsertBefore */,
2573 false /* ThreadLocal */,
2574 0 /* AddressSpace */);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002575
Sean Callanan02fbafa2010-07-27 21:39:39 +00002576 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002577
Sean Callananc0492742011-05-23 21:40:23 +00002578 m_has_side_effects = HasSideEffects(*function);
Sean Callanan05a5a1b2010-12-16 03:17:46 +00002579
Sean Callanan82b74c82010-08-12 01:56:52 +00002580 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00002581 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00002582 //
2583
Sean Callananc0492742011-05-23 21:40:23 +00002584 if (!CreateResultVariable(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002585 {
2586 if (log)
2587 log->Printf("CreateResultVariable() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002588
2589 // CreateResultVariable() reports its own errors, so we don't do so here
2590
Sean Callanan82b74c82010-08-12 01:56:52 +00002591 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002592 }
Sean Callanan47dc4572011-09-15 02:13:07 +00002593
2594 if (m_const_result && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2595 {
2596 m_interpret_success = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +00002597 return true;
Sean Callanan47dc4572011-09-15 02:13:07 +00002598 }
2599
2600 for (bbi = function->begin();
2601 bbi != function->end();
2602 ++bbi)
2603 {
2604 if (!RemoveGuards(*bbi))
2605 {
2606 if (log)
2607 log->Printf("RemoveGuards() failed");
2608
2609 // RemoveGuards() reports its own errors, so we don't do so here
2610
2611 return false;
2612 }
2613
2614 if (!RewritePersistentAllocs(*bbi))
2615 {
2616 if (log)
2617 log->Printf("RewritePersistentAllocs() failed");
2618
2619 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2620
2621 return false;
2622 }
2623 }
2624
2625 if (m_decl_map && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2626 {
2627 IRInterpreter interpreter (*m_decl_map,
2628 m_error_stream);
2629
2630 if (interpreter.maybeRunOnFunction(m_const_result, m_result_name, m_result_type, *function, llvm_module))
2631 {
2632 m_interpret_success = true;
2633 return true;
2634 }
2635 }
Sean Callanan696cf5f2011-05-07 01:06:41 +00002636
Sean Callanan7b8eb762011-11-01 17:33:54 +00002637 if (log && log->GetVerbose())
Sean Callananc0492742011-05-23 21:40:23 +00002638 {
2639 std::string s;
2640 raw_string_ostream oss(s);
2641
2642 m_module->print(oss, NULL);
2643
2644 oss.flush();
2645
2646 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2647 }
2648
Sean Callanan6ba533e2010-11-17 23:00:36 +00002649 ///////////////////////////////////////////////////////////////////////////////
2650 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2651 //
Sean Callanan6ba533e2010-11-17 23:00:36 +00002652
Sean Callananc0492742011-05-23 21:40:23 +00002653 if (!RewriteObjCConstStrings(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002654 {
2655 if (log)
2656 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002657
2658 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2659
Sean Callanan6ba533e2010-11-17 23:00:36 +00002660 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002661 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00002662
Sean Callanan5c9a3c72011-08-04 21:37:47 +00002663 ///////////////////////////////
2664 // Resolve function pointers
2665 //
2666
2667 if (!ResolveFunctionPointers(llvm_module, *function))
2668 {
2669 if (log)
2670 log->Printf("ResolveFunctionPointers() failed");
2671
2672 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2673
2674 return false;
2675 }
2676
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002677 for (bbi = function->begin();
2678 bbi != function->end();
2679 ++bbi)
2680 {
Sean Callananc0492742011-05-23 21:40:23 +00002681 if (!RewriteObjCSelectors(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002682 {
2683 if (log)
2684 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002685
2686 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2687
Sean Callanana48fe162010-08-11 03:57:18 +00002688 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002689 }
Sean Callanana48fe162010-08-11 03:57:18 +00002690
Sean Callananc0492742011-05-23 21:40:23 +00002691 if (!ResolveCalls(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002692 {
2693 if (log)
2694 log->Printf("ResolveCalls() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002695
2696 // ResolveCalls() reports its own errors, so we don't do so here
2697
Sean Callanan8bce6652010-07-13 21:41:46 +00002698 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002699 }
Sean Callananc0492742011-05-23 21:40:23 +00002700
2701 if (!ReplaceStaticLiterals(*bbi))
2702 {
2703 if (log)
2704 log->Printf("ReplaceStaticLiterals() failed");
2705
2706 return false;
2707 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002708 }
2709
Sean Callanan771131d2010-09-30 21:18:25 +00002710 ///////////////////////////////
2711 // Run function-level passes
2712 //
2713
Sean Callananc0492742011-05-23 21:40:23 +00002714 if (!ResolveExternals(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002715 {
2716 if (log)
2717 log->Printf("ResolveExternals() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002718
2719 // ResolveExternals() reports its own errors, so we don't do so here
2720
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002721 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002722 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002723
Sean Callananc0492742011-05-23 21:40:23 +00002724 if (!ReplaceVariables(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002725 {
2726 if (log)
2727 log->Printf("ReplaceVariables() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002728
2729 // ReplaceVariables() reports its own errors, so we don't do so here
2730
Sean Callanan771131d2010-09-30 21:18:25 +00002731 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002732 }
Sean Callanan771131d2010-09-30 21:18:25 +00002733
Sean Callananc0492742011-05-23 21:40:23 +00002734 if (!ReplaceStrings())
2735 {
2736 if (log)
2737 log->Printf("ReplaceStrings() failed");
2738
2739 return false;
2740 }
2741
2742 if (!CompleteDataAllocation())
2743 {
2744 if (log)
2745 log->Printf("CompleteDataAllocation() failed");
2746
2747 return false;
2748 }
2749
Sean Callanan7b8eb762011-11-01 17:33:54 +00002750 if (log && log->GetVerbose())
Sean Callanan8bce6652010-07-13 21:41:46 +00002751 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00002752 std::string s;
2753 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00002754
Sean Callananc0492742011-05-23 21:40:23 +00002755 m_module->print(oss, NULL);
Sean Callanan321fe9e2010-07-28 01:00:59 +00002756
2757 oss.flush();
2758
Greg Claytonb5037af2010-11-15 01:47:11 +00002759 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002760 }
2761
2762 return true;
2763}
2764
2765void
Greg Clayton3c7feb42010-11-19 01:05:25 +00002766IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002767{
2768}
2769
2770PassManagerType
2771IRForTarget::getPotentialPassManagerType() const
2772{
2773 return PMT_ModulePassManager;
2774}