blob: fbbdd610ab2d7d6f5987b7bdfd20baa0d60a8f1b [file] [log] [blame]
Sean Callanan3bfdaa22011-09-15 02:13:07 +00001//===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===//
Sean Callanan2ab712f22010-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"
Chandler Carruth1e157582013-01-02 12:20:07 +000013#include "llvm/IR/Constants.h"
14#include "llvm/IR/DataLayout.h"
15#include "llvm/IR/InstrTypes.h"
16#include "llvm/IR/Instructions.h"
17#include "llvm/IR/Intrinsics.h"
18#include "llvm/IR/Module.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000019#include "llvm/PassManager.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000020#include "llvm/Transforms/IPO.h"
Chandler Carruth1e157582013-01-02 12:20:07 +000021#include "llvm/IR/ValueSymbolTable.h"
Sean Callanan549c9f72010-07-13 21:41:46 +000022
23#include "clang/AST/ASTContext.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000024
25#include "lldb/Core/dwarf.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000026#include "lldb/Core/ConstString.h"
27#include "lldb/Core/DataBufferHeap.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000028#include "lldb/Core/Log.h"
29#include "lldb/Core/Scalar.h"
30#include "lldb/Core/StreamString.h"
31#include "lldb/Expression/ClangExpressionDeclMap.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000032#include "lldb/Expression/IRExecutionUnit.h"
Sean Callanan3bfdaa22011-09-15 02:13:07 +000033#include "lldb/Expression/IRInterpreter.h"
Sean Callanan79763a42011-05-23 21:40:23 +000034#include "lldb/Host/Endian.h"
Sean Callanan63697e52011-05-07 01:06:41 +000035#include "lldb/Symbol/ClangASTContext.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000036
37#include <map>
38
39using namespace llvm;
40
Sean Callananeaacbc92010-08-18 18:50:51 +000041static char ID;
42
Sean Callanan8dfb68e2013-03-19 00:10:07 +000043IRForTarget::StaticDataAllocator::StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit) :
44 m_execution_unit(execution_unit),
45 m_allocation(LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +000046{
47}
48
Sean Callanan8dfb68e2013-03-19 00:10:07 +000049lldb::addr_t IRForTarget::StaticDataAllocator::Allocate()
Sean Callanan79763a42011-05-23 21:40:23 +000050{
Sean Callanan8dfb68e2013-03-19 00:10:07 +000051 lldb_private::Error err;
52
53 if (m_allocation != LLDB_INVALID_ADDRESS)
54 {
55 m_execution_unit.FreeNow(m_allocation);
56 m_allocation = LLDB_INVALID_ADDRESS;
57 }
58
59 m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
60
61 return m_allocation;
Sean Callanan79763a42011-05-23 21:40:23 +000062}
63
Greg Clayton1b95a6f2010-11-19 01:05:25 +000064IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
65 bool resolve_vars,
Sean Callanan3bfdaa22011-09-15 02:13:07 +000066 lldb_private::ExecutionPolicy execution_policy,
Sean Callanan63697e52011-05-07 01:06:41 +000067 lldb::ClangExpressionVariableSP &const_result,
Sean Callanan8dfb68e2013-03-19 00:10:07 +000068 lldb_private::IRExecutionUnit &execution_unit,
Sean Callanan3989fb92011-01-27 01:07:04 +000069 lldb_private::Stream *error_stream,
Greg Clayton1b95a6f2010-11-19 01:05:25 +000070 const char *func_name) :
Sean Callanane2ef6e32010-09-23 03:01:22 +000071 ModulePass(ID),
Stephen Wilson71c21d12011-04-11 19:41:40 +000072 m_resolve_vars(resolve_vars),
Sean Callanan3bfdaa22011-09-15 02:13:07 +000073 m_execution_policy(execution_policy),
74 m_interpret_success(false),
Stephen Wilson71c21d12011-04-11 19:41:40 +000075 m_func_name(func_name),
Sean Callanan79763a42011-05-23 21:40:23 +000076 m_module(NULL),
Johnny Chen44805302011-07-19 19:48:13 +000077 m_decl_map(decl_map),
Sean Callanan8dfb68e2013-03-19 00:10:07 +000078 m_data_allocator(execution_unit),
Sean Callananafe16a72010-11-17 23:00:36 +000079 m_CFStringCreateWithBytes(NULL),
Sean Callanan1a8d4092010-08-27 01:01:44 +000080 m_sel_registerName(NULL),
Johnny Chen44805302011-07-19 19:48:13 +000081 m_const_result(const_result),
Stephen Wilson71c21d12011-04-11 19:41:40 +000082 m_error_stream(error_stream),
Sean Callanan92adcac2011-01-13 08:53:35 +000083 m_has_side_effects(false),
Sean Callanan63697e52011-05-07 01:06:41 +000084 m_result_store(NULL),
85 m_result_is_pointer(false),
Sean Callanan79763a42011-05-23 21:40:23 +000086 m_reloc_placeholder(NULL)
Sean Callanan2ab712f22010-07-03 01:35:46 +000087{
88}
89
Sean Callanan038df5032010-09-30 21:18:25 +000090/* Handy utility functions used at several places in the code */
Sean Callanan2235f322010-08-11 03:57:18 +000091
92static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +000093PrintValue(const Value *value, bool truncate = false)
Sean Callanan2235f322010-08-11 03:57:18 +000094{
95 std::string s;
Jim Ingham28eb5712012-10-12 17:34:26 +000096 if (value)
97 {
98 raw_string_ostream rso(s);
99 value->print(rso);
100 rso.flush();
101 if (truncate)
102 s.resize(s.length() - 1);
103 }
Sean Callanan2235f322010-08-11 03:57:18 +0000104 return s;
105}
106
Sean Callanan038df5032010-09-30 21:18:25 +0000107static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000108PrintType(const Type *type, bool truncate = false)
Sean Callanan038df5032010-09-30 21:18:25 +0000109{
110 std::string s;
111 raw_string_ostream rso(s);
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000112 type->print(rso);
Sean Callanan038df5032010-09-30 21:18:25 +0000113 rso.flush();
114 if (truncate)
115 s.resize(s.length() - 1);
116 return s;
117}
118
Sean Callanan2ab712f22010-07-03 01:35:46 +0000119IRForTarget::~IRForTarget()
120{
121}
122
Sean Callanan79763a42011-05-23 21:40:23 +0000123bool
124IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
125{
Sean Callanan79763a42011-05-23 21:40:23 +0000126 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
127
Sean Callanan7f27d602011-11-19 02:54:21 +0000128 std::string name = llvm_function.getName().str();
Sean Callanan79763a42011-05-23 21:40:23 +0000129
130 return true;
131}
132
Sean Callanand1e5b432010-08-12 01:56:52 +0000133bool
Sean Callanan79763a42011-05-23 21:40:23 +0000134IRForTarget::HasSideEffects (llvm::Function &llvm_function)
Sean Callanane4ec90e2010-12-16 03:17:46 +0000135{
136 llvm::Function::iterator bbi;
137 BasicBlock::iterator ii;
Sean Callanan63697e52011-05-07 01:06:41 +0000138
Sean Callanane4ec90e2010-12-16 03:17:46 +0000139 for (bbi = llvm_function.begin();
140 bbi != llvm_function.end();
141 ++bbi)
142 {
143 BasicBlock &basic_block = *bbi;
144
145 for (ii = basic_block.begin();
146 ii != basic_block.end();
147 ++ii)
148 {
149 switch (ii->getOpcode())
150 {
151 default:
152 return true;
153 case Instruction::Store:
154 {
155 StoreInst *store_inst = dyn_cast<StoreInst>(ii);
156
157 Value *store_ptr = store_inst->getPointerOperand();
158
Sean Callanan63697e52011-05-07 01:06:41 +0000159 std::string ptr_name;
160
161 if (store_ptr->hasName())
Sean Callanan7f27d602011-11-19 02:54:21 +0000162 ptr_name = store_ptr->getName().str();
Sean Callanan63697e52011-05-07 01:06:41 +0000163
164 if (isa <AllocaInst> (store_ptr))
Sean Callanane4ec90e2010-12-16 03:17:46 +0000165 break;
Sean Callanan63697e52011-05-07 01:06:41 +0000166
167 if (ptr_name.find("$__lldb_expr_result") != std::string::npos)
168 {
169 if (ptr_name.find("GV") == std::string::npos)
170 m_result_store = store_inst;
171 }
172 else
173 {
174 return true;
175 }
176
177 break;
Sean Callanane4ec90e2010-12-16 03:17:46 +0000178 }
179 case Instruction::Load:
180 case Instruction::Alloca:
181 case Instruction::GetElementPtr:
Sean Callanan63697e52011-05-07 01:06:41 +0000182 case Instruction::BitCast:
Sean Callanane4ec90e2010-12-16 03:17:46 +0000183 case Instruction::Ret:
Sean Callanan63697e52011-05-07 01:06:41 +0000184 case Instruction::ICmp:
185 case Instruction::Br:
Sean Callanane4ec90e2010-12-16 03:17:46 +0000186 break;
187 }
188 }
189 }
190
191 return false;
192}
193
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000194bool
195IRForTarget::GetFunctionAddress (llvm::Function *fun,
196 uint64_t &fun_addr,
197 lldb_private::ConstString &name,
198 Constant **&value_ptr)
199{
Greg Clayton5160ce52013-03-27 23:08:40 +0000200 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000201
202 fun_addr = LLDB_INVALID_ADDRESS;
203 name.Clear();
204 value_ptr = NULL;
205
206 if (fun->isIntrinsic())
207 {
208 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
209
210 switch (intrinsic_id)
211 {
212 default:
213 if (log)
214 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
215
216 if (m_error_stream)
217 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
218
219 return false;
220 case Intrinsic::memcpy:
221 {
222 static lldb_private::ConstString g_memcpy_str ("memcpy");
223 name = g_memcpy_str;
224 }
225 break;
Sean Callanana6cbf062011-11-16 00:20:50 +0000226 case Intrinsic::memset:
227 {
228 static lldb_private::ConstString g_memset_str ("memset");
229 name = g_memset_str;
230 }
231 break;
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000232 }
233
234 if (log && name)
235 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
236 }
237 else
238 {
239 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
240 }
241
242 // Find the address of the function.
243
244 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000245
246 if (fun_decl)
247 {
Sean Callananc70ed462011-10-25 18:36:40 +0000248 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000249 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000250 lldb_private::ConstString altnernate_name;
Greg Claytonf0705c82011-10-22 03:33:13 +0000251 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
252 if (!found_it)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000253 {
Greg Claytonf0705c82011-10-22 03:33:13 +0000254 // Check for an alternate mangling for "std::basic_string<char>"
255 // that is part of the itanium C++ name mangling scheme
256 const char *name_cstr = name.GetCString();
Jim Ingham28eb5712012-10-12 17:34:26 +0000257 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
Greg Claytonf0705c82011-10-22 03:33:13 +0000258 {
259 std::string alternate_mangling("_ZNKSs");
260 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000261 altnernate_name.SetCString(alternate_mangling.c_str());
262 found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
Greg Claytonf0705c82011-10-22 03:33:13 +0000263 }
264 }
265
266 if (!found_it)
267 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000268 lldb_private::Mangled mangled_name(name);
269 lldb_private::Mangled alt_mangled_name(altnernate_name);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000270 if (log)
Greg Claytonf0705c82011-10-22 03:33:13 +0000271 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000272 if (alt_mangled_name)
273 log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
274 mangled_name.GetName().GetCString(),
275 alt_mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000276 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000277 log->Printf("Function \"%s\" had no address",
278 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000279 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000280
281 if (m_error_stream)
Greg Claytonf0705c82011-10-22 03:33:13 +0000282 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000283 if (alt_mangled_name)
284 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
285 mangled_name.GetName().GetCString(),
286 alt_mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000287 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000288 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
289 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000290 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000291 return false;
292 }
293 }
294 }
295 else
296 {
297 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
298 {
299 if (log)
300 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
301
302 if (m_error_stream)
303 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
304
305 return false;
306 }
307 }
308
309 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000310 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000311
312 return true;
313}
314
315llvm::Constant *
316IRForTarget::BuildFunctionPointer (llvm::Type *type,
317 uint64_t ptr)
318{
319 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +0000320 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000321 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
322 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
323 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
324}
325
Sean Callananfc8feb82011-10-31 22:11:40 +0000326void
327IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
328 llvm::Value *function_ptr,
329 const char *name)
330{
Sean Callananfc8feb82011-10-31 22:11:40 +0000331 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
332 i != e;
333 ++i)
334 {
335 Value *user = *i;
336
337 if (Instruction *user_inst = dyn_cast<Instruction>(user))
338 {
Sean Callanand2b465f2012-02-09 03:22:41 +0000339 Constant *name_array = ConstantDataArray::getString(context, StringRef(name));
Sean Callananfc8feb82011-10-31 22:11:40 +0000340
341 ArrayRef<Value *> md_values(name_array);
342
343 MDNode *metadata = MDNode::get(context, md_values);
344
345 user_inst->setMetadata("lldb.call.realName", metadata);
346 }
347 else
348 {
349 RegisterFunctionMetadata (context, user, name);
350 }
351 }
352}
353
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000354bool
355IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module,
356 llvm::Function &llvm_function)
357{
Greg Clayton5160ce52013-03-27 23:08:40 +0000358 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000359
360 for (llvm::Module::iterator fi = llvm_module.begin();
361 fi != llvm_module.end();
362 ++fi)
363 {
364 Function *fun = fi;
365
366 bool is_decl = fun->isDeclaration();
367
368 if (log)
Sean Callanan7f27d602011-11-19 02:54:21 +0000369 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000370
371 if (!is_decl)
372 continue;
373
374 if (fun->hasNUses(0))
375 continue; // ignore
376
377 uint64_t addr = LLDB_INVALID_ADDRESS;
378 lldb_private::ConstString name;
379 Constant **value_ptr = NULL;
380
381 if (!GetFunctionAddress(fun,
382 addr,
383 name,
384 value_ptr))
385 return false; // GetFunctionAddress reports its own errors
386
387 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
388
Sean Callananfc8feb82011-10-31 22:11:40 +0000389 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
390
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000391 if (value_ptr)
392 *value_ptr = value;
393
394 fun->replaceAllUsesWith(value);
395 }
396
397 return true;
398}
399
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000400
Sean Callanan63697e52011-05-07 01:06:41 +0000401clang::NamedDecl *
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000402IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan63697e52011-05-07 01:06:41 +0000403{
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000404 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan63697e52011-05-07 01:06:41 +0000405
406 if (!named_metadata)
407 return NULL;
408
409 unsigned num_nodes = named_metadata->getNumOperands();
410 unsigned node_index;
411
412 for (node_index = 0;
413 node_index < num_nodes;
414 ++node_index)
415 {
416 MDNode *metadata_node = named_metadata->getOperand(node_index);
417
418 if (!metadata_node)
419 return NULL;
420
421 if (metadata_node->getNumOperands() != 2)
422 continue;
423
424 if (metadata_node->getOperand(0) != global_val)
425 continue;
426
427 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
428
429 if (!constant_int)
430 return NULL;
431
432 uintptr_t ptr = constant_int->getZExtValue();
433
434 return reinterpret_cast<clang::NamedDecl *>(ptr);
435 }
436
437 return NULL;
438}
439
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000440clang::NamedDecl *
441IRForTarget::DeclForGlobal (GlobalValue *global_val)
442{
443 return DeclForGlobal(global_val, m_module);
444}
445
Sean Callanane4ec90e2010-12-16 03:17:46 +0000446void
447IRForTarget::MaybeSetConstantResult (llvm::Constant *initializer,
448 const lldb_private::ConstString &name,
449 lldb_private::TypeFromParser type)
450{
Sean Callanan63697e52011-05-07 01:06:41 +0000451 if (llvm::ConstantExpr *init_expr = dyn_cast<llvm::ConstantExpr>(initializer))
452 {
453 switch (init_expr->getOpcode())
454 {
455 default:
456 return;
457 case Instruction::IntToPtr:
458 MaybeSetConstantResult (init_expr->getOperand(0), name, type);
459 return;
460 }
461 }
462 else if (llvm::ConstantInt *init_int = dyn_cast<llvm::ConstantInt>(initializer))
463 {
464 m_const_result = m_decl_map->BuildIntegerVariable(name, type, init_int->getValue());
465 }
466}
467
468void
Sean Callanan79763a42011-05-23 21:40:23 +0000469IRForTarget::MaybeSetCastResult (lldb_private::TypeFromParser type)
Sean Callanan63697e52011-05-07 01:06:41 +0000470{
Greg Clayton5160ce52013-03-27 23:08:40 +0000471 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan63697e52011-05-07 01:06:41 +0000472
473 if (!m_result_store)
Sean Callanane4ec90e2010-12-16 03:17:46 +0000474 return;
475
Sean Callanan63697e52011-05-07 01:06:41 +0000476 LoadInst *original_load = NULL;
477
478 for (llvm::Value *current_value = m_result_store->getValueOperand(), *next_value;
479 current_value != NULL;
480 current_value = next_value)
Sean Callanane4ec90e2010-12-16 03:17:46 +0000481 {
Sean Callanan63697e52011-05-07 01:06:41 +0000482 CastInst *cast_inst = dyn_cast<CastInst>(current_value);
483 LoadInst *load_inst = dyn_cast<LoadInst>(current_value);
484
485 if (cast_inst)
486 {
487 next_value = cast_inst->getOperand(0);
488 }
Enrico Granata20edcdb2011-07-19 18:03:25 +0000489 else if (load_inst)
Sean Callanan63697e52011-05-07 01:06:41 +0000490 {
491 if (isa<LoadInst>(load_inst->getPointerOperand()))
492 {
493 next_value = load_inst->getPointerOperand();
494 }
495 else
496 {
497 original_load = load_inst;
498 break;
499 }
500 }
501 else
502 {
503 return;
504 }
Sean Callanane4ec90e2010-12-16 03:17:46 +0000505 }
Sean Callanan63697e52011-05-07 01:06:41 +0000506
Jim Ingham28eb5712012-10-12 17:34:26 +0000507 if (!original_load)
508 return;
509
Sean Callanan63697e52011-05-07 01:06:41 +0000510 Value *loaded_value = original_load->getPointerOperand();
511 GlobalVariable *loaded_global = dyn_cast<GlobalVariable>(loaded_value);
512
513 if (!loaded_global)
514 return;
515
Sean Callanan79763a42011-05-23 21:40:23 +0000516 clang::NamedDecl *loaded_decl = DeclForGlobal(loaded_global);
Sean Callanan63697e52011-05-07 01:06:41 +0000517
518 if (!loaded_decl)
519 return;
520
521 clang::VarDecl *loaded_var = dyn_cast<clang::VarDecl>(loaded_decl);
522
523 if (!loaded_var)
524 return;
525
526 if (log)
527 {
528 lldb_private::StreamString type_desc_stream;
529 type.DumpTypeDescription(&type_desc_stream);
530
531 log->Printf("Type to cast variable to: \"%s\"", type_desc_stream.GetString().c_str());
532 }
533
534 m_const_result = m_decl_map->BuildCastVariable(m_result_name, loaded_var, type);
Sean Callanane4ec90e2010-12-16 03:17:46 +0000535}
536
537bool
Sean Callanan79763a42011-05-23 21:40:23 +0000538IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanand1e5b432010-08-12 01:56:52 +0000539{
Greg Clayton5160ce52013-03-27 23:08:40 +0000540 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand1e5b432010-08-12 01:56:52 +0000541
Sean Callanan9e6ed532010-09-13 21:34:21 +0000542 if (!m_resolve_vars)
543 return true;
544
545 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callananfc55f5d2010-09-21 00:44:12 +0000546
Sean Callanan79763a42011-05-23 21:40:23 +0000547 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananfc55f5d2010-09-21 00:44:12 +0000548
Sean Callanancc427fa2011-07-30 02:42:06 +0000549 std::string result_name_str;
Sean Callananfc55f5d2010-09-21 00:44:12 +0000550 const char *result_name = NULL;
551
552 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
553 vi != ve;
554 ++vi)
555 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000556 result_name_str = vi->first().str();
557 const char *value_name = result_name_str.c_str();
558
559 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000560 strncmp(value_name, "_ZGV", 4))
Sean Callanan92adcac2011-01-13 08:53:35 +0000561 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000562 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000563 m_result_is_pointer = true;
564 break;
565 }
566
Sean Callanancc427fa2011-07-30 02:42:06 +0000567 if (strstr(value_name, "$__lldb_expr_result") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000568 strncmp(value_name, "_ZGV", 4))
Sean Callanan46ae9e52010-09-28 21:13:03 +0000569 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000570 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000571 m_result_is_pointer = false;
Sean Callanan46ae9e52010-09-28 21:13:03 +0000572 break;
573 }
Sean Callananfc55f5d2010-09-21 00:44:12 +0000574 }
575
576 if (!result_name)
577 {
578 if (log)
579 log->PutCString("Couldn't find result variable");
580
581 return true;
582 }
583
Sean Callanan46ae9e52010-09-28 21:13:03 +0000584 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000585 log->Printf("Result name: \"%s\"", result_name);
Sean Callanan46ae9e52010-09-28 21:13:03 +0000586
Sean Callanan79763a42011-05-23 21:40:23 +0000587 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanand1e5b432010-08-12 01:56:52 +0000588
589 if (!result_value)
590 {
591 if (log)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000592 log->PutCString("Result variable had no data");
Sean Callanan92adcac2011-01-13 08:53:35 +0000593
Sean Callanan3989fb92011-01-27 01:07:04 +0000594 if (m_error_stream)
595 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
596
Sean Callananfc55f5d2010-09-21 00:44:12 +0000597 return false;
Sean Callanand1e5b432010-08-12 01:56:52 +0000598 }
Sean Callanan9e6ed532010-09-13 21:34:21 +0000599
Sean Callanand1e5b432010-08-12 01:56:52 +0000600 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000601 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000602
603 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
604
605 if (!result_global)
606 {
607 if (log)
608 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000609
610 if (m_error_stream)
611 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
612
Sean Callanand1e5b432010-08-12 01:56:52 +0000613 return false;
614 }
615
Sean Callanan79763a42011-05-23 21:40:23 +0000616 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan63697e52011-05-07 01:06:41 +0000617 if (!result_decl)
Sean Callanand1e5b432010-08-12 01:56:52 +0000618 {
619 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000620 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanand1e5b432010-08-12 01:56:52 +0000621
Sean Callanan3989fb92011-01-27 01:07:04 +0000622 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000623 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name);
Sean Callanan3989fb92011-01-27 01:07:04 +0000624
Sean Callanand1e5b432010-08-12 01:56:52 +0000625 return false;
626 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000627
Sean Callanan63697e52011-05-07 01:06:41 +0000628 if (log)
Sean Callanand1e5b432010-08-12 01:56:52 +0000629 {
Sean Callanan63697e52011-05-07 01:06:41 +0000630 std::string decl_desc_str;
631 raw_string_ostream decl_desc_stream(decl_desc_str);
632 result_decl->print(decl_desc_stream);
633 decl_desc_stream.flush();
Sean Callanand1e5b432010-08-12 01:56:52 +0000634
Sean Callanan63697e52011-05-07 01:06:41 +0000635 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000636 }
637
Sean Callanan63697e52011-05-07 01:06:41 +0000638 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
639 if (!result_var)
Sean Callanand1e5b432010-08-12 01:56:52 +0000640 {
641 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000642 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan3989fb92011-01-27 01:07:04 +0000643
644 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000645 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name);
Sean Callanan3989fb92011-01-27 01:07:04 +0000646
Sean Callanand1e5b432010-08-12 01:56:52 +0000647 return false;
648 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000649
Sean Callanand1e5b432010-08-12 01:56:52 +0000650 // Get the next available result name from m_decl_map and create the persistent
651 // variable for it
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000652
Sean Callanan63697e52011-05-07 01:06:41 +0000653 // If the result is an Lvalue, it is emitted as a pointer; see
654 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan92adcac2011-01-13 08:53:35 +0000655 if (m_result_is_pointer)
656 {
Sean Callanan63697e52011-05-07 01:06:41 +0000657 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanan78e37602011-01-27 04:42:51 +0000658 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
Sean Callanan92adcac2011-01-13 08:53:35 +0000659
Sean Callananfc4f2fb2011-12-14 01:13:04 +0000660 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
661 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
Sean Callanan5780f9d2011-12-08 19:04:34 +0000662
663 if (pointer_pointertype)
664 {
665 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
666
667 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
668 &result_decl->getASTContext());
669 }
670 else if (pointer_objcobjpointertype)
671 {
672 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
673
674 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
675 &result_decl->getASTContext());
676 }
677 else
Sean Callanan92adcac2011-01-13 08:53:35 +0000678 {
679 if (log)
680 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan3989fb92011-01-27 01:07:04 +0000681
682 if (m_error_stream)
683 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
684
Sean Callanan92adcac2011-01-13 08:53:35 +0000685 return false;
686 }
Sean Callanan92adcac2011-01-13 08:53:35 +0000687 }
688 else
689 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000690 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan00f43622011-11-18 03:28:09 +0000691 &result_decl->getASTContext());
692 }
693
694 if (m_result_type.GetClangTypeBitWidth() == 0)
695 {
696 lldb_private::StreamString type_desc_stream;
697 m_result_type.DumpTypeDescription(&type_desc_stream);
698
699 if (log)
700 log->Printf("Result type has size 0");
701
702 if (m_error_stream)
Sean Callanan960534c2011-12-21 23:44:05 +0000703 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
Sean Callanan00f43622011-11-18 03:28:09 +0000704 type_desc_stream.GetData());
Sean Callanan960534c2011-12-21 23:44:05 +0000705 return false;
Sean Callanan92adcac2011-01-13 08:53:35 +0000706 }
707
Sean Callanan63697e52011-05-07 01:06:41 +0000708 if (log)
709 {
710 lldb_private::StreamString type_desc_stream;
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000711 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan63697e52011-05-07 01:06:41 +0000712
Sean Callanan00f43622011-11-18 03:28:09 +0000713 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
Sean Callanan63697e52011-05-07 01:06:41 +0000714 }
715
Sean Callanan92adcac2011-01-13 08:53:35 +0000716 m_result_name = m_decl_map->GetPersistentResultName();
Sean Callanand1e5b432010-08-12 01:56:52 +0000717
718 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +0000719 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
Sean Callanan00f43622011-11-18 03:28:09 +0000720 m_result_name.GetCString(),
721 m_result_type.GetClangTypeBitWidth() / 8);
Sean Callanand1e5b432010-08-12 01:56:52 +0000722
723 // Construct a new result global and set up its metadata
724
Sean Callanan79763a42011-05-23 21:40:23 +0000725 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanand1e5b432010-08-12 01:56:52 +0000726 result_global->getType()->getElementType(),
727 false, /* not constant */
728 GlobalValue::ExternalLinkage,
729 NULL, /* no initializer */
Sean Callanan92adcac2011-01-13 08:53:35 +0000730 m_result_name.GetCString ());
Sean Callanand1e5b432010-08-12 01:56:52 +0000731
732 // It's too late in compilation to create a new VarDecl for this, but we don't
733 // need to. We point the metadata at the old VarDecl. This creates an odd
734 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton7b462cc2010-10-15 22:48:33 +0000735 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanand1e5b432010-08-12 01:56:52 +0000736 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
737 // fixed up.
738
Sean Callanan79763a42011-05-23 21:40:23 +0000739 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan63697e52011-05-07 01:06:41 +0000740 reinterpret_cast<uint64_t>(result_decl),
Sean Callanand1e5b432010-08-12 01:56:52 +0000741 false);
742
743 llvm::Value* values[2];
744 values[0] = new_result_global;
745 values[1] = new_constant_int;
746
Sean Callanand12cf8bb2011-05-15 22:34:38 +0000747 ArrayRef<Value*> value_ref(values, 2);
748
Sean Callanan79763a42011-05-23 21:40:23 +0000749 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
750 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanand1e5b432010-08-12 01:56:52 +0000751 named_metadata->addOperand(persistent_global_md);
752
753 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000754 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan1e87fff2010-09-07 22:43:19 +0000755 PrintValue(result_global).c_str(),
Sean Callanand1e5b432010-08-12 01:56:52 +0000756 PrintValue(new_result_global).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000757
758 if (result_global->hasNUses(0))
759 {
760 // We need to synthesize a store for this variable, because otherwise
761 // there's nothing to put into its equivalent persistent variable.
Sean Callanand1e5b432010-08-12 01:56:52 +0000762
Greg Clayton7b462cc2010-10-15 22:48:33 +0000763 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000764 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
765
766 if (!first_entry_instruction)
767 return false;
768
769 if (!result_global->hasInitializer())
770 {
771 if (log)
772 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000773
774 if (m_error_stream)
775 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
776
Sean Callanan1e87fff2010-09-07 22:43:19 +0000777 return false;
778 }
779
780 Constant *initializer = result_global->getInitializer();
Sean Callanane4ec90e2010-12-16 03:17:46 +0000781
782 // Here we write the initializer into a result variable assuming it
783 // can be computed statically.
784
785 if (!m_has_side_effects)
786 {
Sean Callanan80c48c12011-10-21 05:18:02 +0000787 //MaybeSetConstantResult (initializer,
788 // m_result_name,
789 // m_result_type);
Sean Callanane4ec90e2010-12-16 03:17:46 +0000790 }
Sean Callanan1e87fff2010-09-07 22:43:19 +0000791
Greg Clayton9c139312011-02-05 02:28:58 +0000792 StoreInst *synthesized_store = new StoreInst(initializer,
793 new_result_global,
794 first_entry_instruction);
Sean Callanan1e87fff2010-09-07 22:43:19 +0000795
796 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000797 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000798 }
799 else
800 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000801 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (m_result_type.GetOpaqueQualType()))
Sean Callanan63697e52011-05-07 01:06:41 +0000802 {
Sean Callanan80c48c12011-10-21 05:18:02 +0000803 //MaybeSetCastResult (m_result_type);
Sean Callanan63697e52011-05-07 01:06:41 +0000804 }
805
Sean Callanan1e87fff2010-09-07 22:43:19 +0000806 result_global->replaceAllUsesWith(new_result_global);
807 }
Sean Callanan63697e52011-05-07 01:06:41 +0000808
809 if (!m_const_result)
Sean Callanan00f43622011-11-18 03:28:09 +0000810 if (!m_decl_map->AddPersistentVariable(result_decl,
811 m_result_name,
812 m_result_type,
813 true,
814 m_result_is_pointer))
815 return false;
Sean Callanan1e87fff2010-09-07 22:43:19 +0000816
Sean Callanand1e5b432010-08-12 01:56:52 +0000817 result_global->eraseFromParent();
818
819 return true;
820}
821
Johnny Chenee7a3592011-08-09 23:10:20 +0000822#if 0
Greg Clayton5160ce52013-03-27 23:08:40 +0000823static void DebugUsers(Log *log, Value *value, uint8_t depth)
Sean Callananafe16a72010-11-17 23:00:36 +0000824{
825 if (!depth)
826 return;
827
828 depth--;
829
Johnny Chenee7a3592011-08-09 23:10:20 +0000830 if (log)
831 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callananafe16a72010-11-17 23:00:36 +0000832
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000833 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callananafe16a72010-11-17 23:00:36 +0000834 ui != ue;
835 ++ui)
836 {
Johnny Chenee7a3592011-08-09 23:10:20 +0000837 if (log)
838 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callananafe16a72010-11-17 23:00:36 +0000839 DebugUsers(log, *ui, depth);
840 }
841
Johnny Chenee7a3592011-08-09 23:10:20 +0000842 if (log)
843 log->Printf(" <End uses>");
Sean Callananafe16a72010-11-17 23:00:36 +0000844}
Johnny Chenee7a3592011-08-09 23:10:20 +0000845#endif
Sean Callananafe16a72010-11-17 23:00:36 +0000846
847bool
Sean Callanan79763a42011-05-23 21:40:23 +0000848IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000849 llvm::GlobalVariable *cstr,
850 Instruction *FirstEntryInstruction)
Sean Callananafe16a72010-11-17 23:00:36 +0000851{
Greg Clayton5160ce52013-03-27 23:08:40 +0000852 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000853
Sean Callanancc427fa2011-07-30 02:42:06 +0000854 Type *ns_str_ty = ns_str->getType();
Sean Callanan79763a42011-05-23 21:40:23 +0000855
Sean Callanancc427fa2011-07-30 02:42:06 +0000856 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
857 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +0000858 (m_module->getPointerSize()
Micah Villmow08318972012-10-11 17:21:41 +0000859 == Module::Pointer64) ? 64 : 32);
Sean Callanancc427fa2011-07-30 02:42:06 +0000860 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
861 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananafe16a72010-11-17 23:00:36 +0000862
863 if (!m_CFStringCreateWithBytes)
864 {
865 lldb::addr_t CFStringCreateWithBytes_addr;
866
867 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
868
869 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
870 {
871 if (log)
872 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
873
Sean Callanan3989fb92011-01-27 01:07:04 +0000874 if (m_error_stream)
875 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
876
Sean Callananafe16a72010-11-17 23:00:36 +0000877 return false;
878 }
879
880 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000881 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
Sean Callananafe16a72010-11-17 23:00:36 +0000882
883 // Build the function type:
884 //
885 // CFStringRef CFStringCreateWithBytes (
886 // CFAllocatorRef alloc,
887 // const UInt8 *bytes,
888 // CFIndex numBytes,
889 // CFStringEncoding encoding,
890 // Boolean isExternalRepresentation
891 // );
892 //
893 // We make the following substitutions:
894 //
895 // CFStringRef -> i8*
896 // CFAllocatorRef -> i8*
897 // UInt8 * -> i8*
898 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
899 // CFStringEncoding -> i32
900 // Boolean -> i8
901
Sean Callanancc427fa2011-07-30 02:42:06 +0000902 Type *arg_type_array[5];
903
904 arg_type_array[0] = i8_ptr_ty;
905 arg_type_array[1] = i8_ptr_ty;
906 arg_type_array[2] = intptr_ty;
907 arg_type_array[3] = i32_ty;
908 arg_type_array[4] = i8_ty;
909
910 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
911
Sean Callanan79763a42011-05-23 21:40:23 +0000912 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000913
914 // Build the constant containing the pointer to the function
915 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
916 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
917 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
918 }
919
Sean Callanand2b465f2012-02-09 03:22:41 +0000920 ConstantDataSequential *string_array = NULL;
Sean Callanan229ce2d2011-02-10 22:17:53 +0000921
922 if (cstr)
Sean Callanand2b465f2012-02-09 03:22:41 +0000923 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
Sean Callanancc427fa2011-07-30 02:42:06 +0000924
Sean Callananafe16a72010-11-17 23:00:36 +0000925 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan229ce2d2011-02-10 22:17:53 +0000926 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
Sean Callanand2b465f2012-02-09 03:22:41 +0000927 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000928 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
929 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
930
Sean Callanancc427fa2011-07-30 02:42:06 +0000931 Value *argument_array[5];
932
933 argument_array[0] = alloc_arg;
934 argument_array[1] = bytes_arg;
935 argument_array[2] = numBytes_arg;
936 argument_array[3] = encoding_arg;
937 argument_array[4] = isExternal_arg;
938
939 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callananafe16a72010-11-17 23:00:36 +0000940
941 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanancc427fa2011-07-30 02:42:06 +0000942 CFSCWB_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +0000943 "CFStringCreateWithBytes",
944 FirstEntryInstruction);
Sean Callanan7a55a322010-11-18 22:21:58 +0000945
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000946 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callananafe16a72010-11-17 23:00:36 +0000947 {
948 if (log)
949 log->PutCString("Couldn't replace the NSString with the result of the call");
950
Sean Callanan3989fb92011-01-27 01:07:04 +0000951 if (m_error_stream)
952 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
953
Sean Callananafe16a72010-11-17 23:00:36 +0000954 return false;
955 }
956
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000957 ns_str->eraseFromParent();
Sean Callananafe16a72010-11-17 23:00:36 +0000958
959 return true;
960}
961
962bool
Sean Callanan79763a42011-05-23 21:40:23 +0000963IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callananafe16a72010-11-17 23:00:36 +0000964{
Greg Clayton5160ce52013-03-27 23:08:40 +0000965 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000966
Sean Callanan79763a42011-05-23 21:40:23 +0000967 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananafe16a72010-11-17 23:00:36 +0000968
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000969 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +0000970 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
971
972 if (!FirstEntryInstruction)
973 {
974 if (log)
975 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
976
Sean Callanan3989fb92011-01-27 01:07:04 +0000977 if (m_error_stream)
978 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
979
Sean Callananafe16a72010-11-17 23:00:36 +0000980 return false;
981 }
982
983 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
984 vi != ve;
985 ++vi)
986 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000987 std::string value_name = vi->first().str();
988 const char *value_name_cstr = value_name.c_str();
989
990 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callananafe16a72010-11-17 23:00:36 +0000991 {
992 Value *nsstring_value = vi->second;
993
994 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
995
996 if (!nsstring_global)
997 {
998 if (log)
999 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001000
1001 if (m_error_stream)
1002 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
1003
Sean Callananafe16a72010-11-17 23:00:36 +00001004 return false;
1005 }
1006
1007 if (!nsstring_global->hasInitializer())
1008 {
1009 if (log)
1010 log->PutCString("NSString variable does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +00001011
1012 if (m_error_stream)
1013 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
1014
Sean Callananafe16a72010-11-17 23:00:36 +00001015 return false;
1016 }
1017
1018 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
1019
1020 if (!nsstring_struct)
1021 {
1022 if (log)
1023 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan3989fb92011-01-27 01:07:04 +00001024
1025 if (m_error_stream)
1026 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
1027
Sean Callananafe16a72010-11-17 23:00:36 +00001028 return false;
1029 }
1030
1031 // We expect the following structure:
1032 //
1033 // struct {
1034 // int *isa;
1035 // int flags;
1036 // char *str;
1037 // long length;
1038 // };
1039
1040 if (nsstring_struct->getNumOperands() != 4)
1041 {
1042 if (log)
1043 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands());
Sean Callanan3989fb92011-01-27 01:07:04 +00001044
1045 if (m_error_stream)
1046 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
1047
Sean Callananafe16a72010-11-17 23:00:36 +00001048 return false;
1049 }
1050
1051 Constant *nsstring_member = nsstring_struct->getOperand(2);
1052
1053 if (!nsstring_member)
1054 {
1055 if (log)
1056 log->PutCString("NSString initializer's str element was empty");
Sean Callanan3989fb92011-01-27 01:07:04 +00001057
1058 if (m_error_stream)
1059 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
1060
Sean Callananafe16a72010-11-17 23:00:36 +00001061 return false;
1062 }
1063
1064 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
1065
1066 if (!nsstring_expr)
1067 {
1068 if (log)
1069 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan3989fb92011-01-27 01:07:04 +00001070
1071 if (m_error_stream)
1072 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
1073
Sean Callananafe16a72010-11-17 23:00:36 +00001074 return false;
1075 }
1076
1077 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
1078 {
1079 if (log)
1080 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
Sean Callanan3989fb92011-01-27 01:07:04 +00001081
1082 if (m_error_stream)
1083 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
1084
Sean Callananafe16a72010-11-17 23:00:36 +00001085 return false;
1086 }
1087
1088 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
1089
1090 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
1091
1092 if (!cstr_global)
1093 {
1094 if (log)
1095 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001096
1097 if (m_error_stream)
1098 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
Sean Callanan80eee3a2010-11-20 02:06:01 +00001099
Sean Callananafe16a72010-11-17 23:00:36 +00001100 return false;
1101 }
1102
1103 if (!cstr_global->hasInitializer())
1104 {
1105 if (log)
1106 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +00001107
1108 if (m_error_stream)
1109 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
1110
Sean Callananafe16a72010-11-17 23:00:36 +00001111 return false;
1112 }
Sean Callanan229ce2d2011-02-10 22:17:53 +00001113
1114 /*
Sean Callananafe16a72010-11-17 23:00:36 +00001115 if (!cstr_array)
1116 {
1117 if (log)
1118 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan3989fb92011-01-27 01:07:04 +00001119
1120 if (m_error_stream)
1121 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
1122
Sean Callananafe16a72010-11-17 23:00:36 +00001123 return false;
1124 }
1125
1126 if (!cstr_array->isCString())
1127 {
1128 if (log)
1129 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan3989fb92011-01-27 01:07:04 +00001130
1131 if (m_error_stream)
1132 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
1133
Sean Callananafe16a72010-11-17 23:00:36 +00001134 return false;
1135 }
Sean Callanan229ce2d2011-02-10 22:17:53 +00001136 */
1137
Sean Callanand2b465f2012-02-09 03:22:41 +00001138 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
Sean Callananafe16a72010-11-17 23:00:36 +00001139
1140 if (log)
Sean Callanan229ce2d2011-02-10 22:17:53 +00001141 {
1142 if (cstr_array)
Sean Callanand2b465f2012-02-09 03:22:41 +00001143 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().str().c_str());
Sean Callanan229ce2d2011-02-10 22:17:53 +00001144 else
Sean Callanancc427fa2011-07-30 02:42:06 +00001145 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan229ce2d2011-02-10 22:17:53 +00001146 }
1147
1148 if (!cstr_array)
1149 cstr_global = NULL;
Sean Callananafe16a72010-11-17 23:00:36 +00001150
Sean Callanan79763a42011-05-23 21:40:23 +00001151 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan3989fb92011-01-27 01:07:04 +00001152 {
Sean Callananafe16a72010-11-17 23:00:36 +00001153 if (log)
1154 log->PutCString("Error rewriting the constant string");
Sean Callanan3989fb92011-01-27 01:07:04 +00001155
1156 // We don't print an error message here because RewriteObjCConstString has done so for us.
1157
Sean Callananafe16a72010-11-17 23:00:36 +00001158 return false;
1159 }
Sean Callananafe16a72010-11-17 23:00:36 +00001160 }
1161 }
1162
1163 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1164 vi != ve;
1165 ++vi)
1166 {
Sean Callanancc427fa2011-07-30 02:42:06 +00001167 std::string value_name = vi->first().str();
1168 const char *value_name_cstr = value_name.c_str();
1169
1170 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callananafe16a72010-11-17 23:00:36 +00001171 {
1172 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1173
1174 if (!gv)
1175 {
1176 if (log)
1177 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001178
1179 if (m_error_stream)
1180 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1181
Sean Callananafe16a72010-11-17 23:00:36 +00001182 return false;
1183 }
1184
1185 gv->eraseFromParent();
1186
1187 break;
1188 }
1189 }
1190
1191 return true;
1192}
1193
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001194static bool IsObjCSelectorRef (Value *value)
Sean Callanan5300d372010-07-31 01:32:05 +00001195{
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001196 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callanan5300d372010-07-31 01:32:05 +00001197
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001198 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callanan5300d372010-07-31 01:32:05 +00001199 return false;
1200
1201 return true;
1202}
1203
Sean Callanan3989fb92011-01-27 01:07:04 +00001204// This function does not report errors; its callers are responsible.
Sean Callanan5300d372010-07-31 01:32:05 +00001205bool
Sean Callanan79763a42011-05-23 21:40:23 +00001206IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callanan5300d372010-07-31 01:32:05 +00001207{
Greg Clayton5160ce52013-03-27 23:08:40 +00001208 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001209
1210 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1211
1212 if (!load)
1213 return false;
1214
1215 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1216 //
1217 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1218 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1219 //
1220 // where %obj is the object pointer and %tmp is the selector.
1221 //
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001222 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1223 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callanan5300d372010-07-31 01:32:05 +00001224
1225 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1226
1227 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1228
1229 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1230 return false;
1231
1232 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1233
1234 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1235
1236 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1237 return false;
1238
1239 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1240
1241 if (!osr_initializer_base)
1242 return false;
1243
1244 // Find the string's initializer (a ConstantArray) and get the string from it
1245
1246 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1247
1248 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1249 return false;
1250
1251 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1252
Sean Callanand2b465f2012-02-09 03:22:41 +00001253 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
Sean Callanan5300d372010-07-31 01:32:05 +00001254
1255 if (!omvn_initializer_array->isString())
1256 return false;
1257
1258 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1259
1260 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001261 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callanan5300d372010-07-31 01:32:05 +00001262
1263 // Construct a call to sel_registerName
1264
1265 if (!m_sel_registerName)
1266 {
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001267 lldb::addr_t sel_registerName_addr;
Sean Callanan5300d372010-07-31 01:32:05 +00001268
Greg Clayton7b462cc2010-10-15 22:48:33 +00001269 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001270 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callanan5300d372010-07-31 01:32:05 +00001271 return false;
1272
Sean Callananbe3a1b12010-10-26 00:31:56 +00001273 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001274 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
Sean Callananbe3a1b12010-10-26 00:31:56 +00001275
Sean Callanan5300d372010-07-31 01:32:05 +00001276 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1277
1278 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callanan79763a42011-05-23 21:40:23 +00001279 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001280 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanancc427fa2011-07-30 02:42:06 +00001281 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001282
Sean Callanancc427fa2011-07-30 02:42:06 +00001283 Type *type_array[1];
1284
1285 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1286
1287 ArrayRef<Type *> srN_arg_types(type_array, 1);
1288
Sean Callanan5300d372010-07-31 01:32:05 +00001289 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1290
1291 // Build the constant containing the pointer to the function
Sean Callanancc427fa2011-07-30 02:42:06 +00001292 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001293 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan5300d372010-07-31 01:32:05 +00001294 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001295 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callanan5300d372010-07-31 01:32:05 +00001296 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1297 }
1298
Sean Callanancc427fa2011-07-30 02:42:06 +00001299 Value *argument_array[1];
1300
Sean Callanan79763a42011-05-23 21:40:23 +00001301 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callanan5300d372010-07-31 01:32:05 +00001302
Sean Callanancc427fa2011-07-30 02:42:06 +00001303 argument_array[0] = omvn_pointer;
Sean Callanan5300d372010-07-31 01:32:05 +00001304
Sean Callanancc427fa2011-07-30 02:42:06 +00001305 ArrayRef<Value *> srN_arguments(argument_array, 1);
1306
Sean Callanan5300d372010-07-31 01:32:05 +00001307 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanancc427fa2011-07-30 02:42:06 +00001308 srN_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +00001309 "sel_registerName",
Sean Callanan5300d372010-07-31 01:32:05 +00001310 selector_load);
1311
1312 // Replace the load with the call in all users
1313
1314 selector_load->replaceAllUsesWith(srN_call);
1315
1316 selector_load->eraseFromParent();
1317
1318 return true;
1319}
1320
1321bool
Sean Callanan79763a42011-05-23 21:40:23 +00001322IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callanan5300d372010-07-31 01:32:05 +00001323{
Greg Clayton5160ce52013-03-27 23:08:40 +00001324 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001325
1326 BasicBlock::iterator ii;
1327
1328 typedef SmallVector <Instruction*, 2> InstrList;
1329 typedef InstrList::iterator InstrIterator;
1330
1331 InstrList selector_loads;
1332
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001333 for (ii = basic_block.begin();
1334 ii != basic_block.end();
Sean Callanan5300d372010-07-31 01:32:05 +00001335 ++ii)
1336 {
1337 Instruction &inst = *ii;
1338
1339 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001340 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callanan5300d372010-07-31 01:32:05 +00001341 selector_loads.push_back(&inst);
1342 }
1343
1344 InstrIterator iter;
1345
1346 for (iter = selector_loads.begin();
1347 iter != selector_loads.end();
1348 ++iter)
1349 {
Sean Callanan79763a42011-05-23 21:40:23 +00001350 if (!RewriteObjCSelector(*iter))
Sean Callanan5300d372010-07-31 01:32:05 +00001351 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001352 if (m_error_stream)
1353 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1354
Enrico Granata20edcdb2011-07-19 18:03:25 +00001355 if (log)
Sean Callanan5300d372010-07-31 01:32:05 +00001356 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan3989fb92011-01-27 01:07:04 +00001357
Sean Callanan5300d372010-07-31 01:32:05 +00001358 return false;
1359 }
1360 }
1361
1362 return true;
1363}
1364
Sean Callanan3989fb92011-01-27 01:07:04 +00001365// This function does not report errors; its callers are responsible.
Sean Callanan2235f322010-08-11 03:57:18 +00001366bool
Sean Callanan79763a42011-05-23 21:40:23 +00001367IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanan2235f322010-08-11 03:57:18 +00001368{
Greg Clayton5160ce52013-03-27 23:08:40 +00001369 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanane1175b72011-01-13 21:23:32 +00001370
Sean Callanan2235f322010-08-11 03:57:18 +00001371 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1372
1373 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1374
1375 if (!alloc_md || !alloc_md->getNumOperands())
1376 return false;
1377
1378 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1379
1380 if (!constant_int)
1381 return false;
1382
1383 // We attempt to register this as a new persistent variable with the DeclMap.
1384
1385 uintptr_t ptr = constant_int->getZExtValue();
1386
Sean Callanand1e5b432010-08-12 01:56:52 +00001387 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanan2235f322010-08-11 03:57:18 +00001388
Sean Callanand1e5b432010-08-12 01:56:52 +00001389 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1390 &decl->getASTContext());
1391
Greg Clayton7b462cc2010-10-15 22:48:33 +00001392 StringRef decl_name (decl->getName());
1393 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan92adcac2011-01-13 08:53:35 +00001394 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanan2235f322010-08-11 03:57:18 +00001395 return false;
1396
Sean Callanan79763a42011-05-23 21:40:23 +00001397 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanane1175b72011-01-13 21:23:32 +00001398 alloc->getType(),
Sean Callanan2235f322010-08-11 03:57:18 +00001399 false, /* not constant */
1400 GlobalValue::ExternalLinkage,
1401 NULL, /* no initializer */
1402 alloc->getName().str().c_str());
1403
1404 // What we're going to do here is make believe this was a regular old external
1405 // variable. That means we need to make the metadata valid.
1406
Sean Callanan585c0ec82012-07-04 01:26:26 +00001407 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
Sean Callanan2235f322010-08-11 03:57:18 +00001408
1409 llvm::Value* values[2];
1410 values[0] = persistent_global;
1411 values[1] = constant_int;
Sean Callanand12cf8bb2011-05-15 22:34:38 +00001412
1413 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanan2235f322010-08-11 03:57:18 +00001414
Sean Callanan79763a42011-05-23 21:40:23 +00001415 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanan2235f322010-08-11 03:57:18 +00001416 named_metadata->addOperand(persistent_global_md);
1417
Sean Callanane1175b72011-01-13 21:23:32 +00001418 // Now, since the variable is a pointer variable, we will drop in a load of that
1419 // pointer variable.
1420
1421 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1422
1423 if (log)
1424 log->Printf("Replacing \"%s\" with \"%s\"",
1425 PrintValue(alloc).c_str(),
1426 PrintValue(persistent_load).c_str());
1427
1428 alloc->replaceAllUsesWith(persistent_load);
Sean Callanan2235f322010-08-11 03:57:18 +00001429 alloc->eraseFromParent();
1430
1431 return true;
1432}
1433
1434bool
Sean Callanan79763a42011-05-23 21:40:23 +00001435IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanan2235f322010-08-11 03:57:18 +00001436{
Sean Callanan9e6ed532010-09-13 21:34:21 +00001437 if (!m_resolve_vars)
1438 return true;
1439
Greg Clayton5160ce52013-03-27 23:08:40 +00001440 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2235f322010-08-11 03:57:18 +00001441
1442 BasicBlock::iterator ii;
1443
1444 typedef SmallVector <Instruction*, 2> InstrList;
1445 typedef InstrList::iterator InstrIterator;
1446
1447 InstrList pvar_allocs;
1448
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001449 for (ii = basic_block.begin();
1450 ii != basic_block.end();
Sean Callanan2235f322010-08-11 03:57:18 +00001451 ++ii)
1452 {
1453 Instruction &inst = *ii;
1454
1455 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callananf694a552011-01-21 22:30:25 +00001456 {
1457 llvm::StringRef alloc_name = alloc->getName();
1458
1459 if (alloc_name.startswith("$") &&
1460 !alloc_name.startswith("$__lldb"))
1461 {
1462 if (alloc_name.find_first_of("0123456789") == 1)
1463 {
1464 if (log)
1465 log->Printf("Rejecting a numeric persistent variable.");
1466
Sean Callanan3989fb92011-01-27 01:07:04 +00001467 if (m_error_stream)
1468 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1469
Sean Callananf694a552011-01-21 22:30:25 +00001470 return false;
1471 }
1472
Sean Callanan2235f322010-08-11 03:57:18 +00001473 pvar_allocs.push_back(alloc);
Sean Callananf694a552011-01-21 22:30:25 +00001474 }
1475 }
Sean Callanan2235f322010-08-11 03:57:18 +00001476 }
1477
1478 InstrIterator iter;
1479
1480 for (iter = pvar_allocs.begin();
1481 iter != pvar_allocs.end();
1482 ++iter)
1483 {
Sean Callanan79763a42011-05-23 21:40:23 +00001484 if (!RewritePersistentAlloc(*iter))
Sean Callanan2235f322010-08-11 03:57:18 +00001485 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001486 if (m_error_stream)
1487 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1488
Enrico Granata20edcdb2011-07-19 18:03:25 +00001489 if (log)
Sean Callanan2235f322010-08-11 03:57:18 +00001490 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001491
Sean Callanan2235f322010-08-11 03:57:18 +00001492 return false;
1493 }
1494 }
1495
1496 return true;
1497}
1498
Sean Callananc70ed462011-10-25 18:36:40 +00001499bool
1500IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1501{
1502 if (!initializer)
1503 return true;
1504
Greg Clayton5160ce52013-03-27 23:08:40 +00001505 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc70ed462011-10-25 18:36:40 +00001506
1507 if (log && log->GetVerbose())
1508 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1509
1510 Type *initializer_type = initializer->getType();
1511
1512 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1513 {
1514 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1515 return true;
1516 }
Sean Callanand2b465f2012-02-09 03:22:41 +00001517 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
Sean Callananc70ed462011-10-25 18:36:40 +00001518 {
1519 if (array_initializer->isString())
1520 {
1521 std::string array_initializer_string = array_initializer->getAsString();
1522 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1523 }
1524 else
1525 {
1526 ArrayType *array_initializer_type = array_initializer->getType();
1527 Type *array_element_type = array_initializer_type->getElementType();
1528
1529 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1530
1531 for (int i = 0; i < array_initializer->getNumOperands(); ++i)
1532 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001533 Value *operand_value = array_initializer->getOperand(i);
1534 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1535
1536 if (!operand_constant)
1537 return false;
1538
1539 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
Sean Callananc70ed462011-10-25 18:36:40 +00001540 return false;
1541 }
1542 }
1543 return true;
1544 }
1545 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1546 {
1547 StructType *struct_initializer_type = struct_initializer->getType();
1548 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1549
1550 for (int i = 0;
1551 i < struct_initializer->getNumOperands();
1552 ++i)
1553 {
1554 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1555 return false;
1556 }
1557 return true;
1558 }
1559 return false;
1560}
1561
1562bool
1563IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1564{
1565 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1566 return false;
1567
Sean Callananfe5d1392011-11-15 19:13:54 +00001568 if (global_variable == m_reloc_placeholder)
1569 return true;
1570
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001571 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callananc70ed462011-10-25 18:36:40 +00001572
1573 llvm::Type *variable_type = global_variable->getType();
1574
1575 Constant *initializer = global_variable->getInitializer();
1576
1577 llvm::Type *initializer_type = initializer->getType();
1578
1579 size_t size = m_target_data->getTypeAllocSize(initializer_type);
Sean Callanane3333d62012-06-08 22:20:41 +00001580 size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1581
1582 const size_t mask = (align - 1);
1583 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001584 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00001585 offset = aligned_offset;
Sean Callananc70ed462011-10-25 18:36:40 +00001586
1587 lldb_private::DataBufferHeap data(size, '\0');
1588
1589 if (initializer)
1590 if (!MaterializeInitializer(data.GetBytes(), initializer))
1591 return false;
1592
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001593 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
Sean Callananc70ed462011-10-25 18:36:40 +00001594
1595 Constant *new_pointer = BuildRelocation(variable_type, offset);
1596
1597 global_variable->replaceAllUsesWith(new_pointer);
1598
1599 global_variable->eraseFromParent();
1600
1601 return true;
1602}
1603
Sean Callanan3989fb92011-01-27 01:07:04 +00001604// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001605bool
Sean Callanan79763a42011-05-23 21:40:23 +00001606IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001607{
Greg Clayton5160ce52013-03-27 23:08:40 +00001608 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001609
1610 if (log)
Sean Callanan88339f02010-12-06 22:16:55 +00001611 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callananaf8e96c2011-08-01 17:41:38 +00001612
Greg Clayton7b462cc2010-10-15 22:48:33 +00001613 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callanan4cf04d22010-08-03 00:23:29 +00001614 {
Sean Callanan5666b672010-08-04 01:02:13 +00001615 switch (constant_expr->getOpcode())
Sean Callanan4cf04d22010-08-03 00:23:29 +00001616 {
Sean Callanan5666b672010-08-04 01:02:13 +00001617 default:
1618 break;
1619 case Instruction::GetElementPtr:
1620 case Instruction::BitCast:
Sean Callanan4cf04d22010-08-03 00:23:29 +00001621 Value *s = constant_expr->getOperand(0);
Sean Callanan79763a42011-05-23 21:40:23 +00001622 if (!MaybeHandleVariable(s))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001623 return false;
Sean Callanan4cf04d22010-08-03 00:23:29 +00001624 }
1625 }
Sean Callanand6e04ae2010-12-03 19:51:05 +00001626 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001627 {
Sean Callananc70ed462011-10-25 18:36:40 +00001628 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1629 return MaterializeInternalVariable(global_variable);
1630
Sean Callanan79763a42011-05-23 21:40:23 +00001631 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan2ab712f22010-07-03 01:35:46 +00001632
Sean Callanan5300d372010-07-31 01:32:05 +00001633 if (!named_decl)
1634 {
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001635 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001636 return true;
1637
Sean Callanan14f0b0e2010-12-06 00:56:39 +00001638 if (!global_variable->hasExternalLinkage())
1639 return true;
1640
Sean Callanan5300d372010-07-31 01:32:05 +00001641 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001642 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001643
Sean Callanan5300d372010-07-31 01:32:05 +00001644 return false;
1645 }
1646
Greg Clayton7b462cc2010-10-15 22:48:33 +00001647 std::string name (named_decl->getName().str());
Sean Callananea22d422010-07-16 00:09:46 +00001648
Sean Callanan038df5032010-09-30 21:18:25 +00001649 void *opaque_type = NULL;
Sean Callanan1d180662010-07-20 23:31:16 +00001650 clang::ASTContext *ast_context = NULL;
Sean Callananea22d422010-07-16 00:09:46 +00001651
1652 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callanan1d180662010-07-20 23:31:16 +00001653 {
Sean Callanan038df5032010-09-30 21:18:25 +00001654 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callanan1d180662010-07-20 23:31:16 +00001655 ast_context = &value_decl->getASTContext();
1656 }
Sean Callananea22d422010-07-16 00:09:46 +00001657 else
Sean Callanan1d180662010-07-20 23:31:16 +00001658 {
Sean Callananea22d422010-07-16 00:09:46 +00001659 return false;
Sean Callanan1d180662010-07-20 23:31:16 +00001660 }
Sean Callanan038df5032010-09-30 21:18:25 +00001661
Sean Callanan92adcac2011-01-13 08:53:35 +00001662 clang::QualType qual_type;
Sean Callanan77eaf442011-07-08 00:39:14 +00001663 const Type *value_type = NULL;
Sean Callanan92adcac2011-01-13 08:53:35 +00001664
Sean Callanane1175b72011-01-13 21:23:32 +00001665 if (name[0] == '$')
Sean Callanan92adcac2011-01-13 08:53:35 +00001666 {
1667 // The $__lldb_expr_result name indicates the the return value has allocated as
1668 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1669 // accesses to this static variable need to be redirected to the result of dereferencing
1670 // a pointer that is passed in as one of the arguments.
1671 //
1672 // Consequently, when reporting the size of the type, we report a pointer type pointing
1673 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanane1175b72011-01-13 21:23:32 +00001674 //
1675 // We also do this for any user-declared persistent variables.
Sean Callanan1d180662010-07-20 23:31:16 +00001676
Sean Callanan92adcac2011-01-13 08:53:35 +00001677 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1678 value_type = PointerType::get(global_variable->getType(), 0);
1679 }
1680 else
1681 {
1682 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1683 value_type = global_variable->getType();
1684 }
Sean Callanan038df5032010-09-30 21:18:25 +00001685
Greg Claytonfaac1112013-03-14 18:31:44 +00001686 uint64_t value_size = (ast_context->getTypeSize(qual_type) + 7ull) / 8ull;
1687 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7ull) / 8ull;
Sean Callanan17827832010-12-13 22:46:15 +00001688
Sean Callanan038df5032010-09-30 21:18:25 +00001689 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +00001690 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
Sean Callanan038df5032010-09-30 21:18:25 +00001691 name.c_str(),
1692 qual_type.getAsString().c_str(),
1693 PrintType(value_type).c_str(),
1694 value_size,
1695 value_alignment);
Sean Callanan17827832010-12-13 22:46:15 +00001696
Sean Callanan549c9f72010-07-13 21:41:46 +00001697
Sean Callanan64dfc9a2010-08-23 23:09:38 +00001698 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton7b462cc2010-10-15 22:48:33 +00001699 lldb_private::ConstString (name.c_str()),
1700 llvm_value_ptr,
Sean Callanan4edba2d2010-07-27 02:07:53 +00001701 value_size,
1702 value_alignment))
Sean Callananaf8e96c2011-08-01 17:41:38 +00001703 {
1704 if (!global_variable->hasExternalLinkage())
1705 return true;
Sean Callanan0ff3bf92013-04-11 17:57:16 +00001706 else if (HandleSymbol (global_variable))
1707 return true;
Sean Callananaf8e96c2011-08-01 17:41:38 +00001708 else
1709 return false;
1710 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001711 }
Sean Callanan4a5fcbb2010-12-03 03:02:31 +00001712 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001713 {
1714 if (log)
1715 log->Printf("Function pointers aren't handled right now");
1716
1717 return false;
1718 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001719
1720 return true;
1721}
1722
Sean Callanan3989fb92011-01-27 01:07:04 +00001723// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001724bool
Sean Callanan79763a42011-05-23 21:40:23 +00001725IRForTarget::HandleSymbol (Value *symbol)
Sean Callanand9ca42a2011-05-08 02:21:26 +00001726{
Greg Clayton5160ce52013-03-27 23:08:40 +00001727 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc3a16002011-01-17 23:42:46 +00001728
1729 lldb_private::ConstString name(symbol->getName().str().c_str());
1730
Sean Callanan947ccc72011-12-01 02:04:16 +00001731 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
Sean Callananc3a16002011-01-17 23:42:46 +00001732
Greg Clayton084db102011-06-23 04:25:29 +00001733 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc3a16002011-01-17 23:42:46 +00001734 {
1735 if (log)
1736 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1737
1738 return false;
1739 }
1740
1741 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001742 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
Sean Callananc3a16002011-01-17 23:42:46 +00001743
Sean Callanancc427fa2011-07-30 02:42:06 +00001744 Type *symbol_type = symbol->getType();
Sean Callanancc427fa2011-07-30 02:42:06 +00001745 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001746 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc3a16002011-01-17 23:42:46 +00001747
1748 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1749
1750 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1751
1752 if (log)
1753 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1754
1755 symbol->replaceAllUsesWith(symbol_addr_ptr);
1756
1757 return true;
1758}
1759
1760bool
Sean Callanan79763a42011-05-23 21:40:23 +00001761IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanan85a0a832010-10-05 22:26:43 +00001762{
Greg Clayton5160ce52013-03-27 23:08:40 +00001763 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001764
1765 if (log)
1766 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanan85a0a832010-10-05 22:26:43 +00001767
Sean Callananafe16a72010-11-17 23:00:36 +00001768 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanan85a0a832010-10-05 22:26:43 +00001769 op_index < num_ops;
1770 ++op_index)
Sean Callanan79763a42011-05-23 21:40:23 +00001771 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan3989fb92011-01-27 01:07:04 +00001772 {
1773 if (m_error_stream)
1774 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1775
Sean Callanan85a0a832010-10-05 22:26:43 +00001776 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001777 }
1778
Sean Callanan85a0a832010-10-05 22:26:43 +00001779 return true;
1780}
1781
1782bool
Sean Callananfc89c142011-11-01 23:38:03 +00001783IRForTarget::HandleObjCClass(Value *classlist_reference)
1784{
Greg Clayton5160ce52013-03-27 23:08:40 +00001785 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananfc89c142011-11-01 23:38:03 +00001786
1787 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1788
1789 if (!global_variable)
1790 return false;
1791
1792 Constant *initializer = global_variable->getInitializer();
1793
1794 if (!initializer)
1795 return false;
1796
1797 if (!initializer->hasName())
1798 return false;
1799
1800 StringRef name(initializer->getName());
1801 lldb_private::ConstString name_cstr(name.str().c_str());
Greg Clayton1075aca2011-12-03 20:02:42 +00001802 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
Sean Callananfc89c142011-11-01 23:38:03 +00001803
1804 if (log)
1805 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1806
1807 if (class_ptr == LLDB_INVALID_ADDRESS)
1808 return false;
1809
1810 if (global_variable->use_begin() == global_variable->use_end())
1811 return false;
1812
Sean Callanan719a4d52013-03-23 01:01:16 +00001813 SmallVector<LoadInst *, 2> load_instructions;
1814
Sean Callananfc89c142011-11-01 23:38:03 +00001815 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1816 i != e;
1817 ++i)
1818 {
Sean Callanan719a4d52013-03-23 01:01:16 +00001819 if (LoadInst *load_instruction = dyn_cast<LoadInst>(*i))
1820 load_instructions.push_back(load_instruction);
Sean Callananfc89c142011-11-01 23:38:03 +00001821 }
1822
Sean Callanan719a4d52013-03-23 01:01:16 +00001823 if (load_instructions.empty())
Sean Callananfc89c142011-11-01 23:38:03 +00001824 return false;
1825
1826 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001827 (m_module->getPointerSize()
Micah Villmow08318972012-10-11 17:21:41 +00001828 == Module::Pointer64) ? 64 : 32);
Sean Callananfc89c142011-11-01 23:38:03 +00001829
1830 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
Sean Callananfc89c142011-11-01 23:38:03 +00001831
Sean Callanan719a4d52013-03-23 01:01:16 +00001832 for (LoadInst *load_instruction : load_instructions)
1833 {
1834 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
Sean Callananfc89c142011-11-01 23:38:03 +00001835
Sean Callanan719a4d52013-03-23 01:01:16 +00001836 load_instruction->replaceAllUsesWith(class_bitcast);
1837
1838 load_instruction->eraseFromParent();
1839 }
Sean Callananfc89c142011-11-01 23:38:03 +00001840
1841 return true;
1842}
1843
1844bool
Sean Callanan6e6d4a62012-07-21 02:02:15 +00001845IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1846{
1847 BasicBlock::iterator ii;
1848
1849 std::vector<CallInst *> calls_to_remove;
1850
1851 for (ii = basic_block.begin();
1852 ii != basic_block.end();
1853 ++ii)
1854 {
1855 Instruction &inst = *ii;
1856
1857 CallInst *call = dyn_cast<CallInst>(&inst);
1858
1859 // MaybeHandleCallArguments handles error reporting; we are silent here
1860 if (!call)
1861 continue;
1862
1863 bool remove = false;
1864
1865 llvm::Function *func = call->getCalledFunction();
1866
1867 if (func && func->getName() == "__cxa_atexit")
1868 remove = true;
1869
1870 llvm::Value *val = call->getCalledValue();
1871
1872 if (val && val->getName() == "__cxa_atexit")
1873 remove = true;
1874
1875 if (remove)
1876 calls_to_remove.push_back(call);
1877 }
1878
1879 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1880 ci != ce;
1881 ++ci)
1882 {
1883 (*ci)->eraseFromParent();
1884 }
1885
1886 return true;
1887}
1888
1889bool
Sean Callanan79763a42011-05-23 21:40:23 +00001890IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan549c9f72010-07-13 21:41:46 +00001891{
Sean Callanan2ab712f22010-07-03 01:35:46 +00001892 /////////////////////////////////////////////////////////////////////////
1893 // Prepare the current basic block for execution in the remote process
1894 //
1895
Sean Callanan7ea35012010-07-27 21:39:39 +00001896 BasicBlock::iterator ii;
Sean Callanan549c9f72010-07-13 21:41:46 +00001897
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001898 for (ii = basic_block.begin();
1899 ii != basic_block.end();
Sean Callanan549c9f72010-07-13 21:41:46 +00001900 ++ii)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001901 {
Sean Callanan549c9f72010-07-13 21:41:46 +00001902 Instruction &inst = *ii;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001903
Sean Callanana4e55172010-11-08 00:31:32 +00001904 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callanan4edba2d2010-07-27 02:07:53 +00001905
Sean Callanan3989fb92011-01-27 01:07:04 +00001906 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callanan79763a42011-05-23 21:40:23 +00001907 if (call && !MaybeHandleCallArguments(call))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001908 return false;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001909 }
1910
1911 return true;
1912}
1913
Sean Callanana4e55172010-11-08 00:31:32 +00001914bool
Sean Callanan79763a42011-05-23 21:40:23 +00001915IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanana4e55172010-11-08 00:31:32 +00001916{
Greg Clayton5160ce52013-03-27 23:08:40 +00001917 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7a55a322010-11-18 22:21:58 +00001918
Sean Callanan79763a42011-05-23 21:40:23 +00001919 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanana4e55172010-11-08 00:31:32 +00001920 global != end;
1921 ++global)
1922 {
Sean Callanan694e2442011-12-22 21:24:49 +00001923 if (!global)
1924 {
1925 if (m_error_stream)
1926 m_error_stream->Printf("Internal error [IRForTarget]: global variable is NULL");
1927
1928 return false;
1929 }
1930
1931 std::string global_name = (*global).getName().str();
1932
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001933 if (log)
1934 log->Printf("Examining %s, DeclForGlobalValue returns %p",
Sean Callanan694e2442011-12-22 21:24:49 +00001935 global_name.c_str(),
Sean Callanan79763a42011-05-23 21:40:23 +00001936 DeclForGlobal(global));
Sean Callananfc89c142011-11-01 23:38:03 +00001937
1938 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc3a16002011-01-17 23:42:46 +00001939 {
Sean Callanan79763a42011-05-23 21:40:23 +00001940 if (!HandleSymbol(global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001941 {
1942 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001943 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", global_name.c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001944
Sean Callananc3a16002011-01-17 23:42:46 +00001945 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001946 }
Sean Callananc3a16002011-01-17 23:42:46 +00001947 }
Sean Callananfc89c142011-11-01 23:38:03 +00001948 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1949 {
1950 if (!HandleObjCClass(global))
1951 {
1952 if (m_error_stream)
1953 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1954
1955 return false;
1956 }
1957 }
Sean Callanan79763a42011-05-23 21:40:23 +00001958 else if (DeclForGlobal(global))
Sean Callananc3a16002011-01-17 23:42:46 +00001959 {
Sean Callanan79763a42011-05-23 21:40:23 +00001960 if (!MaybeHandleVariable (global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001961 {
1962 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001963 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", global_name.c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001964
Sean Callananc3a16002011-01-17 23:42:46 +00001965 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001966 }
Sean Callananc3a16002011-01-17 23:42:46 +00001967 }
Sean Callanana4e55172010-11-08 00:31:32 +00001968 }
1969
1970 return true;
1971}
1972
Sean Callanan79763a42011-05-23 21:40:23 +00001973bool
1974IRForTarget::ReplaceStrings ()
1975{
Greg Clayton5160ce52013-03-27 23:08:40 +00001976 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001977
Sean Callanan79763a42011-05-23 21:40:23 +00001978 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1979
1980 OffsetsTy offsets;
1981
1982 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1983 gi != ge;
1984 ++gi)
1985 {
1986 GlobalVariable *gv = gi;
1987
1988 if (!gv->hasInitializer())
1989 continue;
1990
1991 Constant *gc = gv->getInitializer();
1992
Sean Callanan5207a342011-08-10 21:05:52 +00001993 std::string str;
Sean Callanan79763a42011-05-23 21:40:23 +00001994
Sean Callanan5207a342011-08-10 21:05:52 +00001995 if (gc->isNullValue())
1996 {
1997 Type *gc_type = gc->getType();
1998
1999 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
2000
2001 if (!gc_array_type)
2002 continue;
2003
2004 Type *gc_element_type = gc_array_type->getElementType();
2005
2006 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
2007
2008 if (gc_integer_type->getBitWidth() != 8)
2009 continue;
2010
2011 str = "";
2012 }
2013 else
2014 {
Sean Callanand2b465f2012-02-09 03:22:41 +00002015 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
Sean Callanan5207a342011-08-10 21:05:52 +00002016
2017 if (!gc_array)
2018 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00002019
Sean Callanan5207a342011-08-10 21:05:52 +00002020 if (!gc_array->isCString())
2021 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00002022
Sean Callanan5207a342011-08-10 21:05:52 +00002023 if (log)
2024 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00002025
Sean Callanan5207a342011-08-10 21:05:52 +00002026 str = gc_array->getAsString();
2027 }
2028
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002029 offsets[gv] = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00002030
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002031 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
Sean Callanan79763a42011-05-23 21:40:23 +00002032 }
2033
Sean Callanancc427fa2011-07-30 02:42:06 +00002034 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00002035
2036 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
2037 oi != oe;
2038 ++oi)
2039 {
2040 GlobalVariable *gv = oi->first;
2041 size_t offset = oi->second;
2042
2043 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
2044
2045 if (log)
2046 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
2047
2048 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
2049 ui != ue;
2050 ++ui)
2051 {
2052 if (log)
2053 log->Printf("Found use %s", PrintValue(*ui).c_str());
2054
2055 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
2056 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
2057
2058 if (const_expr)
2059 {
2060 if (const_expr->getOpcode() != Instruction::GetElementPtr)
2061 {
2062 if (log)
2063 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
2064
2065 return false;
2066 }
2067
Sean Callanan5207a342011-08-10 21:05:52 +00002068 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
2069 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
2070
2071 const_expr->replaceAllUsesWith(new_gep);
Sean Callanan79763a42011-05-23 21:40:23 +00002072 }
2073 else if (store_inst)
2074 {
2075 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
2076
2077 store_inst->setOperand(0, bit_cast);
2078 }
2079 else
2080 {
2081 if (log)
2082 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
2083
2084 return false;
2085 }
2086 }
2087
2088 gv->eraseFromParent();
2089 }
2090
2091 return true;
2092}
2093
2094bool
2095IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
2096{
Greg Clayton5160ce52013-03-27 23:08:40 +00002097 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002098
2099 typedef SmallVector <Value*, 2> ConstantList;
2100 typedef SmallVector <llvm::Instruction*, 2> UserList;
2101 typedef ConstantList::iterator ConstantIterator;
2102 typedef UserList::iterator UserIterator;
2103
2104 ConstantList static_constants;
2105 UserList static_users;
2106
2107 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
2108 ii != ie;
2109 ++ii)
2110 {
2111 llvm::Instruction &inst = *ii;
2112
2113 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
2114 oi != oe;
2115 ++oi)
2116 {
2117 Value *operand_val = oi->get();
2118
2119 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2120
Sean Callanan822944c2012-04-26 20:51:20 +00002121 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
Sean Callanan79763a42011-05-23 21:40:23 +00002122 {
2123 static_constants.push_back(operand_val);
2124 static_users.push_back(ii);
2125 }
2126 }
2127 }
2128
2129 ConstantIterator constant_iter;
2130 UserIterator user_iter;
Greg Clayton9b72eb72011-05-24 23:06:02 +00002131
Sean Callanan79763a42011-05-23 21:40:23 +00002132 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
2133 constant_iter != static_constants.end();
2134 ++constant_iter, ++user_iter)
2135 {
2136 Value *operand_val = *constant_iter;
2137 llvm::Instruction *inst = *user_iter;
2138
2139 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
Sean Callanane3333d62012-06-08 22:20:41 +00002140 Type *operand_type = operand_constant_fp->getType();
Sean Callanan79763a42011-05-23 21:40:23 +00002141
2142 if (operand_constant_fp)
2143 {
2144 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2145 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2146
2147 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2148 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2149
2150 if (log)
2151 {
2152 std::string s;
2153 raw_string_ostream ss(s);
2154 for (size_t index = 0;
2155 index < operand_data_size;
2156 ++index)
2157 {
2158 ss << (uint32_t)operand_raw_data[index];
2159 ss << " ";
2160 }
2161 ss.flush();
2162
Jason Molendafd54b362011-09-20 21:44:10 +00002163 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00002164 }
2165
2166 lldb_private::DataBufferHeap data(operand_data_size, 0);
2167
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002168 if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
Sean Callanan79763a42011-05-23 21:40:23 +00002169 {
2170 uint8_t *data_bytes = data.GetBytes();
2171
2172 for (size_t index = 0;
2173 index < operand_data_size;
2174 ++index)
2175 {
2176 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2177 }
2178 }
2179 else
2180 {
2181 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2182 }
2183
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002184 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00002185
Sean Callanane3333d62012-06-08 22:20:41 +00002186 size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2187
2188 const size_t mask = (align - 1);
2189 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002190 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00002191 offset = aligned_offset;
2192
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002193 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
Sean Callanan79763a42011-05-23 21:40:23 +00002194
Sean Callanancc427fa2011-07-30 02:42:06 +00002195 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callanan79763a42011-05-23 21:40:23 +00002196
2197 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
2198
2199 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2200
2201 operand_constant_fp->replaceAllUsesWith(fp_load);
2202 }
2203 }
2204
2205 return true;
2206}
2207
Sean Callanan7ea35012010-07-27 21:39:39 +00002208static bool isGuardVariableRef(Value *V)
Sean Callananddb46ef2010-07-24 01:37:44 +00002209{
Sean Callanan77eaf442011-07-08 00:39:14 +00002210 Constant *Old = NULL;
Sean Callananddb46ef2010-07-24 01:37:44 +00002211
Sean Callananafe16a72010-11-17 23:00:36 +00002212 if (!(Old = dyn_cast<Constant>(V)))
Sean Callananddb46ef2010-07-24 01:37:44 +00002213 return false;
2214
Sean Callanan77eaf442011-07-08 00:39:14 +00002215 ConstantExpr *CE = NULL;
Sean Callanane2ef6e32010-09-23 03:01:22 +00002216
2217 if ((CE = dyn_cast<ConstantExpr>(V)))
2218 {
2219 if (CE->getOpcode() != Instruction::BitCast)
2220 return false;
2221
Sean Callananafe16a72010-11-17 23:00:36 +00002222 Old = CE->getOperand(0);
Sean Callanane2ef6e32010-09-23 03:01:22 +00002223 }
2224
Sean Callananafe16a72010-11-17 23:00:36 +00002225 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callananddb46ef2010-07-24 01:37:44 +00002226
2227 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2228 return false;
2229
2230 return true;
2231}
2232
Sean Callanan79763a42011-05-23 21:40:23 +00002233void
2234IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callananddb46ef2010-07-24 01:37:44 +00002235{
Sean Callanan79763a42011-05-23 21:40:23 +00002236 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callananddb46ef2010-07-24 01:37:44 +00002237
2238 Value::use_iterator ui;
2239
2240 for (ui = guard_load->use_begin();
2241 ui != guard_load->use_end();
2242 ++ui)
Sean Callananb27a62f2010-07-27 01:17:28 +00002243 {
Greg Claytone6371122010-07-30 20:30:44 +00002244 if (isa<Constant>(*ui))
Sean Callananb27a62f2010-07-27 01:17:28 +00002245 {
2246 // do nothing for the moment
2247 }
2248 else
2249 {
2250 ui->replaceUsesOfWith(guard_load, zero);
2251 }
2252 }
Sean Callananddb46ef2010-07-24 01:37:44 +00002253
2254 guard_load->eraseFromParent();
2255}
2256
2257static void ExciseGuardStore(Instruction* guard_store)
2258{
2259 guard_store->eraseFromParent();
2260}
2261
2262bool
Sean Callanan79763a42011-05-23 21:40:23 +00002263IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callananddb46ef2010-07-24 01:37:44 +00002264{
2265 ///////////////////////////////////////////////////////
2266 // Eliminate any reference to guard variables found.
2267 //
2268
Sean Callanan7ea35012010-07-27 21:39:39 +00002269 BasicBlock::iterator ii;
Sean Callananddb46ef2010-07-24 01:37:44 +00002270
Sean Callanan7ea35012010-07-27 21:39:39 +00002271 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callananddb46ef2010-07-24 01:37:44 +00002272 typedef InstrList::iterator InstrIterator;
2273
2274 InstrList guard_loads;
2275 InstrList guard_stores;
2276
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002277 for (ii = basic_block.begin();
2278 ii != basic_block.end();
Sean Callananddb46ef2010-07-24 01:37:44 +00002279 ++ii)
2280 {
2281 Instruction &inst = *ii;
2282
2283 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2284 if (isGuardVariableRef(load->getPointerOperand()))
2285 guard_loads.push_back(&inst);
2286
2287 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2288 if (isGuardVariableRef(store->getPointerOperand()))
2289 guard_stores.push_back(&inst);
2290 }
2291
2292 InstrIterator iter;
2293
2294 for (iter = guard_loads.begin();
2295 iter != guard_loads.end();
2296 ++iter)
Sean Callanan79763a42011-05-23 21:40:23 +00002297 TurnGuardLoadIntoZero(*iter);
Sean Callananddb46ef2010-07-24 01:37:44 +00002298
2299 for (iter = guard_stores.begin();
2300 iter != guard_stores.end();
2301 ++iter)
2302 ExciseGuardStore(*iter);
2303
2304 return true;
2305}
2306
Sean Callanan3989fb92011-01-27 01:07:04 +00002307// This function does not report errors; its callers are responsible.
Sean Callananafe16a72010-11-17 23:00:36 +00002308bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002309IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callanan7618f4e2010-07-14 23:40:29 +00002310{
Greg Clayton5160ce52013-03-27 23:08:40 +00002311 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002312
2313 Value::use_iterator ui;
2314
Sean Callanan2235f322010-08-11 03:57:18 +00002315 SmallVector<User*, 16> users;
2316
2317 // We do this because the use list might change, invalidating our iterator.
2318 // Much better to keep a work list ourselves.
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002319 for (ui = old_constant->use_begin();
2320 ui != old_constant->use_end();
Sean Callanan7618f4e2010-07-14 23:40:29 +00002321 ++ui)
Sean Callanan2235f322010-08-11 03:57:18 +00002322 users.push_back(*ui);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002323
Johnny Chen44805302011-07-19 19:48:13 +00002324 for (size_t i = 0;
Sean Callanan2235f322010-08-11 03:57:18 +00002325 i < users.size();
2326 ++i)
2327 {
2328 User *user = users[i];
2329
Sean Callanan7618f4e2010-07-14 23:40:29 +00002330 if (Constant *constant = dyn_cast<Constant>(user))
2331 {
2332 // synthesize a new non-constant equivalent of the constant
2333
2334 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2335 {
2336 switch (constant_expr->getOpcode())
2337 {
2338 default:
2339 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002340 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002341 return false;
2342 case Instruction::BitCast:
2343 {
2344 // UnaryExpr
2345 // OperandList[0] is value
2346
2347 Value *s = constant_expr->getOperand(0);
2348
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002349 if (s == old_constant)
2350 s = new_constant;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002351
Sean Callanan79763a42011-05-23 21:40:23 +00002352 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002353
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002354 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002355 }
2356 break;
2357 case Instruction::GetElementPtr:
2358 {
2359 // GetElementPtrConstantExpr
2360 // OperandList[0] is base
2361 // OperandList[1]... are indices
2362
2363 Value *ptr = constant_expr->getOperand(0);
2364
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002365 if (ptr == old_constant)
2366 ptr = new_constant;
Sean Callanancc427fa2011-07-30 02:42:06 +00002367
2368 std::vector<Value*> index_vector;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002369
2370 unsigned operand_index;
2371 unsigned num_operands = constant_expr->getNumOperands();
2372
2373 for (operand_index = 1;
2374 operand_index < num_operands;
2375 ++operand_index)
2376 {
2377 Value *operand = constant_expr->getOperand(operand_index);
2378
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002379 if (operand == old_constant)
2380 operand = new_constant;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002381
Sean Callanancc427fa2011-07-30 02:42:06 +00002382 index_vector.push_back(operand);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002383 }
2384
Sean Callanancc427fa2011-07-30 02:42:06 +00002385 ArrayRef <Value*> indices(index_vector);
2386
2387 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002388
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002389 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002390 }
2391 break;
2392 }
2393 }
2394 else
2395 {
2396 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002397 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002398 return false;
2399 }
2400 }
2401 else
2402 {
2403 // simple fall-through case for non-constants
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002404 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002405 }
2406 }
2407
2408 return true;
2409}
2410
Sean Callanan549c9f72010-07-13 21:41:46 +00002411bool
Sean Callanan79763a42011-05-23 21:40:23 +00002412IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan549c9f72010-07-13 21:41:46 +00002413{
Sean Callanan9e6ed532010-09-13 21:34:21 +00002414 if (!m_resolve_vars)
2415 return true;
2416
Greg Clayton5160ce52013-03-27 23:08:40 +00002417 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan549c9f72010-07-13 21:41:46 +00002418
2419 m_decl_map->DoStructLayout();
2420
2421 if (log)
2422 log->Printf("Element arrangement:");
2423
2424 uint32_t num_elements;
2425 uint32_t element_index;
2426
2427 size_t size;
2428 off_t alignment;
2429
2430 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2431 return false;
2432
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002433 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan549c9f72010-07-13 21:41:46 +00002434
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002435 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002436 {
2437 if (m_error_stream)
2438 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2439
Sean Callanan549c9f72010-07-13 21:41:46 +00002440 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002441 }
2442
Sean Callanan7ea35012010-07-27 21:39:39 +00002443 Argument *argument = iter;
Sean Callanan549c9f72010-07-13 21:41:46 +00002444
Sean Callananfc55f5d2010-09-21 00:44:12 +00002445 if (argument->getName().equals("this"))
2446 {
2447 ++iter;
2448
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002449 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002450 {
2451 if (m_error_stream)
2452 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2453
Sean Callananfc55f5d2010-09-21 00:44:12 +00002454 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002455 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002456
2457 argument = iter;
2458 }
Sean Callanan17827832010-12-13 22:46:15 +00002459 else if (argument->getName().equals("self"))
2460 {
2461 ++iter;
2462
2463 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002464 {
2465 if (m_error_stream)
2466 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2467
Sean Callanan17827832010-12-13 22:46:15 +00002468 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002469 }
Sean Callanan17827832010-12-13 22:46:15 +00002470
2471 if (!iter->getName().equals("_cmd"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002472 {
2473 if (m_error_stream)
2474 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2475
Sean Callanan17827832010-12-13 22:46:15 +00002476 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002477 }
Sean Callanan17827832010-12-13 22:46:15 +00002478
2479 ++iter;
2480
2481 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002482 {
2483 if (m_error_stream)
2484 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2485
Sean Callanan17827832010-12-13 22:46:15 +00002486 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002487 }
Sean Callanan17827832010-12-13 22:46:15 +00002488
2489 argument = iter;
2490 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002491
Greg Clayton7b462cc2010-10-15 22:48:33 +00002492 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002493 {
2494 if (m_error_stream)
2495 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2496
Sean Callanan549c9f72010-07-13 21:41:46 +00002497 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002498 }
2499
Sean Callanan549c9f72010-07-13 21:41:46 +00002500 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002501 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan549c9f72010-07-13 21:41:46 +00002502
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002503 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +00002504 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan549c9f72010-07-13 21:41:46 +00002505
Sean Callananafe16a72010-11-17 23:00:36 +00002506 if (!FirstEntryInstruction)
Sean Callanan3989fb92011-01-27 01:07:04 +00002507 {
2508 if (m_error_stream)
2509 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2510
Sean Callanan549c9f72010-07-13 21:41:46 +00002511 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002512 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002513
Sean Callanan79763a42011-05-23 21:40:23 +00002514 LLVMContext &context(m_module->getContext());
Sean Callanancc427fa2011-07-30 02:42:06 +00002515 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan549c9f72010-07-13 21:41:46 +00002516
2517 if (!offset_type)
Sean Callanan3989fb92011-01-27 01:07:04 +00002518 {
2519 if (m_error_stream)
2520 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2521
Sean Callanan549c9f72010-07-13 21:41:46 +00002522 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002523 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002524
2525 for (element_index = 0; element_index < num_elements; ++element_index)
2526 {
Sean Callanan77eaf442011-07-08 00:39:14 +00002527 const clang::NamedDecl *decl = NULL;
2528 Value *value = NULL;
Sean Callanan549c9f72010-07-13 21:41:46 +00002529 off_t offset;
Greg Clayton7b462cc2010-10-15 22:48:33 +00002530 lldb_private::ConstString name;
Sean Callanan549c9f72010-07-13 21:41:46 +00002531
Sean Callanan823bb4c2010-08-30 22:17:16 +00002532 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan3989fb92011-01-27 01:07:04 +00002533 {
2534 if (m_error_stream)
2535 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2536
Sean Callanan549c9f72010-07-13 21:41:46 +00002537 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002538 }
2539
Sean Callanan549c9f72010-07-13 21:41:46 +00002540 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002541 log->Printf(" \"%s\" (\"%s\") placed at %" PRId64,
Greg Clayton7b462cc2010-10-15 22:48:33 +00002542 name.GetCString(),
Sean Callananc70ed462011-10-25 18:36:40 +00002543 decl->getNameAsString().c_str(),
Sean Callanan549c9f72010-07-13 21:41:46 +00002544 offset);
2545
Sean Callanancc427fa2011-07-30 02:42:06 +00002546 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callananafe16a72010-11-17 23:00:36 +00002547 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan92adcac2011-01-13 08:53:35 +00002548
Sean Callananc70ed462011-10-25 18:36:40 +00002549 if (value)
Sean Callanan92adcac2011-01-13 08:53:35 +00002550 {
Sean Callananc70ed462011-10-25 18:36:40 +00002551 Value *replacement = NULL;
Sean Callanan92adcac2011-01-13 08:53:35 +00002552
Sean Callananc70ed462011-10-25 18:36:40 +00002553 if (log)
2554 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan92adcac2011-01-13 08:53:35 +00002555
Sean Callananc70ed462011-10-25 18:36:40 +00002556 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2557 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2558 // entry in order to produce the static variable that the AST thinks it is accessing.
2559 if (name == m_result_name && !m_result_is_pointer)
2560 {
2561 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2562
2563 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2564
2565 replacement = load;
2566 }
2567 else
2568 {
2569 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2570
2571 replacement = bit_cast;
2572 }
2573
2574 if (Constant *constant = dyn_cast<Constant>(value))
2575 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2576 else
2577 value->replaceAllUsesWith(replacement);
2578
2579 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2580 var->eraseFromParent();
2581 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002582 }
2583
2584 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002585 log->Printf("Total structure [align %" PRId64 ", size %lu]", alignment, size);
Sean Callanan549c9f72010-07-13 21:41:46 +00002586
2587 return true;
2588}
2589
Sean Callanan79763a42011-05-23 21:40:23 +00002590llvm::Constant *
Greg Clayton5160ce52013-03-27 23:08:40 +00002591IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
Sean Callanan79763a42011-05-23 21:40:23 +00002592{
Sean Callanancc427fa2011-07-30 02:42:06 +00002593 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00002594 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan79763a42011-05-23 21:40:23 +00002595
2596 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanancc427fa2011-07-30 02:42:06 +00002597
2598 llvm::Constant *offset_array[1];
2599
2600 offset_array[0] = offset_int;
2601
2602 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2603
2604 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callanan79763a42011-05-23 21:40:23 +00002605 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2606
2607 return reloc_getbitcast;
2608}
2609
2610bool
2611IRForTarget::CompleteDataAllocation ()
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002612{
Greg Clayton5160ce52013-03-27 23:08:40 +00002613 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002614
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002615 if (!m_data_allocator.GetStream().GetSize())
Sean Callanan79763a42011-05-23 21:40:23 +00002616 return true;
2617
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002618 lldb::addr_t allocation = m_data_allocator.Allocate();
Sean Callanan79763a42011-05-23 21:40:23 +00002619
2620 if (log)
2621 {
2622 if (allocation)
2623 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2624 else
2625 log->Printf("Failed to allocate static data");
2626 }
2627
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002628 if (!allocation || allocation == LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +00002629 return false;
2630
Sean Callanancc427fa2011-07-30 02:42:06 +00002631 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00002632 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan79763a42011-05-23 21:40:23 +00002633
2634 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2635 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2636
2637 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2638
2639 m_reloc_placeholder->eraseFromParent();
2640
2641 return true;
2642}
2643
Sean Callanan2ab712f22010-07-03 01:35:46 +00002644bool
Sean Callanan3d654b32012-09-24 22:25:51 +00002645IRForTarget::StripAllGVs (Module &llvm_module)
2646{
Greg Clayton5160ce52013-03-27 23:08:40 +00002647 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3d654b32012-09-24 22:25:51 +00002648 std::vector<GlobalVariable *> global_vars;
2649 std::set<GlobalVariable *>erased_vars;
2650
2651 bool erased = true;
2652
2653 while (erased)
2654 {
2655 erased = false;
2656
2657 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2658 gi != ge;
2659 ++gi)
2660 {
2661 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2662
2663 global_var->removeDeadConstantUsers();
2664
2665 if (global_var->use_empty())
2666 {
2667 if (log)
2668 log->Printf("Did remove %s",
2669 PrintValue(global_var).c_str());
2670 global_var->eraseFromParent();
2671 erased = true;
2672 break;
2673 }
2674 }
2675 }
2676
2677 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2678 gi != ge;
2679 ++gi)
2680 {
2681 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2682
2683 GlobalValue::use_iterator ui = global_var->use_begin();
2684
Jim Inghamd77557d2012-11-26 19:54:04 +00002685 if (log)
2686 log->Printf("Couldn't remove %s because of %s",
2687 PrintValue(global_var).c_str(),
2688 PrintValue(*ui).c_str());
Sean Callanan3d654b32012-09-24 22:25:51 +00002689 }
2690
2691 return true;
2692}
2693
2694bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002695IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002696{
Greg Clayton5160ce52013-03-27 23:08:40 +00002697 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002698
Sean Callanan79763a42011-05-23 21:40:23 +00002699 m_module = &llvm_module;
Micah Villmow8468dbe2012-10-08 16:28:57 +00002700 m_target_data.reset(new DataLayout(m_module));
Sean Callanan79763a42011-05-23 21:40:23 +00002701
2702 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002703
2704 if (!function)
2705 {
2706 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002707 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00002708
2709 if (m_error_stream)
Sean Callanan79763a42011-05-23 21:40:23 +00002710 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
Sean Callanan92adcac2011-01-13 08:53:35 +00002711
Sean Callanan2ab712f22010-07-03 01:35:46 +00002712 return false;
2713 }
Sean Callanan79763a42011-05-23 21:40:23 +00002714
2715 if (!FixFunctionLinkage (*function))
2716 {
2717 if (log)
2718 log->Printf("Couldn't fix the linkage for the function");
2719
2720 return false;
2721 }
2722
Sean Callananc70ed462011-10-25 18:36:40 +00002723 if (log)
2724 {
2725 std::string s;
2726 raw_string_ostream oss(s);
2727
2728 m_module->print(oss, NULL);
2729
2730 oss.flush();
2731
2732 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2733 }
2734
Sean Callanancc427fa2011-07-30 02:42:06 +00002735 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00002736
2737 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2738 intptr_ty,
Sean Callanan3d654b32012-09-24 22:25:51 +00002739 false /* IsConstant */,
Sean Callanan79763a42011-05-23 21:40:23 +00002740 GlobalVariable::InternalLinkage,
2741 Constant::getNullValue(intptr_ty),
2742 "reloc_placeholder",
2743 NULL /* InsertBefore */,
Sean Callanan3d654b32012-09-24 22:25:51 +00002744 GlobalVariable::NotThreadLocal /* ThreadLocal */,
Sean Callanan79763a42011-05-23 21:40:23 +00002745 0 /* AddressSpace */);
Sean Callanan2ab712f22010-07-03 01:35:46 +00002746
Sean Callanan7ea35012010-07-27 21:39:39 +00002747 Function::iterator bbi;
Sean Callanan2ab712f22010-07-03 01:35:46 +00002748
Sean Callanan79763a42011-05-23 21:40:23 +00002749 m_has_side_effects = HasSideEffects(*function);
Sean Callanane4ec90e2010-12-16 03:17:46 +00002750
Sean Callanand1e5b432010-08-12 01:56:52 +00002751 ////////////////////////////////////////////////////////////
Greg Clayton7b462cc2010-10-15 22:48:33 +00002752 // Replace $__lldb_expr_result with a persistent variable
Sean Callanand1e5b432010-08-12 01:56:52 +00002753 //
2754
Sean Callanan79763a42011-05-23 21:40:23 +00002755 if (!CreateResultVariable(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002756 {
2757 if (log)
2758 log->Printf("CreateResultVariable() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002759
2760 // CreateResultVariable() reports its own errors, so we don't do so here
2761
Sean Callanand1e5b432010-08-12 01:56:52 +00002762 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002763 }
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002764
2765 if (m_const_result && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2766 {
2767 m_interpret_success = true;
Sean Callanan63697e52011-05-07 01:06:41 +00002768 return true;
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002769 }
2770
2771 for (bbi = function->begin();
2772 bbi != function->end();
2773 ++bbi)
2774 {
2775 if (!RemoveGuards(*bbi))
2776 {
2777 if (log)
2778 log->Printf("RemoveGuards() failed");
2779
2780 // RemoveGuards() reports its own errors, so we don't do so here
2781
2782 return false;
2783 }
2784
2785 if (!RewritePersistentAllocs(*bbi))
2786 {
2787 if (log)
2788 log->Printf("RewritePersistentAllocs() failed");
2789
2790 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2791
2792 return false;
2793 }
Sean Callanan6e6d4a62012-07-21 02:02:15 +00002794
2795 if (!RemoveCXAAtExit(*bbi))
2796 {
2797 if (log)
2798 log->Printf("RemoveCXAAtExit() failed");
2799
2800 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2801
2802 return false;
2803 }
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002804 }
2805
2806 if (m_decl_map && m_execution_policy != lldb_private::eExecutionPolicyAlways)
2807 {
2808 IRInterpreter interpreter (*m_decl_map,
2809 m_error_stream);
2810
Sean Callanan175a0d02012-01-24 22:06:48 +00002811 interpreter.maybeRunOnFunction(m_const_result, m_result_name, m_result_type, *function, llvm_module, m_interpreter_error);
2812
2813 if (m_interpreter_error.Success())
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002814 return true;
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002815 }
Sean Callanan63697e52011-05-07 01:06:41 +00002816
Sean Callanan5b26f272012-02-04 08:49:35 +00002817 if (m_execution_policy == lldb_private::eExecutionPolicyNever) {
Sean Callanan4538aa22012-04-24 17:56:40 +00002818 if (m_result_name)
2819 m_decl_map->RemoveResultVariable(m_result_name);
Sean Callanan5b26f272012-02-04 08:49:35 +00002820 return false;
2821 }
2822
Sean Callananea685ae2011-11-01 17:33:54 +00002823 if (log && log->GetVerbose())
Sean Callanan79763a42011-05-23 21:40:23 +00002824 {
2825 std::string s;
2826 raw_string_ostream oss(s);
2827
2828 m_module->print(oss, NULL);
2829
2830 oss.flush();
2831
2832 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2833 }
2834
Sean Callananafe16a72010-11-17 23:00:36 +00002835 ///////////////////////////////////////////////////////////////////////////////
2836 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2837 //
Sean Callananafe16a72010-11-17 23:00:36 +00002838
Sean Callanan79763a42011-05-23 21:40:23 +00002839 if (!RewriteObjCConstStrings(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002840 {
2841 if (log)
2842 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002843
2844 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2845
Sean Callananafe16a72010-11-17 23:00:36 +00002846 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002847 }
Sean Callananafe16a72010-11-17 23:00:36 +00002848
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002849 ///////////////////////////////
2850 // Resolve function pointers
2851 //
2852
2853 if (!ResolveFunctionPointers(llvm_module, *function))
2854 {
2855 if (log)
2856 log->Printf("ResolveFunctionPointers() failed");
2857
2858 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2859
2860 return false;
2861 }
2862
Sean Callanan2ab712f22010-07-03 01:35:46 +00002863 for (bbi = function->begin();
2864 bbi != function->end();
2865 ++bbi)
2866 {
Sean Callanan79763a42011-05-23 21:40:23 +00002867 if (!RewriteObjCSelectors(*bbi))
Sean Callanan17827832010-12-13 22:46:15 +00002868 {
2869 if (log)
2870 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002871
2872 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2873
Sean Callanan2235f322010-08-11 03:57:18 +00002874 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002875 }
Sean Callananbad134f2012-07-27 19:25:24 +00002876 }
Sean Callanan2235f322010-08-11 03:57:18 +00002877
Sean Callananbad134f2012-07-27 19:25:24 +00002878 for (bbi = function->begin();
2879 bbi != function->end();
2880 ++bbi)
2881 {
Sean Callanan79763a42011-05-23 21:40:23 +00002882 if (!ResolveCalls(*bbi))
Sean Callanan17827832010-12-13 22:46:15 +00002883 {
2884 if (log)
2885 log->Printf("ResolveCalls() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002886
2887 // ResolveCalls() reports its own errors, so we don't do so here
2888
Sean Callanan549c9f72010-07-13 21:41:46 +00002889 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002890 }
Sean Callanan79763a42011-05-23 21:40:23 +00002891
2892 if (!ReplaceStaticLiterals(*bbi))
2893 {
2894 if (log)
2895 log->Printf("ReplaceStaticLiterals() failed");
2896
2897 return false;
2898 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002899 }
2900
Sean Callanan038df5032010-09-30 21:18:25 +00002901 ///////////////////////////////
2902 // Run function-level passes
2903 //
2904
Sean Callanan79763a42011-05-23 21:40:23 +00002905 if (!ResolveExternals(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002906 {
2907 if (log)
2908 log->Printf("ResolveExternals() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002909
2910 // ResolveExternals() reports its own errors, so we don't do so here
2911
Sean Callanana4e55172010-11-08 00:31:32 +00002912 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002913 }
Sean Callanana4e55172010-11-08 00:31:32 +00002914
Sean Callanan79763a42011-05-23 21:40:23 +00002915 if (!ReplaceVariables(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002916 {
2917 if (log)
2918 log->Printf("ReplaceVariables() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002919
2920 // ReplaceVariables() reports its own errors, so we don't do so here
2921
Sean Callanan038df5032010-09-30 21:18:25 +00002922 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002923 }
Sean Callanan038df5032010-09-30 21:18:25 +00002924
Sean Callanan79763a42011-05-23 21:40:23 +00002925 if (!ReplaceStrings())
2926 {
2927 if (log)
2928 log->Printf("ReplaceStrings() failed");
2929
2930 return false;
2931 }
2932
2933 if (!CompleteDataAllocation())
2934 {
2935 if (log)
2936 log->Printf("CompleteDataAllocation() failed");
2937
2938 return false;
2939 }
2940
Sean Callanan3d654b32012-09-24 22:25:51 +00002941 if (!StripAllGVs(llvm_module))
2942 {
2943 if (log)
2944 log->Printf("StripAllGVs() failed");
2945 }
2946
Sean Callananea685ae2011-11-01 17:33:54 +00002947 if (log && log->GetVerbose())
Sean Callanan549c9f72010-07-13 21:41:46 +00002948 {
Sean Callanancc54bd32010-07-28 01:00:59 +00002949 std::string s;
2950 raw_string_ostream oss(s);
Sean Callanan549c9f72010-07-13 21:41:46 +00002951
Sean Callanan79763a42011-05-23 21:40:23 +00002952 m_module->print(oss, NULL);
Sean Callanancc54bd32010-07-28 01:00:59 +00002953
2954 oss.flush();
2955
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002956 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan2ab712f22010-07-03 01:35:46 +00002957 }
2958
2959 return true;
2960}
2961
2962void
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002963IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002964{
2965}
2966
2967PassManagerType
2968IRForTarget::getPotentialPassManagerType() const
2969{
2970 return PMT_ModulePassManager;
2971}