blob: 029d4f52482483bca0e7f7c563e2f0bc915c613d [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;
208 }
209
210 if (log && name)
211 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
212 }
213 else
214 {
215 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
216 }
217
218 // Find the address of the function.
219
220 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000221
222 if (fun_decl)
223 {
Sean Callananc7ca4662011-10-25 18:36:40 +0000224 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000225 {
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000226 lldb_private::ConstString alternate_mangling_const_str;
227 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
228 if (!found_it)
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000229 {
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000230 // Check for an alternate mangling for "std::basic_string<char>"
231 // that is part of the itanium C++ name mangling scheme
232 const char *name_cstr = name.GetCString();
233 if (strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
234 {
235 std::string alternate_mangling("_ZNKSs");
236 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
237 alternate_mangling_const_str.SetCString(alternate_mangling.c_str());
238 found_it = m_decl_map->GetFunctionAddress (alternate_mangling_const_str, fun_addr);
239 }
240 }
241
242 if (!found_it)
243 {
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000244 if (log)
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000245 {
246 if (alternate_mangling_const_str)
247 log->Printf("Function \"%s\" (alternate name \"%s\") has no address", name.GetCString(), alternate_mangling_const_str.GetCString());
248 else
249 log->Printf("Function \"%s\" had no address", name.GetCString());
250 }
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000251
252 if (m_error_stream)
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000253 {
254 if (alternate_mangling_const_str)
255 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());
256 else
257 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n", name.GetCString());
258 }
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000259 return false;
260 }
261 }
262 }
263 else
264 {
265 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
266 {
267 if (log)
268 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
269
270 if (m_error_stream)
271 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
272
273 return false;
274 }
275 }
276
277 if (log)
278 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), fun_addr);
279
280 return true;
281}
282
283llvm::Constant *
284IRForTarget::BuildFunctionPointer (llvm::Type *type,
285 uint64_t ptr)
286{
287 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
288 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
289 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
290 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
291 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
292}
293
Sean Callanan715f6b02011-10-31 22:11:40 +0000294void
295IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
296 llvm::Value *function_ptr,
297 const char *name)
298{
299 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
300
301 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
302 i != e;
303 ++i)
304 {
305 Value *user = *i;
306
307 if (Instruction *user_inst = dyn_cast<Instruction>(user))
308 {
309 Constant *name_array = ConstantArray::get(context, StringRef(name));
310
311 ArrayRef<Value *> md_values(name_array);
312
313 MDNode *metadata = MDNode::get(context, md_values);
314
315 user_inst->setMetadata("lldb.call.realName", metadata);
316 }
317 else
318 {
319 RegisterFunctionMetadata (context, user, name);
320 }
321 }
322}
323
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000324bool
325IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module,
326 llvm::Function &llvm_function)
327{
328 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
329
330 for (llvm::Module::iterator fi = llvm_module.begin();
331 fi != llvm_module.end();
332 ++fi)
333 {
334 Function *fun = fi;
335
336 bool is_decl = fun->isDeclaration();
337
338 if (log)
339 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getNameStr().c_str());
340
341 if (!is_decl)
342 continue;
343
344 if (fun->hasNUses(0))
345 continue; // ignore
346
347 uint64_t addr = LLDB_INVALID_ADDRESS;
348 lldb_private::ConstString name;
349 Constant **value_ptr = NULL;
350
351 if (!GetFunctionAddress(fun,
352 addr,
353 name,
354 value_ptr))
355 return false; // GetFunctionAddress reports its own errors
356
357 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
358
Sean Callanan715f6b02011-10-31 22:11:40 +0000359 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
360
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000361 if (value_ptr)
362 *value_ptr = value;
363
364 fun->replaceAllUsesWith(value);
365 }
366
367 return true;
368}
369
Sean Callanan47dc4572011-09-15 02:13:07 +0000370
Sean Callanan696cf5f2011-05-07 01:06:41 +0000371clang::NamedDecl *
Sean Callanan47dc4572011-09-15 02:13:07 +0000372IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000373{
374 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
375
Sean Callanan47dc4572011-09-15 02:13:07 +0000376 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan696cf5f2011-05-07 01:06:41 +0000377
378 if (!named_metadata)
379 return NULL;
380
381 unsigned num_nodes = named_metadata->getNumOperands();
382 unsigned node_index;
383
384 for (node_index = 0;
385 node_index < num_nodes;
386 ++node_index)
387 {
388 MDNode *metadata_node = named_metadata->getOperand(node_index);
389
390 if (!metadata_node)
391 return NULL;
392
393 if (metadata_node->getNumOperands() != 2)
394 continue;
395
396 if (metadata_node->getOperand(0) != global_val)
397 continue;
398
399 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
400
401 if (!constant_int)
402 return NULL;
403
404 uintptr_t ptr = constant_int->getZExtValue();
405
406 return reinterpret_cast<clang::NamedDecl *>(ptr);
407 }
408
409 return NULL;
410}
411
Sean Callanan47dc4572011-09-15 02:13:07 +0000412clang::NamedDecl *
413IRForTarget::DeclForGlobal (GlobalValue *global_val)
414{
415 return DeclForGlobal(global_val, m_module);
416}
417
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000418void
419IRForTarget::MaybeSetConstantResult (llvm::Constant *initializer,
420 const lldb_private::ConstString &name,
421 lldb_private::TypeFromParser type)
422{
Sean Callanan696cf5f2011-05-07 01:06:41 +0000423 if (llvm::ConstantExpr *init_expr = dyn_cast<llvm::ConstantExpr>(initializer))
424 {
425 switch (init_expr->getOpcode())
426 {
427 default:
428 return;
429 case Instruction::IntToPtr:
430 MaybeSetConstantResult (init_expr->getOperand(0), name, type);
431 return;
432 }
433 }
434 else if (llvm::ConstantInt *init_int = dyn_cast<llvm::ConstantInt>(initializer))
435 {
436 m_const_result = m_decl_map->BuildIntegerVariable(name, type, init_int->getValue());
437 }
438}
439
440void
Sean Callananc0492742011-05-23 21:40:23 +0000441IRForTarget::MaybeSetCastResult (lldb_private::TypeFromParser type)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000442{
443 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
444
445 if (!m_result_store)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000446 return;
447
Sean Callanan696cf5f2011-05-07 01:06:41 +0000448 LoadInst *original_load = NULL;
449
450 for (llvm::Value *current_value = m_result_store->getValueOperand(), *next_value;
451 current_value != NULL;
452 current_value = next_value)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000453 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000454 CastInst *cast_inst = dyn_cast<CastInst>(current_value);
455 LoadInst *load_inst = dyn_cast<LoadInst>(current_value);
456
457 if (cast_inst)
458 {
459 next_value = cast_inst->getOperand(0);
460 }
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000461 else if (load_inst)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000462 {
463 if (isa<LoadInst>(load_inst->getPointerOperand()))
464 {
465 next_value = load_inst->getPointerOperand();
466 }
467 else
468 {
469 original_load = load_inst;
470 break;
471 }
472 }
473 else
474 {
475 return;
476 }
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000477 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000478
479 Value *loaded_value = original_load->getPointerOperand();
480 GlobalVariable *loaded_global = dyn_cast<GlobalVariable>(loaded_value);
481
482 if (!loaded_global)
483 return;
484
Sean Callananc0492742011-05-23 21:40:23 +0000485 clang::NamedDecl *loaded_decl = DeclForGlobal(loaded_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000486
487 if (!loaded_decl)
488 return;
489
490 clang::VarDecl *loaded_var = dyn_cast<clang::VarDecl>(loaded_decl);
491
492 if (!loaded_var)
493 return;
494
495 if (log)
496 {
497 lldb_private::StreamString type_desc_stream;
498 type.DumpTypeDescription(&type_desc_stream);
499
500 log->Printf("Type to cast variable to: \"%s\"", type_desc_stream.GetString().c_str());
501 }
502
503 m_const_result = m_decl_map->BuildCastVariable(m_result_name, loaded_var, type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000504}
505
506bool
Sean Callananc0492742011-05-23 21:40:23 +0000507IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanan82b74c82010-08-12 01:56:52 +0000508{
Greg Claytone005f2c2010-11-06 01:53:30 +0000509 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan82b74c82010-08-12 01:56:52 +0000510
Sean Callanane8a59a82010-09-13 21:34:21 +0000511 if (!m_resolve_vars)
512 return true;
513
514 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000515
Sean Callananc0492742011-05-23 21:40:23 +0000516 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000517
Sean Callanan9b6898f2011-07-30 02:42:06 +0000518 std::string result_name_str;
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000519 const char *result_name = NULL;
520
521 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
522 vi != ve;
523 ++vi)
524 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000525 result_name_str = vi->first().str();
526 const char *value_name = result_name_str.c_str();
527
528 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
529 !strstr(value_name, "GV"))
Sean Callanan6a925532011-01-13 08:53:35 +0000530 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000531 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000532 m_result_is_pointer = true;
533 break;
534 }
535
Sean Callanan9b6898f2011-07-30 02:42:06 +0000536 if (strstr(value_name, "$__lldb_expr_result") &&
537 !strstr(value_name, "GV"))
Sean Callananc04743d2010-09-28 21:13:03 +0000538 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000539 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000540 m_result_is_pointer = false;
Sean Callananc04743d2010-09-28 21:13:03 +0000541 break;
542 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000543 }
544
545 if (!result_name)
546 {
547 if (log)
548 log->PutCString("Couldn't find result variable");
549
550 return true;
551 }
552
Sean Callananc04743d2010-09-28 21:13:03 +0000553 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000554 log->Printf("Result name: \"%s\"", result_name);
Sean Callananc04743d2010-09-28 21:13:03 +0000555
Sean Callananc0492742011-05-23 21:40:23 +0000556 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000557
558 if (!result_value)
559 {
560 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000561 log->PutCString("Result variable had no data");
Sean Callanan6a925532011-01-13 08:53:35 +0000562
Sean Callanan97c924e2011-01-27 01:07:04 +0000563 if (m_error_stream)
564 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
565
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000566 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000567 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000568
Sean Callanan82b74c82010-08-12 01:56:52 +0000569 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000570 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000571
572 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
573
574 if (!result_global)
575 {
576 if (log)
577 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000578
579 if (m_error_stream)
580 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
581
Sean Callanan82b74c82010-08-12 01:56:52 +0000582 return false;
583 }
584
Sean Callananc0492742011-05-23 21:40:23 +0000585 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000586 if (!result_decl)
Sean Callanan82b74c82010-08-12 01:56:52 +0000587 {
588 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000589 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanan82b74c82010-08-12 01:56:52 +0000590
Sean Callanan97c924e2011-01-27 01:07:04 +0000591 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000592 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 +0000593
Sean Callanan82b74c82010-08-12 01:56:52 +0000594 return false;
595 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000596
Sean Callanan696cf5f2011-05-07 01:06:41 +0000597 if (log)
Sean Callanan82b74c82010-08-12 01:56:52 +0000598 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000599 std::string decl_desc_str;
600 raw_string_ostream decl_desc_stream(decl_desc_str);
601 result_decl->print(decl_desc_stream);
602 decl_desc_stream.flush();
Sean Callanan82b74c82010-08-12 01:56:52 +0000603
Sean Callanan696cf5f2011-05-07 01:06:41 +0000604 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000605 }
606
Sean Callanan696cf5f2011-05-07 01:06:41 +0000607 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
608 if (!result_var)
Sean Callanan82b74c82010-08-12 01:56:52 +0000609 {
610 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000611 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan97c924e2011-01-27 01:07:04 +0000612
613 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000614 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 +0000615
Sean Callanan82b74c82010-08-12 01:56:52 +0000616 return false;
617 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000618
Sean Callanan82b74c82010-08-12 01:56:52 +0000619 // Get the next available result name from m_decl_map and create the persistent
620 // variable for it
Sean Callanan47dc4572011-09-15 02:13:07 +0000621
Sean Callanan696cf5f2011-05-07 01:06:41 +0000622 // If the result is an Lvalue, it is emitted as a pointer; see
623 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan6a925532011-01-13 08:53:35 +0000624 if (m_result_is_pointer)
625 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000626 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanand5b3c352011-01-27 04:42:51 +0000627 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
628 const clang::PointerType *pointer_pointertype = dyn_cast<clang::PointerType>(pointer_type);
Sean Callanan6a925532011-01-13 08:53:35 +0000629
630 if (!pointer_pointertype)
631 {
632 if (log)
633 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan97c924e2011-01-27 01:07:04 +0000634
635 if (m_error_stream)
636 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
637
Sean Callanan6a925532011-01-13 08:53:35 +0000638 return false;
639 }
640
641 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
642
Sean Callanan47dc4572011-09-15 02:13:07 +0000643 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
Sean Callanan6a925532011-01-13 08:53:35 +0000644 &result_decl->getASTContext());
645 }
646 else
647 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000648 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan6a925532011-01-13 08:53:35 +0000649 &result_decl->getASTContext());
650 }
651
Sean Callanan696cf5f2011-05-07 01:06:41 +0000652 if (log)
653 {
654 lldb_private::StreamString type_desc_stream;
Sean Callanan47dc4572011-09-15 02:13:07 +0000655 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000656
657 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetString().c_str());
658 }
659
Sean Callanan6a925532011-01-13 08:53:35 +0000660 m_result_name = m_decl_map->GetPersistentResultName();
Sean Callanan82b74c82010-08-12 01:56:52 +0000661
662 if (log)
Sean Callanan6a925532011-01-13 08:53:35 +0000663 log->Printf("Creating a new result global: \"%s\"", m_result_name.GetCString());
Sean Callanan82b74c82010-08-12 01:56:52 +0000664
665 // Construct a new result global and set up its metadata
666
Sean Callananc0492742011-05-23 21:40:23 +0000667 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanan82b74c82010-08-12 01:56:52 +0000668 result_global->getType()->getElementType(),
669 false, /* not constant */
670 GlobalValue::ExternalLinkage,
671 NULL, /* no initializer */
Sean Callanan6a925532011-01-13 08:53:35 +0000672 m_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000673
674 // It's too late in compilation to create a new VarDecl for this, but we don't
675 // need to. We point the metadata at the old VarDecl. This creates an odd
676 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000677 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000678 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
679 // fixed up.
680
Sean Callananc0492742011-05-23 21:40:23 +0000681 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan696cf5f2011-05-07 01:06:41 +0000682 reinterpret_cast<uint64_t>(result_decl),
Sean Callanan82b74c82010-08-12 01:56:52 +0000683 false);
684
685 llvm::Value* values[2];
686 values[0] = new_result_global;
687 values[1] = new_constant_int;
688
Sean Callanan0de254a2011-05-15 22:34:38 +0000689 ArrayRef<Value*> value_ref(values, 2);
690
Sean Callananc0492742011-05-23 21:40:23 +0000691 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
692 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000693 named_metadata->addOperand(persistent_global_md);
694
695 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000696 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000697 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000698 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000699
700 if (result_global->hasNUses(0))
701 {
702 // We need to synthesize a store for this variable, because otherwise
703 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000704
Greg Clayton8de27c72010-10-15 22:48:33 +0000705 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000706 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
707
708 if (!first_entry_instruction)
709 return false;
710
711 if (!result_global->hasInitializer())
712 {
713 if (log)
714 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000715
716 if (m_error_stream)
717 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
718
Sean Callanan2e2db532010-09-07 22:43:19 +0000719 return false;
720 }
721
722 Constant *initializer = result_global->getInitializer();
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000723
724 // Here we write the initializer into a result variable assuming it
725 // can be computed statically.
726
727 if (!m_has_side_effects)
728 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000729 //MaybeSetConstantResult (initializer,
730 // m_result_name,
731 // m_result_type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000732 }
Sean Callanan2e2db532010-09-07 22:43:19 +0000733
Greg Clayton2c344ca2011-02-05 02:28:58 +0000734 StoreInst *synthesized_store = new StoreInst(initializer,
735 new_result_global,
736 first_entry_instruction);
Sean Callanan2e2db532010-09-07 22:43:19 +0000737
738 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000739 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000740 }
741 else
742 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000743 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (m_result_type.GetOpaqueQualType()))
Sean Callanan696cf5f2011-05-07 01:06:41 +0000744 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000745 //MaybeSetCastResult (m_result_type);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000746 }
747
Sean Callanan2e2db532010-09-07 22:43:19 +0000748 result_global->replaceAllUsesWith(new_result_global);
749 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000750
751 if (!m_const_result)
752 m_decl_map->AddPersistentVariable(result_decl,
753 m_result_name,
Sean Callanan47dc4572011-09-15 02:13:07 +0000754 m_result_type,
Sean Callanan696cf5f2011-05-07 01:06:41 +0000755 true,
756 m_result_is_pointer);
Sean Callanan2e2db532010-09-07 22:43:19 +0000757
Sean Callanan82b74c82010-08-12 01:56:52 +0000758 result_global->eraseFromParent();
759
760 return true;
761}
762
Johnny Chen58021cc2011-08-09 23:10:20 +0000763#if 0
Greg Clayton3c7feb42010-11-19 01:05:25 +0000764static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000765{
766 if (!depth)
767 return;
768
769 depth--;
770
Johnny Chen58021cc2011-08-09 23:10:20 +0000771 if (log)
772 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000773
Greg Clayton3c7feb42010-11-19 01:05:25 +0000774 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000775 ui != ue;
776 ++ui)
777 {
Johnny Chen58021cc2011-08-09 23:10:20 +0000778 if (log)
779 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000780 DebugUsers(log, *ui, depth);
781 }
782
Johnny Chen58021cc2011-08-09 23:10:20 +0000783 if (log)
784 log->Printf(" <End uses>");
Sean Callanan6ba533e2010-11-17 23:00:36 +0000785}
Johnny Chen58021cc2011-08-09 23:10:20 +0000786#endif
Sean Callanan6ba533e2010-11-17 23:00:36 +0000787
788bool
Sean Callananc0492742011-05-23 21:40:23 +0000789IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton3c7feb42010-11-19 01:05:25 +0000790 llvm::GlobalVariable *cstr,
791 Instruction *FirstEntryInstruction)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000792{
793 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
794
Sean Callanan9b6898f2011-07-30 02:42:06 +0000795 Type *ns_str_ty = ns_str->getType();
Sean Callananc0492742011-05-23 21:40:23 +0000796
Sean Callanan9b6898f2011-07-30 02:42:06 +0000797 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
798 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callananc0492742011-05-23 21:40:23 +0000799 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan9b6898f2011-07-30 02:42:06 +0000800 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
801 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000802
803 if (!m_CFStringCreateWithBytes)
804 {
805 lldb::addr_t CFStringCreateWithBytes_addr;
806
807 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
808
809 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
810 {
811 if (log)
812 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
813
Sean Callanan97c924e2011-01-27 01:07:04 +0000814 if (m_error_stream)
815 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
816
Sean Callanan6ba533e2010-11-17 23:00:36 +0000817 return false;
818 }
819
820 if (log)
821 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr);
822
823 // Build the function type:
824 //
825 // CFStringRef CFStringCreateWithBytes (
826 // CFAllocatorRef alloc,
827 // const UInt8 *bytes,
828 // CFIndex numBytes,
829 // CFStringEncoding encoding,
830 // Boolean isExternalRepresentation
831 // );
832 //
833 // We make the following substitutions:
834 //
835 // CFStringRef -> i8*
836 // CFAllocatorRef -> i8*
837 // UInt8 * -> i8*
838 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
839 // CFStringEncoding -> i32
840 // Boolean -> i8
841
Sean Callanan9b6898f2011-07-30 02:42:06 +0000842 Type *arg_type_array[5];
843
844 arg_type_array[0] = i8_ptr_ty;
845 arg_type_array[1] = i8_ptr_ty;
846 arg_type_array[2] = intptr_ty;
847 arg_type_array[3] = i32_ty;
848 arg_type_array[4] = i8_ty;
849
850 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
851
Sean Callananc0492742011-05-23 21:40:23 +0000852 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000853
854 // Build the constant containing the pointer to the function
855 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
856 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
857 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
858 }
859
Sean Callanan58baaad2011-07-08 00:39:14 +0000860 ConstantArray *string_array = NULL;
Sean Callanan0ece5262011-02-10 22:17:53 +0000861
862 if (cstr)
863 string_array = dyn_cast<ConstantArray>(cstr->getInitializer());
Sean Callanan9b6898f2011-07-30 02:42:06 +0000864
Sean Callanan6ba533e2010-11-17 23:00:36 +0000865 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan0ece5262011-02-10 22:17:53 +0000866 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
867 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getType()->getNumElements() - 1 : 0, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000868 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
869 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
870
Sean Callanan9b6898f2011-07-30 02:42:06 +0000871 Value *argument_array[5];
872
873 argument_array[0] = alloc_arg;
874 argument_array[1] = bytes_arg;
875 argument_array[2] = numBytes_arg;
876 argument_array[3] = encoding_arg;
877 argument_array[4] = isExternal_arg;
878
879 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000880
881 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanan9b6898f2011-07-30 02:42:06 +0000882 CFSCWB_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +0000883 "CFStringCreateWithBytes",
884 FirstEntryInstruction);
Sean Callananae71e302010-11-18 22:21:58 +0000885
Greg Clayton3c7feb42010-11-19 01:05:25 +0000886 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000887 {
888 if (log)
889 log->PutCString("Couldn't replace the NSString with the result of the call");
890
Sean Callanan97c924e2011-01-27 01:07:04 +0000891 if (m_error_stream)
892 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
893
Sean Callanan6ba533e2010-11-17 23:00:36 +0000894 return false;
895 }
896
Greg Clayton3c7feb42010-11-19 01:05:25 +0000897 ns_str->eraseFromParent();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000898
899 return true;
900}
901
902bool
Sean Callananc0492742011-05-23 21:40:23 +0000903IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000904{
905 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
906
Sean Callananc0492742011-05-23 21:40:23 +0000907 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000908
Greg Clayton3c7feb42010-11-19 01:05:25 +0000909 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000910 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
911
912 if (!FirstEntryInstruction)
913 {
914 if (log)
915 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
916
Sean Callanan97c924e2011-01-27 01:07:04 +0000917 if (m_error_stream)
918 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
919
Sean Callanan6ba533e2010-11-17 23:00:36 +0000920 return false;
921 }
922
923 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
924 vi != ve;
925 ++vi)
926 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000927 std::string value_name = vi->first().str();
928 const char *value_name_cstr = value_name.c_str();
929
930 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000931 {
932 Value *nsstring_value = vi->second;
933
934 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
935
936 if (!nsstring_global)
937 {
938 if (log)
939 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000940
941 if (m_error_stream)
942 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
943
Sean Callanan6ba533e2010-11-17 23:00:36 +0000944 return false;
945 }
946
947 if (!nsstring_global->hasInitializer())
948 {
949 if (log)
950 log->PutCString("NSString variable does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000951
952 if (m_error_stream)
953 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
954
Sean Callanan6ba533e2010-11-17 23:00:36 +0000955 return false;
956 }
957
958 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
959
960 if (!nsstring_struct)
961 {
962 if (log)
963 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan97c924e2011-01-27 01:07:04 +0000964
965 if (m_error_stream)
966 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
967
Sean Callanan6ba533e2010-11-17 23:00:36 +0000968 return false;
969 }
970
971 // We expect the following structure:
972 //
973 // struct {
974 // int *isa;
975 // int flags;
976 // char *str;
977 // long length;
978 // };
979
980 if (nsstring_struct->getNumOperands() != 4)
981 {
982 if (log)
983 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 +0000984
985 if (m_error_stream)
986 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
987
Sean Callanan6ba533e2010-11-17 23:00:36 +0000988 return false;
989 }
990
991 Constant *nsstring_member = nsstring_struct->getOperand(2);
992
993 if (!nsstring_member)
994 {
995 if (log)
996 log->PutCString("NSString initializer's str element was empty");
Sean Callanan97c924e2011-01-27 01:07:04 +0000997
998 if (m_error_stream)
999 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
1000
Sean Callanan6ba533e2010-11-17 23:00:36 +00001001 return false;
1002 }
1003
1004 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
1005
1006 if (!nsstring_expr)
1007 {
1008 if (log)
1009 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan97c924e2011-01-27 01:07:04 +00001010
1011 if (m_error_stream)
1012 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
1013
Sean Callanan6ba533e2010-11-17 23:00:36 +00001014 return false;
1015 }
1016
1017 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
1018 {
1019 if (log)
1020 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 +00001021
1022 if (m_error_stream)
1023 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
1024
Sean Callanan6ba533e2010-11-17 23:00:36 +00001025 return false;
1026 }
1027
1028 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
1029
1030 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
1031
1032 if (!cstr_global)
1033 {
1034 if (log)
1035 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001036
1037 if (m_error_stream)
1038 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 +00001039
Sean Callanan6ba533e2010-11-17 23:00:36 +00001040 return false;
1041 }
1042
1043 if (!cstr_global->hasInitializer())
1044 {
1045 if (log)
1046 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +00001047
1048 if (m_error_stream)
1049 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
1050
Sean Callanan6ba533e2010-11-17 23:00:36 +00001051 return false;
1052 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001053
1054 /*
Sean Callanan6ba533e2010-11-17 23:00:36 +00001055 if (!cstr_array)
1056 {
1057 if (log)
1058 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan97c924e2011-01-27 01:07:04 +00001059
1060 if (m_error_stream)
1061 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
1062
Sean Callanan6ba533e2010-11-17 23:00:36 +00001063 return false;
1064 }
1065
1066 if (!cstr_array->isCString())
1067 {
1068 if (log)
1069 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan97c924e2011-01-27 01:07:04 +00001070
1071 if (m_error_stream)
1072 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
1073
Sean Callanan6ba533e2010-11-17 23:00:36 +00001074 return false;
1075 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001076 */
1077
1078 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer());
Sean Callanan6ba533e2010-11-17 23:00:36 +00001079
1080 if (log)
Sean Callanan0ece5262011-02-10 22:17:53 +00001081 {
1082 if (cstr_array)
Sean Callanan9b6898f2011-07-30 02:42:06 +00001083 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().c_str());
Sean Callanan0ece5262011-02-10 22:17:53 +00001084 else
Sean Callanan9b6898f2011-07-30 02:42:06 +00001085 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan0ece5262011-02-10 22:17:53 +00001086 }
1087
1088 if (!cstr_array)
1089 cstr_global = NULL;
Sean Callanan6ba533e2010-11-17 23:00:36 +00001090
Sean Callananc0492742011-05-23 21:40:23 +00001091 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan97c924e2011-01-27 01:07:04 +00001092 {
Sean Callanan6ba533e2010-11-17 23:00:36 +00001093 if (log)
1094 log->PutCString("Error rewriting the constant string");
Sean Callanan97c924e2011-01-27 01:07:04 +00001095
1096 // We don't print an error message here because RewriteObjCConstString has done so for us.
1097
Sean Callanan6ba533e2010-11-17 23:00:36 +00001098 return false;
1099 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00001100 }
1101 }
1102
1103 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1104 vi != ve;
1105 ++vi)
1106 {
Sean Callanan9b6898f2011-07-30 02:42:06 +00001107 std::string value_name = vi->first().str();
1108 const char *value_name_cstr = value_name.c_str();
1109
1110 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callanan6ba533e2010-11-17 23:00:36 +00001111 {
1112 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1113
1114 if (!gv)
1115 {
1116 if (log)
1117 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001118
1119 if (m_error_stream)
1120 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1121
Sean Callanan6ba533e2010-11-17 23:00:36 +00001122 return false;
1123 }
1124
1125 gv->eraseFromParent();
1126
1127 break;
1128 }
1129 }
1130
1131 return true;
1132}
1133
Greg Clayton3c7feb42010-11-19 01:05:25 +00001134static bool IsObjCSelectorRef (Value *value)
Sean Callananf5857a02010-07-31 01:32:05 +00001135{
Greg Clayton3c7feb42010-11-19 01:05:25 +00001136 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callananf5857a02010-07-31 01:32:05 +00001137
Greg Clayton3c7feb42010-11-19 01:05:25 +00001138 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callananf5857a02010-07-31 01:32:05 +00001139 return false;
1140
1141 return true;
1142}
1143
Sean Callanan97c924e2011-01-27 01:07:04 +00001144// This function does not report errors; its callers are responsible.
Sean Callananf5857a02010-07-31 01:32:05 +00001145bool
Sean Callananc0492742011-05-23 21:40:23 +00001146IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callananf5857a02010-07-31 01:32:05 +00001147{
Greg Claytone005f2c2010-11-06 01:53:30 +00001148 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001149
1150 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1151
1152 if (!load)
1153 return false;
1154
1155 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1156 //
1157 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1158 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1159 //
1160 // where %obj is the object pointer and %tmp is the selector.
1161 //
Greg Clayton3c7feb42010-11-19 01:05:25 +00001162 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1163 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callananf5857a02010-07-31 01:32:05 +00001164
1165 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1166
1167 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1168
1169 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1170 return false;
1171
1172 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1173
1174 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1175
1176 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1177 return false;
1178
1179 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1180
1181 if (!osr_initializer_base)
1182 return false;
1183
1184 // Find the string's initializer (a ConstantArray) and get the string from it
1185
1186 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1187
1188 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1189 return false;
1190
1191 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1192
1193 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
1194
1195 if (!omvn_initializer_array->isString())
1196 return false;
1197
1198 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1199
1200 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001201 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +00001202
1203 // Construct a call to sel_registerName
1204
1205 if (!m_sel_registerName)
1206 {
Greg Claytonb5037af2010-11-15 01:47:11 +00001207 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +00001208
Greg Clayton8de27c72010-10-15 22:48:33 +00001209 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +00001210 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001211 return false;
1212
Sean Callananc2c6f772010-10-26 00:31:56 +00001213 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001214 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +00001215
Sean Callananf5857a02010-07-31 01:32:05 +00001216 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1217
1218 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callananc0492742011-05-23 21:40:23 +00001219 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001220 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanan9b6898f2011-07-30 02:42:06 +00001221 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001222
Sean Callanan9b6898f2011-07-30 02:42:06 +00001223 Type *type_array[1];
1224
1225 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1226
1227 ArrayRef<Type *> srN_arg_types(type_array, 1);
1228
Sean Callananf5857a02010-07-31 01:32:05 +00001229 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1230
1231 // Build the constant containing the pointer to the function
Sean Callanan9b6898f2011-07-30 02:42:06 +00001232 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1233 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananf5857a02010-07-31 01:32:05 +00001234 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +00001235 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001236 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1237 }
1238
Sean Callanan9b6898f2011-07-30 02:42:06 +00001239 Value *argument_array[1];
1240
Sean Callananc0492742011-05-23 21:40:23 +00001241 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callananf5857a02010-07-31 01:32:05 +00001242
Sean Callanan9b6898f2011-07-30 02:42:06 +00001243 argument_array[0] = omvn_pointer;
Sean Callananf5857a02010-07-31 01:32:05 +00001244
Sean Callanan9b6898f2011-07-30 02:42:06 +00001245 ArrayRef<Value *> srN_arguments(argument_array, 1);
1246
Sean Callananf5857a02010-07-31 01:32:05 +00001247 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanan9b6898f2011-07-30 02:42:06 +00001248 srN_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +00001249 "sel_registerName",
Sean Callananf5857a02010-07-31 01:32:05 +00001250 selector_load);
1251
1252 // Replace the load with the call in all users
1253
1254 selector_load->replaceAllUsesWith(srN_call);
1255
1256 selector_load->eraseFromParent();
1257
1258 return true;
1259}
1260
1261bool
Sean Callananc0492742011-05-23 21:40:23 +00001262IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callananf5857a02010-07-31 01:32:05 +00001263{
Greg Claytone005f2c2010-11-06 01:53:30 +00001264 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001265
1266 BasicBlock::iterator ii;
1267
1268 typedef SmallVector <Instruction*, 2> InstrList;
1269 typedef InstrList::iterator InstrIterator;
1270
1271 InstrList selector_loads;
1272
Greg Clayton3c7feb42010-11-19 01:05:25 +00001273 for (ii = basic_block.begin();
1274 ii != basic_block.end();
Sean Callananf5857a02010-07-31 01:32:05 +00001275 ++ii)
1276 {
1277 Instruction &inst = *ii;
1278
1279 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton3c7feb42010-11-19 01:05:25 +00001280 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callananf5857a02010-07-31 01:32:05 +00001281 selector_loads.push_back(&inst);
1282 }
1283
1284 InstrIterator iter;
1285
1286 for (iter = selector_loads.begin();
1287 iter != selector_loads.end();
1288 ++iter)
1289 {
Sean Callananc0492742011-05-23 21:40:23 +00001290 if (!RewriteObjCSelector(*iter))
Sean Callananf5857a02010-07-31 01:32:05 +00001291 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001292 if (m_error_stream)
1293 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1294
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001295 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +00001296 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan97c924e2011-01-27 01:07:04 +00001297
Sean Callananf5857a02010-07-31 01:32:05 +00001298 return false;
1299 }
1300 }
1301
1302 return true;
1303}
1304
Sean Callanan97c924e2011-01-27 01:07:04 +00001305// This function does not report errors; its callers are responsible.
Sean Callanana48fe162010-08-11 03:57:18 +00001306bool
Sean Callananc0492742011-05-23 21:40:23 +00001307IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanana48fe162010-08-11 03:57:18 +00001308{
Sean Callanan97678d12011-01-13 21:23:32 +00001309 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1310
Sean Callanana48fe162010-08-11 03:57:18 +00001311 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1312
1313 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1314
1315 if (!alloc_md || !alloc_md->getNumOperands())
1316 return false;
1317
1318 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1319
1320 if (!constant_int)
1321 return false;
1322
1323 // We attempt to register this as a new persistent variable with the DeclMap.
1324
1325 uintptr_t ptr = constant_int->getZExtValue();
1326
Sean Callanan82b74c82010-08-12 01:56:52 +00001327 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +00001328
Sean Callanan82b74c82010-08-12 01:56:52 +00001329 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1330 &decl->getASTContext());
1331
Greg Clayton8de27c72010-10-15 22:48:33 +00001332 StringRef decl_name (decl->getName());
1333 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan6a925532011-01-13 08:53:35 +00001334 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanana48fe162010-08-11 03:57:18 +00001335 return false;
1336
Sean Callananc0492742011-05-23 21:40:23 +00001337 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanan97678d12011-01-13 21:23:32 +00001338 alloc->getType(),
Sean Callanana48fe162010-08-11 03:57:18 +00001339 false, /* not constant */
1340 GlobalValue::ExternalLinkage,
1341 NULL, /* no initializer */
1342 alloc->getName().str().c_str());
1343
1344 // What we're going to do here is make believe this was a regular old external
1345 // variable. That means we need to make the metadata valid.
1346
Sean Callananc0492742011-05-23 21:40:23 +00001347 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +00001348
1349 llvm::Value* values[2];
1350 values[0] = persistent_global;
1351 values[1] = constant_int;
Sean Callanan0de254a2011-05-15 22:34:38 +00001352
1353 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +00001354
Sean Callananc0492742011-05-23 21:40:23 +00001355 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanana48fe162010-08-11 03:57:18 +00001356 named_metadata->addOperand(persistent_global_md);
1357
Sean Callanan97678d12011-01-13 21:23:32 +00001358 // Now, since the variable is a pointer variable, we will drop in a load of that
1359 // pointer variable.
1360
1361 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1362
1363 if (log)
1364 log->Printf("Replacing \"%s\" with \"%s\"",
1365 PrintValue(alloc).c_str(),
1366 PrintValue(persistent_load).c_str());
1367
1368 alloc->replaceAllUsesWith(persistent_load);
Sean Callanana48fe162010-08-11 03:57:18 +00001369 alloc->eraseFromParent();
1370
1371 return true;
1372}
1373
1374bool
Sean Callananc0492742011-05-23 21:40:23 +00001375IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanana48fe162010-08-11 03:57:18 +00001376{
Sean Callanane8a59a82010-09-13 21:34:21 +00001377 if (!m_resolve_vars)
1378 return true;
1379
Greg Claytone005f2c2010-11-06 01:53:30 +00001380 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +00001381
1382 BasicBlock::iterator ii;
1383
1384 typedef SmallVector <Instruction*, 2> InstrList;
1385 typedef InstrList::iterator InstrIterator;
1386
1387 InstrList pvar_allocs;
1388
Greg Clayton3c7feb42010-11-19 01:05:25 +00001389 for (ii = basic_block.begin();
1390 ii != basic_block.end();
Sean Callanana48fe162010-08-11 03:57:18 +00001391 ++ii)
1392 {
1393 Instruction &inst = *ii;
1394
1395 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan237e4742011-01-21 22:30:25 +00001396 {
1397 llvm::StringRef alloc_name = alloc->getName();
1398
1399 if (alloc_name.startswith("$") &&
1400 !alloc_name.startswith("$__lldb"))
1401 {
1402 if (alloc_name.find_first_of("0123456789") == 1)
1403 {
1404 if (log)
1405 log->Printf("Rejecting a numeric persistent variable.");
1406
Sean Callanan97c924e2011-01-27 01:07:04 +00001407 if (m_error_stream)
1408 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1409
Sean Callanan237e4742011-01-21 22:30:25 +00001410 return false;
1411 }
1412
Sean Callanana48fe162010-08-11 03:57:18 +00001413 pvar_allocs.push_back(alloc);
Sean Callanan237e4742011-01-21 22:30:25 +00001414 }
1415 }
Sean Callanana48fe162010-08-11 03:57:18 +00001416 }
1417
1418 InstrIterator iter;
1419
1420 for (iter = pvar_allocs.begin();
1421 iter != pvar_allocs.end();
1422 ++iter)
1423 {
Sean Callananc0492742011-05-23 21:40:23 +00001424 if (!RewritePersistentAlloc(*iter))
Sean Callanana48fe162010-08-11 03:57:18 +00001425 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001426 if (m_error_stream)
1427 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1428
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001429 if (log)
Sean Callanana48fe162010-08-11 03:57:18 +00001430 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001431
Sean Callanana48fe162010-08-11 03:57:18 +00001432 return false;
1433 }
1434 }
1435
1436 return true;
1437}
1438
Sean Callananc7ca4662011-10-25 18:36:40 +00001439bool
1440IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1441{
1442 if (!initializer)
1443 return true;
1444
1445 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1446
1447 if (log && log->GetVerbose())
1448 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1449
1450 Type *initializer_type = initializer->getType();
1451
1452 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1453 {
1454 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1455 return true;
1456 }
1457 else if (ConstantArray *array_initializer = dyn_cast<ConstantArray>(initializer))
1458 {
1459 if (array_initializer->isString())
1460 {
1461 std::string array_initializer_string = array_initializer->getAsString();
1462 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1463 }
1464 else
1465 {
1466 ArrayType *array_initializer_type = array_initializer->getType();
1467 Type *array_element_type = array_initializer_type->getElementType();
1468
1469 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1470
1471 for (int i = 0; i < array_initializer->getNumOperands(); ++i)
1472 {
1473 if (!MaterializeInitializer(data + (i * element_size), array_initializer->getOperand(i)))
1474 return false;
1475 }
1476 }
1477 return true;
1478 }
1479 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1480 {
1481 StructType *struct_initializer_type = struct_initializer->getType();
1482 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1483
1484 for (int i = 0;
1485 i < struct_initializer->getNumOperands();
1486 ++i)
1487 {
1488 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1489 return false;
1490 }
1491 return true;
1492 }
1493 return false;
1494}
1495
1496bool
1497IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1498{
1499 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1500 return false;
1501
1502 uint64_t offset = m_data_allocator->GetStream().GetSize();
1503
1504 llvm::Type *variable_type = global_variable->getType();
1505
1506 Constant *initializer = global_variable->getInitializer();
1507
1508 llvm::Type *initializer_type = initializer->getType();
1509
1510 size_t size = m_target_data->getTypeAllocSize(initializer_type);
1511
1512 lldb_private::DataBufferHeap data(size, '\0');
1513
1514 if (initializer)
1515 if (!MaterializeInitializer(data.GetBytes(), initializer))
1516 return false;
1517
1518 m_data_allocator->GetStream().Write(data.GetBytes(), data.GetByteSize());
1519
1520 Constant *new_pointer = BuildRelocation(variable_type, offset);
1521
1522 global_variable->replaceAllUsesWith(new_pointer);
1523
1524 global_variable->eraseFromParent();
1525
1526 return true;
1527}
1528
Sean Callanan97c924e2011-01-27 01:07:04 +00001529// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001530bool
Sean Callananc0492742011-05-23 21:40:23 +00001531IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001532{
Greg Claytone005f2c2010-11-06 01:53:30 +00001533 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan48443652010-12-02 19:47:57 +00001534
1535 if (log)
Sean Callananb9f09a62010-12-06 22:16:55 +00001536 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callanan9a877432011-08-01 17:41:38 +00001537
Greg Clayton8de27c72010-10-15 22:48:33 +00001538 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +00001539 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001540 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +00001541 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001542 default:
1543 break;
1544 case Instruction::GetElementPtr:
1545 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +00001546 Value *s = constant_expr->getOperand(0);
Sean Callananc0492742011-05-23 21:40:23 +00001547 if (!MaybeHandleVariable(s))
Sean Callanan48443652010-12-02 19:47:57 +00001548 return false;
Sean Callananbc2928a2010-08-03 00:23:29 +00001549 }
1550 }
Sean Callananf921cf52010-12-03 19:51:05 +00001551 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001552 {
Sean Callananc7ca4662011-10-25 18:36:40 +00001553 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1554 return MaterializeInternalVariable(global_variable);
1555
Sean Callananc0492742011-05-23 21:40:23 +00001556 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001557
Sean Callananf5857a02010-07-31 01:32:05 +00001558 if (!named_decl)
1559 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001560 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001561 return true;
1562
Sean Callanan7cd46742010-12-06 00:56:39 +00001563 if (!global_variable->hasExternalLinkage())
1564 return true;
1565
Sean Callananf5857a02010-07-31 01:32:05 +00001566 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001567 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001568
Sean Callananf5857a02010-07-31 01:32:05 +00001569 return false;
1570 }
1571
Greg Clayton8de27c72010-10-15 22:48:33 +00001572 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +00001573
Sean Callanan771131d2010-09-30 21:18:25 +00001574 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +00001575 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +00001576
1577 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +00001578 {
Sean Callanan771131d2010-09-30 21:18:25 +00001579 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +00001580 ast_context = &value_decl->getASTContext();
1581 }
Sean Callanan810f22d2010-07-16 00:09:46 +00001582 else
Sean Callananf328c9f2010-07-20 23:31:16 +00001583 {
Sean Callanan810f22d2010-07-16 00:09:46 +00001584 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +00001585 }
Sean Callanan771131d2010-09-30 21:18:25 +00001586
Sean Callanan6a925532011-01-13 08:53:35 +00001587 clang::QualType qual_type;
Sean Callanan58baaad2011-07-08 00:39:14 +00001588 const Type *value_type = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00001589
Sean Callanan97678d12011-01-13 21:23:32 +00001590 if (name[0] == '$')
Sean Callanan6a925532011-01-13 08:53:35 +00001591 {
1592 // The $__lldb_expr_result name indicates the the return value has allocated as
1593 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1594 // accesses to this static variable need to be redirected to the result of dereferencing
1595 // a pointer that is passed in as one of the arguments.
1596 //
1597 // Consequently, when reporting the size of the type, we report a pointer type pointing
1598 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanan97678d12011-01-13 21:23:32 +00001599 //
1600 // We also do this for any user-declared persistent variables.
Sean Callananf328c9f2010-07-20 23:31:16 +00001601
Sean Callanan6a925532011-01-13 08:53:35 +00001602 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1603 value_type = PointerType::get(global_variable->getType(), 0);
1604 }
1605 else
1606 {
1607 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1608 value_type = global_variable->getType();
1609 }
Sean Callanan771131d2010-09-30 21:18:25 +00001610
1611 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
1612 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001613
Sean Callanan771131d2010-09-30 21:18:25 +00001614 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001615 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %lu, align %lld]",
Sean Callanan771131d2010-09-30 21:18:25 +00001616 name.c_str(),
1617 qual_type.getAsString().c_str(),
1618 PrintType(value_type).c_str(),
1619 value_size,
1620 value_alignment);
Sean Callanan3aa7da52010-12-13 22:46:15 +00001621
Sean Callanan8bce6652010-07-13 21:41:46 +00001622
Sean Callanan8c127202010-08-23 23:09:38 +00001623 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +00001624 lldb_private::ConstString (name.c_str()),
1625 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +00001626 value_size,
1627 value_alignment))
Sean Callanan9a877432011-08-01 17:41:38 +00001628 {
1629 if (!global_variable->hasExternalLinkage())
1630 return true;
1631 else
1632 return false;
1633 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001634 }
Sean Callananf3143b72010-12-03 03:02:31 +00001635 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanan48443652010-12-02 19:47:57 +00001636 {
1637 if (log)
1638 log->Printf("Function pointers aren't handled right now");
1639
1640 return false;
1641 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001642
1643 return true;
1644}
1645
Sean Callanan97c924e2011-01-27 01:07:04 +00001646// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001647bool
Sean Callananc0492742011-05-23 21:40:23 +00001648IRForTarget::HandleSymbol (Value *symbol)
Sean Callanan81974962011-05-08 02:21:26 +00001649{
Sean Callananc7674af2011-01-17 23:42:46 +00001650 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1651
1652 lldb_private::ConstString name(symbol->getName().str().c_str());
1653
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001654 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name);
Sean Callananc7674af2011-01-17 23:42:46 +00001655
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001656 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc7674af2011-01-17 23:42:46 +00001657 {
1658 if (log)
1659 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1660
1661 return false;
1662 }
1663
1664 if (log)
1665 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), symbol_addr);
1666
Sean Callanan9b6898f2011-07-30 02:42:06 +00001667 Type *symbol_type = symbol->getType();
Sean Callananc7674af2011-01-17 23:42:46 +00001668
Sean Callanan9b6898f2011-07-30 02:42:06 +00001669 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1670 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc7674af2011-01-17 23:42:46 +00001671
1672 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1673
1674 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1675
1676 if (log)
1677 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1678
1679 symbol->replaceAllUsesWith(symbol_addr_ptr);
1680
1681 return true;
1682}
1683
1684bool
Sean Callananc0492742011-05-23 21:40:23 +00001685IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +00001686{
Sean Callanan48443652010-12-02 19:47:57 +00001687 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1688
1689 if (log)
1690 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanandc27aba2010-10-05 22:26:43 +00001691
Sean Callanan6ba533e2010-11-17 23:00:36 +00001692 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +00001693 op_index < num_ops;
1694 ++op_index)
Sean Callananc0492742011-05-23 21:40:23 +00001695 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan97c924e2011-01-27 01:07:04 +00001696 {
1697 if (m_error_stream)
1698 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1699
Sean Callanandc27aba2010-10-05 22:26:43 +00001700 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001701 }
1702
Sean Callanandc27aba2010-10-05 22:26:43 +00001703 return true;
1704}
1705
1706bool
Sean Callananc0492742011-05-23 21:40:23 +00001707IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan8bce6652010-07-13 21:41:46 +00001708{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001709 /////////////////////////////////////////////////////////////////////////
1710 // Prepare the current basic block for execution in the remote process
1711 //
1712
Sean Callanan02fbafa2010-07-27 21:39:39 +00001713 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001714
Greg Clayton3c7feb42010-11-19 01:05:25 +00001715 for (ii = basic_block.begin();
1716 ii != basic_block.end();
Sean Callanan8bce6652010-07-13 21:41:46 +00001717 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001718 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001719 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001720
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001721 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001722
Sean Callanan97c924e2011-01-27 01:07:04 +00001723 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001724 if (call && !MaybeHandleCallArguments(call))
Sean Callanan48443652010-12-02 19:47:57 +00001725 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001726 }
1727
1728 return true;
1729}
1730
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001731bool
Sean Callananc0492742011-05-23 21:40:23 +00001732IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001733{
Sean Callananae71e302010-11-18 22:21:58 +00001734 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1735
Sean Callananc0492742011-05-23 21:40:23 +00001736 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001737 global != end;
1738 ++global)
1739 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001740 if (log)
1741 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1742 (*global).getName().str().c_str(),
Sean Callananc0492742011-05-23 21:40:23 +00001743 DeclForGlobal(global));
Greg Clayton3c7feb42010-11-19 01:05:25 +00001744
Sean Callananc7674af2011-01-17 23:42:46 +00001745 if ((*global).getName().str().find("OBJC_IVAR") == 0)
1746 {
Sean Callananc0492742011-05-23 21:40:23 +00001747 if (!HandleSymbol(global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001748 {
1749 if (m_error_stream)
1750 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str());
1751
Sean Callananc7674af2011-01-17 23:42:46 +00001752 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001753 }
Sean Callananc7674af2011-01-17 23:42:46 +00001754 }
Sean Callananc0492742011-05-23 21:40:23 +00001755 else if (DeclForGlobal(global))
Sean Callananc7674af2011-01-17 23:42:46 +00001756 {
Sean Callananc0492742011-05-23 21:40:23 +00001757 if (!MaybeHandleVariable (global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001758 {
1759 if (m_error_stream)
1760 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str());
1761
Sean Callananc7674af2011-01-17 23:42:46 +00001762 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001763 }
Sean Callananc7674af2011-01-17 23:42:46 +00001764 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001765 }
1766
1767 return true;
1768}
1769
Sean Callananc0492742011-05-23 21:40:23 +00001770bool
1771IRForTarget::ReplaceStrings ()
1772{
1773 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1774
1775 if (!m_data_allocator)
1776 return true; // hope for the best; some clients may not want static allocation!
1777
1778 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1779
1780 OffsetsTy offsets;
1781
1782 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1783 gi != ge;
1784 ++gi)
1785 {
1786 GlobalVariable *gv = gi;
1787
1788 if (!gv->hasInitializer())
1789 continue;
1790
1791 Constant *gc = gv->getInitializer();
1792
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001793 std::string str;
Sean Callananc0492742011-05-23 21:40:23 +00001794
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001795 if (gc->isNullValue())
1796 {
1797 Type *gc_type = gc->getType();
1798
1799 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1800
1801 if (!gc_array_type)
1802 continue;
1803
1804 Type *gc_element_type = gc_array_type->getElementType();
1805
1806 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1807
1808 if (gc_integer_type->getBitWidth() != 8)
1809 continue;
1810
1811 str = "";
1812 }
1813 else
1814 {
1815 ConstantArray *gc_array = dyn_cast<ConstantArray>(gc);
1816
1817 if (!gc_array)
1818 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001819
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001820 if (!gc_array->isCString())
1821 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001822
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001823 if (log)
1824 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callananc0492742011-05-23 21:40:23 +00001825
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001826 str = gc_array->getAsString();
1827 }
1828
Sean Callananc0492742011-05-23 21:40:23 +00001829 offsets[gv] = m_data_allocator->GetStream().GetSize();
1830
1831 m_data_allocator->GetStream().Write(str.c_str(), str.length() + 1);
1832 }
1833
Sean Callanan9b6898f2011-07-30 02:42:06 +00001834 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00001835
1836 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1837 oi != oe;
1838 ++oi)
1839 {
1840 GlobalVariable *gv = oi->first;
1841 size_t offset = oi->second;
1842
1843 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1844
1845 if (log)
1846 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1847
1848 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1849 ui != ue;
1850 ++ui)
1851 {
1852 if (log)
1853 log->Printf("Found use %s", PrintValue(*ui).c_str());
1854
1855 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1856 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1857
1858 if (const_expr)
1859 {
1860 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1861 {
1862 if (log)
1863 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1864
1865 return false;
1866 }
1867
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001868 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1869 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1870
1871 const_expr->replaceAllUsesWith(new_gep);
Sean Callananc0492742011-05-23 21:40:23 +00001872 }
1873 else if (store_inst)
1874 {
1875 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1876
1877 store_inst->setOperand(0, bit_cast);
1878 }
1879 else
1880 {
1881 if (log)
1882 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1883
1884 return false;
1885 }
1886 }
1887
1888 gv->eraseFromParent();
1889 }
1890
1891 return true;
1892}
1893
1894bool
1895IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1896{
1897 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1898
1899 if (!m_data_allocator)
1900 return true;
1901
1902 typedef SmallVector <Value*, 2> ConstantList;
1903 typedef SmallVector <llvm::Instruction*, 2> UserList;
1904 typedef ConstantList::iterator ConstantIterator;
1905 typedef UserList::iterator UserIterator;
1906
1907 ConstantList static_constants;
1908 UserList static_users;
1909
1910 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1911 ii != ie;
1912 ++ii)
1913 {
1914 llvm::Instruction &inst = *ii;
1915
1916 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1917 oi != oe;
1918 ++oi)
1919 {
1920 Value *operand_val = oi->get();
1921
1922 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1923
1924 if (operand_constant_fp && operand_constant_fp->getType()->isX86_FP80Ty())
1925 {
1926 static_constants.push_back(operand_val);
1927 static_users.push_back(ii);
1928 }
1929 }
1930 }
1931
1932 ConstantIterator constant_iter;
1933 UserIterator user_iter;
Greg Clayton54b38412011-05-24 23:06:02 +00001934
Sean Callananc0492742011-05-23 21:40:23 +00001935 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1936 constant_iter != static_constants.end();
1937 ++constant_iter, ++user_iter)
1938 {
1939 Value *operand_val = *constant_iter;
1940 llvm::Instruction *inst = *user_iter;
1941
1942 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1943
1944 if (operand_constant_fp)
1945 {
1946 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
1947 APInt operand_apint = operand_apfloat.bitcastToAPInt();
1948
1949 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
1950 size_t operand_data_size = operand_apint.getBitWidth() / 8;
1951
1952 if (log)
1953 {
1954 std::string s;
1955 raw_string_ostream ss(s);
1956 for (size_t index = 0;
1957 index < operand_data_size;
1958 ++index)
1959 {
1960 ss << (uint32_t)operand_raw_data[index];
1961 ss << " ";
1962 }
1963 ss.flush();
1964
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001965 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callananc0492742011-05-23 21:40:23 +00001966 }
1967
1968 lldb_private::DataBufferHeap data(operand_data_size, 0);
1969
1970 if (lldb::endian::InlHostByteOrder() != m_data_allocator->GetStream().GetByteOrder())
1971 {
1972 uint8_t *data_bytes = data.GetBytes();
1973
1974 for (size_t index = 0;
1975 index < operand_data_size;
1976 ++index)
1977 {
1978 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
1979 }
1980 }
1981 else
1982 {
1983 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
1984 }
1985
1986 uint64_t offset = m_data_allocator->GetStream().GetSize();
1987
1988 m_data_allocator->GetStream().Write(data.GetBytes(), operand_data_size);
1989
Sean Callanan9b6898f2011-07-30 02:42:06 +00001990 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callananc0492742011-05-23 21:40:23 +00001991
1992 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
1993
1994 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
1995
1996 operand_constant_fp->replaceAllUsesWith(fp_load);
1997 }
1998 }
1999
2000 return true;
2001}
2002
Sean Callanan02fbafa2010-07-27 21:39:39 +00002003static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00002004{
Sean Callanan58baaad2011-07-08 00:39:14 +00002005 Constant *Old = NULL;
Sean Callanan45839272010-07-24 01:37:44 +00002006
Sean Callanan6ba533e2010-11-17 23:00:36 +00002007 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00002008 return false;
2009
Sean Callanan58baaad2011-07-08 00:39:14 +00002010 ConstantExpr *CE = NULL;
Sean Callanan47a5c4c2010-09-23 03:01:22 +00002011
2012 if ((CE = dyn_cast<ConstantExpr>(V)))
2013 {
2014 if (CE->getOpcode() != Instruction::BitCast)
2015 return false;
2016
Sean Callanan6ba533e2010-11-17 23:00:36 +00002017 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00002018 }
2019
Sean Callanan6ba533e2010-11-17 23:00:36 +00002020 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00002021
2022 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2023 return false;
2024
2025 return true;
2026}
2027
Sean Callananc0492742011-05-23 21:40:23 +00002028void
2029IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callanan45839272010-07-24 01:37:44 +00002030{
Sean Callananc0492742011-05-23 21:40:23 +00002031 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callanan45839272010-07-24 01:37:44 +00002032
2033 Value::use_iterator ui;
2034
2035 for (ui = guard_load->use_begin();
2036 ui != guard_load->use_end();
2037 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00002038 {
Greg Clayton6e713402010-07-30 20:30:44 +00002039 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00002040 {
2041 // do nothing for the moment
2042 }
2043 else
2044 {
2045 ui->replaceUsesOfWith(guard_load, zero);
2046 }
2047 }
Sean Callanan45839272010-07-24 01:37:44 +00002048
2049 guard_load->eraseFromParent();
2050}
2051
2052static void ExciseGuardStore(Instruction* guard_store)
2053{
2054 guard_store->eraseFromParent();
2055}
2056
2057bool
Sean Callananc0492742011-05-23 21:40:23 +00002058IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callanan45839272010-07-24 01:37:44 +00002059{
2060 ///////////////////////////////////////////////////////
2061 // Eliminate any reference to guard variables found.
2062 //
2063
Sean Callanan02fbafa2010-07-27 21:39:39 +00002064 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00002065
Sean Callanan02fbafa2010-07-27 21:39:39 +00002066 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00002067 typedef InstrList::iterator InstrIterator;
2068
2069 InstrList guard_loads;
2070 InstrList guard_stores;
2071
Greg Clayton3c7feb42010-11-19 01:05:25 +00002072 for (ii = basic_block.begin();
2073 ii != basic_block.end();
Sean Callanan45839272010-07-24 01:37:44 +00002074 ++ii)
2075 {
2076 Instruction &inst = *ii;
2077
2078 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2079 if (isGuardVariableRef(load->getPointerOperand()))
2080 guard_loads.push_back(&inst);
2081
2082 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2083 if (isGuardVariableRef(store->getPointerOperand()))
2084 guard_stores.push_back(&inst);
2085 }
2086
2087 InstrIterator iter;
2088
2089 for (iter = guard_loads.begin();
2090 iter != guard_loads.end();
2091 ++iter)
Sean Callananc0492742011-05-23 21:40:23 +00002092 TurnGuardLoadIntoZero(*iter);
Sean Callanan45839272010-07-24 01:37:44 +00002093
2094 for (iter = guard_stores.begin();
2095 iter != guard_stores.end();
2096 ++iter)
2097 ExciseGuardStore(*iter);
2098
2099 return true;
2100}
2101
Sean Callanan97c924e2011-01-27 01:07:04 +00002102// This function does not report errors; its callers are responsible.
Sean Callanan6ba533e2010-11-17 23:00:36 +00002103bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002104IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callananbafd6852010-07-14 23:40:29 +00002105{
Greg Claytone005f2c2010-11-06 01:53:30 +00002106 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00002107
2108 Value::use_iterator ui;
2109
Sean Callanana48fe162010-08-11 03:57:18 +00002110 SmallVector<User*, 16> users;
2111
2112 // We do this because the use list might change, invalidating our iterator.
2113 // Much better to keep a work list ourselves.
Greg Clayton3c7feb42010-11-19 01:05:25 +00002114 for (ui = old_constant->use_begin();
2115 ui != old_constant->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00002116 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00002117 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00002118
Johnny Chen2bc9eb32011-07-19 19:48:13 +00002119 for (size_t i = 0;
Sean Callanana48fe162010-08-11 03:57:18 +00002120 i < users.size();
2121 ++i)
2122 {
2123 User *user = users[i];
2124
Sean Callananbafd6852010-07-14 23:40:29 +00002125 if (Constant *constant = dyn_cast<Constant>(user))
2126 {
2127 // synthesize a new non-constant equivalent of the constant
2128
2129 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2130 {
2131 switch (constant_expr->getOpcode())
2132 {
2133 default:
2134 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002135 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002136 return false;
2137 case Instruction::BitCast:
2138 {
2139 // UnaryExpr
2140 // OperandList[0] is value
2141
2142 Value *s = constant_expr->getOperand(0);
2143
Greg Clayton3c7feb42010-11-19 01:05:25 +00002144 if (s == old_constant)
2145 s = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002146
Sean Callananc0492742011-05-23 21:40:23 +00002147 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002148
Greg Clayton3c7feb42010-11-19 01:05:25 +00002149 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002150 }
2151 break;
2152 case Instruction::GetElementPtr:
2153 {
2154 // GetElementPtrConstantExpr
2155 // OperandList[0] is base
2156 // OperandList[1]... are indices
2157
2158 Value *ptr = constant_expr->getOperand(0);
2159
Greg Clayton3c7feb42010-11-19 01:05:25 +00002160 if (ptr == old_constant)
2161 ptr = new_constant;
Sean Callanan9b6898f2011-07-30 02:42:06 +00002162
2163 std::vector<Value*> index_vector;
Sean Callananbafd6852010-07-14 23:40:29 +00002164
2165 unsigned operand_index;
2166 unsigned num_operands = constant_expr->getNumOperands();
2167
2168 for (operand_index = 1;
2169 operand_index < num_operands;
2170 ++operand_index)
2171 {
2172 Value *operand = constant_expr->getOperand(operand_index);
2173
Greg Clayton3c7feb42010-11-19 01:05:25 +00002174 if (operand == old_constant)
2175 operand = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002176
Sean Callanan9b6898f2011-07-30 02:42:06 +00002177 index_vector.push_back(operand);
Sean Callananbafd6852010-07-14 23:40:29 +00002178 }
2179
Sean Callanan9b6898f2011-07-30 02:42:06 +00002180 ArrayRef <Value*> indices(index_vector);
2181
2182 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002183
Greg Clayton3c7feb42010-11-19 01:05:25 +00002184 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002185 }
2186 break;
2187 }
2188 }
2189 else
2190 {
2191 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002192 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002193 return false;
2194 }
2195 }
2196 else
2197 {
2198 // simple fall-through case for non-constants
Greg Clayton3c7feb42010-11-19 01:05:25 +00002199 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callananbafd6852010-07-14 23:40:29 +00002200 }
2201 }
2202
2203 return true;
2204}
2205
Sean Callanan8bce6652010-07-13 21:41:46 +00002206bool
Sean Callananc0492742011-05-23 21:40:23 +00002207IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan8bce6652010-07-13 21:41:46 +00002208{
Sean Callanane8a59a82010-09-13 21:34:21 +00002209 if (!m_resolve_vars)
2210 return true;
2211
Greg Claytone005f2c2010-11-06 01:53:30 +00002212 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00002213
2214 m_decl_map->DoStructLayout();
2215
2216 if (log)
2217 log->Printf("Element arrangement:");
2218
2219 uint32_t num_elements;
2220 uint32_t element_index;
2221
2222 size_t size;
2223 off_t alignment;
2224
2225 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2226 return false;
2227
Greg Clayton3c7feb42010-11-19 01:05:25 +00002228 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00002229
Greg Clayton3c7feb42010-11-19 01:05:25 +00002230 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002231 {
2232 if (m_error_stream)
2233 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2234
Sean Callanan8bce6652010-07-13 21:41:46 +00002235 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002236 }
2237
Sean Callanan02fbafa2010-07-27 21:39:39 +00002238 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00002239
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002240 if (argument->getName().equals("this"))
2241 {
2242 ++iter;
2243
Greg Clayton3c7feb42010-11-19 01:05:25 +00002244 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002245 {
2246 if (m_error_stream)
2247 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2248
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002249 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002250 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002251
2252 argument = iter;
2253 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002254 else if (argument->getName().equals("self"))
2255 {
2256 ++iter;
2257
2258 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002259 {
2260 if (m_error_stream)
2261 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2262
Sean Callanan3aa7da52010-12-13 22:46:15 +00002263 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002264 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002265
2266 if (!iter->getName().equals("_cmd"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002267 {
2268 if (m_error_stream)
2269 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2270
Sean Callanan3aa7da52010-12-13 22:46:15 +00002271 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002272 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002273
2274 ++iter;
2275
2276 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002277 {
2278 if (m_error_stream)
2279 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2280
Sean Callanan3aa7da52010-12-13 22:46:15 +00002281 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002282 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002283
2284 argument = iter;
2285 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002286
Greg Clayton8de27c72010-10-15 22:48:33 +00002287 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002288 {
2289 if (m_error_stream)
2290 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2291
Sean Callanan8bce6652010-07-13 21:41:46 +00002292 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002293 }
2294
Sean Callanan8bce6652010-07-13 21:41:46 +00002295 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002296 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00002297
Greg Clayton3c7feb42010-11-19 01:05:25 +00002298 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00002299 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00002300
Sean Callanan6ba533e2010-11-17 23:00:36 +00002301 if (!FirstEntryInstruction)
Sean Callanan97c924e2011-01-27 01:07:04 +00002302 {
2303 if (m_error_stream)
2304 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2305
Sean Callanan8bce6652010-07-13 21:41:46 +00002306 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002307 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002308
Sean Callananc0492742011-05-23 21:40:23 +00002309 LLVMContext &context(m_module->getContext());
Sean Callanan9b6898f2011-07-30 02:42:06 +00002310 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan8bce6652010-07-13 21:41:46 +00002311
2312 if (!offset_type)
Sean Callanan97c924e2011-01-27 01:07:04 +00002313 {
2314 if (m_error_stream)
2315 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2316
Sean Callanan8bce6652010-07-13 21:41:46 +00002317 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002318 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002319
2320 for (element_index = 0; element_index < num_elements; ++element_index)
2321 {
Sean Callanan58baaad2011-07-08 00:39:14 +00002322 const clang::NamedDecl *decl = NULL;
2323 Value *value = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002324 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00002325 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00002326
Sean Callanan45690fe2010-08-30 22:17:16 +00002327 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan97c924e2011-01-27 01:07:04 +00002328 {
2329 if (m_error_stream)
2330 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2331
Sean Callanan8bce6652010-07-13 21:41:46 +00002332 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002333 }
2334
Sean Callanan8bce6652010-07-13 21:41:46 +00002335 if (log)
Sean Callananc7ca4662011-10-25 18:36:40 +00002336 log->Printf(" \"%s\" (\"%s\") placed at %lld",
Greg Clayton8de27c72010-10-15 22:48:33 +00002337 name.GetCString(),
Sean Callananc7ca4662011-10-25 18:36:40 +00002338 decl->getNameAsString().c_str(),
Sean Callanan8bce6652010-07-13 21:41:46 +00002339 offset);
2340
Sean Callanan9b6898f2011-07-30 02:42:06 +00002341 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callanan6ba533e2010-11-17 23:00:36 +00002342 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan6a925532011-01-13 08:53:35 +00002343
Sean Callananc7ca4662011-10-25 18:36:40 +00002344 if (value)
Sean Callanan6a925532011-01-13 08:53:35 +00002345 {
Sean Callananc7ca4662011-10-25 18:36:40 +00002346 Value *replacement = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00002347
Sean Callananc7ca4662011-10-25 18:36:40 +00002348 if (log)
2349 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan6a925532011-01-13 08:53:35 +00002350
Sean Callananc7ca4662011-10-25 18:36:40 +00002351 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2352 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2353 // entry in order to produce the static variable that the AST thinks it is accessing.
2354 if (name == m_result_name && !m_result_is_pointer)
2355 {
2356 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2357
2358 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2359
2360 replacement = load;
2361 }
2362 else
2363 {
2364 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2365
2366 replacement = bit_cast;
2367 }
2368
2369 if (Constant *constant = dyn_cast<Constant>(value))
2370 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2371 else
2372 value->replaceAllUsesWith(replacement);
2373
2374 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2375 var->eraseFromParent();
2376 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002377 }
2378
2379 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002380 log->Printf("Total structure [align %lld, size %lu]", alignment, size);
Sean Callanan8bce6652010-07-13 21:41:46 +00002381
2382 return true;
2383}
2384
Sean Callananc0492742011-05-23 21:40:23 +00002385llvm::Constant *
Sean Callanan9b6898f2011-07-30 02:42:06 +00002386IRForTarget::BuildRelocation(llvm::Type *type,
Sean Callananc0492742011-05-23 21:40:23 +00002387 uint64_t offset)
2388{
2389 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2390
Sean Callanan9b6898f2011-07-30 02:42:06 +00002391 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2392 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002393
2394 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanan9b6898f2011-07-30 02:42:06 +00002395
2396 llvm::Constant *offset_array[1];
2397
2398 offset_array[0] = offset_int;
2399
2400 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2401
2402 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callananc0492742011-05-23 21:40:23 +00002403 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2404
2405 return reloc_getbitcast;
2406}
2407
2408bool
2409IRForTarget::CompleteDataAllocation ()
2410{
Sean Callanan47dc4572011-09-15 02:13:07 +00002411 if (!m_data_allocator)
2412 return true;
2413
Sean Callananc0492742011-05-23 21:40:23 +00002414 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2415
2416 if (!m_data_allocator->GetStream().GetSize())
2417 return true;
2418
2419 lldb::addr_t allocation = m_data_allocator->Allocate();
2420
2421 if (log)
2422 {
2423 if (allocation)
2424 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2425 else
2426 log->Printf("Failed to allocate static data");
2427 }
2428
2429 if (!allocation)
2430 return false;
2431
Sean Callanan9b6898f2011-07-30 02:42:06 +00002432 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2433 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002434
2435 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2436 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2437
2438 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2439
2440 m_reloc_placeholder->eraseFromParent();
2441
2442 return true;
2443}
2444
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002445bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002446IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002447{
Greg Claytone005f2c2010-11-06 01:53:30 +00002448 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002449
Sean Callananc0492742011-05-23 21:40:23 +00002450 m_module = &llvm_module;
Sean Callananc7ca4662011-10-25 18:36:40 +00002451 m_target_data.reset(new TargetData(m_module));
Sean Callananc0492742011-05-23 21:40:23 +00002452
2453 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002454
2455 if (!function)
2456 {
2457 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002458 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00002459
2460 if (m_error_stream)
Sean Callananc0492742011-05-23 21:40:23 +00002461 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 +00002462
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002463 return false;
2464 }
Sean Callananc0492742011-05-23 21:40:23 +00002465
2466 if (!FixFunctionLinkage (*function))
2467 {
2468 if (log)
2469 log->Printf("Couldn't fix the linkage for the function");
2470
2471 return false;
2472 }
2473
Sean Callananc7ca4662011-10-25 18:36:40 +00002474 if (log)
2475 {
2476 std::string s;
2477 raw_string_ostream oss(s);
2478
2479 m_module->print(oss, NULL);
2480
2481 oss.flush();
2482
2483 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2484 }
2485
Sean Callanan9b6898f2011-07-30 02:42:06 +00002486 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00002487
2488 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2489 intptr_ty,
2490 false /* isConstant */,
2491 GlobalVariable::InternalLinkage,
2492 Constant::getNullValue(intptr_ty),
2493 "reloc_placeholder",
2494 NULL /* InsertBefore */,
2495 false /* ThreadLocal */,
2496 0 /* AddressSpace */);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002497
Sean Callanan02fbafa2010-07-27 21:39:39 +00002498 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002499
Sean Callananc0492742011-05-23 21:40:23 +00002500 m_has_side_effects = HasSideEffects(*function);
Sean Callanan05a5a1b2010-12-16 03:17:46 +00002501
Sean Callanan82b74c82010-08-12 01:56:52 +00002502 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00002503 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00002504 //
2505
Sean Callananc0492742011-05-23 21:40:23 +00002506 if (!CreateResultVariable(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002507 {
2508 if (log)
2509 log->Printf("CreateResultVariable() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002510
2511 // CreateResultVariable() reports its own errors, so we don't do so here
2512
Sean Callanan82b74c82010-08-12 01:56:52 +00002513 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002514 }
Sean Callanan47dc4572011-09-15 02:13:07 +00002515
2516 if (m_const_result && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2517 {
2518 m_interpret_success = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +00002519 return true;
Sean Callanan47dc4572011-09-15 02:13:07 +00002520 }
2521
2522 for (bbi = function->begin();
2523 bbi != function->end();
2524 ++bbi)
2525 {
2526 if (!RemoveGuards(*bbi))
2527 {
2528 if (log)
2529 log->Printf("RemoveGuards() failed");
2530
2531 // RemoveGuards() reports its own errors, so we don't do so here
2532
2533 return false;
2534 }
2535
2536 if (!RewritePersistentAllocs(*bbi))
2537 {
2538 if (log)
2539 log->Printf("RewritePersistentAllocs() failed");
2540
2541 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2542
2543 return false;
2544 }
2545 }
2546
2547 if (m_decl_map && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2548 {
2549 IRInterpreter interpreter (*m_decl_map,
2550 m_error_stream);
2551
2552 if (interpreter.maybeRunOnFunction(m_const_result, m_result_name, m_result_type, *function, llvm_module))
2553 {
2554 m_interpret_success = true;
2555 return true;
2556 }
2557 }
Sean Callanan696cf5f2011-05-07 01:06:41 +00002558
Sean Callananc0492742011-05-23 21:40:23 +00002559 if (log)
2560 {
2561 std::string s;
2562 raw_string_ostream oss(s);
2563
2564 m_module->print(oss, NULL);
2565
2566 oss.flush();
2567
2568 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2569 }
2570
Sean Callanan6ba533e2010-11-17 23:00:36 +00002571 ///////////////////////////////////////////////////////////////////////////////
2572 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2573 //
Sean Callanan6ba533e2010-11-17 23:00:36 +00002574
Sean Callananc0492742011-05-23 21:40:23 +00002575 if (!RewriteObjCConstStrings(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002576 {
2577 if (log)
2578 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002579
2580 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2581
Sean Callanan6ba533e2010-11-17 23:00:36 +00002582 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002583 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00002584
Sean Callanan5c9a3c72011-08-04 21:37:47 +00002585 ///////////////////////////////
2586 // Resolve function pointers
2587 //
2588
2589 if (!ResolveFunctionPointers(llvm_module, *function))
2590 {
2591 if (log)
2592 log->Printf("ResolveFunctionPointers() failed");
2593
2594 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2595
2596 return false;
2597 }
2598
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002599 for (bbi = function->begin();
2600 bbi != function->end();
2601 ++bbi)
2602 {
Sean Callananc0492742011-05-23 21:40:23 +00002603 if (!RewriteObjCSelectors(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002604 {
2605 if (log)
2606 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002607
2608 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2609
Sean Callanana48fe162010-08-11 03:57:18 +00002610 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002611 }
Sean Callanana48fe162010-08-11 03:57:18 +00002612
Sean Callananc0492742011-05-23 21:40:23 +00002613 if (!ResolveCalls(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002614 {
2615 if (log)
2616 log->Printf("ResolveCalls() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002617
2618 // ResolveCalls() reports its own errors, so we don't do so here
2619
Sean Callanan8bce6652010-07-13 21:41:46 +00002620 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002621 }
Sean Callananc0492742011-05-23 21:40:23 +00002622
2623 if (!ReplaceStaticLiterals(*bbi))
2624 {
2625 if (log)
2626 log->Printf("ReplaceStaticLiterals() failed");
2627
2628 return false;
2629 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002630 }
2631
Sean Callanan771131d2010-09-30 21:18:25 +00002632 ///////////////////////////////
2633 // Run function-level passes
2634 //
2635
Sean Callananc0492742011-05-23 21:40:23 +00002636 if (!ResolveExternals(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002637 {
2638 if (log)
2639 log->Printf("ResolveExternals() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002640
2641 // ResolveExternals() reports its own errors, so we don't do so here
2642
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002643 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002644 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002645
Sean Callananc0492742011-05-23 21:40:23 +00002646 if (!ReplaceVariables(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002647 {
2648 if (log)
2649 log->Printf("ReplaceVariables() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002650
2651 // ReplaceVariables() reports its own errors, so we don't do so here
2652
Sean Callanan771131d2010-09-30 21:18:25 +00002653 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002654 }
Sean Callanan771131d2010-09-30 21:18:25 +00002655
Sean Callananc0492742011-05-23 21:40:23 +00002656 if (!ReplaceStrings())
2657 {
2658 if (log)
2659 log->Printf("ReplaceStrings() failed");
2660
2661 return false;
2662 }
2663
2664 if (!CompleteDataAllocation())
2665 {
2666 if (log)
2667 log->Printf("CompleteDataAllocation() failed");
2668
2669 return false;
2670 }
2671
Sean Callanan8bce6652010-07-13 21:41:46 +00002672 if (log)
2673 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00002674 std::string s;
2675 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00002676
Sean Callananc0492742011-05-23 21:40:23 +00002677 m_module->print(oss, NULL);
Sean Callanan321fe9e2010-07-28 01:00:59 +00002678
2679 oss.flush();
2680
Greg Claytonb5037af2010-11-15 01:47:11 +00002681 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002682 }
2683
2684 return true;
2685}
2686
2687void
Greg Clayton3c7feb42010-11-19 01:05:25 +00002688IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002689{
2690}
2691
2692PassManagerType
2693IRForTarget::getPotentialPassManagerType() const
2694{
2695 return PMT_ModulePassManager;
2696}