blob: 6a70d4df095e4d839506da00bc2697c217845a88 [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);
221 Value **fun_value_ptr = NULL;
222
223 if (fun_decl)
224 {
225 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_value_ptr, fun_addr))
226 {
227 fun_value_ptr = NULL;
228
229 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
230 {
231 if (log)
232 log->Printf("Function \"%s\" had no address", name.GetCString());
233
234 if (m_error_stream)
235 m_error_stream->Printf("Error [IRForTarget]: Call to a function '%s' that is not present in the target\n", name.GetCString());
236
237 return false;
238 }
239 }
240 }
241 else
242 {
243 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
244 {
245 if (log)
246 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
247
248 if (m_error_stream)
249 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
250
251 return false;
252 }
253 }
254
255 if (log)
256 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), fun_addr);
257
258 return true;
259}
260
261llvm::Constant *
262IRForTarget::BuildFunctionPointer (llvm::Type *type,
263 uint64_t ptr)
264{
265 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
266 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
267 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
268 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
269 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
270}
271
272bool
273IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module,
274 llvm::Function &llvm_function)
275{
276 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
277
278 for (llvm::Module::iterator fi = llvm_module.begin();
279 fi != llvm_module.end();
280 ++fi)
281 {
282 Function *fun = fi;
283
284 bool is_decl = fun->isDeclaration();
285
286 if (log)
287 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getNameStr().c_str());
288
289 if (!is_decl)
290 continue;
291
292 if (fun->hasNUses(0))
293 continue; // ignore
294
295 uint64_t addr = LLDB_INVALID_ADDRESS;
296 lldb_private::ConstString name;
297 Constant **value_ptr = NULL;
298
299 if (!GetFunctionAddress(fun,
300 addr,
301 name,
302 value_ptr))
303 return false; // GetFunctionAddress reports its own errors
304
305 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
306
307 if (value_ptr)
308 *value_ptr = value;
309
310 fun->replaceAllUsesWith(value);
311 }
312
313 return true;
314}
315
Sean Callanan47dc4572011-09-15 02:13:07 +0000316
Sean Callanan696cf5f2011-05-07 01:06:41 +0000317clang::NamedDecl *
Sean Callanan47dc4572011-09-15 02:13:07 +0000318IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000319{
320 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
321
Sean Callanan47dc4572011-09-15 02:13:07 +0000322 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan696cf5f2011-05-07 01:06:41 +0000323
324 if (!named_metadata)
325 return NULL;
326
327 unsigned num_nodes = named_metadata->getNumOperands();
328 unsigned node_index;
329
330 for (node_index = 0;
331 node_index < num_nodes;
332 ++node_index)
333 {
334 MDNode *metadata_node = named_metadata->getOperand(node_index);
335
336 if (!metadata_node)
337 return NULL;
338
339 if (metadata_node->getNumOperands() != 2)
340 continue;
341
342 if (metadata_node->getOperand(0) != global_val)
343 continue;
344
345 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
346
347 if (!constant_int)
348 return NULL;
349
350 uintptr_t ptr = constant_int->getZExtValue();
351
352 return reinterpret_cast<clang::NamedDecl *>(ptr);
353 }
354
355 return NULL;
356}
357
Sean Callanan47dc4572011-09-15 02:13:07 +0000358clang::NamedDecl *
359IRForTarget::DeclForGlobal (GlobalValue *global_val)
360{
361 return DeclForGlobal(global_val, m_module);
362}
363
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000364void
365IRForTarget::MaybeSetConstantResult (llvm::Constant *initializer,
366 const lldb_private::ConstString &name,
367 lldb_private::TypeFromParser type)
368{
Sean Callanan696cf5f2011-05-07 01:06:41 +0000369 if (llvm::ConstantExpr *init_expr = dyn_cast<llvm::ConstantExpr>(initializer))
370 {
371 switch (init_expr->getOpcode())
372 {
373 default:
374 return;
375 case Instruction::IntToPtr:
376 MaybeSetConstantResult (init_expr->getOperand(0), name, type);
377 return;
378 }
379 }
380 else if (llvm::ConstantInt *init_int = dyn_cast<llvm::ConstantInt>(initializer))
381 {
382 m_const_result = m_decl_map->BuildIntegerVariable(name, type, init_int->getValue());
383 }
384}
385
386void
Sean Callananc0492742011-05-23 21:40:23 +0000387IRForTarget::MaybeSetCastResult (lldb_private::TypeFromParser type)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000388{
389 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
390
391 if (!m_result_store)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000392 return;
393
Sean Callanan696cf5f2011-05-07 01:06:41 +0000394 LoadInst *original_load = NULL;
395
396 for (llvm::Value *current_value = m_result_store->getValueOperand(), *next_value;
397 current_value != NULL;
398 current_value = next_value)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000399 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000400 CastInst *cast_inst = dyn_cast<CastInst>(current_value);
401 LoadInst *load_inst = dyn_cast<LoadInst>(current_value);
402
403 if (cast_inst)
404 {
405 next_value = cast_inst->getOperand(0);
406 }
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000407 else if (load_inst)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000408 {
409 if (isa<LoadInst>(load_inst->getPointerOperand()))
410 {
411 next_value = load_inst->getPointerOperand();
412 }
413 else
414 {
415 original_load = load_inst;
416 break;
417 }
418 }
419 else
420 {
421 return;
422 }
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000423 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000424
425 Value *loaded_value = original_load->getPointerOperand();
426 GlobalVariable *loaded_global = dyn_cast<GlobalVariable>(loaded_value);
427
428 if (!loaded_global)
429 return;
430
Sean Callananc0492742011-05-23 21:40:23 +0000431 clang::NamedDecl *loaded_decl = DeclForGlobal(loaded_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000432
433 if (!loaded_decl)
434 return;
435
436 clang::VarDecl *loaded_var = dyn_cast<clang::VarDecl>(loaded_decl);
437
438 if (!loaded_var)
439 return;
440
441 if (log)
442 {
443 lldb_private::StreamString type_desc_stream;
444 type.DumpTypeDescription(&type_desc_stream);
445
446 log->Printf("Type to cast variable to: \"%s\"", type_desc_stream.GetString().c_str());
447 }
448
449 m_const_result = m_decl_map->BuildCastVariable(m_result_name, loaded_var, type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000450}
451
452bool
Sean Callananc0492742011-05-23 21:40:23 +0000453IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanan82b74c82010-08-12 01:56:52 +0000454{
Greg Claytone005f2c2010-11-06 01:53:30 +0000455 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan82b74c82010-08-12 01:56:52 +0000456
Sean Callanane8a59a82010-09-13 21:34:21 +0000457 if (!m_resolve_vars)
458 return true;
459
460 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000461
Sean Callananc0492742011-05-23 21:40:23 +0000462 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000463
Sean Callanan9b6898f2011-07-30 02:42:06 +0000464 std::string result_name_str;
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000465 const char *result_name = NULL;
466
467 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
468 vi != ve;
469 ++vi)
470 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000471 result_name_str = vi->first().str();
472 const char *value_name = result_name_str.c_str();
473
474 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
475 !strstr(value_name, "GV"))
Sean Callanan6a925532011-01-13 08:53:35 +0000476 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000477 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000478 m_result_is_pointer = true;
479 break;
480 }
481
Sean Callanan9b6898f2011-07-30 02:42:06 +0000482 if (strstr(value_name, "$__lldb_expr_result") &&
483 !strstr(value_name, "GV"))
Sean Callananc04743d2010-09-28 21:13:03 +0000484 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000485 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000486 m_result_is_pointer = false;
Sean Callananc04743d2010-09-28 21:13:03 +0000487 break;
488 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000489 }
490
491 if (!result_name)
492 {
493 if (log)
494 log->PutCString("Couldn't find result variable");
495
496 return true;
497 }
498
Sean Callananc04743d2010-09-28 21:13:03 +0000499 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000500 log->Printf("Result name: \"%s\"", result_name);
Sean Callananc04743d2010-09-28 21:13:03 +0000501
Sean Callananc0492742011-05-23 21:40:23 +0000502 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000503
504 if (!result_value)
505 {
506 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000507 log->PutCString("Result variable had no data");
Sean Callanan6a925532011-01-13 08:53:35 +0000508
Sean Callanan97c924e2011-01-27 01:07:04 +0000509 if (m_error_stream)
510 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
511
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000512 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000513 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000514
Sean Callanan82b74c82010-08-12 01:56:52 +0000515 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000516 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000517
518 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
519
520 if (!result_global)
521 {
522 if (log)
523 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000524
525 if (m_error_stream)
526 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
527
Sean Callanan82b74c82010-08-12 01:56:52 +0000528 return false;
529 }
530
Sean Callananc0492742011-05-23 21:40:23 +0000531 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000532 if (!result_decl)
Sean Callanan82b74c82010-08-12 01:56:52 +0000533 {
534 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000535 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanan82b74c82010-08-12 01:56:52 +0000536
Sean Callanan97c924e2011-01-27 01:07:04 +0000537 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000538 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 +0000539
Sean Callanan82b74c82010-08-12 01:56:52 +0000540 return false;
541 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000542
Sean Callanan696cf5f2011-05-07 01:06:41 +0000543 if (log)
Sean Callanan82b74c82010-08-12 01:56:52 +0000544 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000545 std::string decl_desc_str;
546 raw_string_ostream decl_desc_stream(decl_desc_str);
547 result_decl->print(decl_desc_stream);
548 decl_desc_stream.flush();
Sean Callanan82b74c82010-08-12 01:56:52 +0000549
Sean Callanan696cf5f2011-05-07 01:06:41 +0000550 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000551 }
552
Sean Callanan696cf5f2011-05-07 01:06:41 +0000553 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
554 if (!result_var)
Sean Callanan82b74c82010-08-12 01:56:52 +0000555 {
556 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000557 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan97c924e2011-01-27 01:07:04 +0000558
559 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000560 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 +0000561
Sean Callanan82b74c82010-08-12 01:56:52 +0000562 return false;
563 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000564
Sean Callanan82b74c82010-08-12 01:56:52 +0000565 // Get the next available result name from m_decl_map and create the persistent
566 // variable for it
Sean Callanan47dc4572011-09-15 02:13:07 +0000567
Sean Callanan696cf5f2011-05-07 01:06:41 +0000568 // If the result is an Lvalue, it is emitted as a pointer; see
569 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan6a925532011-01-13 08:53:35 +0000570 if (m_result_is_pointer)
571 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000572 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanand5b3c352011-01-27 04:42:51 +0000573 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
574 const clang::PointerType *pointer_pointertype = dyn_cast<clang::PointerType>(pointer_type);
Sean Callanan6a925532011-01-13 08:53:35 +0000575
576 if (!pointer_pointertype)
577 {
578 if (log)
579 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan97c924e2011-01-27 01:07:04 +0000580
581 if (m_error_stream)
582 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
583
Sean Callanan6a925532011-01-13 08:53:35 +0000584 return false;
585 }
586
587 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
588
Sean Callanan47dc4572011-09-15 02:13:07 +0000589 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
Sean Callanan6a925532011-01-13 08:53:35 +0000590 &result_decl->getASTContext());
591 }
592 else
593 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000594 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan6a925532011-01-13 08:53:35 +0000595 &result_decl->getASTContext());
596 }
597
Sean Callanan696cf5f2011-05-07 01:06:41 +0000598 if (log)
599 {
600 lldb_private::StreamString type_desc_stream;
Sean Callanan47dc4572011-09-15 02:13:07 +0000601 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000602
603 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetString().c_str());
604 }
605
Sean Callanan6a925532011-01-13 08:53:35 +0000606 m_result_name = m_decl_map->GetPersistentResultName();
Sean Callanan82b74c82010-08-12 01:56:52 +0000607
608 if (log)
Sean Callanan6a925532011-01-13 08:53:35 +0000609 log->Printf("Creating a new result global: \"%s\"", m_result_name.GetCString());
Sean Callanan82b74c82010-08-12 01:56:52 +0000610
611 // Construct a new result global and set up its metadata
612
Sean Callananc0492742011-05-23 21:40:23 +0000613 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanan82b74c82010-08-12 01:56:52 +0000614 result_global->getType()->getElementType(),
615 false, /* not constant */
616 GlobalValue::ExternalLinkage,
617 NULL, /* no initializer */
Sean Callanan6a925532011-01-13 08:53:35 +0000618 m_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000619
620 // It's too late in compilation to create a new VarDecl for this, but we don't
621 // need to. We point the metadata at the old VarDecl. This creates an odd
622 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000623 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000624 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
625 // fixed up.
626
Sean Callananc0492742011-05-23 21:40:23 +0000627 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan696cf5f2011-05-07 01:06:41 +0000628 reinterpret_cast<uint64_t>(result_decl),
Sean Callanan82b74c82010-08-12 01:56:52 +0000629 false);
630
631 llvm::Value* values[2];
632 values[0] = new_result_global;
633 values[1] = new_constant_int;
634
Sean Callanan0de254a2011-05-15 22:34:38 +0000635 ArrayRef<Value*> value_ref(values, 2);
636
Sean Callananc0492742011-05-23 21:40:23 +0000637 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
638 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000639 named_metadata->addOperand(persistent_global_md);
640
641 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000642 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000643 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000644 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000645
646 if (result_global->hasNUses(0))
647 {
648 // We need to synthesize a store for this variable, because otherwise
649 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000650
Greg Clayton8de27c72010-10-15 22:48:33 +0000651 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000652 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
653
654 if (!first_entry_instruction)
655 return false;
656
657 if (!result_global->hasInitializer())
658 {
659 if (log)
660 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000661
662 if (m_error_stream)
663 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
664
Sean Callanan2e2db532010-09-07 22:43:19 +0000665 return false;
666 }
667
668 Constant *initializer = result_global->getInitializer();
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000669
670 // Here we write the initializer into a result variable assuming it
671 // can be computed statically.
672
673 if (!m_has_side_effects)
674 {
675 MaybeSetConstantResult (initializer,
Sean Callanan6a925532011-01-13 08:53:35 +0000676 m_result_name,
Sean Callanan47dc4572011-09-15 02:13:07 +0000677 m_result_type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000678 }
Sean Callanan2e2db532010-09-07 22:43:19 +0000679
Greg Clayton2c344ca2011-02-05 02:28:58 +0000680 StoreInst *synthesized_store = new StoreInst(initializer,
681 new_result_global,
682 first_entry_instruction);
Sean Callanan2e2db532010-09-07 22:43:19 +0000683
684 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000685 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000686 }
687 else
688 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000689 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (m_result_type.GetOpaqueQualType()))
Sean Callanan696cf5f2011-05-07 01:06:41 +0000690 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000691 MaybeSetCastResult (m_result_type);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000692 }
693
Sean Callanan2e2db532010-09-07 22:43:19 +0000694 result_global->replaceAllUsesWith(new_result_global);
695 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000696
697 if (!m_const_result)
698 m_decl_map->AddPersistentVariable(result_decl,
699 m_result_name,
Sean Callanan47dc4572011-09-15 02:13:07 +0000700 m_result_type,
Sean Callanan696cf5f2011-05-07 01:06:41 +0000701 true,
702 m_result_is_pointer);
Sean Callanan2e2db532010-09-07 22:43:19 +0000703
Sean Callanan82b74c82010-08-12 01:56:52 +0000704 result_global->eraseFromParent();
705
706 return true;
707}
708
Johnny Chen58021cc2011-08-09 23:10:20 +0000709#if 0
Greg Clayton3c7feb42010-11-19 01:05:25 +0000710static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000711{
712 if (!depth)
713 return;
714
715 depth--;
716
Johnny Chen58021cc2011-08-09 23:10:20 +0000717 if (log)
718 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000719
Greg Clayton3c7feb42010-11-19 01:05:25 +0000720 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000721 ui != ue;
722 ++ui)
723 {
Johnny Chen58021cc2011-08-09 23:10:20 +0000724 if (log)
725 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000726 DebugUsers(log, *ui, depth);
727 }
728
Johnny Chen58021cc2011-08-09 23:10:20 +0000729 if (log)
730 log->Printf(" <End uses>");
Sean Callanan6ba533e2010-11-17 23:00:36 +0000731}
Johnny Chen58021cc2011-08-09 23:10:20 +0000732#endif
Sean Callanan6ba533e2010-11-17 23:00:36 +0000733
734bool
Sean Callananc0492742011-05-23 21:40:23 +0000735IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton3c7feb42010-11-19 01:05:25 +0000736 llvm::GlobalVariable *cstr,
737 Instruction *FirstEntryInstruction)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000738{
739 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
740
Sean Callanan9b6898f2011-07-30 02:42:06 +0000741 Type *ns_str_ty = ns_str->getType();
Sean Callananc0492742011-05-23 21:40:23 +0000742
Sean Callanan9b6898f2011-07-30 02:42:06 +0000743 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
744 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callananc0492742011-05-23 21:40:23 +0000745 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan9b6898f2011-07-30 02:42:06 +0000746 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
747 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000748
749 if (!m_CFStringCreateWithBytes)
750 {
751 lldb::addr_t CFStringCreateWithBytes_addr;
752
753 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
754
755 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
756 {
757 if (log)
758 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
759
Sean Callanan97c924e2011-01-27 01:07:04 +0000760 if (m_error_stream)
761 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
762
Sean Callanan6ba533e2010-11-17 23:00:36 +0000763 return false;
764 }
765
766 if (log)
767 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr);
768
769 // Build the function type:
770 //
771 // CFStringRef CFStringCreateWithBytes (
772 // CFAllocatorRef alloc,
773 // const UInt8 *bytes,
774 // CFIndex numBytes,
775 // CFStringEncoding encoding,
776 // Boolean isExternalRepresentation
777 // );
778 //
779 // We make the following substitutions:
780 //
781 // CFStringRef -> i8*
782 // CFAllocatorRef -> i8*
783 // UInt8 * -> i8*
784 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
785 // CFStringEncoding -> i32
786 // Boolean -> i8
787
Sean Callanan9b6898f2011-07-30 02:42:06 +0000788 Type *arg_type_array[5];
789
790 arg_type_array[0] = i8_ptr_ty;
791 arg_type_array[1] = i8_ptr_ty;
792 arg_type_array[2] = intptr_ty;
793 arg_type_array[3] = i32_ty;
794 arg_type_array[4] = i8_ty;
795
796 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
797
Sean Callananc0492742011-05-23 21:40:23 +0000798 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000799
800 // Build the constant containing the pointer to the function
801 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
802 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
803 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
804 }
805
Sean Callanan58baaad2011-07-08 00:39:14 +0000806 ConstantArray *string_array = NULL;
Sean Callanan0ece5262011-02-10 22:17:53 +0000807
808 if (cstr)
809 string_array = dyn_cast<ConstantArray>(cstr->getInitializer());
Sean Callanan9b6898f2011-07-30 02:42:06 +0000810
Sean Callanan6ba533e2010-11-17 23:00:36 +0000811 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan0ece5262011-02-10 22:17:53 +0000812 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
813 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getType()->getNumElements() - 1 : 0, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000814 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
815 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
816
Sean Callanan9b6898f2011-07-30 02:42:06 +0000817 Value *argument_array[5];
818
819 argument_array[0] = alloc_arg;
820 argument_array[1] = bytes_arg;
821 argument_array[2] = numBytes_arg;
822 argument_array[3] = encoding_arg;
823 argument_array[4] = isExternal_arg;
824
825 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000826
827 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanan9b6898f2011-07-30 02:42:06 +0000828 CFSCWB_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +0000829 "CFStringCreateWithBytes",
830 FirstEntryInstruction);
Sean Callananae71e302010-11-18 22:21:58 +0000831
Greg Clayton3c7feb42010-11-19 01:05:25 +0000832 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000833 {
834 if (log)
835 log->PutCString("Couldn't replace the NSString with the result of the call");
836
Sean Callanan97c924e2011-01-27 01:07:04 +0000837 if (m_error_stream)
838 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
839
Sean Callanan6ba533e2010-11-17 23:00:36 +0000840 return false;
841 }
842
Greg Clayton3c7feb42010-11-19 01:05:25 +0000843 ns_str->eraseFromParent();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000844
845 return true;
846}
847
848bool
Sean Callananc0492742011-05-23 21:40:23 +0000849IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000850{
851 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
852
Sean Callananc0492742011-05-23 21:40:23 +0000853 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000854
Greg Clayton3c7feb42010-11-19 01:05:25 +0000855 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000856 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
857
858 if (!FirstEntryInstruction)
859 {
860 if (log)
861 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
862
Sean Callanan97c924e2011-01-27 01:07:04 +0000863 if (m_error_stream)
864 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
865
Sean Callanan6ba533e2010-11-17 23:00:36 +0000866 return false;
867 }
868
869 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
870 vi != ve;
871 ++vi)
872 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000873 std::string value_name = vi->first().str();
874 const char *value_name_cstr = value_name.c_str();
875
876 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000877 {
878 Value *nsstring_value = vi->second;
879
880 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
881
882 if (!nsstring_global)
883 {
884 if (log)
885 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000886
887 if (m_error_stream)
888 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
889
Sean Callanan6ba533e2010-11-17 23:00:36 +0000890 return false;
891 }
892
893 if (!nsstring_global->hasInitializer())
894 {
895 if (log)
896 log->PutCString("NSString variable does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000897
898 if (m_error_stream)
899 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
900
Sean Callanan6ba533e2010-11-17 23:00:36 +0000901 return false;
902 }
903
904 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
905
906 if (!nsstring_struct)
907 {
908 if (log)
909 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan97c924e2011-01-27 01:07:04 +0000910
911 if (m_error_stream)
912 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
913
Sean Callanan6ba533e2010-11-17 23:00:36 +0000914 return false;
915 }
916
917 // We expect the following structure:
918 //
919 // struct {
920 // int *isa;
921 // int flags;
922 // char *str;
923 // long length;
924 // };
925
926 if (nsstring_struct->getNumOperands() != 4)
927 {
928 if (log)
929 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 +0000930
931 if (m_error_stream)
932 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
933
Sean Callanan6ba533e2010-11-17 23:00:36 +0000934 return false;
935 }
936
937 Constant *nsstring_member = nsstring_struct->getOperand(2);
938
939 if (!nsstring_member)
940 {
941 if (log)
942 log->PutCString("NSString initializer's str element was empty");
Sean Callanan97c924e2011-01-27 01:07:04 +0000943
944 if (m_error_stream)
945 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
946
Sean Callanan6ba533e2010-11-17 23:00:36 +0000947 return false;
948 }
949
950 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
951
952 if (!nsstring_expr)
953 {
954 if (log)
955 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan97c924e2011-01-27 01:07:04 +0000956
957 if (m_error_stream)
958 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
959
Sean Callanan6ba533e2010-11-17 23:00:36 +0000960 return false;
961 }
962
963 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
964 {
965 if (log)
966 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 +0000967
968 if (m_error_stream)
969 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
970
Sean Callanan6ba533e2010-11-17 23:00:36 +0000971 return false;
972 }
973
974 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
975
976 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
977
978 if (!cstr_global)
979 {
980 if (log)
981 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000982
983 if (m_error_stream)
984 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 +0000985
Sean Callanan6ba533e2010-11-17 23:00:36 +0000986 return false;
987 }
988
989 if (!cstr_global->hasInitializer())
990 {
991 if (log)
992 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000993
994 if (m_error_stream)
995 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
996
Sean Callanan6ba533e2010-11-17 23:00:36 +0000997 return false;
998 }
Sean Callanan0ece5262011-02-10 22:17:53 +0000999
1000 /*
Sean Callanan6ba533e2010-11-17 23:00:36 +00001001 if (!cstr_array)
1002 {
1003 if (log)
1004 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan97c924e2011-01-27 01:07:04 +00001005
1006 if (m_error_stream)
1007 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
1008
Sean Callanan6ba533e2010-11-17 23:00:36 +00001009 return false;
1010 }
1011
1012 if (!cstr_array->isCString())
1013 {
1014 if (log)
1015 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan97c924e2011-01-27 01:07:04 +00001016
1017 if (m_error_stream)
1018 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
1019
Sean Callanan6ba533e2010-11-17 23:00:36 +00001020 return false;
1021 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001022 */
1023
1024 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer());
Sean Callanan6ba533e2010-11-17 23:00:36 +00001025
1026 if (log)
Sean Callanan0ece5262011-02-10 22:17:53 +00001027 {
1028 if (cstr_array)
Sean Callanan9b6898f2011-07-30 02:42:06 +00001029 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().c_str());
Sean Callanan0ece5262011-02-10 22:17:53 +00001030 else
Sean Callanan9b6898f2011-07-30 02:42:06 +00001031 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan0ece5262011-02-10 22:17:53 +00001032 }
1033
1034 if (!cstr_array)
1035 cstr_global = NULL;
Sean Callanan6ba533e2010-11-17 23:00:36 +00001036
Sean Callananc0492742011-05-23 21:40:23 +00001037 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan97c924e2011-01-27 01:07:04 +00001038 {
Sean Callanan6ba533e2010-11-17 23:00:36 +00001039 if (log)
1040 log->PutCString("Error rewriting the constant string");
Sean Callanan97c924e2011-01-27 01:07:04 +00001041
1042 // We don't print an error message here because RewriteObjCConstString has done so for us.
1043
Sean Callanan6ba533e2010-11-17 23:00:36 +00001044 return false;
1045 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00001046 }
1047 }
1048
1049 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1050 vi != ve;
1051 ++vi)
1052 {
Sean Callanan9b6898f2011-07-30 02:42:06 +00001053 std::string value_name = vi->first().str();
1054 const char *value_name_cstr = value_name.c_str();
1055
1056 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callanan6ba533e2010-11-17 23:00:36 +00001057 {
1058 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1059
1060 if (!gv)
1061 {
1062 if (log)
1063 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001064
1065 if (m_error_stream)
1066 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1067
Sean Callanan6ba533e2010-11-17 23:00:36 +00001068 return false;
1069 }
1070
1071 gv->eraseFromParent();
1072
1073 break;
1074 }
1075 }
1076
1077 return true;
1078}
1079
Greg Clayton3c7feb42010-11-19 01:05:25 +00001080static bool IsObjCSelectorRef (Value *value)
Sean Callananf5857a02010-07-31 01:32:05 +00001081{
Greg Clayton3c7feb42010-11-19 01:05:25 +00001082 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callananf5857a02010-07-31 01:32:05 +00001083
Greg Clayton3c7feb42010-11-19 01:05:25 +00001084 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callananf5857a02010-07-31 01:32:05 +00001085 return false;
1086
1087 return true;
1088}
1089
Sean Callanan97c924e2011-01-27 01:07:04 +00001090// This function does not report errors; its callers are responsible.
Sean Callananf5857a02010-07-31 01:32:05 +00001091bool
Sean Callananc0492742011-05-23 21:40:23 +00001092IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callananf5857a02010-07-31 01:32:05 +00001093{
Greg Claytone005f2c2010-11-06 01:53:30 +00001094 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001095
1096 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1097
1098 if (!load)
1099 return false;
1100
1101 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1102 //
1103 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1104 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1105 //
1106 // where %obj is the object pointer and %tmp is the selector.
1107 //
Greg Clayton3c7feb42010-11-19 01:05:25 +00001108 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1109 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callananf5857a02010-07-31 01:32:05 +00001110
1111 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1112
1113 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1114
1115 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1116 return false;
1117
1118 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1119
1120 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1121
1122 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1123 return false;
1124
1125 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1126
1127 if (!osr_initializer_base)
1128 return false;
1129
1130 // Find the string's initializer (a ConstantArray) and get the string from it
1131
1132 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1133
1134 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1135 return false;
1136
1137 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1138
1139 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
1140
1141 if (!omvn_initializer_array->isString())
1142 return false;
1143
1144 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1145
1146 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001147 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +00001148
1149 // Construct a call to sel_registerName
1150
1151 if (!m_sel_registerName)
1152 {
Greg Claytonb5037af2010-11-15 01:47:11 +00001153 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +00001154
Greg Clayton8de27c72010-10-15 22:48:33 +00001155 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +00001156 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001157 return false;
1158
Sean Callananc2c6f772010-10-26 00:31:56 +00001159 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001160 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +00001161
Sean Callananf5857a02010-07-31 01:32:05 +00001162 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1163
1164 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callananc0492742011-05-23 21:40:23 +00001165 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001166 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanan9b6898f2011-07-30 02:42:06 +00001167 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001168
Sean Callanan9b6898f2011-07-30 02:42:06 +00001169 Type *type_array[1];
1170
1171 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1172
1173 ArrayRef<Type *> srN_arg_types(type_array, 1);
1174
Sean Callananf5857a02010-07-31 01:32:05 +00001175 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1176
1177 // Build the constant containing the pointer to the function
Sean Callanan9b6898f2011-07-30 02:42:06 +00001178 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1179 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananf5857a02010-07-31 01:32:05 +00001180 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +00001181 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001182 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1183 }
1184
Sean Callanan9b6898f2011-07-30 02:42:06 +00001185 Value *argument_array[1];
1186
Sean Callananc0492742011-05-23 21:40:23 +00001187 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callananf5857a02010-07-31 01:32:05 +00001188
Sean Callanan9b6898f2011-07-30 02:42:06 +00001189 argument_array[0] = omvn_pointer;
Sean Callananf5857a02010-07-31 01:32:05 +00001190
Sean Callanan9b6898f2011-07-30 02:42:06 +00001191 ArrayRef<Value *> srN_arguments(argument_array, 1);
1192
Sean Callananf5857a02010-07-31 01:32:05 +00001193 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanan9b6898f2011-07-30 02:42:06 +00001194 srN_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +00001195 "sel_registerName",
Sean Callananf5857a02010-07-31 01:32:05 +00001196 selector_load);
1197
1198 // Replace the load with the call in all users
1199
1200 selector_load->replaceAllUsesWith(srN_call);
1201
1202 selector_load->eraseFromParent();
1203
1204 return true;
1205}
1206
1207bool
Sean Callananc0492742011-05-23 21:40:23 +00001208IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callananf5857a02010-07-31 01:32:05 +00001209{
Greg Claytone005f2c2010-11-06 01:53:30 +00001210 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001211
1212 BasicBlock::iterator ii;
1213
1214 typedef SmallVector <Instruction*, 2> InstrList;
1215 typedef InstrList::iterator InstrIterator;
1216
1217 InstrList selector_loads;
1218
Greg Clayton3c7feb42010-11-19 01:05:25 +00001219 for (ii = basic_block.begin();
1220 ii != basic_block.end();
Sean Callananf5857a02010-07-31 01:32:05 +00001221 ++ii)
1222 {
1223 Instruction &inst = *ii;
1224
1225 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton3c7feb42010-11-19 01:05:25 +00001226 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callananf5857a02010-07-31 01:32:05 +00001227 selector_loads.push_back(&inst);
1228 }
1229
1230 InstrIterator iter;
1231
1232 for (iter = selector_loads.begin();
1233 iter != selector_loads.end();
1234 ++iter)
1235 {
Sean Callananc0492742011-05-23 21:40:23 +00001236 if (!RewriteObjCSelector(*iter))
Sean Callananf5857a02010-07-31 01:32:05 +00001237 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001238 if (m_error_stream)
1239 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1240
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001241 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +00001242 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan97c924e2011-01-27 01:07:04 +00001243
Sean Callananf5857a02010-07-31 01:32:05 +00001244 return false;
1245 }
1246 }
1247
1248 return true;
1249}
1250
Sean Callanan97c924e2011-01-27 01:07:04 +00001251// This function does not report errors; its callers are responsible.
Sean Callanana48fe162010-08-11 03:57:18 +00001252bool
Sean Callananc0492742011-05-23 21:40:23 +00001253IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanana48fe162010-08-11 03:57:18 +00001254{
Sean Callanan97678d12011-01-13 21:23:32 +00001255 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1256
Sean Callanana48fe162010-08-11 03:57:18 +00001257 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1258
1259 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1260
1261 if (!alloc_md || !alloc_md->getNumOperands())
1262 return false;
1263
1264 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1265
1266 if (!constant_int)
1267 return false;
1268
1269 // We attempt to register this as a new persistent variable with the DeclMap.
1270
1271 uintptr_t ptr = constant_int->getZExtValue();
1272
Sean Callanan82b74c82010-08-12 01:56:52 +00001273 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +00001274
Sean Callanan82b74c82010-08-12 01:56:52 +00001275 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1276 &decl->getASTContext());
1277
Greg Clayton8de27c72010-10-15 22:48:33 +00001278 StringRef decl_name (decl->getName());
1279 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan6a925532011-01-13 08:53:35 +00001280 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanana48fe162010-08-11 03:57:18 +00001281 return false;
1282
Sean Callananc0492742011-05-23 21:40:23 +00001283 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanan97678d12011-01-13 21:23:32 +00001284 alloc->getType(),
Sean Callanana48fe162010-08-11 03:57:18 +00001285 false, /* not constant */
1286 GlobalValue::ExternalLinkage,
1287 NULL, /* no initializer */
1288 alloc->getName().str().c_str());
1289
1290 // What we're going to do here is make believe this was a regular old external
1291 // variable. That means we need to make the metadata valid.
1292
Sean Callananc0492742011-05-23 21:40:23 +00001293 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +00001294
1295 llvm::Value* values[2];
1296 values[0] = persistent_global;
1297 values[1] = constant_int;
Sean Callanan0de254a2011-05-15 22:34:38 +00001298
1299 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +00001300
Sean Callananc0492742011-05-23 21:40:23 +00001301 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanana48fe162010-08-11 03:57:18 +00001302 named_metadata->addOperand(persistent_global_md);
1303
Sean Callanan97678d12011-01-13 21:23:32 +00001304 // Now, since the variable is a pointer variable, we will drop in a load of that
1305 // pointer variable.
1306
1307 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1308
1309 if (log)
1310 log->Printf("Replacing \"%s\" with \"%s\"",
1311 PrintValue(alloc).c_str(),
1312 PrintValue(persistent_load).c_str());
1313
1314 alloc->replaceAllUsesWith(persistent_load);
Sean Callanana48fe162010-08-11 03:57:18 +00001315 alloc->eraseFromParent();
1316
1317 return true;
1318}
1319
1320bool
Sean Callananc0492742011-05-23 21:40:23 +00001321IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanana48fe162010-08-11 03:57:18 +00001322{
Sean Callanane8a59a82010-09-13 21:34:21 +00001323 if (!m_resolve_vars)
1324 return true;
1325
Greg Claytone005f2c2010-11-06 01:53:30 +00001326 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +00001327
1328 BasicBlock::iterator ii;
1329
1330 typedef SmallVector <Instruction*, 2> InstrList;
1331 typedef InstrList::iterator InstrIterator;
1332
1333 InstrList pvar_allocs;
1334
Greg Clayton3c7feb42010-11-19 01:05:25 +00001335 for (ii = basic_block.begin();
1336 ii != basic_block.end();
Sean Callanana48fe162010-08-11 03:57:18 +00001337 ++ii)
1338 {
1339 Instruction &inst = *ii;
1340
1341 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan237e4742011-01-21 22:30:25 +00001342 {
1343 llvm::StringRef alloc_name = alloc->getName();
1344
1345 if (alloc_name.startswith("$") &&
1346 !alloc_name.startswith("$__lldb"))
1347 {
1348 if (alloc_name.find_first_of("0123456789") == 1)
1349 {
1350 if (log)
1351 log->Printf("Rejecting a numeric persistent variable.");
1352
Sean Callanan97c924e2011-01-27 01:07:04 +00001353 if (m_error_stream)
1354 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1355
Sean Callanan237e4742011-01-21 22:30:25 +00001356 return false;
1357 }
1358
Sean Callanana48fe162010-08-11 03:57:18 +00001359 pvar_allocs.push_back(alloc);
Sean Callanan237e4742011-01-21 22:30:25 +00001360 }
1361 }
Sean Callanana48fe162010-08-11 03:57:18 +00001362 }
1363
1364 InstrIterator iter;
1365
1366 for (iter = pvar_allocs.begin();
1367 iter != pvar_allocs.end();
1368 ++iter)
1369 {
Sean Callananc0492742011-05-23 21:40:23 +00001370 if (!RewritePersistentAlloc(*iter))
Sean Callanana48fe162010-08-11 03:57:18 +00001371 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001372 if (m_error_stream)
1373 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1374
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001375 if (log)
Sean Callanana48fe162010-08-11 03:57:18 +00001376 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001377
Sean Callanana48fe162010-08-11 03:57:18 +00001378 return false;
1379 }
1380 }
1381
1382 return true;
1383}
1384
Sean Callanan97c924e2011-01-27 01:07:04 +00001385// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001386bool
Sean Callananc0492742011-05-23 21:40:23 +00001387IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001388{
Greg Claytone005f2c2010-11-06 01:53:30 +00001389 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan48443652010-12-02 19:47:57 +00001390
1391 if (log)
Sean Callananb9f09a62010-12-06 22:16:55 +00001392 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callanan9a877432011-08-01 17:41:38 +00001393
Greg Clayton8de27c72010-10-15 22:48:33 +00001394 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +00001395 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001396 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +00001397 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001398 default:
1399 break;
1400 case Instruction::GetElementPtr:
1401 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +00001402 Value *s = constant_expr->getOperand(0);
Sean Callananc0492742011-05-23 21:40:23 +00001403 if (!MaybeHandleVariable(s))
Sean Callanan48443652010-12-02 19:47:57 +00001404 return false;
Sean Callananbc2928a2010-08-03 00:23:29 +00001405 }
1406 }
Sean Callananf921cf52010-12-03 19:51:05 +00001407 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001408 {
Sean Callananc0492742011-05-23 21:40:23 +00001409 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001410
Sean Callananf5857a02010-07-31 01:32:05 +00001411 if (!named_decl)
1412 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001413 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001414 return true;
1415
Sean Callanan7cd46742010-12-06 00:56:39 +00001416 if (!global_variable->hasExternalLinkage())
1417 return true;
1418
Sean Callananf5857a02010-07-31 01:32:05 +00001419 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001420 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001421
Sean Callananf5857a02010-07-31 01:32:05 +00001422 return false;
1423 }
1424
Greg Clayton8de27c72010-10-15 22:48:33 +00001425 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +00001426
Sean Callanan771131d2010-09-30 21:18:25 +00001427 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +00001428 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +00001429
1430 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +00001431 {
Sean Callanan771131d2010-09-30 21:18:25 +00001432 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +00001433 ast_context = &value_decl->getASTContext();
1434 }
Sean Callanan810f22d2010-07-16 00:09:46 +00001435 else
Sean Callananf328c9f2010-07-20 23:31:16 +00001436 {
Sean Callanan810f22d2010-07-16 00:09:46 +00001437 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +00001438 }
Sean Callanan771131d2010-09-30 21:18:25 +00001439
Sean Callanan6a925532011-01-13 08:53:35 +00001440 clang::QualType qual_type;
Sean Callanan58baaad2011-07-08 00:39:14 +00001441 const Type *value_type = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00001442
Sean Callanan97678d12011-01-13 21:23:32 +00001443 if (name[0] == '$')
Sean Callanan6a925532011-01-13 08:53:35 +00001444 {
1445 // The $__lldb_expr_result name indicates the the return value has allocated as
1446 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1447 // accesses to this static variable need to be redirected to the result of dereferencing
1448 // a pointer that is passed in as one of the arguments.
1449 //
1450 // Consequently, when reporting the size of the type, we report a pointer type pointing
1451 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanan97678d12011-01-13 21:23:32 +00001452 //
1453 // We also do this for any user-declared persistent variables.
Sean Callananf328c9f2010-07-20 23:31:16 +00001454
Sean Callanan6a925532011-01-13 08:53:35 +00001455 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1456 value_type = PointerType::get(global_variable->getType(), 0);
1457 }
1458 else
1459 {
1460 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1461 value_type = global_variable->getType();
1462 }
Sean Callanan771131d2010-09-30 21:18:25 +00001463
1464 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
1465 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001466
Sean Callanan771131d2010-09-30 21:18:25 +00001467 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001468 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %lu, align %lld]",
Sean Callanan771131d2010-09-30 21:18:25 +00001469 name.c_str(),
1470 qual_type.getAsString().c_str(),
1471 PrintType(value_type).c_str(),
1472 value_size,
1473 value_alignment);
Sean Callanan3aa7da52010-12-13 22:46:15 +00001474
Sean Callanan8bce6652010-07-13 21:41:46 +00001475
Sean Callanan8c127202010-08-23 23:09:38 +00001476 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +00001477 lldb_private::ConstString (name.c_str()),
1478 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +00001479 value_size,
1480 value_alignment))
Sean Callanan9a877432011-08-01 17:41:38 +00001481 {
1482 if (!global_variable->hasExternalLinkage())
1483 return true;
1484 else
1485 return false;
1486 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001487 }
Sean Callananf3143b72010-12-03 03:02:31 +00001488 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanan48443652010-12-02 19:47:57 +00001489 {
1490 if (log)
1491 log->Printf("Function pointers aren't handled right now");
1492
1493 return false;
1494 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001495
1496 return true;
1497}
1498
Sean Callanan97c924e2011-01-27 01:07:04 +00001499// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001500bool
Sean Callananc0492742011-05-23 21:40:23 +00001501IRForTarget::HandleSymbol (Value *symbol)
Sean Callanan81974962011-05-08 02:21:26 +00001502{
Sean Callananc7674af2011-01-17 23:42:46 +00001503 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1504
1505 lldb_private::ConstString name(symbol->getName().str().c_str());
1506
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001507 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name);
Sean Callananc7674af2011-01-17 23:42:46 +00001508
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001509 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc7674af2011-01-17 23:42:46 +00001510 {
1511 if (log)
1512 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1513
1514 return false;
1515 }
1516
1517 if (log)
1518 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), symbol_addr);
1519
Sean Callanan9b6898f2011-07-30 02:42:06 +00001520 Type *symbol_type = symbol->getType();
Sean Callananc7674af2011-01-17 23:42:46 +00001521
Sean Callanan9b6898f2011-07-30 02:42:06 +00001522 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1523 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc7674af2011-01-17 23:42:46 +00001524
1525 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1526
1527 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1528
1529 if (log)
1530 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1531
1532 symbol->replaceAllUsesWith(symbol_addr_ptr);
1533
1534 return true;
1535}
1536
1537bool
Sean Callananc0492742011-05-23 21:40:23 +00001538IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +00001539{
Sean Callanan48443652010-12-02 19:47:57 +00001540 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1541
1542 if (log)
1543 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanandc27aba2010-10-05 22:26:43 +00001544
Sean Callanan6ba533e2010-11-17 23:00:36 +00001545 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +00001546 op_index < num_ops;
1547 ++op_index)
Sean Callananc0492742011-05-23 21:40:23 +00001548 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan97c924e2011-01-27 01:07:04 +00001549 {
1550 if (m_error_stream)
1551 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1552
Sean Callanandc27aba2010-10-05 22:26:43 +00001553 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001554 }
1555
Sean Callanandc27aba2010-10-05 22:26:43 +00001556 return true;
1557}
1558
1559bool
Sean Callananc0492742011-05-23 21:40:23 +00001560IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan8bce6652010-07-13 21:41:46 +00001561{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001562 /////////////////////////////////////////////////////////////////////////
1563 // Prepare the current basic block for execution in the remote process
1564 //
1565
Sean Callanan02fbafa2010-07-27 21:39:39 +00001566 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001567
Greg Clayton3c7feb42010-11-19 01:05:25 +00001568 for (ii = basic_block.begin();
1569 ii != basic_block.end();
Sean Callanan8bce6652010-07-13 21:41:46 +00001570 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001571 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001572 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001573
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001574 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001575
Sean Callanan97c924e2011-01-27 01:07:04 +00001576 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001577 if (call && !MaybeHandleCallArguments(call))
Sean Callanan48443652010-12-02 19:47:57 +00001578 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001579 }
1580
1581 return true;
1582}
1583
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001584bool
Sean Callananc0492742011-05-23 21:40:23 +00001585IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001586{
Sean Callananae71e302010-11-18 22:21:58 +00001587 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1588
Sean Callananc0492742011-05-23 21:40:23 +00001589 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001590 global != end;
1591 ++global)
1592 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001593 if (log)
1594 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1595 (*global).getName().str().c_str(),
Sean Callananc0492742011-05-23 21:40:23 +00001596 DeclForGlobal(global));
Greg Clayton3c7feb42010-11-19 01:05:25 +00001597
Sean Callananc7674af2011-01-17 23:42:46 +00001598 if ((*global).getName().str().find("OBJC_IVAR") == 0)
1599 {
Sean Callananc0492742011-05-23 21:40:23 +00001600 if (!HandleSymbol(global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001601 {
1602 if (m_error_stream)
1603 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str());
1604
Sean Callananc7674af2011-01-17 23:42:46 +00001605 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001606 }
Sean Callananc7674af2011-01-17 23:42:46 +00001607 }
Sean Callananc0492742011-05-23 21:40:23 +00001608 else if (DeclForGlobal(global))
Sean Callananc7674af2011-01-17 23:42:46 +00001609 {
Sean Callananc0492742011-05-23 21:40:23 +00001610 if (!MaybeHandleVariable (global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001611 {
1612 if (m_error_stream)
1613 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str());
1614
Sean Callananc7674af2011-01-17 23:42:46 +00001615 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001616 }
Sean Callananc7674af2011-01-17 23:42:46 +00001617 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001618 }
1619
1620 return true;
1621}
1622
Sean Callananc0492742011-05-23 21:40:23 +00001623bool
1624IRForTarget::ReplaceStrings ()
1625{
1626 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1627
1628 if (!m_data_allocator)
1629 return true; // hope for the best; some clients may not want static allocation!
1630
1631 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1632
1633 OffsetsTy offsets;
1634
1635 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1636 gi != ge;
1637 ++gi)
1638 {
1639 GlobalVariable *gv = gi;
1640
1641 if (!gv->hasInitializer())
1642 continue;
1643
1644 Constant *gc = gv->getInitializer();
1645
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001646 std::string str;
Sean Callananc0492742011-05-23 21:40:23 +00001647
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001648 if (gc->isNullValue())
1649 {
1650 Type *gc_type = gc->getType();
1651
1652 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1653
1654 if (!gc_array_type)
1655 continue;
1656
1657 Type *gc_element_type = gc_array_type->getElementType();
1658
1659 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1660
1661 if (gc_integer_type->getBitWidth() != 8)
1662 continue;
1663
1664 str = "";
1665 }
1666 else
1667 {
1668 ConstantArray *gc_array = dyn_cast<ConstantArray>(gc);
1669
1670 if (!gc_array)
1671 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001672
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001673 if (!gc_array->isCString())
1674 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001675
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001676 if (log)
1677 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callananc0492742011-05-23 21:40:23 +00001678
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001679 str = gc_array->getAsString();
1680 }
1681
Sean Callananc0492742011-05-23 21:40:23 +00001682 offsets[gv] = m_data_allocator->GetStream().GetSize();
1683
1684 m_data_allocator->GetStream().Write(str.c_str(), str.length() + 1);
1685 }
1686
Sean Callanan9b6898f2011-07-30 02:42:06 +00001687 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00001688
1689 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1690 oi != oe;
1691 ++oi)
1692 {
1693 GlobalVariable *gv = oi->first;
1694 size_t offset = oi->second;
1695
1696 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1697
1698 if (log)
1699 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1700
1701 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1702 ui != ue;
1703 ++ui)
1704 {
1705 if (log)
1706 log->Printf("Found use %s", PrintValue(*ui).c_str());
1707
1708 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1709 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1710
1711 if (const_expr)
1712 {
1713 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1714 {
1715 if (log)
1716 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1717
1718 return false;
1719 }
1720
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001721 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1722 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1723
1724 const_expr->replaceAllUsesWith(new_gep);
Sean Callananc0492742011-05-23 21:40:23 +00001725 }
1726 else if (store_inst)
1727 {
1728 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1729
1730 store_inst->setOperand(0, bit_cast);
1731 }
1732 else
1733 {
1734 if (log)
1735 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1736
1737 return false;
1738 }
1739 }
1740
1741 gv->eraseFromParent();
1742 }
1743
1744 return true;
1745}
1746
1747bool
1748IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1749{
1750 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1751
1752 if (!m_data_allocator)
1753 return true;
1754
1755 typedef SmallVector <Value*, 2> ConstantList;
1756 typedef SmallVector <llvm::Instruction*, 2> UserList;
1757 typedef ConstantList::iterator ConstantIterator;
1758 typedef UserList::iterator UserIterator;
1759
1760 ConstantList static_constants;
1761 UserList static_users;
1762
1763 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1764 ii != ie;
1765 ++ii)
1766 {
1767 llvm::Instruction &inst = *ii;
1768
1769 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1770 oi != oe;
1771 ++oi)
1772 {
1773 Value *operand_val = oi->get();
1774
1775 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1776
1777 if (operand_constant_fp && operand_constant_fp->getType()->isX86_FP80Ty())
1778 {
1779 static_constants.push_back(operand_val);
1780 static_users.push_back(ii);
1781 }
1782 }
1783 }
1784
1785 ConstantIterator constant_iter;
1786 UserIterator user_iter;
Greg Clayton54b38412011-05-24 23:06:02 +00001787
Sean Callananc0492742011-05-23 21:40:23 +00001788 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1789 constant_iter != static_constants.end();
1790 ++constant_iter, ++user_iter)
1791 {
1792 Value *operand_val = *constant_iter;
1793 llvm::Instruction *inst = *user_iter;
1794
1795 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1796
1797 if (operand_constant_fp)
1798 {
1799 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
1800 APInt operand_apint = operand_apfloat.bitcastToAPInt();
1801
1802 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
1803 size_t operand_data_size = operand_apint.getBitWidth() / 8;
1804
1805 if (log)
1806 {
1807 std::string s;
1808 raw_string_ostream ss(s);
1809 for (size_t index = 0;
1810 index < operand_data_size;
1811 ++index)
1812 {
1813 ss << (uint32_t)operand_raw_data[index];
1814 ss << " ";
1815 }
1816 ss.flush();
1817
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001818 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callananc0492742011-05-23 21:40:23 +00001819 }
1820
1821 lldb_private::DataBufferHeap data(operand_data_size, 0);
1822
1823 if (lldb::endian::InlHostByteOrder() != m_data_allocator->GetStream().GetByteOrder())
1824 {
1825 uint8_t *data_bytes = data.GetBytes();
1826
1827 for (size_t index = 0;
1828 index < operand_data_size;
1829 ++index)
1830 {
1831 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
1832 }
1833 }
1834 else
1835 {
1836 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
1837 }
1838
1839 uint64_t offset = m_data_allocator->GetStream().GetSize();
1840
1841 m_data_allocator->GetStream().Write(data.GetBytes(), operand_data_size);
1842
Sean Callanan9b6898f2011-07-30 02:42:06 +00001843 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callananc0492742011-05-23 21:40:23 +00001844
1845 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
1846
1847 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
1848
1849 operand_constant_fp->replaceAllUsesWith(fp_load);
1850 }
1851 }
1852
1853 return true;
1854}
1855
Sean Callanan02fbafa2010-07-27 21:39:39 +00001856static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00001857{
Sean Callanan58baaad2011-07-08 00:39:14 +00001858 Constant *Old = NULL;
Sean Callanan45839272010-07-24 01:37:44 +00001859
Sean Callanan6ba533e2010-11-17 23:00:36 +00001860 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00001861 return false;
1862
Sean Callanan58baaad2011-07-08 00:39:14 +00001863 ConstantExpr *CE = NULL;
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001864
1865 if ((CE = dyn_cast<ConstantExpr>(V)))
1866 {
1867 if (CE->getOpcode() != Instruction::BitCast)
1868 return false;
1869
Sean Callanan6ba533e2010-11-17 23:00:36 +00001870 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001871 }
1872
Sean Callanan6ba533e2010-11-17 23:00:36 +00001873 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00001874
1875 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
1876 return false;
1877
1878 return true;
1879}
1880
Sean Callananc0492742011-05-23 21:40:23 +00001881void
1882IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callanan45839272010-07-24 01:37:44 +00001883{
Sean Callananc0492742011-05-23 21:40:23 +00001884 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callanan45839272010-07-24 01:37:44 +00001885
1886 Value::use_iterator ui;
1887
1888 for (ui = guard_load->use_begin();
1889 ui != guard_load->use_end();
1890 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00001891 {
Greg Clayton6e713402010-07-30 20:30:44 +00001892 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00001893 {
1894 // do nothing for the moment
1895 }
1896 else
1897 {
1898 ui->replaceUsesOfWith(guard_load, zero);
1899 }
1900 }
Sean Callanan45839272010-07-24 01:37:44 +00001901
1902 guard_load->eraseFromParent();
1903}
1904
1905static void ExciseGuardStore(Instruction* guard_store)
1906{
1907 guard_store->eraseFromParent();
1908}
1909
1910bool
Sean Callananc0492742011-05-23 21:40:23 +00001911IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callanan45839272010-07-24 01:37:44 +00001912{
1913 ///////////////////////////////////////////////////////
1914 // Eliminate any reference to guard variables found.
1915 //
1916
Sean Callanan02fbafa2010-07-27 21:39:39 +00001917 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00001918
Sean Callanan02fbafa2010-07-27 21:39:39 +00001919 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00001920 typedef InstrList::iterator InstrIterator;
1921
1922 InstrList guard_loads;
1923 InstrList guard_stores;
1924
Greg Clayton3c7feb42010-11-19 01:05:25 +00001925 for (ii = basic_block.begin();
1926 ii != basic_block.end();
Sean Callanan45839272010-07-24 01:37:44 +00001927 ++ii)
1928 {
1929 Instruction &inst = *ii;
1930
1931 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1932 if (isGuardVariableRef(load->getPointerOperand()))
1933 guard_loads.push_back(&inst);
1934
1935 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1936 if (isGuardVariableRef(store->getPointerOperand()))
1937 guard_stores.push_back(&inst);
1938 }
1939
1940 InstrIterator iter;
1941
1942 for (iter = guard_loads.begin();
1943 iter != guard_loads.end();
1944 ++iter)
Sean Callananc0492742011-05-23 21:40:23 +00001945 TurnGuardLoadIntoZero(*iter);
Sean Callanan45839272010-07-24 01:37:44 +00001946
1947 for (iter = guard_stores.begin();
1948 iter != guard_stores.end();
1949 ++iter)
1950 ExciseGuardStore(*iter);
1951
1952 return true;
1953}
1954
Sean Callanan97c924e2011-01-27 01:07:04 +00001955// This function does not report errors; its callers are responsible.
Sean Callanan6ba533e2010-11-17 23:00:36 +00001956bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00001957IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callananbafd6852010-07-14 23:40:29 +00001958{
Greg Claytone005f2c2010-11-06 01:53:30 +00001959 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00001960
1961 Value::use_iterator ui;
1962
Sean Callanana48fe162010-08-11 03:57:18 +00001963 SmallVector<User*, 16> users;
1964
1965 // We do this because the use list might change, invalidating our iterator.
1966 // Much better to keep a work list ourselves.
Greg Clayton3c7feb42010-11-19 01:05:25 +00001967 for (ui = old_constant->use_begin();
1968 ui != old_constant->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00001969 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00001970 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00001971
Johnny Chen2bc9eb32011-07-19 19:48:13 +00001972 for (size_t i = 0;
Sean Callanana48fe162010-08-11 03:57:18 +00001973 i < users.size();
1974 ++i)
1975 {
1976 User *user = users[i];
1977
Sean Callananbafd6852010-07-14 23:40:29 +00001978 if (Constant *constant = dyn_cast<Constant>(user))
1979 {
1980 // synthesize a new non-constant equivalent of the constant
1981
1982 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
1983 {
1984 switch (constant_expr->getOpcode())
1985 {
1986 default:
1987 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001988 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00001989 return false;
1990 case Instruction::BitCast:
1991 {
1992 // UnaryExpr
1993 // OperandList[0] is value
1994
1995 Value *s = constant_expr->getOperand(0);
1996
Greg Clayton3c7feb42010-11-19 01:05:25 +00001997 if (s == old_constant)
1998 s = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00001999
Sean Callananc0492742011-05-23 21:40:23 +00002000 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002001
Greg Clayton3c7feb42010-11-19 01:05:25 +00002002 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002003 }
2004 break;
2005 case Instruction::GetElementPtr:
2006 {
2007 // GetElementPtrConstantExpr
2008 // OperandList[0] is base
2009 // OperandList[1]... are indices
2010
2011 Value *ptr = constant_expr->getOperand(0);
2012
Greg Clayton3c7feb42010-11-19 01:05:25 +00002013 if (ptr == old_constant)
2014 ptr = new_constant;
Sean Callanan9b6898f2011-07-30 02:42:06 +00002015
2016 std::vector<Value*> index_vector;
Sean Callananbafd6852010-07-14 23:40:29 +00002017
2018 unsigned operand_index;
2019 unsigned num_operands = constant_expr->getNumOperands();
2020
2021 for (operand_index = 1;
2022 operand_index < num_operands;
2023 ++operand_index)
2024 {
2025 Value *operand = constant_expr->getOperand(operand_index);
2026
Greg Clayton3c7feb42010-11-19 01:05:25 +00002027 if (operand == old_constant)
2028 operand = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002029
Sean Callanan9b6898f2011-07-30 02:42:06 +00002030 index_vector.push_back(operand);
Sean Callananbafd6852010-07-14 23:40:29 +00002031 }
2032
Sean Callanan9b6898f2011-07-30 02:42:06 +00002033 ArrayRef <Value*> indices(index_vector);
2034
2035 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002036
Greg Clayton3c7feb42010-11-19 01:05:25 +00002037 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002038 }
2039 break;
2040 }
2041 }
2042 else
2043 {
2044 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002045 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002046 return false;
2047 }
2048 }
2049 else
2050 {
2051 // simple fall-through case for non-constants
Greg Clayton3c7feb42010-11-19 01:05:25 +00002052 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callananbafd6852010-07-14 23:40:29 +00002053 }
2054 }
2055
2056 return true;
2057}
2058
Sean Callanan8bce6652010-07-13 21:41:46 +00002059bool
Sean Callananc0492742011-05-23 21:40:23 +00002060IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan8bce6652010-07-13 21:41:46 +00002061{
Sean Callanane8a59a82010-09-13 21:34:21 +00002062 if (!m_resolve_vars)
2063 return true;
2064
Greg Claytone005f2c2010-11-06 01:53:30 +00002065 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00002066
2067 m_decl_map->DoStructLayout();
2068
2069 if (log)
2070 log->Printf("Element arrangement:");
2071
2072 uint32_t num_elements;
2073 uint32_t element_index;
2074
2075 size_t size;
2076 off_t alignment;
2077
2078 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2079 return false;
2080
Greg Clayton3c7feb42010-11-19 01:05:25 +00002081 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00002082
Greg Clayton3c7feb42010-11-19 01:05:25 +00002083 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002084 {
2085 if (m_error_stream)
2086 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2087
Sean Callanan8bce6652010-07-13 21:41:46 +00002088 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002089 }
2090
Sean Callanan02fbafa2010-07-27 21:39:39 +00002091 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00002092
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002093 if (argument->getName().equals("this"))
2094 {
2095 ++iter;
2096
Greg Clayton3c7feb42010-11-19 01:05:25 +00002097 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002098 {
2099 if (m_error_stream)
2100 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2101
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002102 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002103 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002104
2105 argument = iter;
2106 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002107 else if (argument->getName().equals("self"))
2108 {
2109 ++iter;
2110
2111 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002112 {
2113 if (m_error_stream)
2114 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2115
Sean Callanan3aa7da52010-12-13 22:46:15 +00002116 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002117 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002118
2119 if (!iter->getName().equals("_cmd"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002120 {
2121 if (m_error_stream)
2122 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2123
Sean Callanan3aa7da52010-12-13 22:46:15 +00002124 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002125 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002126
2127 ++iter;
2128
2129 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002130 {
2131 if (m_error_stream)
2132 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2133
Sean Callanan3aa7da52010-12-13 22:46:15 +00002134 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002135 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002136
2137 argument = iter;
2138 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002139
Greg Clayton8de27c72010-10-15 22:48:33 +00002140 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002141 {
2142 if (m_error_stream)
2143 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2144
Sean Callanan8bce6652010-07-13 21:41:46 +00002145 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002146 }
2147
Sean Callanan8bce6652010-07-13 21:41:46 +00002148 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002149 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00002150
Greg Clayton3c7feb42010-11-19 01:05:25 +00002151 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00002152 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00002153
Sean Callanan6ba533e2010-11-17 23:00:36 +00002154 if (!FirstEntryInstruction)
Sean Callanan97c924e2011-01-27 01:07:04 +00002155 {
2156 if (m_error_stream)
2157 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2158
Sean Callanan8bce6652010-07-13 21:41:46 +00002159 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002160 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002161
Sean Callananc0492742011-05-23 21:40:23 +00002162 LLVMContext &context(m_module->getContext());
Sean Callanan9b6898f2011-07-30 02:42:06 +00002163 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan8bce6652010-07-13 21:41:46 +00002164
2165 if (!offset_type)
Sean Callanan97c924e2011-01-27 01:07:04 +00002166 {
2167 if (m_error_stream)
2168 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2169
Sean Callanan8bce6652010-07-13 21:41:46 +00002170 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002171 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002172
2173 for (element_index = 0; element_index < num_elements; ++element_index)
2174 {
Sean Callanan58baaad2011-07-08 00:39:14 +00002175 const clang::NamedDecl *decl = NULL;
2176 Value *value = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002177 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00002178 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00002179
Sean Callanan45690fe2010-08-30 22:17:16 +00002180 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan97c924e2011-01-27 01:07:04 +00002181 {
2182 if (m_error_stream)
2183 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2184
Sean Callanan8bce6652010-07-13 21:41:46 +00002185 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002186 }
2187
Sean Callanan8bce6652010-07-13 21:41:46 +00002188 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002189 log->Printf(" \"%s\" [\"%s\"] (\"%s\") placed at %lld",
Sean Callanan82b74c82010-08-12 01:56:52 +00002190 value->getName().str().c_str(),
Greg Clayton8de27c72010-10-15 22:48:33 +00002191 name.GetCString(),
Sean Callanan8bce6652010-07-13 21:41:46 +00002192 PrintValue(value, true).c_str(),
2193 offset);
2194
Sean Callanan9b6898f2011-07-30 02:42:06 +00002195 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callanan6ba533e2010-11-17 23:00:36 +00002196 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan6a925532011-01-13 08:53:35 +00002197
Sean Callanan58baaad2011-07-08 00:39:14 +00002198 Value *replacement = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002199
Sean Callanan6a925532011-01-13 08:53:35 +00002200 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2201 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2202 // entry in order to produce the static variable that the AST thinks it is accessing.
2203 if (name == m_result_name && !m_result_is_pointer)
2204 {
2205 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2206
2207 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2208
2209 replacement = load;
2210 }
Sean Callananbafd6852010-07-14 23:40:29 +00002211 else
Sean Callanan6a925532011-01-13 08:53:35 +00002212 {
2213 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2214
2215 replacement = bit_cast;
2216 }
2217
2218 if (Constant *constant = dyn_cast<Constant>(value))
2219 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2220 else
2221 value->replaceAllUsesWith(replacement);
Sean Callananb51ee982010-11-02 23:51:17 +00002222
2223 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2224 var->eraseFromParent();
Sean Callanan8bce6652010-07-13 21:41:46 +00002225 }
2226
2227 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002228 log->Printf("Total structure [align %lld, size %lu]", alignment, size);
Sean Callanan8bce6652010-07-13 21:41:46 +00002229
2230 return true;
2231}
2232
Sean Callananc0492742011-05-23 21:40:23 +00002233llvm::Constant *
Sean Callanan9b6898f2011-07-30 02:42:06 +00002234IRForTarget::BuildRelocation(llvm::Type *type,
Sean Callananc0492742011-05-23 21:40:23 +00002235 uint64_t offset)
2236{
2237 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2238
Sean Callanan9b6898f2011-07-30 02:42:06 +00002239 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2240 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002241
2242 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanan9b6898f2011-07-30 02:42:06 +00002243
2244 llvm::Constant *offset_array[1];
2245
2246 offset_array[0] = offset_int;
2247
2248 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2249
2250 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callananc0492742011-05-23 21:40:23 +00002251 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2252
2253 return reloc_getbitcast;
2254}
2255
2256bool
2257IRForTarget::CompleteDataAllocation ()
2258{
Sean Callanan47dc4572011-09-15 02:13:07 +00002259 if (!m_data_allocator)
2260 return true;
2261
Sean Callananc0492742011-05-23 21:40:23 +00002262 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2263
2264 if (!m_data_allocator->GetStream().GetSize())
2265 return true;
2266
2267 lldb::addr_t allocation = m_data_allocator->Allocate();
2268
2269 if (log)
2270 {
2271 if (allocation)
2272 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2273 else
2274 log->Printf("Failed to allocate static data");
2275 }
2276
2277 if (!allocation)
2278 return false;
2279
Sean Callanan9b6898f2011-07-30 02:42:06 +00002280 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2281 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002282
2283 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2284 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2285
2286 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2287
2288 m_reloc_placeholder->eraseFromParent();
2289
2290 return true;
2291}
2292
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002293bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002294IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002295{
Greg Claytone005f2c2010-11-06 01:53:30 +00002296 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002297
Sean Callananc0492742011-05-23 21:40:23 +00002298 m_module = &llvm_module;
2299
2300 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002301
2302 if (!function)
2303 {
2304 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002305 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00002306
2307 if (m_error_stream)
Sean Callananc0492742011-05-23 21:40:23 +00002308 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 +00002309
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002310 return false;
2311 }
Sean Callananc0492742011-05-23 21:40:23 +00002312
2313 if (!FixFunctionLinkage (*function))
2314 {
2315 if (log)
2316 log->Printf("Couldn't fix the linkage for the function");
2317
2318 return false;
2319 }
2320
Sean Callanan9b6898f2011-07-30 02:42:06 +00002321 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00002322
2323 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2324 intptr_ty,
2325 false /* isConstant */,
2326 GlobalVariable::InternalLinkage,
2327 Constant::getNullValue(intptr_ty),
2328 "reloc_placeholder",
2329 NULL /* InsertBefore */,
2330 false /* ThreadLocal */,
2331 0 /* AddressSpace */);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002332
Sean Callanan02fbafa2010-07-27 21:39:39 +00002333 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002334
Sean Callananc0492742011-05-23 21:40:23 +00002335 m_has_side_effects = HasSideEffects(*function);
Sean Callanan05a5a1b2010-12-16 03:17:46 +00002336
Sean Callanan82b74c82010-08-12 01:56:52 +00002337 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00002338 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00002339 //
2340
Sean Callananc0492742011-05-23 21:40:23 +00002341 if (!CreateResultVariable(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002342 {
2343 if (log)
2344 log->Printf("CreateResultVariable() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002345
2346 // CreateResultVariable() reports its own errors, so we don't do so here
2347
Sean Callanan82b74c82010-08-12 01:56:52 +00002348 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002349 }
Sean Callanan47dc4572011-09-15 02:13:07 +00002350
2351 if (m_const_result && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2352 {
2353 m_interpret_success = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +00002354 return true;
Sean Callanan47dc4572011-09-15 02:13:07 +00002355 }
2356
2357 for (bbi = function->begin();
2358 bbi != function->end();
2359 ++bbi)
2360 {
2361 if (!RemoveGuards(*bbi))
2362 {
2363 if (log)
2364 log->Printf("RemoveGuards() failed");
2365
2366 // RemoveGuards() reports its own errors, so we don't do so here
2367
2368 return false;
2369 }
2370
2371 if (!RewritePersistentAllocs(*bbi))
2372 {
2373 if (log)
2374 log->Printf("RewritePersistentAllocs() failed");
2375
2376 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2377
2378 return false;
2379 }
2380 }
2381
2382 if (m_decl_map && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2383 {
2384 IRInterpreter interpreter (*m_decl_map,
2385 m_error_stream);
2386
2387 if (interpreter.maybeRunOnFunction(m_const_result, m_result_name, m_result_type, *function, llvm_module))
2388 {
2389 m_interpret_success = true;
2390 return true;
2391 }
2392 }
Sean Callanan696cf5f2011-05-07 01:06:41 +00002393
Sean Callananc0492742011-05-23 21:40:23 +00002394 if (log)
2395 {
2396 std::string s;
2397 raw_string_ostream oss(s);
2398
2399 m_module->print(oss, NULL);
2400
2401 oss.flush();
2402
2403 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2404 }
2405
Sean Callanan6ba533e2010-11-17 23:00:36 +00002406 ///////////////////////////////////////////////////////////////////////////////
2407 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2408 //
Sean Callanan6ba533e2010-11-17 23:00:36 +00002409
Sean Callananc0492742011-05-23 21:40:23 +00002410 if (!RewriteObjCConstStrings(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002411 {
2412 if (log)
2413 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002414
2415 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2416
Sean Callanan6ba533e2010-11-17 23:00:36 +00002417 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002418 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00002419
Sean Callanan5c9a3c72011-08-04 21:37:47 +00002420 ///////////////////////////////
2421 // Resolve function pointers
2422 //
2423
2424 if (!ResolveFunctionPointers(llvm_module, *function))
2425 {
2426 if (log)
2427 log->Printf("ResolveFunctionPointers() failed");
2428
2429 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2430
2431 return false;
2432 }
2433
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002434 for (bbi = function->begin();
2435 bbi != function->end();
2436 ++bbi)
2437 {
Sean Callananc0492742011-05-23 21:40:23 +00002438 if (!RewriteObjCSelectors(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002439 {
2440 if (log)
2441 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002442
2443 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2444
Sean Callanana48fe162010-08-11 03:57:18 +00002445 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002446 }
Sean Callanana48fe162010-08-11 03:57:18 +00002447
Sean Callananc0492742011-05-23 21:40:23 +00002448 if (!ResolveCalls(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002449 {
2450 if (log)
2451 log->Printf("ResolveCalls() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002452
2453 // ResolveCalls() reports its own errors, so we don't do so here
2454
Sean Callanan8bce6652010-07-13 21:41:46 +00002455 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002456 }
Sean Callananc0492742011-05-23 21:40:23 +00002457
2458 if (!ReplaceStaticLiterals(*bbi))
2459 {
2460 if (log)
2461 log->Printf("ReplaceStaticLiterals() failed");
2462
2463 return false;
2464 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002465 }
2466
Sean Callanan771131d2010-09-30 21:18:25 +00002467 ///////////////////////////////
2468 // Run function-level passes
2469 //
2470
Sean Callananc0492742011-05-23 21:40:23 +00002471 if (!ResolveExternals(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002472 {
2473 if (log)
2474 log->Printf("ResolveExternals() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002475
2476 // ResolveExternals() reports its own errors, so we don't do so here
2477
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002478 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002479 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002480
Sean Callananc0492742011-05-23 21:40:23 +00002481 if (!ReplaceVariables(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002482 {
2483 if (log)
2484 log->Printf("ReplaceVariables() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002485
2486 // ReplaceVariables() reports its own errors, so we don't do so here
2487
Sean Callanan771131d2010-09-30 21:18:25 +00002488 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002489 }
Sean Callanan771131d2010-09-30 21:18:25 +00002490
Sean Callananc0492742011-05-23 21:40:23 +00002491 if (!ReplaceStrings())
2492 {
2493 if (log)
2494 log->Printf("ReplaceStrings() failed");
2495
2496 return false;
2497 }
2498
2499 if (!CompleteDataAllocation())
2500 {
2501 if (log)
2502 log->Printf("CompleteDataAllocation() failed");
2503
2504 return false;
2505 }
2506
Sean Callanan8bce6652010-07-13 21:41:46 +00002507 if (log)
2508 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00002509 std::string s;
2510 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00002511
Sean Callananc0492742011-05-23 21:40:23 +00002512 m_module->print(oss, NULL);
Sean Callanan321fe9e2010-07-28 01:00:59 +00002513
2514 oss.flush();
2515
Greg Claytonb5037af2010-11-15 01:47:11 +00002516 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002517 }
2518
2519 return true;
2520}
2521
2522void
Greg Clayton3c7feb42010-11-19 01:05:25 +00002523IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002524{
2525}
2526
2527PassManagerType
2528IRForTarget::getPotentialPassManagerType() const
2529{
2530 return PMT_ModulePassManager;
2531}