blob: 50cd0cc289692eb592e6d23697c96788c7260918 [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 {
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000227 lldb_private::ConstString alternate_mangling_const_str;
228 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
229 if (!found_it)
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000230 {
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000231 // Check for an alternate mangling for "std::basic_string<char>"
232 // that is part of the itanium C++ name mangling scheme
233 const char *name_cstr = name.GetCString();
234 if (strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
235 {
236 std::string alternate_mangling("_ZNKSs");
237 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
238 alternate_mangling_const_str.SetCString(alternate_mangling.c_str());
239 found_it = m_decl_map->GetFunctionAddress (alternate_mangling_const_str, fun_addr);
240 }
241 }
242
243 if (!found_it)
244 {
245 fun_value_ptr = NULL;
246
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000247 if (log)
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000248 {
249 if (alternate_mangling_const_str)
250 log->Printf("Function \"%s\" (alternate name \"%s\") has no address", name.GetCString(), alternate_mangling_const_str.GetCString());
251 else
252 log->Printf("Function \"%s\" had no address", name.GetCString());
253 }
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000254
255 if (m_error_stream)
Greg Claytonf6a5bd72011-10-22 03:33:13 +0000256 {
257 if (alternate_mangling_const_str)
258 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n", name.GetCString(), alternate_mangling_const_str.GetCString());
259 else
260 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n", name.GetCString());
261 }
Sean Callanan5c9a3c72011-08-04 21:37:47 +0000262 return false;
263 }
264 }
265 }
266 else
267 {
268 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
269 {
270 if (log)
271 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
272
273 if (m_error_stream)
274 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
275
276 return false;
277 }
278 }
279
280 if (log)
281 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), fun_addr);
282
283 return true;
284}
285
286llvm::Constant *
287IRForTarget::BuildFunctionPointer (llvm::Type *type,
288 uint64_t ptr)
289{
290 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
291 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
292 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
293 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
294 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
295}
296
297bool
298IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module,
299 llvm::Function &llvm_function)
300{
301 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
302
303 for (llvm::Module::iterator fi = llvm_module.begin();
304 fi != llvm_module.end();
305 ++fi)
306 {
307 Function *fun = fi;
308
309 bool is_decl = fun->isDeclaration();
310
311 if (log)
312 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getNameStr().c_str());
313
314 if (!is_decl)
315 continue;
316
317 if (fun->hasNUses(0))
318 continue; // ignore
319
320 uint64_t addr = LLDB_INVALID_ADDRESS;
321 lldb_private::ConstString name;
322 Constant **value_ptr = NULL;
323
324 if (!GetFunctionAddress(fun,
325 addr,
326 name,
327 value_ptr))
328 return false; // GetFunctionAddress reports its own errors
329
330 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
331
332 if (value_ptr)
333 *value_ptr = value;
334
335 fun->replaceAllUsesWith(value);
336 }
337
338 return true;
339}
340
Sean Callanan47dc4572011-09-15 02:13:07 +0000341
Sean Callanan696cf5f2011-05-07 01:06:41 +0000342clang::NamedDecl *
Sean Callanan47dc4572011-09-15 02:13:07 +0000343IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000344{
345 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
346
Sean Callanan47dc4572011-09-15 02:13:07 +0000347 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan696cf5f2011-05-07 01:06:41 +0000348
349 if (!named_metadata)
350 return NULL;
351
352 unsigned num_nodes = named_metadata->getNumOperands();
353 unsigned node_index;
354
355 for (node_index = 0;
356 node_index < num_nodes;
357 ++node_index)
358 {
359 MDNode *metadata_node = named_metadata->getOperand(node_index);
360
361 if (!metadata_node)
362 return NULL;
363
364 if (metadata_node->getNumOperands() != 2)
365 continue;
366
367 if (metadata_node->getOperand(0) != global_val)
368 continue;
369
370 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
371
372 if (!constant_int)
373 return NULL;
374
375 uintptr_t ptr = constant_int->getZExtValue();
376
377 return reinterpret_cast<clang::NamedDecl *>(ptr);
378 }
379
380 return NULL;
381}
382
Sean Callanan47dc4572011-09-15 02:13:07 +0000383clang::NamedDecl *
384IRForTarget::DeclForGlobal (GlobalValue *global_val)
385{
386 return DeclForGlobal(global_val, m_module);
387}
388
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000389void
390IRForTarget::MaybeSetConstantResult (llvm::Constant *initializer,
391 const lldb_private::ConstString &name,
392 lldb_private::TypeFromParser type)
393{
Sean Callanan696cf5f2011-05-07 01:06:41 +0000394 if (llvm::ConstantExpr *init_expr = dyn_cast<llvm::ConstantExpr>(initializer))
395 {
396 switch (init_expr->getOpcode())
397 {
398 default:
399 return;
400 case Instruction::IntToPtr:
401 MaybeSetConstantResult (init_expr->getOperand(0), name, type);
402 return;
403 }
404 }
405 else if (llvm::ConstantInt *init_int = dyn_cast<llvm::ConstantInt>(initializer))
406 {
407 m_const_result = m_decl_map->BuildIntegerVariable(name, type, init_int->getValue());
408 }
409}
410
411void
Sean Callananc0492742011-05-23 21:40:23 +0000412IRForTarget::MaybeSetCastResult (lldb_private::TypeFromParser type)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000413{
414 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
415
416 if (!m_result_store)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000417 return;
418
Sean Callanan696cf5f2011-05-07 01:06:41 +0000419 LoadInst *original_load = NULL;
420
421 for (llvm::Value *current_value = m_result_store->getValueOperand(), *next_value;
422 current_value != NULL;
423 current_value = next_value)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000424 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000425 CastInst *cast_inst = dyn_cast<CastInst>(current_value);
426 LoadInst *load_inst = dyn_cast<LoadInst>(current_value);
427
428 if (cast_inst)
429 {
430 next_value = cast_inst->getOperand(0);
431 }
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000432 else if (load_inst)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000433 {
434 if (isa<LoadInst>(load_inst->getPointerOperand()))
435 {
436 next_value = load_inst->getPointerOperand();
437 }
438 else
439 {
440 original_load = load_inst;
441 break;
442 }
443 }
444 else
445 {
446 return;
447 }
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000448 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000449
450 Value *loaded_value = original_load->getPointerOperand();
451 GlobalVariable *loaded_global = dyn_cast<GlobalVariable>(loaded_value);
452
453 if (!loaded_global)
454 return;
455
Sean Callananc0492742011-05-23 21:40:23 +0000456 clang::NamedDecl *loaded_decl = DeclForGlobal(loaded_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000457
458 if (!loaded_decl)
459 return;
460
461 clang::VarDecl *loaded_var = dyn_cast<clang::VarDecl>(loaded_decl);
462
463 if (!loaded_var)
464 return;
465
466 if (log)
467 {
468 lldb_private::StreamString type_desc_stream;
469 type.DumpTypeDescription(&type_desc_stream);
470
471 log->Printf("Type to cast variable to: \"%s\"", type_desc_stream.GetString().c_str());
472 }
473
474 m_const_result = m_decl_map->BuildCastVariable(m_result_name, loaded_var, type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000475}
476
477bool
Sean Callananc0492742011-05-23 21:40:23 +0000478IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanan82b74c82010-08-12 01:56:52 +0000479{
Greg Claytone005f2c2010-11-06 01:53:30 +0000480 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan82b74c82010-08-12 01:56:52 +0000481
Sean Callanane8a59a82010-09-13 21:34:21 +0000482 if (!m_resolve_vars)
483 return true;
484
485 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000486
Sean Callananc0492742011-05-23 21:40:23 +0000487 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000488
Sean Callanan9b6898f2011-07-30 02:42:06 +0000489 std::string result_name_str;
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000490 const char *result_name = NULL;
491
492 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
493 vi != ve;
494 ++vi)
495 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000496 result_name_str = vi->first().str();
497 const char *value_name = result_name_str.c_str();
498
499 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
500 !strstr(value_name, "GV"))
Sean Callanan6a925532011-01-13 08:53:35 +0000501 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000502 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000503 m_result_is_pointer = true;
504 break;
505 }
506
Sean Callanan9b6898f2011-07-30 02:42:06 +0000507 if (strstr(value_name, "$__lldb_expr_result") &&
508 !strstr(value_name, "GV"))
Sean Callananc04743d2010-09-28 21:13:03 +0000509 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000510 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000511 m_result_is_pointer = false;
Sean Callananc04743d2010-09-28 21:13:03 +0000512 break;
513 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000514 }
515
516 if (!result_name)
517 {
518 if (log)
519 log->PutCString("Couldn't find result variable");
520
521 return true;
522 }
523
Sean Callananc04743d2010-09-28 21:13:03 +0000524 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000525 log->Printf("Result name: \"%s\"", result_name);
Sean Callananc04743d2010-09-28 21:13:03 +0000526
Sean Callananc0492742011-05-23 21:40:23 +0000527 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000528
529 if (!result_value)
530 {
531 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000532 log->PutCString("Result variable had no data");
Sean Callanan6a925532011-01-13 08:53:35 +0000533
Sean Callanan97c924e2011-01-27 01:07:04 +0000534 if (m_error_stream)
535 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
536
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000537 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000538 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000539
Sean Callanan82b74c82010-08-12 01:56:52 +0000540 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000541 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000542
543 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
544
545 if (!result_global)
546 {
547 if (log)
548 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000549
550 if (m_error_stream)
551 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
552
Sean Callanan82b74c82010-08-12 01:56:52 +0000553 return false;
554 }
555
Sean Callananc0492742011-05-23 21:40:23 +0000556 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000557 if (!result_decl)
Sean Callanan82b74c82010-08-12 01:56:52 +0000558 {
559 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000560 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanan82b74c82010-08-12 01:56:52 +0000561
Sean Callanan97c924e2011-01-27 01:07:04 +0000562 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000563 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 +0000564
Sean Callanan82b74c82010-08-12 01:56:52 +0000565 return false;
566 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000567
Sean Callanan696cf5f2011-05-07 01:06:41 +0000568 if (log)
Sean Callanan82b74c82010-08-12 01:56:52 +0000569 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000570 std::string decl_desc_str;
571 raw_string_ostream decl_desc_stream(decl_desc_str);
572 result_decl->print(decl_desc_stream);
573 decl_desc_stream.flush();
Sean Callanan82b74c82010-08-12 01:56:52 +0000574
Sean Callanan696cf5f2011-05-07 01:06:41 +0000575 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000576 }
577
Sean Callanan696cf5f2011-05-07 01:06:41 +0000578 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
579 if (!result_var)
Sean Callanan82b74c82010-08-12 01:56:52 +0000580 {
581 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000582 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan97c924e2011-01-27 01:07:04 +0000583
584 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000585 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 +0000586
Sean Callanan82b74c82010-08-12 01:56:52 +0000587 return false;
588 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000589
Sean Callanan82b74c82010-08-12 01:56:52 +0000590 // Get the next available result name from m_decl_map and create the persistent
591 // variable for it
Sean Callanan47dc4572011-09-15 02:13:07 +0000592
Sean Callanan696cf5f2011-05-07 01:06:41 +0000593 // If the result is an Lvalue, it is emitted as a pointer; see
594 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan6a925532011-01-13 08:53:35 +0000595 if (m_result_is_pointer)
596 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000597 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanand5b3c352011-01-27 04:42:51 +0000598 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
599 const clang::PointerType *pointer_pointertype = dyn_cast<clang::PointerType>(pointer_type);
Sean Callanan6a925532011-01-13 08:53:35 +0000600
601 if (!pointer_pointertype)
602 {
603 if (log)
604 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan97c924e2011-01-27 01:07:04 +0000605
606 if (m_error_stream)
607 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
608
Sean Callanan6a925532011-01-13 08:53:35 +0000609 return false;
610 }
611
612 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
613
Sean Callanan47dc4572011-09-15 02:13:07 +0000614 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
Sean Callanan6a925532011-01-13 08:53:35 +0000615 &result_decl->getASTContext());
616 }
617 else
618 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000619 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan6a925532011-01-13 08:53:35 +0000620 &result_decl->getASTContext());
621 }
622
Sean Callanan696cf5f2011-05-07 01:06:41 +0000623 if (log)
624 {
625 lldb_private::StreamString type_desc_stream;
Sean Callanan47dc4572011-09-15 02:13:07 +0000626 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000627
628 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetString().c_str());
629 }
630
Sean Callanan6a925532011-01-13 08:53:35 +0000631 m_result_name = m_decl_map->GetPersistentResultName();
Sean Callanan82b74c82010-08-12 01:56:52 +0000632
633 if (log)
Sean Callanan6a925532011-01-13 08:53:35 +0000634 log->Printf("Creating a new result global: \"%s\"", m_result_name.GetCString());
Sean Callanan82b74c82010-08-12 01:56:52 +0000635
636 // Construct a new result global and set up its metadata
637
Sean Callananc0492742011-05-23 21:40:23 +0000638 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanan82b74c82010-08-12 01:56:52 +0000639 result_global->getType()->getElementType(),
640 false, /* not constant */
641 GlobalValue::ExternalLinkage,
642 NULL, /* no initializer */
Sean Callanan6a925532011-01-13 08:53:35 +0000643 m_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000644
645 // It's too late in compilation to create a new VarDecl for this, but we don't
646 // need to. We point the metadata at the old VarDecl. This creates an odd
647 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000648 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000649 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
650 // fixed up.
651
Sean Callananc0492742011-05-23 21:40:23 +0000652 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan696cf5f2011-05-07 01:06:41 +0000653 reinterpret_cast<uint64_t>(result_decl),
Sean Callanan82b74c82010-08-12 01:56:52 +0000654 false);
655
656 llvm::Value* values[2];
657 values[0] = new_result_global;
658 values[1] = new_constant_int;
659
Sean Callanan0de254a2011-05-15 22:34:38 +0000660 ArrayRef<Value*> value_ref(values, 2);
661
Sean Callananc0492742011-05-23 21:40:23 +0000662 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
663 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000664 named_metadata->addOperand(persistent_global_md);
665
666 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000667 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000668 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000669 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000670
671 if (result_global->hasNUses(0))
672 {
673 // We need to synthesize a store for this variable, because otherwise
674 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000675
Greg Clayton8de27c72010-10-15 22:48:33 +0000676 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000677 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
678
679 if (!first_entry_instruction)
680 return false;
681
682 if (!result_global->hasInitializer())
683 {
684 if (log)
685 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000686
687 if (m_error_stream)
688 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
689
Sean Callanan2e2db532010-09-07 22:43:19 +0000690 return false;
691 }
692
693 Constant *initializer = result_global->getInitializer();
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000694
695 // Here we write the initializer into a result variable assuming it
696 // can be computed statically.
697
698 if (!m_has_side_effects)
699 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000700 //MaybeSetConstantResult (initializer,
701 // m_result_name,
702 // m_result_type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000703 }
Sean Callanan2e2db532010-09-07 22:43:19 +0000704
Greg Clayton2c344ca2011-02-05 02:28:58 +0000705 StoreInst *synthesized_store = new StoreInst(initializer,
706 new_result_global,
707 first_entry_instruction);
Sean Callanan2e2db532010-09-07 22:43:19 +0000708
709 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000710 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000711 }
712 else
713 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000714 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (m_result_type.GetOpaqueQualType()))
Sean Callanan696cf5f2011-05-07 01:06:41 +0000715 {
Sean Callanan557ccd62011-10-21 05:18:02 +0000716 //MaybeSetCastResult (m_result_type);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000717 }
718
Sean Callanan2e2db532010-09-07 22:43:19 +0000719 result_global->replaceAllUsesWith(new_result_global);
720 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000721
722 if (!m_const_result)
723 m_decl_map->AddPersistentVariable(result_decl,
724 m_result_name,
Sean Callanan47dc4572011-09-15 02:13:07 +0000725 m_result_type,
Sean Callanan696cf5f2011-05-07 01:06:41 +0000726 true,
727 m_result_is_pointer);
Sean Callanan2e2db532010-09-07 22:43:19 +0000728
Sean Callanan82b74c82010-08-12 01:56:52 +0000729 result_global->eraseFromParent();
730
731 return true;
732}
733
Johnny Chen58021cc2011-08-09 23:10:20 +0000734#if 0
Greg Clayton3c7feb42010-11-19 01:05:25 +0000735static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000736{
737 if (!depth)
738 return;
739
740 depth--;
741
Johnny Chen58021cc2011-08-09 23:10:20 +0000742 if (log)
743 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000744
Greg Clayton3c7feb42010-11-19 01:05:25 +0000745 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000746 ui != ue;
747 ++ui)
748 {
Johnny Chen58021cc2011-08-09 23:10:20 +0000749 if (log)
750 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000751 DebugUsers(log, *ui, depth);
752 }
753
Johnny Chen58021cc2011-08-09 23:10:20 +0000754 if (log)
755 log->Printf(" <End uses>");
Sean Callanan6ba533e2010-11-17 23:00:36 +0000756}
Johnny Chen58021cc2011-08-09 23:10:20 +0000757#endif
Sean Callanan6ba533e2010-11-17 23:00:36 +0000758
759bool
Sean Callananc0492742011-05-23 21:40:23 +0000760IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton3c7feb42010-11-19 01:05:25 +0000761 llvm::GlobalVariable *cstr,
762 Instruction *FirstEntryInstruction)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000763{
764 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
765
Sean Callanan9b6898f2011-07-30 02:42:06 +0000766 Type *ns_str_ty = ns_str->getType();
Sean Callananc0492742011-05-23 21:40:23 +0000767
Sean Callanan9b6898f2011-07-30 02:42:06 +0000768 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
769 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callananc0492742011-05-23 21:40:23 +0000770 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan9b6898f2011-07-30 02:42:06 +0000771 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
772 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000773
774 if (!m_CFStringCreateWithBytes)
775 {
776 lldb::addr_t CFStringCreateWithBytes_addr;
777
778 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
779
780 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
781 {
782 if (log)
783 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
784
Sean Callanan97c924e2011-01-27 01:07:04 +0000785 if (m_error_stream)
786 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
787
Sean Callanan6ba533e2010-11-17 23:00:36 +0000788 return false;
789 }
790
791 if (log)
792 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr);
793
794 // Build the function type:
795 //
796 // CFStringRef CFStringCreateWithBytes (
797 // CFAllocatorRef alloc,
798 // const UInt8 *bytes,
799 // CFIndex numBytes,
800 // CFStringEncoding encoding,
801 // Boolean isExternalRepresentation
802 // );
803 //
804 // We make the following substitutions:
805 //
806 // CFStringRef -> i8*
807 // CFAllocatorRef -> i8*
808 // UInt8 * -> i8*
809 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
810 // CFStringEncoding -> i32
811 // Boolean -> i8
812
Sean Callanan9b6898f2011-07-30 02:42:06 +0000813 Type *arg_type_array[5];
814
815 arg_type_array[0] = i8_ptr_ty;
816 arg_type_array[1] = i8_ptr_ty;
817 arg_type_array[2] = intptr_ty;
818 arg_type_array[3] = i32_ty;
819 arg_type_array[4] = i8_ty;
820
821 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
822
Sean Callananc0492742011-05-23 21:40:23 +0000823 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000824
825 // Build the constant containing the pointer to the function
826 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
827 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
828 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
829 }
830
Sean Callanan58baaad2011-07-08 00:39:14 +0000831 ConstantArray *string_array = NULL;
Sean Callanan0ece5262011-02-10 22:17:53 +0000832
833 if (cstr)
834 string_array = dyn_cast<ConstantArray>(cstr->getInitializer());
Sean Callanan9b6898f2011-07-30 02:42:06 +0000835
Sean Callanan6ba533e2010-11-17 23:00:36 +0000836 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan0ece5262011-02-10 22:17:53 +0000837 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
838 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getType()->getNumElements() - 1 : 0, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000839 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
840 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
841
Sean Callanan9b6898f2011-07-30 02:42:06 +0000842 Value *argument_array[5];
843
844 argument_array[0] = alloc_arg;
845 argument_array[1] = bytes_arg;
846 argument_array[2] = numBytes_arg;
847 argument_array[3] = encoding_arg;
848 argument_array[4] = isExternal_arg;
849
850 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000851
852 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanan9b6898f2011-07-30 02:42:06 +0000853 CFSCWB_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +0000854 "CFStringCreateWithBytes",
855 FirstEntryInstruction);
Sean Callananae71e302010-11-18 22:21:58 +0000856
Greg Clayton3c7feb42010-11-19 01:05:25 +0000857 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000858 {
859 if (log)
860 log->PutCString("Couldn't replace the NSString with the result of the call");
861
Sean Callanan97c924e2011-01-27 01:07:04 +0000862 if (m_error_stream)
863 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
864
Sean Callanan6ba533e2010-11-17 23:00:36 +0000865 return false;
866 }
867
Greg Clayton3c7feb42010-11-19 01:05:25 +0000868 ns_str->eraseFromParent();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000869
870 return true;
871}
872
873bool
Sean Callananc0492742011-05-23 21:40:23 +0000874IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000875{
876 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
877
Sean Callananc0492742011-05-23 21:40:23 +0000878 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000879
Greg Clayton3c7feb42010-11-19 01:05:25 +0000880 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000881 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
882
883 if (!FirstEntryInstruction)
884 {
885 if (log)
886 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
887
Sean Callanan97c924e2011-01-27 01:07:04 +0000888 if (m_error_stream)
889 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
890
Sean Callanan6ba533e2010-11-17 23:00:36 +0000891 return false;
892 }
893
894 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
895 vi != ve;
896 ++vi)
897 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000898 std::string value_name = vi->first().str();
899 const char *value_name_cstr = value_name.c_str();
900
901 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000902 {
903 Value *nsstring_value = vi->second;
904
905 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
906
907 if (!nsstring_global)
908 {
909 if (log)
910 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000911
912 if (m_error_stream)
913 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
914
Sean Callanan6ba533e2010-11-17 23:00:36 +0000915 return false;
916 }
917
918 if (!nsstring_global->hasInitializer())
919 {
920 if (log)
921 log->PutCString("NSString variable does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000922
923 if (m_error_stream)
924 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
925
Sean Callanan6ba533e2010-11-17 23:00:36 +0000926 return false;
927 }
928
929 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
930
931 if (!nsstring_struct)
932 {
933 if (log)
934 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan97c924e2011-01-27 01:07:04 +0000935
936 if (m_error_stream)
937 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
938
Sean Callanan6ba533e2010-11-17 23:00:36 +0000939 return false;
940 }
941
942 // We expect the following structure:
943 //
944 // struct {
945 // int *isa;
946 // int flags;
947 // char *str;
948 // long length;
949 // };
950
951 if (nsstring_struct->getNumOperands() != 4)
952 {
953 if (log)
954 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 +0000955
956 if (m_error_stream)
957 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
958
Sean Callanan6ba533e2010-11-17 23:00:36 +0000959 return false;
960 }
961
962 Constant *nsstring_member = nsstring_struct->getOperand(2);
963
964 if (!nsstring_member)
965 {
966 if (log)
967 log->PutCString("NSString initializer's str element was empty");
Sean Callanan97c924e2011-01-27 01:07:04 +0000968
969 if (m_error_stream)
970 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
971
Sean Callanan6ba533e2010-11-17 23:00:36 +0000972 return false;
973 }
974
975 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
976
977 if (!nsstring_expr)
978 {
979 if (log)
980 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan97c924e2011-01-27 01:07:04 +0000981
982 if (m_error_stream)
983 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
984
Sean Callanan6ba533e2010-11-17 23:00:36 +0000985 return false;
986 }
987
988 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
989 {
990 if (log)
991 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 +0000992
993 if (m_error_stream)
994 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
995
Sean Callanan6ba533e2010-11-17 23:00:36 +0000996 return false;
997 }
998
999 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
1000
1001 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
1002
1003 if (!cstr_global)
1004 {
1005 if (log)
1006 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001007
1008 if (m_error_stream)
1009 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 +00001010
Sean Callanan6ba533e2010-11-17 23:00:36 +00001011 return false;
1012 }
1013
1014 if (!cstr_global->hasInitializer())
1015 {
1016 if (log)
1017 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +00001018
1019 if (m_error_stream)
1020 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
1021
Sean Callanan6ba533e2010-11-17 23:00:36 +00001022 return false;
1023 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001024
1025 /*
Sean Callanan6ba533e2010-11-17 23:00:36 +00001026 if (!cstr_array)
1027 {
1028 if (log)
1029 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan97c924e2011-01-27 01:07:04 +00001030
1031 if (m_error_stream)
1032 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
1033
Sean Callanan6ba533e2010-11-17 23:00:36 +00001034 return false;
1035 }
1036
1037 if (!cstr_array->isCString())
1038 {
1039 if (log)
1040 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan97c924e2011-01-27 01:07:04 +00001041
1042 if (m_error_stream)
1043 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
1044
Sean Callanan6ba533e2010-11-17 23:00:36 +00001045 return false;
1046 }
Sean Callanan0ece5262011-02-10 22:17:53 +00001047 */
1048
1049 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer());
Sean Callanan6ba533e2010-11-17 23:00:36 +00001050
1051 if (log)
Sean Callanan0ece5262011-02-10 22:17:53 +00001052 {
1053 if (cstr_array)
Sean Callanan9b6898f2011-07-30 02:42:06 +00001054 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().c_str());
Sean Callanan0ece5262011-02-10 22:17:53 +00001055 else
Sean Callanan9b6898f2011-07-30 02:42:06 +00001056 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan0ece5262011-02-10 22:17:53 +00001057 }
1058
1059 if (!cstr_array)
1060 cstr_global = NULL;
Sean Callanan6ba533e2010-11-17 23:00:36 +00001061
Sean Callananc0492742011-05-23 21:40:23 +00001062 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan97c924e2011-01-27 01:07:04 +00001063 {
Sean Callanan6ba533e2010-11-17 23:00:36 +00001064 if (log)
1065 log->PutCString("Error rewriting the constant string");
Sean Callanan97c924e2011-01-27 01:07:04 +00001066
1067 // We don't print an error message here because RewriteObjCConstString has done so for us.
1068
Sean Callanan6ba533e2010-11-17 23:00:36 +00001069 return false;
1070 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00001071 }
1072 }
1073
1074 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1075 vi != ve;
1076 ++vi)
1077 {
Sean Callanan9b6898f2011-07-30 02:42:06 +00001078 std::string value_name = vi->first().str();
1079 const char *value_name_cstr = value_name.c_str();
1080
1081 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callanan6ba533e2010-11-17 23:00:36 +00001082 {
1083 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1084
1085 if (!gv)
1086 {
1087 if (log)
1088 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001089
1090 if (m_error_stream)
1091 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1092
Sean Callanan6ba533e2010-11-17 23:00:36 +00001093 return false;
1094 }
1095
1096 gv->eraseFromParent();
1097
1098 break;
1099 }
1100 }
1101
1102 return true;
1103}
1104
Greg Clayton3c7feb42010-11-19 01:05:25 +00001105static bool IsObjCSelectorRef (Value *value)
Sean Callananf5857a02010-07-31 01:32:05 +00001106{
Greg Clayton3c7feb42010-11-19 01:05:25 +00001107 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callananf5857a02010-07-31 01:32:05 +00001108
Greg Clayton3c7feb42010-11-19 01:05:25 +00001109 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callananf5857a02010-07-31 01:32:05 +00001110 return false;
1111
1112 return true;
1113}
1114
Sean Callanan97c924e2011-01-27 01:07:04 +00001115// This function does not report errors; its callers are responsible.
Sean Callananf5857a02010-07-31 01:32:05 +00001116bool
Sean Callananc0492742011-05-23 21:40:23 +00001117IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callananf5857a02010-07-31 01:32:05 +00001118{
Greg Claytone005f2c2010-11-06 01:53:30 +00001119 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001120
1121 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1122
1123 if (!load)
1124 return false;
1125
1126 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1127 //
1128 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1129 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1130 //
1131 // where %obj is the object pointer and %tmp is the selector.
1132 //
Greg Clayton3c7feb42010-11-19 01:05:25 +00001133 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1134 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callananf5857a02010-07-31 01:32:05 +00001135
1136 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1137
1138 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1139
1140 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1141 return false;
1142
1143 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1144
1145 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1146
1147 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1148 return false;
1149
1150 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1151
1152 if (!osr_initializer_base)
1153 return false;
1154
1155 // Find the string's initializer (a ConstantArray) and get the string from it
1156
1157 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1158
1159 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1160 return false;
1161
1162 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1163
1164 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
1165
1166 if (!omvn_initializer_array->isString())
1167 return false;
1168
1169 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1170
1171 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001172 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +00001173
1174 // Construct a call to sel_registerName
1175
1176 if (!m_sel_registerName)
1177 {
Greg Claytonb5037af2010-11-15 01:47:11 +00001178 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +00001179
Greg Clayton8de27c72010-10-15 22:48:33 +00001180 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +00001181 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001182 return false;
1183
Sean Callananc2c6f772010-10-26 00:31:56 +00001184 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001185 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +00001186
Sean Callananf5857a02010-07-31 01:32:05 +00001187 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1188
1189 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callananc0492742011-05-23 21:40:23 +00001190 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001191 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanan9b6898f2011-07-30 02:42:06 +00001192 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001193
Sean Callanan9b6898f2011-07-30 02:42:06 +00001194 Type *type_array[1];
1195
1196 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1197
1198 ArrayRef<Type *> srN_arg_types(type_array, 1);
1199
Sean Callananf5857a02010-07-31 01:32:05 +00001200 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1201
1202 // Build the constant containing the pointer to the function
Sean Callanan9b6898f2011-07-30 02:42:06 +00001203 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1204 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananf5857a02010-07-31 01:32:05 +00001205 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +00001206 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001207 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1208 }
1209
Sean Callanan9b6898f2011-07-30 02:42:06 +00001210 Value *argument_array[1];
1211
Sean Callananc0492742011-05-23 21:40:23 +00001212 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callananf5857a02010-07-31 01:32:05 +00001213
Sean Callanan9b6898f2011-07-30 02:42:06 +00001214 argument_array[0] = omvn_pointer;
Sean Callananf5857a02010-07-31 01:32:05 +00001215
Sean Callanan9b6898f2011-07-30 02:42:06 +00001216 ArrayRef<Value *> srN_arguments(argument_array, 1);
1217
Sean Callananf5857a02010-07-31 01:32:05 +00001218 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanan9b6898f2011-07-30 02:42:06 +00001219 srN_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +00001220 "sel_registerName",
Sean Callananf5857a02010-07-31 01:32:05 +00001221 selector_load);
1222
1223 // Replace the load with the call in all users
1224
1225 selector_load->replaceAllUsesWith(srN_call);
1226
1227 selector_load->eraseFromParent();
1228
1229 return true;
1230}
1231
1232bool
Sean Callananc0492742011-05-23 21:40:23 +00001233IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callananf5857a02010-07-31 01:32:05 +00001234{
Greg Claytone005f2c2010-11-06 01:53:30 +00001235 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001236
1237 BasicBlock::iterator ii;
1238
1239 typedef SmallVector <Instruction*, 2> InstrList;
1240 typedef InstrList::iterator InstrIterator;
1241
1242 InstrList selector_loads;
1243
Greg Clayton3c7feb42010-11-19 01:05:25 +00001244 for (ii = basic_block.begin();
1245 ii != basic_block.end();
Sean Callananf5857a02010-07-31 01:32:05 +00001246 ++ii)
1247 {
1248 Instruction &inst = *ii;
1249
1250 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton3c7feb42010-11-19 01:05:25 +00001251 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callananf5857a02010-07-31 01:32:05 +00001252 selector_loads.push_back(&inst);
1253 }
1254
1255 InstrIterator iter;
1256
1257 for (iter = selector_loads.begin();
1258 iter != selector_loads.end();
1259 ++iter)
1260 {
Sean Callananc0492742011-05-23 21:40:23 +00001261 if (!RewriteObjCSelector(*iter))
Sean Callananf5857a02010-07-31 01:32:05 +00001262 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001263 if (m_error_stream)
1264 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1265
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001266 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +00001267 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan97c924e2011-01-27 01:07:04 +00001268
Sean Callananf5857a02010-07-31 01:32:05 +00001269 return false;
1270 }
1271 }
1272
1273 return true;
1274}
1275
Sean Callanan97c924e2011-01-27 01:07:04 +00001276// This function does not report errors; its callers are responsible.
Sean Callanana48fe162010-08-11 03:57:18 +00001277bool
Sean Callananc0492742011-05-23 21:40:23 +00001278IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanana48fe162010-08-11 03:57:18 +00001279{
Sean Callanan97678d12011-01-13 21:23:32 +00001280 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1281
Sean Callanana48fe162010-08-11 03:57:18 +00001282 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1283
1284 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1285
1286 if (!alloc_md || !alloc_md->getNumOperands())
1287 return false;
1288
1289 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1290
1291 if (!constant_int)
1292 return false;
1293
1294 // We attempt to register this as a new persistent variable with the DeclMap.
1295
1296 uintptr_t ptr = constant_int->getZExtValue();
1297
Sean Callanan82b74c82010-08-12 01:56:52 +00001298 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +00001299
Sean Callanan82b74c82010-08-12 01:56:52 +00001300 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1301 &decl->getASTContext());
1302
Greg Clayton8de27c72010-10-15 22:48:33 +00001303 StringRef decl_name (decl->getName());
1304 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan6a925532011-01-13 08:53:35 +00001305 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanana48fe162010-08-11 03:57:18 +00001306 return false;
1307
Sean Callananc0492742011-05-23 21:40:23 +00001308 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanan97678d12011-01-13 21:23:32 +00001309 alloc->getType(),
Sean Callanana48fe162010-08-11 03:57:18 +00001310 false, /* not constant */
1311 GlobalValue::ExternalLinkage,
1312 NULL, /* no initializer */
1313 alloc->getName().str().c_str());
1314
1315 // What we're going to do here is make believe this was a regular old external
1316 // variable. That means we need to make the metadata valid.
1317
Sean Callananc0492742011-05-23 21:40:23 +00001318 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +00001319
1320 llvm::Value* values[2];
1321 values[0] = persistent_global;
1322 values[1] = constant_int;
Sean Callanan0de254a2011-05-15 22:34:38 +00001323
1324 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +00001325
Sean Callananc0492742011-05-23 21:40:23 +00001326 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanana48fe162010-08-11 03:57:18 +00001327 named_metadata->addOperand(persistent_global_md);
1328
Sean Callanan97678d12011-01-13 21:23:32 +00001329 // Now, since the variable is a pointer variable, we will drop in a load of that
1330 // pointer variable.
1331
1332 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1333
1334 if (log)
1335 log->Printf("Replacing \"%s\" with \"%s\"",
1336 PrintValue(alloc).c_str(),
1337 PrintValue(persistent_load).c_str());
1338
1339 alloc->replaceAllUsesWith(persistent_load);
Sean Callanana48fe162010-08-11 03:57:18 +00001340 alloc->eraseFromParent();
1341
1342 return true;
1343}
1344
1345bool
Sean Callananc0492742011-05-23 21:40:23 +00001346IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanana48fe162010-08-11 03:57:18 +00001347{
Sean Callanane8a59a82010-09-13 21:34:21 +00001348 if (!m_resolve_vars)
1349 return true;
1350
Greg Claytone005f2c2010-11-06 01:53:30 +00001351 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +00001352
1353 BasicBlock::iterator ii;
1354
1355 typedef SmallVector <Instruction*, 2> InstrList;
1356 typedef InstrList::iterator InstrIterator;
1357
1358 InstrList pvar_allocs;
1359
Greg Clayton3c7feb42010-11-19 01:05:25 +00001360 for (ii = basic_block.begin();
1361 ii != basic_block.end();
Sean Callanana48fe162010-08-11 03:57:18 +00001362 ++ii)
1363 {
1364 Instruction &inst = *ii;
1365
1366 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan237e4742011-01-21 22:30:25 +00001367 {
1368 llvm::StringRef alloc_name = alloc->getName();
1369
1370 if (alloc_name.startswith("$") &&
1371 !alloc_name.startswith("$__lldb"))
1372 {
1373 if (alloc_name.find_first_of("0123456789") == 1)
1374 {
1375 if (log)
1376 log->Printf("Rejecting a numeric persistent variable.");
1377
Sean Callanan97c924e2011-01-27 01:07:04 +00001378 if (m_error_stream)
1379 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1380
Sean Callanan237e4742011-01-21 22:30:25 +00001381 return false;
1382 }
1383
Sean Callanana48fe162010-08-11 03:57:18 +00001384 pvar_allocs.push_back(alloc);
Sean Callanan237e4742011-01-21 22:30:25 +00001385 }
1386 }
Sean Callanana48fe162010-08-11 03:57:18 +00001387 }
1388
1389 InstrIterator iter;
1390
1391 for (iter = pvar_allocs.begin();
1392 iter != pvar_allocs.end();
1393 ++iter)
1394 {
Sean Callananc0492742011-05-23 21:40:23 +00001395 if (!RewritePersistentAlloc(*iter))
Sean Callanana48fe162010-08-11 03:57:18 +00001396 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001397 if (m_error_stream)
1398 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1399
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001400 if (log)
Sean Callanana48fe162010-08-11 03:57:18 +00001401 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001402
Sean Callanana48fe162010-08-11 03:57:18 +00001403 return false;
1404 }
1405 }
1406
1407 return true;
1408}
1409
Sean Callanan97c924e2011-01-27 01:07:04 +00001410// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001411bool
Sean Callananc0492742011-05-23 21:40:23 +00001412IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001413{
Greg Claytone005f2c2010-11-06 01:53:30 +00001414 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan48443652010-12-02 19:47:57 +00001415
1416 if (log)
Sean Callananb9f09a62010-12-06 22:16:55 +00001417 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callanan9a877432011-08-01 17:41:38 +00001418
Greg Clayton8de27c72010-10-15 22:48:33 +00001419 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +00001420 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001421 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +00001422 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001423 default:
1424 break;
1425 case Instruction::GetElementPtr:
1426 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +00001427 Value *s = constant_expr->getOperand(0);
Sean Callananc0492742011-05-23 21:40:23 +00001428 if (!MaybeHandleVariable(s))
Sean Callanan48443652010-12-02 19:47:57 +00001429 return false;
Sean Callananbc2928a2010-08-03 00:23:29 +00001430 }
1431 }
Sean Callananf921cf52010-12-03 19:51:05 +00001432 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001433 {
Sean Callananc0492742011-05-23 21:40:23 +00001434 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001435
Sean Callananf5857a02010-07-31 01:32:05 +00001436 if (!named_decl)
1437 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001438 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001439 return true;
1440
Sean Callanan7cd46742010-12-06 00:56:39 +00001441 if (!global_variable->hasExternalLinkage())
1442 return true;
1443
Sean Callananf5857a02010-07-31 01:32:05 +00001444 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001445 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001446
Sean Callananf5857a02010-07-31 01:32:05 +00001447 return false;
1448 }
1449
Greg Clayton8de27c72010-10-15 22:48:33 +00001450 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +00001451
Sean Callanan771131d2010-09-30 21:18:25 +00001452 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +00001453 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +00001454
1455 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +00001456 {
Sean Callanan771131d2010-09-30 21:18:25 +00001457 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +00001458 ast_context = &value_decl->getASTContext();
1459 }
Sean Callanan810f22d2010-07-16 00:09:46 +00001460 else
Sean Callananf328c9f2010-07-20 23:31:16 +00001461 {
Sean Callanan810f22d2010-07-16 00:09:46 +00001462 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +00001463 }
Sean Callanan771131d2010-09-30 21:18:25 +00001464
Sean Callanan6a925532011-01-13 08:53:35 +00001465 clang::QualType qual_type;
Sean Callanan58baaad2011-07-08 00:39:14 +00001466 const Type *value_type = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00001467
Sean Callanan97678d12011-01-13 21:23:32 +00001468 if (name[0] == '$')
Sean Callanan6a925532011-01-13 08:53:35 +00001469 {
1470 // The $__lldb_expr_result name indicates the the return value has allocated as
1471 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1472 // accesses to this static variable need to be redirected to the result of dereferencing
1473 // a pointer that is passed in as one of the arguments.
1474 //
1475 // Consequently, when reporting the size of the type, we report a pointer type pointing
1476 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanan97678d12011-01-13 21:23:32 +00001477 //
1478 // We also do this for any user-declared persistent variables.
Sean Callananf328c9f2010-07-20 23:31:16 +00001479
Sean Callanan6a925532011-01-13 08:53:35 +00001480 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1481 value_type = PointerType::get(global_variable->getType(), 0);
1482 }
1483 else
1484 {
1485 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1486 value_type = global_variable->getType();
1487 }
Sean Callanan771131d2010-09-30 21:18:25 +00001488
1489 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
1490 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001491
Sean Callanan771131d2010-09-30 21:18:25 +00001492 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001493 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %lu, align %lld]",
Sean Callanan771131d2010-09-30 21:18:25 +00001494 name.c_str(),
1495 qual_type.getAsString().c_str(),
1496 PrintType(value_type).c_str(),
1497 value_size,
1498 value_alignment);
Sean Callanan3aa7da52010-12-13 22:46:15 +00001499
Sean Callanan8bce6652010-07-13 21:41:46 +00001500
Sean Callanan8c127202010-08-23 23:09:38 +00001501 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +00001502 lldb_private::ConstString (name.c_str()),
1503 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +00001504 value_size,
1505 value_alignment))
Sean Callanan9a877432011-08-01 17:41:38 +00001506 {
1507 if (!global_variable->hasExternalLinkage())
1508 return true;
1509 else
1510 return false;
1511 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001512 }
Sean Callananf3143b72010-12-03 03:02:31 +00001513 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanan48443652010-12-02 19:47:57 +00001514 {
1515 if (log)
1516 log->Printf("Function pointers aren't handled right now");
1517
1518 return false;
1519 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001520
1521 return true;
1522}
1523
Sean Callanan97c924e2011-01-27 01:07:04 +00001524// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001525bool
Sean Callananc0492742011-05-23 21:40:23 +00001526IRForTarget::HandleSymbol (Value *symbol)
Sean Callanan81974962011-05-08 02:21:26 +00001527{
Sean Callananc7674af2011-01-17 23:42:46 +00001528 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1529
1530 lldb_private::ConstString name(symbol->getName().str().c_str());
1531
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001532 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name);
Sean Callananc7674af2011-01-17 23:42:46 +00001533
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001534 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc7674af2011-01-17 23:42:46 +00001535 {
1536 if (log)
1537 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1538
1539 return false;
1540 }
1541
1542 if (log)
1543 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), symbol_addr);
1544
Sean Callanan9b6898f2011-07-30 02:42:06 +00001545 Type *symbol_type = symbol->getType();
Sean Callananc7674af2011-01-17 23:42:46 +00001546
Sean Callanan9b6898f2011-07-30 02:42:06 +00001547 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1548 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc7674af2011-01-17 23:42:46 +00001549
1550 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1551
1552 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1553
1554 if (log)
1555 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1556
1557 symbol->replaceAllUsesWith(symbol_addr_ptr);
1558
1559 return true;
1560}
1561
1562bool
Sean Callananc0492742011-05-23 21:40:23 +00001563IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +00001564{
Sean Callanan48443652010-12-02 19:47:57 +00001565 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1566
1567 if (log)
1568 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanandc27aba2010-10-05 22:26:43 +00001569
Sean Callanan6ba533e2010-11-17 23:00:36 +00001570 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +00001571 op_index < num_ops;
1572 ++op_index)
Sean Callananc0492742011-05-23 21:40:23 +00001573 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan97c924e2011-01-27 01:07:04 +00001574 {
1575 if (m_error_stream)
1576 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1577
Sean Callanandc27aba2010-10-05 22:26:43 +00001578 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001579 }
1580
Sean Callanandc27aba2010-10-05 22:26:43 +00001581 return true;
1582}
1583
1584bool
Sean Callananc0492742011-05-23 21:40:23 +00001585IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan8bce6652010-07-13 21:41:46 +00001586{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001587 /////////////////////////////////////////////////////////////////////////
1588 // Prepare the current basic block for execution in the remote process
1589 //
1590
Sean Callanan02fbafa2010-07-27 21:39:39 +00001591 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001592
Greg Clayton3c7feb42010-11-19 01:05:25 +00001593 for (ii = basic_block.begin();
1594 ii != basic_block.end();
Sean Callanan8bce6652010-07-13 21:41:46 +00001595 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001596 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001597 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001598
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001599 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001600
Sean Callanan97c924e2011-01-27 01:07:04 +00001601 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001602 if (call && !MaybeHandleCallArguments(call))
Sean Callanan48443652010-12-02 19:47:57 +00001603 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001604 }
1605
1606 return true;
1607}
1608
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001609bool
Sean Callananc0492742011-05-23 21:40:23 +00001610IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001611{
Sean Callananae71e302010-11-18 22:21:58 +00001612 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1613
Sean Callananc0492742011-05-23 21:40:23 +00001614 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001615 global != end;
1616 ++global)
1617 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001618 if (log)
1619 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1620 (*global).getName().str().c_str(),
Sean Callananc0492742011-05-23 21:40:23 +00001621 DeclForGlobal(global));
Greg Clayton3c7feb42010-11-19 01:05:25 +00001622
Sean Callananc7674af2011-01-17 23:42:46 +00001623 if ((*global).getName().str().find("OBJC_IVAR") == 0)
1624 {
Sean Callananc0492742011-05-23 21:40:23 +00001625 if (!HandleSymbol(global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001626 {
1627 if (m_error_stream)
1628 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str());
1629
Sean Callananc7674af2011-01-17 23:42:46 +00001630 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001631 }
Sean Callananc7674af2011-01-17 23:42:46 +00001632 }
Sean Callananc0492742011-05-23 21:40:23 +00001633 else if (DeclForGlobal(global))
Sean Callananc7674af2011-01-17 23:42:46 +00001634 {
Sean Callananc0492742011-05-23 21:40:23 +00001635 if (!MaybeHandleVariable (global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001636 {
1637 if (m_error_stream)
1638 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str());
1639
Sean Callananc7674af2011-01-17 23:42:46 +00001640 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001641 }
Sean Callananc7674af2011-01-17 23:42:46 +00001642 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001643 }
1644
1645 return true;
1646}
1647
Sean Callananc0492742011-05-23 21:40:23 +00001648bool
1649IRForTarget::ReplaceStrings ()
1650{
1651 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1652
1653 if (!m_data_allocator)
1654 return true; // hope for the best; some clients may not want static allocation!
1655
1656 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1657
1658 OffsetsTy offsets;
1659
1660 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1661 gi != ge;
1662 ++gi)
1663 {
1664 GlobalVariable *gv = gi;
1665
1666 if (!gv->hasInitializer())
1667 continue;
1668
1669 Constant *gc = gv->getInitializer();
1670
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001671 std::string str;
Sean Callananc0492742011-05-23 21:40:23 +00001672
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001673 if (gc->isNullValue())
1674 {
1675 Type *gc_type = gc->getType();
1676
1677 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1678
1679 if (!gc_array_type)
1680 continue;
1681
1682 Type *gc_element_type = gc_array_type->getElementType();
1683
1684 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1685
1686 if (gc_integer_type->getBitWidth() != 8)
1687 continue;
1688
1689 str = "";
1690 }
1691 else
1692 {
1693 ConstantArray *gc_array = dyn_cast<ConstantArray>(gc);
1694
1695 if (!gc_array)
1696 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001697
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001698 if (!gc_array->isCString())
1699 continue;
Sean Callananc0492742011-05-23 21:40:23 +00001700
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001701 if (log)
1702 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callananc0492742011-05-23 21:40:23 +00001703
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001704 str = gc_array->getAsString();
1705 }
1706
Sean Callananc0492742011-05-23 21:40:23 +00001707 offsets[gv] = m_data_allocator->GetStream().GetSize();
1708
1709 m_data_allocator->GetStream().Write(str.c_str(), str.length() + 1);
1710 }
1711
Sean Callanan9b6898f2011-07-30 02:42:06 +00001712 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00001713
1714 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1715 oi != oe;
1716 ++oi)
1717 {
1718 GlobalVariable *gv = oi->first;
1719 size_t offset = oi->second;
1720
1721 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1722
1723 if (log)
1724 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1725
1726 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1727 ui != ue;
1728 ++ui)
1729 {
1730 if (log)
1731 log->Printf("Found use %s", PrintValue(*ui).c_str());
1732
1733 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1734 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1735
1736 if (const_expr)
1737 {
1738 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1739 {
1740 if (log)
1741 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1742
1743 return false;
1744 }
1745
Sean Callanan1b3d1df2011-08-10 21:05:52 +00001746 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1747 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1748
1749 const_expr->replaceAllUsesWith(new_gep);
Sean Callananc0492742011-05-23 21:40:23 +00001750 }
1751 else if (store_inst)
1752 {
1753 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1754
1755 store_inst->setOperand(0, bit_cast);
1756 }
1757 else
1758 {
1759 if (log)
1760 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1761
1762 return false;
1763 }
1764 }
1765
1766 gv->eraseFromParent();
1767 }
1768
1769 return true;
1770}
1771
1772bool
1773IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1774{
1775 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1776
1777 if (!m_data_allocator)
1778 return true;
1779
1780 typedef SmallVector <Value*, 2> ConstantList;
1781 typedef SmallVector <llvm::Instruction*, 2> UserList;
1782 typedef ConstantList::iterator ConstantIterator;
1783 typedef UserList::iterator UserIterator;
1784
1785 ConstantList static_constants;
1786 UserList static_users;
1787
1788 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1789 ii != ie;
1790 ++ii)
1791 {
1792 llvm::Instruction &inst = *ii;
1793
1794 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1795 oi != oe;
1796 ++oi)
1797 {
1798 Value *operand_val = oi->get();
1799
1800 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1801
1802 if (operand_constant_fp && operand_constant_fp->getType()->isX86_FP80Ty())
1803 {
1804 static_constants.push_back(operand_val);
1805 static_users.push_back(ii);
1806 }
1807 }
1808 }
1809
1810 ConstantIterator constant_iter;
1811 UserIterator user_iter;
Greg Clayton54b38412011-05-24 23:06:02 +00001812
Sean Callananc0492742011-05-23 21:40:23 +00001813 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1814 constant_iter != static_constants.end();
1815 ++constant_iter, ++user_iter)
1816 {
1817 Value *operand_val = *constant_iter;
1818 llvm::Instruction *inst = *user_iter;
1819
1820 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1821
1822 if (operand_constant_fp)
1823 {
1824 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
1825 APInt operand_apint = operand_apfloat.bitcastToAPInt();
1826
1827 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
1828 size_t operand_data_size = operand_apint.getBitWidth() / 8;
1829
1830 if (log)
1831 {
1832 std::string s;
1833 raw_string_ostream ss(s);
1834 for (size_t index = 0;
1835 index < operand_data_size;
1836 ++index)
1837 {
1838 ss << (uint32_t)operand_raw_data[index];
1839 ss << " ";
1840 }
1841 ss.flush();
1842
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001843 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callananc0492742011-05-23 21:40:23 +00001844 }
1845
1846 lldb_private::DataBufferHeap data(operand_data_size, 0);
1847
1848 if (lldb::endian::InlHostByteOrder() != m_data_allocator->GetStream().GetByteOrder())
1849 {
1850 uint8_t *data_bytes = data.GetBytes();
1851
1852 for (size_t index = 0;
1853 index < operand_data_size;
1854 ++index)
1855 {
1856 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
1857 }
1858 }
1859 else
1860 {
1861 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
1862 }
1863
1864 uint64_t offset = m_data_allocator->GetStream().GetSize();
1865
1866 m_data_allocator->GetStream().Write(data.GetBytes(), operand_data_size);
1867
Sean Callanan9b6898f2011-07-30 02:42:06 +00001868 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callananc0492742011-05-23 21:40:23 +00001869
1870 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
1871
1872 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
1873
1874 operand_constant_fp->replaceAllUsesWith(fp_load);
1875 }
1876 }
1877
1878 return true;
1879}
1880
Sean Callanan02fbafa2010-07-27 21:39:39 +00001881static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00001882{
Sean Callanan58baaad2011-07-08 00:39:14 +00001883 Constant *Old = NULL;
Sean Callanan45839272010-07-24 01:37:44 +00001884
Sean Callanan6ba533e2010-11-17 23:00:36 +00001885 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00001886 return false;
1887
Sean Callanan58baaad2011-07-08 00:39:14 +00001888 ConstantExpr *CE = NULL;
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001889
1890 if ((CE = dyn_cast<ConstantExpr>(V)))
1891 {
1892 if (CE->getOpcode() != Instruction::BitCast)
1893 return false;
1894
Sean Callanan6ba533e2010-11-17 23:00:36 +00001895 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001896 }
1897
Sean Callanan6ba533e2010-11-17 23:00:36 +00001898 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00001899
1900 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
1901 return false;
1902
1903 return true;
1904}
1905
Sean Callananc0492742011-05-23 21:40:23 +00001906void
1907IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callanan45839272010-07-24 01:37:44 +00001908{
Sean Callananc0492742011-05-23 21:40:23 +00001909 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callanan45839272010-07-24 01:37:44 +00001910
1911 Value::use_iterator ui;
1912
1913 for (ui = guard_load->use_begin();
1914 ui != guard_load->use_end();
1915 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00001916 {
Greg Clayton6e713402010-07-30 20:30:44 +00001917 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00001918 {
1919 // do nothing for the moment
1920 }
1921 else
1922 {
1923 ui->replaceUsesOfWith(guard_load, zero);
1924 }
1925 }
Sean Callanan45839272010-07-24 01:37:44 +00001926
1927 guard_load->eraseFromParent();
1928}
1929
1930static void ExciseGuardStore(Instruction* guard_store)
1931{
1932 guard_store->eraseFromParent();
1933}
1934
1935bool
Sean Callananc0492742011-05-23 21:40:23 +00001936IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callanan45839272010-07-24 01:37:44 +00001937{
1938 ///////////////////////////////////////////////////////
1939 // Eliminate any reference to guard variables found.
1940 //
1941
Sean Callanan02fbafa2010-07-27 21:39:39 +00001942 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00001943
Sean Callanan02fbafa2010-07-27 21:39:39 +00001944 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00001945 typedef InstrList::iterator InstrIterator;
1946
1947 InstrList guard_loads;
1948 InstrList guard_stores;
1949
Greg Clayton3c7feb42010-11-19 01:05:25 +00001950 for (ii = basic_block.begin();
1951 ii != basic_block.end();
Sean Callanan45839272010-07-24 01:37:44 +00001952 ++ii)
1953 {
1954 Instruction &inst = *ii;
1955
1956 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1957 if (isGuardVariableRef(load->getPointerOperand()))
1958 guard_loads.push_back(&inst);
1959
1960 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1961 if (isGuardVariableRef(store->getPointerOperand()))
1962 guard_stores.push_back(&inst);
1963 }
1964
1965 InstrIterator iter;
1966
1967 for (iter = guard_loads.begin();
1968 iter != guard_loads.end();
1969 ++iter)
Sean Callananc0492742011-05-23 21:40:23 +00001970 TurnGuardLoadIntoZero(*iter);
Sean Callanan45839272010-07-24 01:37:44 +00001971
1972 for (iter = guard_stores.begin();
1973 iter != guard_stores.end();
1974 ++iter)
1975 ExciseGuardStore(*iter);
1976
1977 return true;
1978}
1979
Sean Callanan97c924e2011-01-27 01:07:04 +00001980// This function does not report errors; its callers are responsible.
Sean Callanan6ba533e2010-11-17 23:00:36 +00001981bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00001982IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callananbafd6852010-07-14 23:40:29 +00001983{
Greg Claytone005f2c2010-11-06 01:53:30 +00001984 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00001985
1986 Value::use_iterator ui;
1987
Sean Callanana48fe162010-08-11 03:57:18 +00001988 SmallVector<User*, 16> users;
1989
1990 // We do this because the use list might change, invalidating our iterator.
1991 // Much better to keep a work list ourselves.
Greg Clayton3c7feb42010-11-19 01:05:25 +00001992 for (ui = old_constant->use_begin();
1993 ui != old_constant->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00001994 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00001995 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00001996
Johnny Chen2bc9eb32011-07-19 19:48:13 +00001997 for (size_t i = 0;
Sean Callanana48fe162010-08-11 03:57:18 +00001998 i < users.size();
1999 ++i)
2000 {
2001 User *user = users[i];
2002
Sean Callananbafd6852010-07-14 23:40:29 +00002003 if (Constant *constant = dyn_cast<Constant>(user))
2004 {
2005 // synthesize a new non-constant equivalent of the constant
2006
2007 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2008 {
2009 switch (constant_expr->getOpcode())
2010 {
2011 default:
2012 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002013 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002014 return false;
2015 case Instruction::BitCast:
2016 {
2017 // UnaryExpr
2018 // OperandList[0] is value
2019
2020 Value *s = constant_expr->getOperand(0);
2021
Greg Clayton3c7feb42010-11-19 01:05:25 +00002022 if (s == old_constant)
2023 s = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002024
Sean Callananc0492742011-05-23 21:40:23 +00002025 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002026
Greg Clayton3c7feb42010-11-19 01:05:25 +00002027 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002028 }
2029 break;
2030 case Instruction::GetElementPtr:
2031 {
2032 // GetElementPtrConstantExpr
2033 // OperandList[0] is base
2034 // OperandList[1]... are indices
2035
2036 Value *ptr = constant_expr->getOperand(0);
2037
Greg Clayton3c7feb42010-11-19 01:05:25 +00002038 if (ptr == old_constant)
2039 ptr = new_constant;
Sean Callanan9b6898f2011-07-30 02:42:06 +00002040
2041 std::vector<Value*> index_vector;
Sean Callananbafd6852010-07-14 23:40:29 +00002042
2043 unsigned operand_index;
2044 unsigned num_operands = constant_expr->getNumOperands();
2045
2046 for (operand_index = 1;
2047 operand_index < num_operands;
2048 ++operand_index)
2049 {
2050 Value *operand = constant_expr->getOperand(operand_index);
2051
Greg Clayton3c7feb42010-11-19 01:05:25 +00002052 if (operand == old_constant)
2053 operand = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00002054
Sean Callanan9b6898f2011-07-30 02:42:06 +00002055 index_vector.push_back(operand);
Sean Callananbafd6852010-07-14 23:40:29 +00002056 }
2057
Sean Callanan9b6898f2011-07-30 02:42:06 +00002058 ArrayRef <Value*> indices(index_vector);
2059
2060 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002061
Greg Clayton3c7feb42010-11-19 01:05:25 +00002062 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002063 }
2064 break;
2065 }
2066 }
2067 else
2068 {
2069 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002070 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002071 return false;
2072 }
2073 }
2074 else
2075 {
2076 // simple fall-through case for non-constants
Greg Clayton3c7feb42010-11-19 01:05:25 +00002077 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callananbafd6852010-07-14 23:40:29 +00002078 }
2079 }
2080
2081 return true;
2082}
2083
Sean Callanan8bce6652010-07-13 21:41:46 +00002084bool
Sean Callananc0492742011-05-23 21:40:23 +00002085IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan8bce6652010-07-13 21:41:46 +00002086{
Sean Callanane8a59a82010-09-13 21:34:21 +00002087 if (!m_resolve_vars)
2088 return true;
2089
Greg Claytone005f2c2010-11-06 01:53:30 +00002090 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00002091
2092 m_decl_map->DoStructLayout();
2093
2094 if (log)
2095 log->Printf("Element arrangement:");
2096
2097 uint32_t num_elements;
2098 uint32_t element_index;
2099
2100 size_t size;
2101 off_t alignment;
2102
2103 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2104 return false;
2105
Greg Clayton3c7feb42010-11-19 01:05:25 +00002106 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00002107
Greg Clayton3c7feb42010-11-19 01:05:25 +00002108 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002109 {
2110 if (m_error_stream)
2111 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2112
Sean Callanan8bce6652010-07-13 21:41:46 +00002113 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002114 }
2115
Sean Callanan02fbafa2010-07-27 21:39:39 +00002116 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00002117
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002118 if (argument->getName().equals("this"))
2119 {
2120 ++iter;
2121
Greg Clayton3c7feb42010-11-19 01:05:25 +00002122 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002123 {
2124 if (m_error_stream)
2125 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2126
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002127 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002128 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002129
2130 argument = iter;
2131 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002132 else if (argument->getName().equals("self"))
2133 {
2134 ++iter;
2135
2136 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002137 {
2138 if (m_error_stream)
2139 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2140
Sean Callanan3aa7da52010-12-13 22:46:15 +00002141 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002142 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002143
2144 if (!iter->getName().equals("_cmd"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002145 {
2146 if (m_error_stream)
2147 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2148
Sean Callanan3aa7da52010-12-13 22:46:15 +00002149 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002150 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002151
2152 ++iter;
2153
2154 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002155 {
2156 if (m_error_stream)
2157 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2158
Sean Callanan3aa7da52010-12-13 22:46:15 +00002159 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002160 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002161
2162 argument = iter;
2163 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002164
Greg Clayton8de27c72010-10-15 22:48:33 +00002165 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002166 {
2167 if (m_error_stream)
2168 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2169
Sean Callanan8bce6652010-07-13 21:41:46 +00002170 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002171 }
2172
Sean Callanan8bce6652010-07-13 21:41:46 +00002173 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002174 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00002175
Greg Clayton3c7feb42010-11-19 01:05:25 +00002176 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00002177 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00002178
Sean Callanan6ba533e2010-11-17 23:00:36 +00002179 if (!FirstEntryInstruction)
Sean Callanan97c924e2011-01-27 01:07:04 +00002180 {
2181 if (m_error_stream)
2182 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2183
Sean Callanan8bce6652010-07-13 21:41:46 +00002184 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002185 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002186
Sean Callananc0492742011-05-23 21:40:23 +00002187 LLVMContext &context(m_module->getContext());
Sean Callanan9b6898f2011-07-30 02:42:06 +00002188 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan8bce6652010-07-13 21:41:46 +00002189
2190 if (!offset_type)
Sean Callanan97c924e2011-01-27 01:07:04 +00002191 {
2192 if (m_error_stream)
2193 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2194
Sean Callanan8bce6652010-07-13 21:41:46 +00002195 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002196 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002197
2198 for (element_index = 0; element_index < num_elements; ++element_index)
2199 {
Sean Callanan58baaad2011-07-08 00:39:14 +00002200 const clang::NamedDecl *decl = NULL;
2201 Value *value = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002202 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00002203 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00002204
Sean Callanan45690fe2010-08-30 22:17:16 +00002205 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan97c924e2011-01-27 01:07:04 +00002206 {
2207 if (m_error_stream)
2208 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2209
Sean Callanan8bce6652010-07-13 21:41:46 +00002210 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002211 }
2212
Sean Callanan8bce6652010-07-13 21:41:46 +00002213 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002214 log->Printf(" \"%s\" [\"%s\"] (\"%s\") placed at %lld",
Sean Callanan82b74c82010-08-12 01:56:52 +00002215 value->getName().str().c_str(),
Greg Clayton8de27c72010-10-15 22:48:33 +00002216 name.GetCString(),
Sean Callanan8bce6652010-07-13 21:41:46 +00002217 PrintValue(value, true).c_str(),
2218 offset);
2219
Sean Callanan9b6898f2011-07-30 02:42:06 +00002220 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callanan6ba533e2010-11-17 23:00:36 +00002221 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan6a925532011-01-13 08:53:35 +00002222
Sean Callanan58baaad2011-07-08 00:39:14 +00002223 Value *replacement = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002224
Sean Callanan6a925532011-01-13 08:53:35 +00002225 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2226 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2227 // entry in order to produce the static variable that the AST thinks it is accessing.
2228 if (name == m_result_name && !m_result_is_pointer)
2229 {
2230 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2231
2232 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2233
2234 replacement = load;
2235 }
Sean Callananbafd6852010-07-14 23:40:29 +00002236 else
Sean Callanan6a925532011-01-13 08:53:35 +00002237 {
2238 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2239
2240 replacement = bit_cast;
2241 }
2242
2243 if (Constant *constant = dyn_cast<Constant>(value))
2244 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2245 else
2246 value->replaceAllUsesWith(replacement);
Sean Callananb51ee982010-11-02 23:51:17 +00002247
2248 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2249 var->eraseFromParent();
Sean Callanan8bce6652010-07-13 21:41:46 +00002250 }
2251
2252 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002253 log->Printf("Total structure [align %lld, size %lu]", alignment, size);
Sean Callanan8bce6652010-07-13 21:41:46 +00002254
2255 return true;
2256}
2257
Sean Callananc0492742011-05-23 21:40:23 +00002258llvm::Constant *
Sean Callanan9b6898f2011-07-30 02:42:06 +00002259IRForTarget::BuildRelocation(llvm::Type *type,
Sean Callananc0492742011-05-23 21:40:23 +00002260 uint64_t offset)
2261{
2262 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2263
Sean Callanan9b6898f2011-07-30 02:42:06 +00002264 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2265 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002266
2267 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanan9b6898f2011-07-30 02:42:06 +00002268
2269 llvm::Constant *offset_array[1];
2270
2271 offset_array[0] = offset_int;
2272
2273 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2274
2275 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callananc0492742011-05-23 21:40:23 +00002276 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2277
2278 return reloc_getbitcast;
2279}
2280
2281bool
2282IRForTarget::CompleteDataAllocation ()
2283{
Sean Callanan47dc4572011-09-15 02:13:07 +00002284 if (!m_data_allocator)
2285 return true;
2286
Sean Callananc0492742011-05-23 21:40:23 +00002287 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2288
2289 if (!m_data_allocator->GetStream().GetSize())
2290 return true;
2291
2292 lldb::addr_t allocation = m_data_allocator->Allocate();
2293
2294 if (log)
2295 {
2296 if (allocation)
2297 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2298 else
2299 log->Printf("Failed to allocate static data");
2300 }
2301
2302 if (!allocation)
2303 return false;
2304
Sean Callanan9b6898f2011-07-30 02:42:06 +00002305 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2306 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002307
2308 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2309 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2310
2311 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2312
2313 m_reloc_placeholder->eraseFromParent();
2314
2315 return true;
2316}
2317
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002318bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002319IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002320{
Greg Claytone005f2c2010-11-06 01:53:30 +00002321 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002322
Sean Callananc0492742011-05-23 21:40:23 +00002323 m_module = &llvm_module;
2324
2325 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002326
2327 if (!function)
2328 {
2329 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002330 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00002331
2332 if (m_error_stream)
Sean Callananc0492742011-05-23 21:40:23 +00002333 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 +00002334
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002335 return false;
2336 }
Sean Callananc0492742011-05-23 21:40:23 +00002337
2338 if (!FixFunctionLinkage (*function))
2339 {
2340 if (log)
2341 log->Printf("Couldn't fix the linkage for the function");
2342
2343 return false;
2344 }
2345
Sean Callanan9b6898f2011-07-30 02:42:06 +00002346 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00002347
2348 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2349 intptr_ty,
2350 false /* isConstant */,
2351 GlobalVariable::InternalLinkage,
2352 Constant::getNullValue(intptr_ty),
2353 "reloc_placeholder",
2354 NULL /* InsertBefore */,
2355 false /* ThreadLocal */,
2356 0 /* AddressSpace */);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002357
Sean Callanan02fbafa2010-07-27 21:39:39 +00002358 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002359
Sean Callananc0492742011-05-23 21:40:23 +00002360 m_has_side_effects = HasSideEffects(*function);
Sean Callanan05a5a1b2010-12-16 03:17:46 +00002361
Sean Callanan82b74c82010-08-12 01:56:52 +00002362 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00002363 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00002364 //
2365
Sean Callananc0492742011-05-23 21:40:23 +00002366 if (!CreateResultVariable(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002367 {
2368 if (log)
2369 log->Printf("CreateResultVariable() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002370
2371 // CreateResultVariable() reports its own errors, so we don't do so here
2372
Sean Callanan82b74c82010-08-12 01:56:52 +00002373 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002374 }
Sean Callanan47dc4572011-09-15 02:13:07 +00002375
2376 if (m_const_result && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2377 {
2378 m_interpret_success = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +00002379 return true;
Sean Callanan47dc4572011-09-15 02:13:07 +00002380 }
2381
2382 for (bbi = function->begin();
2383 bbi != function->end();
2384 ++bbi)
2385 {
2386 if (!RemoveGuards(*bbi))
2387 {
2388 if (log)
2389 log->Printf("RemoveGuards() failed");
2390
2391 // RemoveGuards() reports its own errors, so we don't do so here
2392
2393 return false;
2394 }
2395
2396 if (!RewritePersistentAllocs(*bbi))
2397 {
2398 if (log)
2399 log->Printf("RewritePersistentAllocs() failed");
2400
2401 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2402
2403 return false;
2404 }
2405 }
2406
2407 if (m_decl_map && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2408 {
2409 IRInterpreter interpreter (*m_decl_map,
2410 m_error_stream);
2411
2412 if (interpreter.maybeRunOnFunction(m_const_result, m_result_name, m_result_type, *function, llvm_module))
2413 {
2414 m_interpret_success = true;
2415 return true;
2416 }
2417 }
Sean Callanan696cf5f2011-05-07 01:06:41 +00002418
Sean Callananc0492742011-05-23 21:40:23 +00002419 if (log)
2420 {
2421 std::string s;
2422 raw_string_ostream oss(s);
2423
2424 m_module->print(oss, NULL);
2425
2426 oss.flush();
2427
2428 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2429 }
2430
Sean Callanan6ba533e2010-11-17 23:00:36 +00002431 ///////////////////////////////////////////////////////////////////////////////
2432 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2433 //
Sean Callanan6ba533e2010-11-17 23:00:36 +00002434
Sean Callananc0492742011-05-23 21:40:23 +00002435 if (!RewriteObjCConstStrings(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002436 {
2437 if (log)
2438 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002439
2440 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2441
Sean Callanan6ba533e2010-11-17 23:00:36 +00002442 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002443 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00002444
Sean Callanan5c9a3c72011-08-04 21:37:47 +00002445 ///////////////////////////////
2446 // Resolve function pointers
2447 //
2448
2449 if (!ResolveFunctionPointers(llvm_module, *function))
2450 {
2451 if (log)
2452 log->Printf("ResolveFunctionPointers() failed");
2453
2454 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2455
2456 return false;
2457 }
2458
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002459 for (bbi = function->begin();
2460 bbi != function->end();
2461 ++bbi)
2462 {
Sean Callananc0492742011-05-23 21:40:23 +00002463 if (!RewriteObjCSelectors(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002464 {
2465 if (log)
2466 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002467
2468 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2469
Sean Callanana48fe162010-08-11 03:57:18 +00002470 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002471 }
Sean Callanana48fe162010-08-11 03:57:18 +00002472
Sean Callananc0492742011-05-23 21:40:23 +00002473 if (!ResolveCalls(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002474 {
2475 if (log)
2476 log->Printf("ResolveCalls() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002477
2478 // ResolveCalls() reports its own errors, so we don't do so here
2479
Sean Callanan8bce6652010-07-13 21:41:46 +00002480 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002481 }
Sean Callananc0492742011-05-23 21:40:23 +00002482
2483 if (!ReplaceStaticLiterals(*bbi))
2484 {
2485 if (log)
2486 log->Printf("ReplaceStaticLiterals() failed");
2487
2488 return false;
2489 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002490 }
2491
Sean Callanan771131d2010-09-30 21:18:25 +00002492 ///////////////////////////////
2493 // Run function-level passes
2494 //
2495
Sean Callananc0492742011-05-23 21:40:23 +00002496 if (!ResolveExternals(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002497 {
2498 if (log)
2499 log->Printf("ResolveExternals() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002500
2501 // ResolveExternals() reports its own errors, so we don't do so here
2502
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002503 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002504 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002505
Sean Callananc0492742011-05-23 21:40:23 +00002506 if (!ReplaceVariables(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002507 {
2508 if (log)
2509 log->Printf("ReplaceVariables() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002510
2511 // ReplaceVariables() reports its own errors, so we don't do so here
2512
Sean Callanan771131d2010-09-30 21:18:25 +00002513 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002514 }
Sean Callanan771131d2010-09-30 21:18:25 +00002515
Sean Callananc0492742011-05-23 21:40:23 +00002516 if (!ReplaceStrings())
2517 {
2518 if (log)
2519 log->Printf("ReplaceStrings() failed");
2520
2521 return false;
2522 }
2523
2524 if (!CompleteDataAllocation())
2525 {
2526 if (log)
2527 log->Printf("CompleteDataAllocation() failed");
2528
2529 return false;
2530 }
2531
Sean Callanan8bce6652010-07-13 21:41:46 +00002532 if (log)
2533 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00002534 std::string s;
2535 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00002536
Sean Callananc0492742011-05-23 21:40:23 +00002537 m_module->print(oss, NULL);
Sean Callanan321fe9e2010-07-28 01:00:59 +00002538
2539 oss.flush();
2540
Greg Claytonb5037af2010-11-15 01:47:11 +00002541 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002542 }
2543
2544 return true;
2545}
2546
2547void
Greg Clayton3c7feb42010-11-19 01:05:25 +00002548IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002549{
2550}
2551
2552PassManagerType
2553IRForTarget::getPotentialPassManagerType() const
2554{
2555 return PMT_ModulePassManager;
2556}