blob: feac49284a7570588a05724d15a3e02cce3c6fcf [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
294bool
295IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module,
296 llvm::Function &llvm_function)
297{
298 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
299
300 for (llvm::Module::iterator fi = llvm_module.begin();
301 fi != llvm_module.end();
302 ++fi)
303 {
304 Function *fun = fi;
305
306 bool is_decl = fun->isDeclaration();
307
308 if (log)
309 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getNameStr().c_str());
310
311 if (!is_decl)
312 continue;
313
314 if (fun->hasNUses(0))
315 continue; // ignore
316
317 uint64_t addr = LLDB_INVALID_ADDRESS;
318 lldb_private::ConstString name;
319 Constant **value_ptr = NULL;
320
321 if (!GetFunctionAddress(fun,
322 addr,
323 name,
324 value_ptr))
325 return false; // GetFunctionAddress reports its own errors
326
327 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
328
329 if (value_ptr)
330 *value_ptr = value;
331
332 fun->replaceAllUsesWith(value);
333 }
334
335 return true;
336}
337
Sean Callanan47dc4572011-09-15 02:13:07 +0000338
Sean Callanan696cf5f2011-05-07 01:06:41 +0000339clang::NamedDecl *
Sean Callanan47dc4572011-09-15 02:13:07 +0000340IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000341{
342 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
343
Sean Callanan47dc4572011-09-15 02:13:07 +0000344 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan696cf5f2011-05-07 01:06:41 +0000345
346 if (!named_metadata)
347 return NULL;
348
349 unsigned num_nodes = named_metadata->getNumOperands();
350 unsigned node_index;
351
352 for (node_index = 0;
353 node_index < num_nodes;
354 ++node_index)
355 {
356 MDNode *metadata_node = named_metadata->getOperand(node_index);
357
358 if (!metadata_node)
359 return NULL;
360
361 if (metadata_node->getNumOperands() != 2)
362 continue;
363
364 if (metadata_node->getOperand(0) != global_val)
365 continue;
366
367 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
368
369 if (!constant_int)
370 return NULL;
371
372 uintptr_t ptr = constant_int->getZExtValue();
373
374 return reinterpret_cast<clang::NamedDecl *>(ptr);
375 }
376
377 return NULL;
378}
379
Sean Callanan47dc4572011-09-15 02:13:07 +0000380clang::NamedDecl *
381IRForTarget::DeclForGlobal (GlobalValue *global_val)
382{
383 return DeclForGlobal(global_val, m_module);
384}
385
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000386void
387IRForTarget::MaybeSetConstantResult (llvm::Constant *initializer,
388 const lldb_private::ConstString &name,
389 lldb_private::TypeFromParser type)
390{
Sean Callanan696cf5f2011-05-07 01:06:41 +0000391 if (llvm::ConstantExpr *init_expr = dyn_cast<llvm::ConstantExpr>(initializer))
392 {
393 switch (init_expr->getOpcode())
394 {
395 default:
396 return;
397 case Instruction::IntToPtr:
398 MaybeSetConstantResult (init_expr->getOperand(0), name, type);
399 return;
400 }
401 }
402 else if (llvm::ConstantInt *init_int = dyn_cast<llvm::ConstantInt>(initializer))
403 {
404 m_const_result = m_decl_map->BuildIntegerVariable(name, type, init_int->getValue());
405 }
406}
407
408void
Sean Callananc0492742011-05-23 21:40:23 +0000409IRForTarget::MaybeSetCastResult (lldb_private::TypeFromParser type)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000410{
411 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
412
413 if (!m_result_store)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000414 return;
415
Sean Callanan696cf5f2011-05-07 01:06:41 +0000416 LoadInst *original_load = NULL;
417
418 for (llvm::Value *current_value = m_result_store->getValueOperand(), *next_value;
419 current_value != NULL;
420 current_value = next_value)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000421 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000422 CastInst *cast_inst = dyn_cast<CastInst>(current_value);
423 LoadInst *load_inst = dyn_cast<LoadInst>(current_value);
424
425 if (cast_inst)
426 {
427 next_value = cast_inst->getOperand(0);
428 }
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000429 else if (load_inst)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000430 {
431 if (isa<LoadInst>(load_inst->getPointerOperand()))
432 {
433 next_value = load_inst->getPointerOperand();
434 }
435 else
436 {
437 original_load = load_inst;
438 break;
439 }
440 }
441 else
442 {
443 return;
444 }
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000445 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000446
447 Value *loaded_value = original_load->getPointerOperand();
448 GlobalVariable *loaded_global = dyn_cast<GlobalVariable>(loaded_value);
449
450 if (!loaded_global)
451 return;
452
Sean Callananc0492742011-05-23 21:40:23 +0000453 clang::NamedDecl *loaded_decl = DeclForGlobal(loaded_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000454
455 if (!loaded_decl)
456 return;
457
458 clang::VarDecl *loaded_var = dyn_cast<clang::VarDecl>(loaded_decl);
459
460 if (!loaded_var)
461 return;
462
463 if (log)
464 {
465 lldb_private::StreamString type_desc_stream;
466 type.DumpTypeDescription(&type_desc_stream);
467
468 log->Printf("Type to cast variable to: \"%s\"", type_desc_stream.GetString().c_str());
469 }
470
471 m_const_result = m_decl_map->BuildCastVariable(m_result_name, loaded_var, type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000472}
473
474bool
Sean Callananc0492742011-05-23 21:40:23 +0000475IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanan82b74c82010-08-12 01:56:52 +0000476{
Greg Claytone005f2c2010-11-06 01:53:30 +0000477 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan82b74c82010-08-12 01:56:52 +0000478
Sean Callanane8a59a82010-09-13 21:34:21 +0000479 if (!m_resolve_vars)
480 return true;
481
482 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000483
Sean Callananc0492742011-05-23 21:40:23 +0000484 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000485
Sean Callanan9b6898f2011-07-30 02:42:06 +0000486 std::string result_name_str;
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000487 const char *result_name = NULL;
488
489 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
490 vi != ve;
491 ++vi)
492 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000493 result_name_str = vi->first().str();
494 const char *value_name = result_name_str.c_str();
495
496 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
497 !strstr(value_name, "GV"))
Sean Callanan6a925532011-01-13 08:53:35 +0000498 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000499 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000500 m_result_is_pointer = true;
501 break;
502 }
503
Sean Callanan9b6898f2011-07-30 02:42:06 +0000504 if (strstr(value_name, "$__lldb_expr_result") &&
505 !strstr(value_name, "GV"))
Sean Callananc04743d2010-09-28 21:13:03 +0000506 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000507 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000508 m_result_is_pointer = false;
Sean Callananc04743d2010-09-28 21:13:03 +0000509 break;
510 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000511 }
512
513 if (!result_name)
514 {
515 if (log)
516 log->PutCString("Couldn't find result variable");
517
518 return true;
519 }
520
Sean Callananc04743d2010-09-28 21:13:03 +0000521 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000522 log->Printf("Result name: \"%s\"", result_name);
Sean Callananc04743d2010-09-28 21:13:03 +0000523
Sean Callananc0492742011-05-23 21:40:23 +0000524 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000525
526 if (!result_value)
527 {
528 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000529 log->PutCString("Result variable had no data");
Sean Callanan6a925532011-01-13 08:53:35 +0000530
Sean Callanan97c924e2011-01-27 01:07:04 +0000531 if (m_error_stream)
532 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
533
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000534 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000535 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000536
Sean Callanan82b74c82010-08-12 01:56:52 +0000537 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000538 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000539
540 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
541
542 if (!result_global)
543 {
544 if (log)
545 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000546
547 if (m_error_stream)
548 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
549
Sean Callanan82b74c82010-08-12 01:56:52 +0000550 return false;
551 }
552
Sean Callananc0492742011-05-23 21:40:23 +0000553 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000554 if (!result_decl)
Sean Callanan82b74c82010-08-12 01:56:52 +0000555 {
556 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000557 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanan82b74c82010-08-12 01:56:52 +0000558
Sean Callanan97c924e2011-01-27 01:07:04 +0000559 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000560 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 +0000561
Sean Callanan82b74c82010-08-12 01:56:52 +0000562 return false;
563 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000564
Sean Callanan696cf5f2011-05-07 01:06:41 +0000565 if (log)
Sean Callanan82b74c82010-08-12 01:56:52 +0000566 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000567 std::string decl_desc_str;
568 raw_string_ostream decl_desc_stream(decl_desc_str);
569 result_decl->print(decl_desc_stream);
570 decl_desc_stream.flush();
Sean Callanan82b74c82010-08-12 01:56:52 +0000571
Sean Callanan696cf5f2011-05-07 01:06:41 +0000572 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000573 }
574
Sean Callanan696cf5f2011-05-07 01:06:41 +0000575 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
576 if (!result_var)
Sean Callanan82b74c82010-08-12 01:56:52 +0000577 {
578 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000579 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan97c924e2011-01-27 01:07:04 +0000580
581 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000582 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 +0000583
Sean Callanan82b74c82010-08-12 01:56:52 +0000584 return false;
585 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000586
Sean Callanan82b74c82010-08-12 01:56:52 +0000587 // Get the next available result name from m_decl_map and create the persistent
588 // variable for it
Sean Callanan47dc4572011-09-15 02:13:07 +0000589
Sean Callanan696cf5f2011-05-07 01:06:41 +0000590 // If the result is an Lvalue, it is emitted as a pointer; see
591 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan6a925532011-01-13 08:53:35 +0000592 if (m_result_is_pointer)
593 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000594 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanand5b3c352011-01-27 04:42:51 +0000595 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
596 const clang::PointerType *pointer_pointertype = dyn_cast<clang::PointerType>(pointer_type);
Sean Callanan6a925532011-01-13 08:53:35 +0000597
598 if (!pointer_pointertype)
599 {
600 if (log)
601 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan97c924e2011-01-27 01:07:04 +0000602
603 if (m_error_stream)
604 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
605
Sean Callanan6a925532011-01-13 08:53:35 +0000606 return false;
607 }
608
609 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
610
Sean Callanan47dc4572011-09-15 02:13:07 +0000611 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
Sean Callanan6a925532011-01-13 08:53:35 +0000612 &result_decl->getASTContext());
613 }
614 else
615 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000616 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan6a925532011-01-13 08:53:35 +0000617 &result_decl->getASTContext());
618 }
619
Sean Callanan696cf5f2011-05-07 01:06:41 +0000620 if (log)
621 {
622 lldb_private::StreamString type_desc_stream;
Sean Callanan47dc4572011-09-15 02:13:07 +0000623 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000624
625 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetString().c_str());
626 }
627
Sean Callanan6a925532011-01-13 08:53:35 +0000628 m_result_name = m_decl_map->GetPersistentResultName();
Sean Callanan82b74c82010-08-12 01:56:52 +0000629
630 if (log)
Sean Callanan6a925532011-01-13 08:53:35 +0000631 log->Printf("Creating a new result global: \"%s\"", m_result_name.GetCString());
Sean Callanan82b74c82010-08-12 01:56:52 +0000632
633 // Construct a new result global and set up its metadata
634
Sean Callananc0492742011-05-23 21:40:23 +0000635 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanan82b74c82010-08-12 01:56:52 +0000636 result_global->getType()->getElementType(),
637 false, /* not constant */
638 GlobalValue::ExternalLinkage,
639 NULL, /* no initializer */
Sean Callanan6a925532011-01-13 08:53:35 +0000640 m_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000641
642 // It's too late in compilation to create a new VarDecl for this, but we don't
643 // need to. We point the metadata at the old VarDecl. This creates an odd
644 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000645 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000646 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
647 // fixed up.
648
Sean Callananc0492742011-05-23 21:40:23 +0000649 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan696cf5f2011-05-07 01:06:41 +0000650 reinterpret_cast<uint64_t>(result_decl),
Sean Callanan82b74c82010-08-12 01:56:52 +0000651 false);
652
653 llvm::Value* values[2];
654 values[0] = new_result_global;
655 values[1] = new_constant_int;
656
Sean Callanan0de254a2011-05-15 22:34:38 +0000657 ArrayRef<Value*> value_ref(values, 2);
658
Sean Callananc0492742011-05-23 21:40:23 +0000659 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
660 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000661 named_metadata->addOperand(persistent_global_md);
662
663 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000664 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000665 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000666 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000667
668 if (result_global->hasNUses(0))
669 {
670 // We need to synthesize a store for this variable, because otherwise
671 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000672
Greg Clayton8de27c72010-10-15 22:48:33 +0000673 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000674 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
675
676 if (!first_entry_instruction)
677 return false;
678
679 if (!result_global->hasInitializer())
680 {
681 if (log)
682 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000683
684 if (m_error_stream)
685 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
686
Sean Callanan2e2db532010-09-07 22:43:19 +0000687 return false;
688 }
689
690 Constant *initializer = result_global->getInitializer();
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000691
692 // Here we write the initializer into a result variable assuming it
693 // can be computed statically.
694
695 if (!m_has_side_effects)
696 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000697 //MaybeSetConstantResult (initializer,
698 // m_result_name,
699 // m_result_type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000700 }
Sean Callanan2e2db532010-09-07 22:43:19 +0000701
Greg Clayton2c344ca2011-02-05 02:28:58 +0000702 StoreInst *synthesized_store = new StoreInst(initializer,
703 new_result_global,
704 first_entry_instruction);
Sean Callanan2e2db532010-09-07 22:43:19 +0000705
706 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000707 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000708 }
709 else
710 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000711 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (m_result_type.GetOpaqueQualType()))
Sean Callanan696cf5f2011-05-07 01:06:41 +0000712 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000713 //MaybeSetCastResult (m_result_type);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000714 }
715
Sean Callanan2e2db532010-09-07 22:43:19 +0000716 result_global->replaceAllUsesWith(new_result_global);
717 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000718
719 if (!m_const_result)
720 m_decl_map->AddPersistentVariable(result_decl,
721 m_result_name,
Sean Callanan47dc4572011-09-15 02:13:07 +0000722 m_result_type,
Sean Callanan696cf5f2011-05-07 01:06:41 +0000723 true,
724 m_result_is_pointer);
Sean Callanan2e2db532010-09-07 22:43:19 +0000725
Sean Callanan82b74c82010-08-12 01:56:52 +0000726 result_global->eraseFromParent();
727
728 return true;
729}
730
Johnny Chen58021cc2011-08-09 23:10:20 +0000731#if 0
Greg Clayton3c7feb42010-11-19 01:05:25 +0000732static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000733{
734 if (!depth)
735 return;
736
737 depth--;
738
Johnny Chen58021cc2011-08-09 23:10:20 +0000739 if (log)
740 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000741
Greg Clayton3c7feb42010-11-19 01:05:25 +0000742 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000743 ui != ue;
744 ++ui)
745 {
Johnny Chen58021cc2011-08-09 23:10:20 +0000746 if (log)
747 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000748 DebugUsers(log, *ui, depth);
749 }
750
Johnny Chen58021cc2011-08-09 23:10:20 +0000751 if (log)
752 log->Printf(" <End uses>");
Sean Callanan6ba533e2010-11-17 23:00:36 +0000753}
Johnny Chen58021cc2011-08-09 23:10:20 +0000754#endif
Sean Callanan6ba533e2010-11-17 23:00:36 +0000755
756bool
Sean Callananc0492742011-05-23 21:40:23 +0000757IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton3c7feb42010-11-19 01:05:25 +0000758 llvm::GlobalVariable *cstr,
759 Instruction *FirstEntryInstruction)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000760{
761 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
762
Sean Callanan9b6898f2011-07-30 02:42:06 +0000763 Type *ns_str_ty = ns_str->getType();
Sean Callananc0492742011-05-23 21:40:23 +0000764
Sean Callanan9b6898f2011-07-30 02:42:06 +0000765 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
766 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callananc0492742011-05-23 21:40:23 +0000767 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan9b6898f2011-07-30 02:42:06 +0000768 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
769 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000770
771 if (!m_CFStringCreateWithBytes)
772 {
773 lldb::addr_t CFStringCreateWithBytes_addr;
774
775 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
776
777 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
778 {
779 if (log)
780 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
781
Sean Callanan97c924e2011-01-27 01:07:04 +0000782 if (m_error_stream)
783 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
784
Sean Callanan6ba533e2010-11-17 23:00:36 +0000785 return false;
786 }
787
788 if (log)
789 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr);
790
791 // Build the function type:
792 //
793 // CFStringRef CFStringCreateWithBytes (
794 // CFAllocatorRef alloc,
795 // const UInt8 *bytes,
796 // CFIndex numBytes,
797 // CFStringEncoding encoding,
798 // Boolean isExternalRepresentation
799 // );
800 //
801 // We make the following substitutions:
802 //
803 // CFStringRef -> i8*
804 // CFAllocatorRef -> i8*
805 // UInt8 * -> i8*
806 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
807 // CFStringEncoding -> i32
808 // Boolean -> i8
809
Sean Callanan9b6898f2011-07-30 02:42:06 +0000810 Type *arg_type_array[5];
811
812 arg_type_array[0] = i8_ptr_ty;
813 arg_type_array[1] = i8_ptr_ty;
814 arg_type_array[2] = intptr_ty;
815 arg_type_array[3] = i32_ty;
816 arg_type_array[4] = i8_ty;
817
818 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
819
Sean Callananc0492742011-05-23 21:40:23 +0000820 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000821
822 // Build the constant containing the pointer to the function
823 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
824 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
825 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
826 }
827
Sean Callanan58baaad2011-07-08 00:39:14 +0000828 ConstantArray *string_array = NULL;
Sean Callanan0ece5262011-02-10 22:17:53 +0000829
830 if (cstr)
831 string_array = dyn_cast<ConstantArray>(cstr->getInitializer());
Sean Callanan9b6898f2011-07-30 02:42:06 +0000832
Sean Callanan6ba533e2010-11-17 23:00:36 +0000833 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan0ece5262011-02-10 22:17:53 +0000834 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
835 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getType()->getNumElements() - 1 : 0, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000836 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
837 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
838
Sean Callanan9b6898f2011-07-30 02:42:06 +0000839 Value *argument_array[5];
840
841 argument_array[0] = alloc_arg;
842 argument_array[1] = bytes_arg;
843 argument_array[2] = numBytes_arg;
844 argument_array[3] = encoding_arg;
845 argument_array[4] = isExternal_arg;
846
847 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000848
849 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanan9b6898f2011-07-30 02:42:06 +0000850 CFSCWB_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +0000851 "CFStringCreateWithBytes",
852 FirstEntryInstruction);
Sean Callananae71e302010-11-18 22:21:58 +0000853
Greg Clayton3c7feb42010-11-19 01:05:25 +0000854 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000855 {
856 if (log)
857 log->PutCString("Couldn't replace the NSString with the result of the call");
858
Sean Callanan97c924e2011-01-27 01:07:04 +0000859 if (m_error_stream)
860 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
861
Sean Callanan6ba533e2010-11-17 23:00:36 +0000862 return false;
863 }
864
Greg Clayton3c7feb42010-11-19 01:05:25 +0000865 ns_str->eraseFromParent();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000866
867 return true;
868}
869
870bool
Sean Callananc0492742011-05-23 21:40:23 +0000871IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000872{
873 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
874
Sean Callananc0492742011-05-23 21:40:23 +0000875 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000876
Greg Clayton3c7feb42010-11-19 01:05:25 +0000877 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000878 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
879
880 if (!FirstEntryInstruction)
881 {
882 if (log)
883 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
884
Sean Callanan97c924e2011-01-27 01:07:04 +0000885 if (m_error_stream)
886 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
887
Sean Callanan6ba533e2010-11-17 23:00:36 +0000888 return false;
889 }
890
891 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
892 vi != ve;
893 ++vi)
894 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000895 std::string value_name = vi->first().str();
896 const char *value_name_cstr = value_name.c_str();
897
898 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000899 {
900 Value *nsstring_value = vi->second;
901
902 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
903
904 if (!nsstring_global)
905 {
906 if (log)
907 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000908
909 if (m_error_stream)
910 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
911
Sean Callanan6ba533e2010-11-17 23:00:36 +0000912 return false;
913 }
914
915 if (!nsstring_global->hasInitializer())
916 {
917 if (log)
918 log->PutCString("NSString variable does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000919
920 if (m_error_stream)
921 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
922
Sean Callanan6ba533e2010-11-17 23:00:36 +0000923 return false;
924 }
925
926 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
927
928 if (!nsstring_struct)
929 {
930 if (log)
931 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan97c924e2011-01-27 01:07:04 +0000932
933 if (m_error_stream)
934 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
935
Sean Callanan6ba533e2010-11-17 23:00:36 +0000936 return false;
937 }
938
939 // We expect the following structure:
940 //
941 // struct {
942 // int *isa;
943 // int flags;
944 // char *str;
945 // long length;
946 // };
947
948 if (nsstring_struct->getNumOperands() != 4)
949 {
950 if (log)
951 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 +0000952
953 if (m_error_stream)
954 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
955
Sean Callanan6ba533e2010-11-17 23:00:36 +0000956 return false;
957 }
958
959 Constant *nsstring_member = nsstring_struct->getOperand(2);
960
961 if (!nsstring_member)
962 {
963 if (log)
964 log->PutCString("NSString initializer's str element was empty");
Sean Callanan97c924e2011-01-27 01:07:04 +0000965
966 if (m_error_stream)
967 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
968
Sean Callanan6ba533e2010-11-17 23:00:36 +0000969 return false;
970 }
971
972 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
973
974 if (!nsstring_expr)
975 {
976 if (log)
977 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan97c924e2011-01-27 01:07:04 +0000978
979 if (m_error_stream)
980 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
981
Sean Callanan6ba533e2010-11-17 23:00:36 +0000982 return false;
983 }
984
985 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
986 {
987 if (log)
988 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 +0000989
990 if (m_error_stream)
991 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
992
Sean Callanan6ba533e2010-11-17 23:00:36 +0000993 return false;
994 }
995
996 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
997
998 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
999
1000 if (!cstr_global)
1001 {
1002 if (log)
1003 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001004
1005 if (m_error_stream)
1006 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 +00001007
Sean Callanan6ba533e2010-11-17 23:00:36 +00001008 return false;
1009 }
1010
1011 if (!cstr_global->hasInitializer())
1012 {
1013 if (log)
1014 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +00001015
1016 if (m_error_stream)
1017 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
1018
Sean Callanan6ba533e2010-11-17 23:00:36 +00001019 return false;
1020 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001021
1022 /*
Sean Callanan6ba533e2010-11-17 23:00:36 +00001023 if (!cstr_array)
1024 {
1025 if (log)
1026 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan97c924e2011-01-27 01:07:04 +00001027
1028 if (m_error_stream)
1029 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
1030
Sean Callanan6ba533e2010-11-17 23:00:36 +00001031 return false;
1032 }
1033
1034 if (!cstr_array->isCString())
1035 {
1036 if (log)
1037 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan97c924e2011-01-27 01:07:04 +00001038
1039 if (m_error_stream)
1040 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
1041
Sean Callanan6ba533e2010-11-17 23:00:36 +00001042 return false;
1043 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001044 */
1045
1046 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer());
Sean Callanan6ba533e2010-11-17 23:00:36 +00001047
1048 if (log)
Sean Callanan0ece5262011-02-10 22:17:53 +00001049 {
1050 if (cstr_array)
Sean Callanan9b6898f2011-07-30 02:42:06 +00001051 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().c_str());
Sean Callanan0ece5262011-02-10 22:17:53 +00001052 else
Sean Callanan9b6898f2011-07-30 02:42:06 +00001053 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan0ece5262011-02-10 22:17:53 +00001054 }
1055
1056 if (!cstr_array)
1057 cstr_global = NULL;
Sean Callanan6ba533e2010-11-17 23:00:36 +00001058
Sean Callananc0492742011-05-23 21:40:23 +00001059 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan97c924e2011-01-27 01:07:04 +00001060 {
Sean Callanan6ba533e2010-11-17 23:00:36 +00001061 if (log)
1062 log->PutCString("Error rewriting the constant string");
Sean Callanan97c924e2011-01-27 01:07:04 +00001063
1064 // We don't print an error message here because RewriteObjCConstString has done so for us.
1065
Sean Callanan6ba533e2010-11-17 23:00:36 +00001066 return false;
1067 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00001068 }
1069 }
1070
1071 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1072 vi != ve;
1073 ++vi)
1074 {
Sean Callanan9b6898f2011-07-30 02:42:06 +00001075 std::string value_name = vi->first().str();
1076 const char *value_name_cstr = value_name.c_str();
1077
1078 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callanan6ba533e2010-11-17 23:00:36 +00001079 {
1080 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1081
1082 if (!gv)
1083 {
1084 if (log)
1085 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001086
1087 if (m_error_stream)
1088 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1089
Sean Callanan6ba533e2010-11-17 23:00:36 +00001090 return false;
1091 }
1092
1093 gv->eraseFromParent();
1094
1095 break;
1096 }
1097 }
1098
1099 return true;
1100}
1101
Greg Clayton3c7feb42010-11-19 01:05:25 +00001102static bool IsObjCSelectorRef (Value *value)
Sean Callananf5857a02010-07-31 01:32:05 +00001103{
Greg Clayton3c7feb42010-11-19 01:05:25 +00001104 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callananf5857a02010-07-31 01:32:05 +00001105
Greg Clayton3c7feb42010-11-19 01:05:25 +00001106 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callananf5857a02010-07-31 01:32:05 +00001107 return false;
1108
1109 return true;
1110}
1111
Sean Callanan97c924e2011-01-27 01:07:04 +00001112// This function does not report errors; its callers are responsible.
Sean Callananf5857a02010-07-31 01:32:05 +00001113bool
Sean Callananc0492742011-05-23 21:40:23 +00001114IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callananf5857a02010-07-31 01:32:05 +00001115{
Greg Claytone005f2c2010-11-06 01:53:30 +00001116 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001117
1118 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1119
1120 if (!load)
1121 return false;
1122
1123 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1124 //
1125 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1126 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1127 //
1128 // where %obj is the object pointer and %tmp is the selector.
1129 //
Greg Clayton3c7feb42010-11-19 01:05:25 +00001130 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1131 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callananf5857a02010-07-31 01:32:05 +00001132
1133 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1134
1135 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1136
1137 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1138 return false;
1139
1140 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1141
1142 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1143
1144 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1145 return false;
1146
1147 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1148
1149 if (!osr_initializer_base)
1150 return false;
1151
1152 // Find the string's initializer (a ConstantArray) and get the string from it
1153
1154 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1155
1156 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1157 return false;
1158
1159 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1160
1161 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
1162
1163 if (!omvn_initializer_array->isString())
1164 return false;
1165
1166 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1167
1168 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001169 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +00001170
1171 // Construct a call to sel_registerName
1172
1173 if (!m_sel_registerName)
1174 {
Greg Claytonb5037af2010-11-15 01:47:11 +00001175 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +00001176
Greg Clayton8de27c72010-10-15 22:48:33 +00001177 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +00001178 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001179 return false;
1180
Sean Callananc2c6f772010-10-26 00:31:56 +00001181 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001182 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +00001183
Sean Callananf5857a02010-07-31 01:32:05 +00001184 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1185
1186 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callananc0492742011-05-23 21:40:23 +00001187 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001188 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanan9b6898f2011-07-30 02:42:06 +00001189 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001190
Sean Callanan9b6898f2011-07-30 02:42:06 +00001191 Type *type_array[1];
1192
1193 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1194
1195 ArrayRef<Type *> srN_arg_types(type_array, 1);
1196
Sean Callananf5857a02010-07-31 01:32:05 +00001197 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1198
1199 // Build the constant containing the pointer to the function
Sean Callanan9b6898f2011-07-30 02:42:06 +00001200 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1201 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananf5857a02010-07-31 01:32:05 +00001202 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +00001203 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001204 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1205 }
1206
Sean Callanan9b6898f2011-07-30 02:42:06 +00001207 Value *argument_array[1];
1208
Sean Callananc0492742011-05-23 21:40:23 +00001209 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callananf5857a02010-07-31 01:32:05 +00001210
Sean Callanan9b6898f2011-07-30 02:42:06 +00001211 argument_array[0] = omvn_pointer;
Sean Callananf5857a02010-07-31 01:32:05 +00001212
Sean Callanan9b6898f2011-07-30 02:42:06 +00001213 ArrayRef<Value *> srN_arguments(argument_array, 1);
1214
Sean Callananf5857a02010-07-31 01:32:05 +00001215 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanan9b6898f2011-07-30 02:42:06 +00001216 srN_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +00001217 "sel_registerName",
Sean Callananf5857a02010-07-31 01:32:05 +00001218 selector_load);
1219
1220 // Replace the load with the call in all users
1221
1222 selector_load->replaceAllUsesWith(srN_call);
1223
1224 selector_load->eraseFromParent();
1225
1226 return true;
1227}
1228
1229bool
Sean Callananc0492742011-05-23 21:40:23 +00001230IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callananf5857a02010-07-31 01:32:05 +00001231{
Greg Claytone005f2c2010-11-06 01:53:30 +00001232 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001233
1234 BasicBlock::iterator ii;
1235
1236 typedef SmallVector <Instruction*, 2> InstrList;
1237 typedef InstrList::iterator InstrIterator;
1238
1239 InstrList selector_loads;
1240
Greg Clayton3c7feb42010-11-19 01:05:25 +00001241 for (ii = basic_block.begin();
1242 ii != basic_block.end();
Sean Callananf5857a02010-07-31 01:32:05 +00001243 ++ii)
1244 {
1245 Instruction &inst = *ii;
1246
1247 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton3c7feb42010-11-19 01:05:25 +00001248 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callananf5857a02010-07-31 01:32:05 +00001249 selector_loads.push_back(&inst);
1250 }
1251
1252 InstrIterator iter;
1253
1254 for (iter = selector_loads.begin();
1255 iter != selector_loads.end();
1256 ++iter)
1257 {
Sean Callananc0492742011-05-23 21:40:23 +00001258 if (!RewriteObjCSelector(*iter))
Sean Callananf5857a02010-07-31 01:32:05 +00001259 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001260 if (m_error_stream)
1261 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1262
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001263 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +00001264 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan97c924e2011-01-27 01:07:04 +00001265
Sean Callananf5857a02010-07-31 01:32:05 +00001266 return false;
1267 }
1268 }
1269
1270 return true;
1271}
1272
Sean Callanan97c924e2011-01-27 01:07:04 +00001273// This function does not report errors; its callers are responsible.
Sean Callanana48fe162010-08-11 03:57:18 +00001274bool
Sean Callananc0492742011-05-23 21:40:23 +00001275IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanana48fe162010-08-11 03:57:18 +00001276{
Sean Callanan97678d12011-01-13 21:23:32 +00001277 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1278
Sean Callanana48fe162010-08-11 03:57:18 +00001279 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1280
1281 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1282
1283 if (!alloc_md || !alloc_md->getNumOperands())
1284 return false;
1285
1286 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1287
1288 if (!constant_int)
1289 return false;
1290
1291 // We attempt to register this as a new persistent variable with the DeclMap.
1292
1293 uintptr_t ptr = constant_int->getZExtValue();
1294
Sean Callanan82b74c82010-08-12 01:56:52 +00001295 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +00001296
Sean Callanan82b74c82010-08-12 01:56:52 +00001297 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1298 &decl->getASTContext());
1299
Greg Clayton8de27c72010-10-15 22:48:33 +00001300 StringRef decl_name (decl->getName());
1301 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan6a925532011-01-13 08:53:35 +00001302 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanana48fe162010-08-11 03:57:18 +00001303 return false;
1304
Sean Callananc0492742011-05-23 21:40:23 +00001305 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanan97678d12011-01-13 21:23:32 +00001306 alloc->getType(),
Sean Callanana48fe162010-08-11 03:57:18 +00001307 false, /* not constant */
1308 GlobalValue::ExternalLinkage,
1309 NULL, /* no initializer */
1310 alloc->getName().str().c_str());
1311
1312 // What we're going to do here is make believe this was a regular old external
1313 // variable. That means we need to make the metadata valid.
1314
Sean Callananc0492742011-05-23 21:40:23 +00001315 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +00001316
1317 llvm::Value* values[2];
1318 values[0] = persistent_global;
1319 values[1] = constant_int;
Sean Callanan0de254a2011-05-15 22:34:38 +00001320
1321 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +00001322
Sean Callananc0492742011-05-23 21:40:23 +00001323 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanana48fe162010-08-11 03:57:18 +00001324 named_metadata->addOperand(persistent_global_md);
1325
Sean Callanan97678d12011-01-13 21:23:32 +00001326 // Now, since the variable is a pointer variable, we will drop in a load of that
1327 // pointer variable.
1328
1329 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1330
1331 if (log)
1332 log->Printf("Replacing \"%s\" with \"%s\"",
1333 PrintValue(alloc).c_str(),
1334 PrintValue(persistent_load).c_str());
1335
1336 alloc->replaceAllUsesWith(persistent_load);
Sean Callanana48fe162010-08-11 03:57:18 +00001337 alloc->eraseFromParent();
1338
1339 return true;
1340}
1341
1342bool
Sean Callananc0492742011-05-23 21:40:23 +00001343IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanana48fe162010-08-11 03:57:18 +00001344{
Sean Callanane8a59a82010-09-13 21:34:21 +00001345 if (!m_resolve_vars)
1346 return true;
1347
Greg Claytone005f2c2010-11-06 01:53:30 +00001348 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +00001349
1350 BasicBlock::iterator ii;
1351
1352 typedef SmallVector <Instruction*, 2> InstrList;
1353 typedef InstrList::iterator InstrIterator;
1354
1355 InstrList pvar_allocs;
1356
Greg Clayton3c7feb42010-11-19 01:05:25 +00001357 for (ii = basic_block.begin();
1358 ii != basic_block.end();
Sean Callanana48fe162010-08-11 03:57:18 +00001359 ++ii)
1360 {
1361 Instruction &inst = *ii;
1362
1363 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan237e4742011-01-21 22:30:25 +00001364 {
1365 llvm::StringRef alloc_name = alloc->getName();
1366
1367 if (alloc_name.startswith("$") &&
1368 !alloc_name.startswith("$__lldb"))
1369 {
1370 if (alloc_name.find_first_of("0123456789") == 1)
1371 {
1372 if (log)
1373 log->Printf("Rejecting a numeric persistent variable.");
1374
Sean Callanan97c924e2011-01-27 01:07:04 +00001375 if (m_error_stream)
1376 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1377
Sean Callanan237e4742011-01-21 22:30:25 +00001378 return false;
1379 }
1380
Sean Callanana48fe162010-08-11 03:57:18 +00001381 pvar_allocs.push_back(alloc);
Sean Callanan237e4742011-01-21 22:30:25 +00001382 }
1383 }
Sean Callanana48fe162010-08-11 03:57:18 +00001384 }
1385
1386 InstrIterator iter;
1387
1388 for (iter = pvar_allocs.begin();
1389 iter != pvar_allocs.end();
1390 ++iter)
1391 {
Sean Callananc0492742011-05-23 21:40:23 +00001392 if (!RewritePersistentAlloc(*iter))
Sean Callanana48fe162010-08-11 03:57:18 +00001393 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001394 if (m_error_stream)
1395 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1396
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001397 if (log)
Sean Callanana48fe162010-08-11 03:57:18 +00001398 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001399
Sean Callanana48fe162010-08-11 03:57:18 +00001400 return false;
1401 }
1402 }
1403
1404 return true;
1405}
1406
Sean Callananc7ca4662011-10-25 18:36:40 +00001407bool
1408IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1409{
1410 if (!initializer)
1411 return true;
1412
1413 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1414
1415 if (log && log->GetVerbose())
1416 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1417
1418 Type *initializer_type = initializer->getType();
1419
1420 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1421 {
1422 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1423 return true;
1424 }
1425 else if (ConstantArray *array_initializer = dyn_cast<ConstantArray>(initializer))
1426 {
1427 if (array_initializer->isString())
1428 {
1429 std::string array_initializer_string = array_initializer->getAsString();
1430 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1431 }
1432 else
1433 {
1434 ArrayType *array_initializer_type = array_initializer->getType();
1435 Type *array_element_type = array_initializer_type->getElementType();
1436
1437 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1438
1439 for (int i = 0; i < array_initializer->getNumOperands(); ++i)
1440 {
1441 if (!MaterializeInitializer(data + (i * element_size), array_initializer->getOperand(i)))
1442 return false;
1443 }
1444 }
1445 return true;
1446 }
1447 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1448 {
1449 StructType *struct_initializer_type = struct_initializer->getType();
1450 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1451
1452 for (int i = 0;
1453 i < struct_initializer->getNumOperands();
1454 ++i)
1455 {
1456 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1457 return false;
1458 }
1459 return true;
1460 }
1461 return false;
1462}
1463
1464bool
1465IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1466{
1467 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1468 return false;
1469
1470 uint64_t offset = m_data_allocator->GetStream().GetSize();
1471
1472 llvm::Type *variable_type = global_variable->getType();
1473
1474 Constant *initializer = global_variable->getInitializer();
1475
1476 llvm::Type *initializer_type = initializer->getType();
1477
1478 size_t size = m_target_data->getTypeAllocSize(initializer_type);
1479
1480 lldb_private::DataBufferHeap data(size, '\0');
1481
1482 if (initializer)
1483 if (!MaterializeInitializer(data.GetBytes(), initializer))
1484 return false;
1485
1486 m_data_allocator->GetStream().Write(data.GetBytes(), data.GetByteSize());
1487
1488 Constant *new_pointer = BuildRelocation(variable_type, offset);
1489
1490 global_variable->replaceAllUsesWith(new_pointer);
1491
1492 global_variable->eraseFromParent();
1493
1494 return true;
1495}
1496
Sean Callanan97c924e2011-01-27 01:07:04 +00001497// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001498bool
Sean Callananc0492742011-05-23 21:40:23 +00001499IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001500{
Greg Claytone005f2c2010-11-06 01:53:30 +00001501 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan48443652010-12-02 19:47:57 +00001502
1503 if (log)
Sean Callananb9f09a62010-12-06 22:16:55 +00001504 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callanan9a877432011-08-01 17:41:38 +00001505
Greg Clayton8de27c72010-10-15 22:48:33 +00001506 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +00001507 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001508 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +00001509 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001510 default:
1511 break;
1512 case Instruction::GetElementPtr:
1513 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +00001514 Value *s = constant_expr->getOperand(0);
Sean Callananc0492742011-05-23 21:40:23 +00001515 if (!MaybeHandleVariable(s))
Sean Callanan48443652010-12-02 19:47:57 +00001516 return false;
Sean Callananbc2928a2010-08-03 00:23:29 +00001517 }
1518 }
Sean Callananf921cf52010-12-03 19:51:05 +00001519 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001520 {
Sean Callananc7ca4662011-10-25 18:36:40 +00001521 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1522 return MaterializeInternalVariable(global_variable);
1523
Sean Callananc0492742011-05-23 21:40:23 +00001524 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001525
Sean Callananf5857a02010-07-31 01:32:05 +00001526 if (!named_decl)
1527 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001528 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001529 return true;
1530
Sean Callanan7cd46742010-12-06 00:56:39 +00001531 if (!global_variable->hasExternalLinkage())
1532 return true;
1533
Sean Callananf5857a02010-07-31 01:32:05 +00001534 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001535 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001536
Sean Callananf5857a02010-07-31 01:32:05 +00001537 return false;
1538 }
1539
Greg Clayton8de27c72010-10-15 22:48:33 +00001540 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +00001541
Sean Callanan771131d2010-09-30 21:18:25 +00001542 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +00001543 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +00001544
1545 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +00001546 {
Sean Callanan771131d2010-09-30 21:18:25 +00001547 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +00001548 ast_context = &value_decl->getASTContext();
1549 }
Sean Callanan810f22d2010-07-16 00:09:46 +00001550 else
Sean Callananf328c9f2010-07-20 23:31:16 +00001551 {
Sean Callanan810f22d2010-07-16 00:09:46 +00001552 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +00001553 }
Sean Callanan771131d2010-09-30 21:18:25 +00001554
Sean Callanan6a925532011-01-13 08:53:35 +00001555 clang::QualType qual_type;
Sean Callanan58baaad2011-07-08 00:39:14 +00001556 const Type *value_type = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00001557
Sean Callanan97678d12011-01-13 21:23:32 +00001558 if (name[0] == '$')
Sean Callanan6a925532011-01-13 08:53:35 +00001559 {
1560 // The $__lldb_expr_result name indicates the the return value has allocated as
1561 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1562 // accesses to this static variable need to be redirected to the result of dereferencing
1563 // a pointer that is passed in as one of the arguments.
1564 //
1565 // Consequently, when reporting the size of the type, we report a pointer type pointing
1566 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanan97678d12011-01-13 21:23:32 +00001567 //
1568 // We also do this for any user-declared persistent variables.
Sean Callananf328c9f2010-07-20 23:31:16 +00001569
Sean Callanan6a925532011-01-13 08:53:35 +00001570 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1571 value_type = PointerType::get(global_variable->getType(), 0);
1572 }
1573 else
1574 {
1575 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1576 value_type = global_variable->getType();
1577 }
Sean Callanan771131d2010-09-30 21:18:25 +00001578
1579 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
1580 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001581
Sean Callanan771131d2010-09-30 21:18:25 +00001582 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001583 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %lu, align %lld]",
Sean Callanan771131d2010-09-30 21:18:25 +00001584 name.c_str(),
1585 qual_type.getAsString().c_str(),
1586 PrintType(value_type).c_str(),
1587 value_size,
1588 value_alignment);
Sean Callanan3aa7da52010-12-13 22:46:15 +00001589
Sean Callanan8bce6652010-07-13 21:41:46 +00001590
Sean Callanan8c127202010-08-23 23:09:38 +00001591 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +00001592 lldb_private::ConstString (name.c_str()),
1593 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +00001594 value_size,
1595 value_alignment))
Sean Callanan9a877432011-08-01 17:41:38 +00001596 {
1597 if (!global_variable->hasExternalLinkage())
1598 return true;
1599 else
1600 return false;
1601 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001602 }
Sean Callananf3143b72010-12-03 03:02:31 +00001603 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanan48443652010-12-02 19:47:57 +00001604 {
1605 if (log)
1606 log->Printf("Function pointers aren't handled right now");
1607
1608 return false;
1609 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001610
1611 return true;
1612}
1613
Sean Callanan97c924e2011-01-27 01:07:04 +00001614// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001615bool
Sean Callananc0492742011-05-23 21:40:23 +00001616IRForTarget::HandleSymbol (Value *symbol)
Sean Callanan81974962011-05-08 02:21:26 +00001617{
Sean Callananc7674af2011-01-17 23:42:46 +00001618 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1619
1620 lldb_private::ConstString name(symbol->getName().str().c_str());
1621
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001622 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name);
Sean Callananc7674af2011-01-17 23:42:46 +00001623
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001624 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc7674af2011-01-17 23:42:46 +00001625 {
1626 if (log)
1627 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1628
1629 return false;
1630 }
1631
1632 if (log)
1633 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), symbol_addr);
1634
Sean Callanan9b6898f2011-07-30 02:42:06 +00001635 Type *symbol_type = symbol->getType();
Sean Callananc7674af2011-01-17 23:42:46 +00001636
Sean Callanan9b6898f2011-07-30 02:42:06 +00001637 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1638 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc7674af2011-01-17 23:42:46 +00001639
1640 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1641
1642 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1643
1644 if (log)
1645 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1646
1647 symbol->replaceAllUsesWith(symbol_addr_ptr);
1648
1649 return true;
1650}
1651
1652bool
Sean Callananc0492742011-05-23 21:40:23 +00001653IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +00001654{
Sean Callanan48443652010-12-02 19:47:57 +00001655 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1656
1657 if (log)
1658 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanandc27aba2010-10-05 22:26:43 +00001659
Sean Callanan6ba533e2010-11-17 23:00:36 +00001660 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +00001661 op_index < num_ops;
1662 ++op_index)
Sean Callananc0492742011-05-23 21:40:23 +00001663 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan97c924e2011-01-27 01:07:04 +00001664 {
1665 if (m_error_stream)
1666 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1667
Sean Callanandc27aba2010-10-05 22:26:43 +00001668 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001669 }
1670
Sean Callanandc27aba2010-10-05 22:26:43 +00001671 return true;
1672}
1673
1674bool
Sean Callananc0492742011-05-23 21:40:23 +00001675IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan8bce6652010-07-13 21:41:46 +00001676{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001677 /////////////////////////////////////////////////////////////////////////
1678 // Prepare the current basic block for execution in the remote process
1679 //
1680
Sean Callanan02fbafa2010-07-27 21:39:39 +00001681 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001682
Greg Clayton3c7feb42010-11-19 01:05:25 +00001683 for (ii = basic_block.begin();
1684 ii != basic_block.end();
Sean Callanan8bce6652010-07-13 21:41:46 +00001685 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001686 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001687 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001688
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001689 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001690
Sean Callanan97c924e2011-01-27 01:07:04 +00001691 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001692 if (call && !MaybeHandleCallArguments(call))
Sean Callanan48443652010-12-02 19:47:57 +00001693 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001694 }
1695
1696 return true;
1697}
1698
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001699bool
Sean Callananc0492742011-05-23 21:40:23 +00001700IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001701{
Sean Callananae71e302010-11-18 22:21:58 +00001702 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1703
Sean Callananc0492742011-05-23 21:40:23 +00001704 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001705 global != end;
1706 ++global)
1707 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001708 if (log)
1709 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1710 (*global).getName().str().c_str(),
Sean Callananc0492742011-05-23 21:40:23 +00001711 DeclForGlobal(global));
Greg Clayton3c7feb42010-11-19 01:05:25 +00001712
Sean Callananc7674af2011-01-17 23:42:46 +00001713 if ((*global).getName().str().find("OBJC_IVAR") == 0)
1714 {
Sean Callananc0492742011-05-23 21:40:23 +00001715 if (!HandleSymbol(global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001716 {
1717 if (m_error_stream)
1718 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str());
1719
Sean Callananc7674af2011-01-17 23:42:46 +00001720 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001721 }
Sean Callananc7674af2011-01-17 23:42:46 +00001722 }
Sean Callananc0492742011-05-23 21:40:23 +00001723 else if (DeclForGlobal(global))
Sean Callananc7674af2011-01-17 23:42:46 +00001724 {
Sean Callananc0492742011-05-23 21:40:23 +00001725 if (!MaybeHandleVariable (global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001726 {
1727 if (m_error_stream)
1728 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str());
1729
Sean Callananc7674af2011-01-17 23:42:46 +00001730 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001731 }
Sean Callananc7674af2011-01-17 23:42:46 +00001732 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001733 }
1734
1735 return true;
1736}
1737
Sean Callananc0492742011-05-23 21:40:23 +00001738bool
1739IRForTarget::ReplaceStrings ()
1740{
1741 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1742
1743 if (!m_data_allocator)
1744 return true; // hope for the best; some clients may not want static allocation!
1745
1746 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1747
1748 OffsetsTy offsets;
1749
1750 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1751 gi != ge;
1752 ++gi)
1753 {
1754 GlobalVariable *gv = gi;
1755
1756 if (!gv->hasInitializer())
1757 continue;
1758
1759 Constant *gc = gv->getInitializer();
1760
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001761 std::string str;
Sean Callananc0492742011-05-23 21:40:23 +00001762
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001763 if (gc->isNullValue())
1764 {
1765 Type *gc_type = gc->getType();
1766
1767 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1768
1769 if (!gc_array_type)
1770 continue;
1771
1772 Type *gc_element_type = gc_array_type->getElementType();
1773
1774 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1775
1776 if (gc_integer_type->getBitWidth() != 8)
1777 continue;
1778
1779 str = "";
1780 }
1781 else
1782 {
1783 ConstantArray *gc_array = dyn_cast<ConstantArray>(gc);
1784
1785 if (!gc_array)
1786 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001787
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001788 if (!gc_array->isCString())
1789 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001790
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001791 if (log)
1792 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callananc0492742011-05-23 21:40:23 +00001793
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001794 str = gc_array->getAsString();
1795 }
1796
Sean Callananc0492742011-05-23 21:40:23 +00001797 offsets[gv] = m_data_allocator->GetStream().GetSize();
1798
1799 m_data_allocator->GetStream().Write(str.c_str(), str.length() + 1);
1800 }
1801
Sean Callanan9b6898f2011-07-30 02:42:06 +00001802 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00001803
1804 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1805 oi != oe;
1806 ++oi)
1807 {
1808 GlobalVariable *gv = oi->first;
1809 size_t offset = oi->second;
1810
1811 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1812
1813 if (log)
1814 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1815
1816 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1817 ui != ue;
1818 ++ui)
1819 {
1820 if (log)
1821 log->Printf("Found use %s", PrintValue(*ui).c_str());
1822
1823 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1824 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1825
1826 if (const_expr)
1827 {
1828 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1829 {
1830 if (log)
1831 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1832
1833 return false;
1834 }
1835
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001836 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1837 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1838
1839 const_expr->replaceAllUsesWith(new_gep);
Sean Callananc0492742011-05-23 21:40:23 +00001840 }
1841 else if (store_inst)
1842 {
1843 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1844
1845 store_inst->setOperand(0, bit_cast);
1846 }
1847 else
1848 {
1849 if (log)
1850 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1851
1852 return false;
1853 }
1854 }
1855
1856 gv->eraseFromParent();
1857 }
1858
1859 return true;
1860}
1861
1862bool
1863IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1864{
1865 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1866
1867 if (!m_data_allocator)
1868 return true;
1869
1870 typedef SmallVector <Value*, 2> ConstantList;
1871 typedef SmallVector <llvm::Instruction*, 2> UserList;
1872 typedef ConstantList::iterator ConstantIterator;
1873 typedef UserList::iterator UserIterator;
1874
1875 ConstantList static_constants;
1876 UserList static_users;
1877
1878 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1879 ii != ie;
1880 ++ii)
1881 {
1882 llvm::Instruction &inst = *ii;
1883
1884 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1885 oi != oe;
1886 ++oi)
1887 {
1888 Value *operand_val = oi->get();
1889
1890 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1891
1892 if (operand_constant_fp && operand_constant_fp->getType()->isX86_FP80Ty())
1893 {
1894 static_constants.push_back(operand_val);
1895 static_users.push_back(ii);
1896 }
1897 }
1898 }
1899
1900 ConstantIterator constant_iter;
1901 UserIterator user_iter;
Greg Clayton54b38412011-05-24 23:06:02 +00001902
Sean Callananc0492742011-05-23 21:40:23 +00001903 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1904 constant_iter != static_constants.end();
1905 ++constant_iter, ++user_iter)
1906 {
1907 Value *operand_val = *constant_iter;
1908 llvm::Instruction *inst = *user_iter;
1909
1910 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1911
1912 if (operand_constant_fp)
1913 {
1914 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
1915 APInt operand_apint = operand_apfloat.bitcastToAPInt();
1916
1917 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
1918 size_t operand_data_size = operand_apint.getBitWidth() / 8;
1919
1920 if (log)
1921 {
1922 std::string s;
1923 raw_string_ostream ss(s);
1924 for (size_t index = 0;
1925 index < operand_data_size;
1926 ++index)
1927 {
1928 ss << (uint32_t)operand_raw_data[index];
1929 ss << " ";
1930 }
1931 ss.flush();
1932
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001933 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callananc0492742011-05-23 21:40:23 +00001934 }
1935
1936 lldb_private::DataBufferHeap data(operand_data_size, 0);
1937
1938 if (lldb::endian::InlHostByteOrder() != m_data_allocator->GetStream().GetByteOrder())
1939 {
1940 uint8_t *data_bytes = data.GetBytes();
1941
1942 for (size_t index = 0;
1943 index < operand_data_size;
1944 ++index)
1945 {
1946 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
1947 }
1948 }
1949 else
1950 {
1951 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
1952 }
1953
1954 uint64_t offset = m_data_allocator->GetStream().GetSize();
1955
1956 m_data_allocator->GetStream().Write(data.GetBytes(), operand_data_size);
1957
Sean Callanan9b6898f2011-07-30 02:42:06 +00001958 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callananc0492742011-05-23 21:40:23 +00001959
1960 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
1961
1962 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
1963
1964 operand_constant_fp->replaceAllUsesWith(fp_load);
1965 }
1966 }
1967
1968 return true;
1969}
1970
Sean Callanan02fbafa2010-07-27 21:39:39 +00001971static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00001972{
Sean Callanan58baaad2011-07-08 00:39:14 +00001973 Constant *Old = NULL;
Sean Callanan45839272010-07-24 01:37:44 +00001974
Sean Callanan6ba533e2010-11-17 23:00:36 +00001975 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00001976 return false;
1977
Sean Callanan58baaad2011-07-08 00:39:14 +00001978 ConstantExpr *CE = NULL;
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001979
1980 if ((CE = dyn_cast<ConstantExpr>(V)))
1981 {
1982 if (CE->getOpcode() != Instruction::BitCast)
1983 return false;
1984
Sean Callanan6ba533e2010-11-17 23:00:36 +00001985 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001986 }
1987
Sean Callanan6ba533e2010-11-17 23:00:36 +00001988 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00001989
1990 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
1991 return false;
1992
1993 return true;
1994}
1995
Sean Callananc0492742011-05-23 21:40:23 +00001996void
1997IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callanan45839272010-07-24 01:37:44 +00001998{
Sean Callananc0492742011-05-23 21:40:23 +00001999 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callanan45839272010-07-24 01:37:44 +00002000
2001 Value::use_iterator ui;
2002
2003 for (ui = guard_load->use_begin();
2004 ui != guard_load->use_end();
2005 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00002006 {
Greg Clayton6e713402010-07-30 20:30:44 +00002007 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00002008 {
2009 // do nothing for the moment
2010 }
2011 else
2012 {
2013 ui->replaceUsesOfWith(guard_load, zero);
2014 }
2015 }
Sean Callanan45839272010-07-24 01:37:44 +00002016
2017 guard_load->eraseFromParent();
2018}
2019
2020static void ExciseGuardStore(Instruction* guard_store)
2021{
2022 guard_store->eraseFromParent();
2023}
2024
2025bool
Sean Callananc0492742011-05-23 21:40:23 +00002026IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callanan45839272010-07-24 01:37:44 +00002027{
2028 ///////////////////////////////////////////////////////
2029 // Eliminate any reference to guard variables found.
2030 //
2031
Sean Callanan02fbafa2010-07-27 21:39:39 +00002032 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00002033
Sean Callanan02fbafa2010-07-27 21:39:39 +00002034 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00002035 typedef InstrList::iterator InstrIterator;
2036
2037 InstrList guard_loads;
2038 InstrList guard_stores;
2039
Greg Clayton3c7feb42010-11-19 01:05:25 +00002040 for (ii = basic_block.begin();
2041 ii != basic_block.end();
Sean Callanan45839272010-07-24 01:37:44 +00002042 ++ii)
2043 {
2044 Instruction &inst = *ii;
2045
2046 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2047 if (isGuardVariableRef(load->getPointerOperand()))
2048 guard_loads.push_back(&inst);
2049
2050 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2051 if (isGuardVariableRef(store->getPointerOperand()))
2052 guard_stores.push_back(&inst);
2053 }
2054
2055 InstrIterator iter;
2056
2057 for (iter = guard_loads.begin();
2058 iter != guard_loads.end();
2059 ++iter)
Sean Callananc0492742011-05-23 21:40:23 +00002060 TurnGuardLoadIntoZero(*iter);
Sean Callanan45839272010-07-24 01:37:44 +00002061
2062 for (iter = guard_stores.begin();
2063 iter != guard_stores.end();
2064 ++iter)
2065 ExciseGuardStore(*iter);
2066
2067 return true;
2068}
2069
Sean Callanan97c924e2011-01-27 01:07:04 +00002070// This function does not report errors; its callers are responsible.
Sean Callanan6ba533e2010-11-17 23:00:36 +00002071bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002072IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callananbafd6852010-07-14 23:40:29 +00002073{
Greg Claytone005f2c2010-11-06 01:53:30 +00002074 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00002075
2076 Value::use_iterator ui;
2077
Sean Callanana48fe162010-08-11 03:57:18 +00002078 SmallVector<User*, 16> users;
2079
2080 // We do this because the use list might change, invalidating our iterator.
2081 // Much better to keep a work list ourselves.
Greg Clayton3c7feb42010-11-19 01:05:25 +00002082 for (ui = old_constant->use_begin();
2083 ui != old_constant->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00002084 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00002085 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00002086
Johnny Chen2bc9eb32011-07-19 19:48:13 +00002087 for (size_t i = 0;
Sean Callanana48fe162010-08-11 03:57:18 +00002088 i < users.size();
2089 ++i)
2090 {
2091 User *user = users[i];
2092
Sean Callananbafd6852010-07-14 23:40:29 +00002093 if (Constant *constant = dyn_cast<Constant>(user))
2094 {
2095 // synthesize a new non-constant equivalent of the constant
2096
2097 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2098 {
2099 switch (constant_expr->getOpcode())
2100 {
2101 default:
2102 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002103 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002104 return false;
2105 case Instruction::BitCast:
2106 {
2107 // UnaryExpr
2108 // OperandList[0] is value
2109
2110 Value *s = constant_expr->getOperand(0);
2111
Greg Clayton3c7feb42010-11-19 01:05:25 +00002112 if (s == old_constant)
2113 s = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002114
Sean Callananc0492742011-05-23 21:40:23 +00002115 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002116
Greg Clayton3c7feb42010-11-19 01:05:25 +00002117 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002118 }
2119 break;
2120 case Instruction::GetElementPtr:
2121 {
2122 // GetElementPtrConstantExpr
2123 // OperandList[0] is base
2124 // OperandList[1]... are indices
2125
2126 Value *ptr = constant_expr->getOperand(0);
2127
Greg Clayton3c7feb42010-11-19 01:05:25 +00002128 if (ptr == old_constant)
2129 ptr = new_constant;
Sean Callanan9b6898f2011-07-30 02:42:06 +00002130
2131 std::vector<Value*> index_vector;
Sean Callananbafd6852010-07-14 23:40:29 +00002132
2133 unsigned operand_index;
2134 unsigned num_operands = constant_expr->getNumOperands();
2135
2136 for (operand_index = 1;
2137 operand_index < num_operands;
2138 ++operand_index)
2139 {
2140 Value *operand = constant_expr->getOperand(operand_index);
2141
Greg Clayton3c7feb42010-11-19 01:05:25 +00002142 if (operand == old_constant)
2143 operand = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002144
Sean Callanan9b6898f2011-07-30 02:42:06 +00002145 index_vector.push_back(operand);
Sean Callananbafd6852010-07-14 23:40:29 +00002146 }
2147
Sean Callanan9b6898f2011-07-30 02:42:06 +00002148 ArrayRef <Value*> indices(index_vector);
2149
2150 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002151
Greg Clayton3c7feb42010-11-19 01:05:25 +00002152 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002153 }
2154 break;
2155 }
2156 }
2157 else
2158 {
2159 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002160 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002161 return false;
2162 }
2163 }
2164 else
2165 {
2166 // simple fall-through case for non-constants
Greg Clayton3c7feb42010-11-19 01:05:25 +00002167 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callananbafd6852010-07-14 23:40:29 +00002168 }
2169 }
2170
2171 return true;
2172}
2173
Sean Callanan8bce6652010-07-13 21:41:46 +00002174bool
Sean Callananc0492742011-05-23 21:40:23 +00002175IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan8bce6652010-07-13 21:41:46 +00002176{
Sean Callanane8a59a82010-09-13 21:34:21 +00002177 if (!m_resolve_vars)
2178 return true;
2179
Greg Claytone005f2c2010-11-06 01:53:30 +00002180 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00002181
2182 m_decl_map->DoStructLayout();
2183
2184 if (log)
2185 log->Printf("Element arrangement:");
2186
2187 uint32_t num_elements;
2188 uint32_t element_index;
2189
2190 size_t size;
2191 off_t alignment;
2192
2193 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2194 return false;
2195
Greg Clayton3c7feb42010-11-19 01:05:25 +00002196 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00002197
Greg Clayton3c7feb42010-11-19 01:05:25 +00002198 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002199 {
2200 if (m_error_stream)
2201 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2202
Sean Callanan8bce6652010-07-13 21:41:46 +00002203 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002204 }
2205
Sean Callanan02fbafa2010-07-27 21:39:39 +00002206 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00002207
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002208 if (argument->getName().equals("this"))
2209 {
2210 ++iter;
2211
Greg Clayton3c7feb42010-11-19 01:05:25 +00002212 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002213 {
2214 if (m_error_stream)
2215 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2216
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002217 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002218 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002219
2220 argument = iter;
2221 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002222 else if (argument->getName().equals("self"))
2223 {
2224 ++iter;
2225
2226 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002227 {
2228 if (m_error_stream)
2229 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2230
Sean Callanan3aa7da52010-12-13 22:46:15 +00002231 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002232 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002233
2234 if (!iter->getName().equals("_cmd"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002235 {
2236 if (m_error_stream)
2237 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2238
Sean Callanan3aa7da52010-12-13 22:46:15 +00002239 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002240 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002241
2242 ++iter;
2243
2244 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 'self' and '_cmd' arguments (should take a struct pointer too)");
2248
Sean Callanan3aa7da52010-12-13 22:46:15 +00002249 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002250 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002251
2252 argument = iter;
2253 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002254
Greg Clayton8de27c72010-10-15 22:48:33 +00002255 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002256 {
2257 if (m_error_stream)
2258 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2259
Sean Callanan8bce6652010-07-13 21:41:46 +00002260 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002261 }
2262
Sean Callanan8bce6652010-07-13 21:41:46 +00002263 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002264 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00002265
Greg Clayton3c7feb42010-11-19 01:05:25 +00002266 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00002267 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00002268
Sean Callanan6ba533e2010-11-17 23:00:36 +00002269 if (!FirstEntryInstruction)
Sean Callanan97c924e2011-01-27 01:07:04 +00002270 {
2271 if (m_error_stream)
2272 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2273
Sean Callanan8bce6652010-07-13 21:41:46 +00002274 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002275 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002276
Sean Callananc0492742011-05-23 21:40:23 +00002277 LLVMContext &context(m_module->getContext());
Sean Callanan9b6898f2011-07-30 02:42:06 +00002278 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan8bce6652010-07-13 21:41:46 +00002279
2280 if (!offset_type)
Sean Callanan97c924e2011-01-27 01:07:04 +00002281 {
2282 if (m_error_stream)
2283 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2284
Sean Callanan8bce6652010-07-13 21:41:46 +00002285 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002286 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002287
2288 for (element_index = 0; element_index < num_elements; ++element_index)
2289 {
Sean Callanan58baaad2011-07-08 00:39:14 +00002290 const clang::NamedDecl *decl = NULL;
2291 Value *value = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002292 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00002293 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00002294
Sean Callanan45690fe2010-08-30 22:17:16 +00002295 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan97c924e2011-01-27 01:07:04 +00002296 {
2297 if (m_error_stream)
2298 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2299
Sean Callanan8bce6652010-07-13 21:41:46 +00002300 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002301 }
2302
Sean Callanan8bce6652010-07-13 21:41:46 +00002303 if (log)
Sean Callananc7ca4662011-10-25 18:36:40 +00002304 log->Printf(" \"%s\" (\"%s\") placed at %lld",
Greg Clayton8de27c72010-10-15 22:48:33 +00002305 name.GetCString(),
Sean Callananc7ca4662011-10-25 18:36:40 +00002306 decl->getNameAsString().c_str(),
Sean Callanan8bce6652010-07-13 21:41:46 +00002307 offset);
2308
Sean Callanan9b6898f2011-07-30 02:42:06 +00002309 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callanan6ba533e2010-11-17 23:00:36 +00002310 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan6a925532011-01-13 08:53:35 +00002311
Sean Callananc7ca4662011-10-25 18:36:40 +00002312 if (value)
Sean Callanan6a925532011-01-13 08:53:35 +00002313 {
Sean Callananc7ca4662011-10-25 18:36:40 +00002314 Value *replacement = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00002315
Sean Callananc7ca4662011-10-25 18:36:40 +00002316 if (log)
2317 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan6a925532011-01-13 08:53:35 +00002318
Sean Callananc7ca4662011-10-25 18:36:40 +00002319 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2320 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2321 // entry in order to produce the static variable that the AST thinks it is accessing.
2322 if (name == m_result_name && !m_result_is_pointer)
2323 {
2324 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2325
2326 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2327
2328 replacement = load;
2329 }
2330 else
2331 {
2332 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2333
2334 replacement = bit_cast;
2335 }
2336
2337 if (Constant *constant = dyn_cast<Constant>(value))
2338 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2339 else
2340 value->replaceAllUsesWith(replacement);
2341
2342 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2343 var->eraseFromParent();
2344 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002345 }
2346
2347 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002348 log->Printf("Total structure [align %lld, size %lu]", alignment, size);
Sean Callanan8bce6652010-07-13 21:41:46 +00002349
2350 return true;
2351}
2352
Sean Callananc0492742011-05-23 21:40:23 +00002353llvm::Constant *
Sean Callanan9b6898f2011-07-30 02:42:06 +00002354IRForTarget::BuildRelocation(llvm::Type *type,
Sean Callananc0492742011-05-23 21:40:23 +00002355 uint64_t offset)
2356{
2357 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2358
Sean Callanan9b6898f2011-07-30 02:42:06 +00002359 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2360 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002361
2362 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanan9b6898f2011-07-30 02:42:06 +00002363
2364 llvm::Constant *offset_array[1];
2365
2366 offset_array[0] = offset_int;
2367
2368 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2369
2370 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callananc0492742011-05-23 21:40:23 +00002371 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2372
2373 return reloc_getbitcast;
2374}
2375
2376bool
2377IRForTarget::CompleteDataAllocation ()
2378{
Sean Callanan47dc4572011-09-15 02:13:07 +00002379 if (!m_data_allocator)
2380 return true;
2381
Sean Callananc0492742011-05-23 21:40:23 +00002382 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2383
2384 if (!m_data_allocator->GetStream().GetSize())
2385 return true;
2386
2387 lldb::addr_t allocation = m_data_allocator->Allocate();
2388
2389 if (log)
2390 {
2391 if (allocation)
2392 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2393 else
2394 log->Printf("Failed to allocate static data");
2395 }
2396
2397 if (!allocation)
2398 return false;
2399
Sean Callanan9b6898f2011-07-30 02:42:06 +00002400 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2401 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002402
2403 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2404 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2405
2406 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2407
2408 m_reloc_placeholder->eraseFromParent();
2409
2410 return true;
2411}
2412
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002413bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002414IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002415{
Greg Claytone005f2c2010-11-06 01:53:30 +00002416 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002417
Sean Callananc0492742011-05-23 21:40:23 +00002418 m_module = &llvm_module;
Sean Callananc7ca4662011-10-25 18:36:40 +00002419 m_target_data.reset(new TargetData(m_module));
Sean Callananc0492742011-05-23 21:40:23 +00002420
2421 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002422
2423 if (!function)
2424 {
2425 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002426 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00002427
2428 if (m_error_stream)
Sean Callananc0492742011-05-23 21:40:23 +00002429 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 +00002430
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002431 return false;
2432 }
Sean Callananc0492742011-05-23 21:40:23 +00002433
2434 if (!FixFunctionLinkage (*function))
2435 {
2436 if (log)
2437 log->Printf("Couldn't fix the linkage for the function");
2438
2439 return false;
2440 }
2441
Sean Callananc7ca4662011-10-25 18:36:40 +00002442 if (log)
2443 {
2444 std::string s;
2445 raw_string_ostream oss(s);
2446
2447 m_module->print(oss, NULL);
2448
2449 oss.flush();
2450
2451 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2452 }
2453
Sean Callanan9b6898f2011-07-30 02:42:06 +00002454 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00002455
2456 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2457 intptr_ty,
2458 false /* isConstant */,
2459 GlobalVariable::InternalLinkage,
2460 Constant::getNullValue(intptr_ty),
2461 "reloc_placeholder",
2462 NULL /* InsertBefore */,
2463 false /* ThreadLocal */,
2464 0 /* AddressSpace */);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002465
Sean Callanan02fbafa2010-07-27 21:39:39 +00002466 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002467
Sean Callananc0492742011-05-23 21:40:23 +00002468 m_has_side_effects = HasSideEffects(*function);
Sean Callanan05a5a1b2010-12-16 03:17:46 +00002469
Sean Callanan82b74c82010-08-12 01:56:52 +00002470 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00002471 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00002472 //
2473
Sean Callananc0492742011-05-23 21:40:23 +00002474 if (!CreateResultVariable(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002475 {
2476 if (log)
2477 log->Printf("CreateResultVariable() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002478
2479 // CreateResultVariable() reports its own errors, so we don't do so here
2480
Sean Callanan82b74c82010-08-12 01:56:52 +00002481 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002482 }
Sean Callanan47dc4572011-09-15 02:13:07 +00002483
2484 if (m_const_result && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2485 {
2486 m_interpret_success = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +00002487 return true;
Sean Callanan47dc4572011-09-15 02:13:07 +00002488 }
2489
2490 for (bbi = function->begin();
2491 bbi != function->end();
2492 ++bbi)
2493 {
2494 if (!RemoveGuards(*bbi))
2495 {
2496 if (log)
2497 log->Printf("RemoveGuards() failed");
2498
2499 // RemoveGuards() reports its own errors, so we don't do so here
2500
2501 return false;
2502 }
2503
2504 if (!RewritePersistentAllocs(*bbi))
2505 {
2506 if (log)
2507 log->Printf("RewritePersistentAllocs() failed");
2508
2509 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2510
2511 return false;
2512 }
2513 }
2514
2515 if (m_decl_map && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2516 {
2517 IRInterpreter interpreter (*m_decl_map,
2518 m_error_stream);
2519
2520 if (interpreter.maybeRunOnFunction(m_const_result, m_result_name, m_result_type, *function, llvm_module))
2521 {
2522 m_interpret_success = true;
2523 return true;
2524 }
2525 }
Sean Callanan696cf5f2011-05-07 01:06:41 +00002526
Sean Callananc0492742011-05-23 21:40:23 +00002527 if (log)
2528 {
2529 std::string s;
2530 raw_string_ostream oss(s);
2531
2532 m_module->print(oss, NULL);
2533
2534 oss.flush();
2535
2536 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2537 }
2538
Sean Callanan6ba533e2010-11-17 23:00:36 +00002539 ///////////////////////////////////////////////////////////////////////////////
2540 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2541 //
Sean Callanan6ba533e2010-11-17 23:00:36 +00002542
Sean Callananc0492742011-05-23 21:40:23 +00002543 if (!RewriteObjCConstStrings(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002544 {
2545 if (log)
2546 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002547
2548 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2549
Sean Callanan6ba533e2010-11-17 23:00:36 +00002550 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002551 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00002552
Sean Callanan5c9a3c72011-08-04 21:37:47 +00002553 ///////////////////////////////
2554 // Resolve function pointers
2555 //
2556
2557 if (!ResolveFunctionPointers(llvm_module, *function))
2558 {
2559 if (log)
2560 log->Printf("ResolveFunctionPointers() failed");
2561
2562 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2563
2564 return false;
2565 }
2566
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002567 for (bbi = function->begin();
2568 bbi != function->end();
2569 ++bbi)
2570 {
Sean Callananc0492742011-05-23 21:40:23 +00002571 if (!RewriteObjCSelectors(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002572 {
2573 if (log)
2574 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002575
2576 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2577
Sean Callanana48fe162010-08-11 03:57:18 +00002578 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002579 }
Sean Callanana48fe162010-08-11 03:57:18 +00002580
Sean Callananc0492742011-05-23 21:40:23 +00002581 if (!ResolveCalls(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002582 {
2583 if (log)
2584 log->Printf("ResolveCalls() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002585
2586 // ResolveCalls() reports its own errors, so we don't do so here
2587
Sean Callanan8bce6652010-07-13 21:41:46 +00002588 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002589 }
Sean Callananc0492742011-05-23 21:40:23 +00002590
2591 if (!ReplaceStaticLiterals(*bbi))
2592 {
2593 if (log)
2594 log->Printf("ReplaceStaticLiterals() failed");
2595
2596 return false;
2597 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002598 }
2599
Sean Callanan771131d2010-09-30 21:18:25 +00002600 ///////////////////////////////
2601 // Run function-level passes
2602 //
2603
Sean Callananc0492742011-05-23 21:40:23 +00002604 if (!ResolveExternals(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002605 {
2606 if (log)
2607 log->Printf("ResolveExternals() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002608
2609 // ResolveExternals() reports its own errors, so we don't do so here
2610
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002611 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002612 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002613
Sean Callananc0492742011-05-23 21:40:23 +00002614 if (!ReplaceVariables(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002615 {
2616 if (log)
2617 log->Printf("ReplaceVariables() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002618
2619 // ReplaceVariables() reports its own errors, so we don't do so here
2620
Sean Callanan771131d2010-09-30 21:18:25 +00002621 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002622 }
Sean Callanan771131d2010-09-30 21:18:25 +00002623
Sean Callananc0492742011-05-23 21:40:23 +00002624 if (!ReplaceStrings())
2625 {
2626 if (log)
2627 log->Printf("ReplaceStrings() failed");
2628
2629 return false;
2630 }
2631
2632 if (!CompleteDataAllocation())
2633 {
2634 if (log)
2635 log->Printf("CompleteDataAllocation() failed");
2636
2637 return false;
2638 }
2639
Sean Callanan8bce6652010-07-13 21:41:46 +00002640 if (log)
2641 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00002642 std::string s;
2643 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00002644
Sean Callananc0492742011-05-23 21:40:23 +00002645 m_module->print(oss, NULL);
Sean Callanan321fe9e2010-07-28 01:00:59 +00002646
2647 oss.flush();
2648
Greg Claytonb5037af2010-11-15 01:47:11 +00002649 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002650 }
2651
2652 return true;
2653}
2654
2655void
Greg Clayton3c7feb42010-11-19 01:05:25 +00002656IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002657{
2658}
2659
2660PassManagerType
2661IRForTarget::getPotentialPassManagerType() const
2662{
2663 return PMT_ModulePassManager;
2664}