blob: b4d96552379a92d208847e285e77d2a14f31e75f [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),
Sean Callanan1582ee62013-04-18 22:06:33 +000045 m_stream_string(lldb_private::Stream::eBinary, execution_unit.GetAddressByteSize(), execution_unit.GetByteOrder()),
Sean Callanan8dfb68e2013-03-19 00:10:07 +000046 m_allocation(LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +000047{
48}
49
Sean Callanan8dfb68e2013-03-19 00:10:07 +000050lldb::addr_t IRForTarget::StaticDataAllocator::Allocate()
Sean Callanan79763a42011-05-23 21:40:23 +000051{
Sean Callanan8dfb68e2013-03-19 00:10:07 +000052 lldb_private::Error err;
53
54 if (m_allocation != LLDB_INVALID_ADDRESS)
55 {
56 m_execution_unit.FreeNow(m_allocation);
57 m_allocation = LLDB_INVALID_ADDRESS;
58 }
59
60 m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
61
62 return m_allocation;
Sean Callanan79763a42011-05-23 21:40:23 +000063}
64
Greg Clayton1b95a6f2010-11-19 01:05:25 +000065IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
66 bool resolve_vars,
Sean Callanan8dfb68e2013-03-19 00:10:07 +000067 lldb_private::IRExecutionUnit &execution_unit,
Sean Callanan3989fb92011-01-27 01:07:04 +000068 lldb_private::Stream *error_stream,
Greg Clayton1b95a6f2010-11-19 01:05:25 +000069 const char *func_name) :
Sean Callanane2ef6e32010-09-23 03:01:22 +000070 ModulePass(ID),
Stephen Wilson71c21d12011-04-11 19:41:40 +000071 m_resolve_vars(resolve_vars),
72 m_func_name(func_name),
Sean Callanan79763a42011-05-23 21:40:23 +000073 m_module(NULL),
Johnny Chen44805302011-07-19 19:48:13 +000074 m_decl_map(decl_map),
Sean Callanan8dfb68e2013-03-19 00:10:07 +000075 m_data_allocator(execution_unit),
Sean Callanan179b5482013-04-16 23:49:09 +000076 m_memory_map(execution_unit),
Sean Callananafe16a72010-11-17 23:00:36 +000077 m_CFStringCreateWithBytes(NULL),
Sean Callanan1a8d4092010-08-27 01:01:44 +000078 m_sel_registerName(NULL),
Stephen Wilson71c21d12011-04-11 19:41:40 +000079 m_error_stream(error_stream),
Sean Callanan92adcac2011-01-13 08:53:35 +000080 m_has_side_effects(false),
Sean Callanan63697e52011-05-07 01:06:41 +000081 m_result_store(NULL),
82 m_result_is_pointer(false),
Sean Callanan79763a42011-05-23 21:40:23 +000083 m_reloc_placeholder(NULL)
Sean Callanan2ab712f22010-07-03 01:35:46 +000084{
85}
86
Sean Callanan038df5032010-09-30 21:18:25 +000087/* Handy utility functions used at several places in the code */
Sean Callanan2235f322010-08-11 03:57:18 +000088
89static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +000090PrintValue(const Value *value, bool truncate = false)
Sean Callanan2235f322010-08-11 03:57:18 +000091{
92 std::string s;
Jim Ingham28eb5712012-10-12 17:34:26 +000093 if (value)
94 {
95 raw_string_ostream rso(s);
96 value->print(rso);
97 rso.flush();
98 if (truncate)
99 s.resize(s.length() - 1);
100 }
Sean Callanan2235f322010-08-11 03:57:18 +0000101 return s;
102}
103
Sean Callanan038df5032010-09-30 21:18:25 +0000104static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000105PrintType(const Type *type, bool truncate = false)
Sean Callanan038df5032010-09-30 21:18:25 +0000106{
107 std::string s;
108 raw_string_ostream rso(s);
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000109 type->print(rso);
Sean Callanan038df5032010-09-30 21:18:25 +0000110 rso.flush();
111 if (truncate)
112 s.resize(s.length() - 1);
113 return s;
114}
115
Sean Callanan2ab712f22010-07-03 01:35:46 +0000116IRForTarget::~IRForTarget()
117{
118}
119
Sean Callanan79763a42011-05-23 21:40:23 +0000120bool
121IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
122{
Sean Callanan79763a42011-05-23 21:40:23 +0000123 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
124
Sean Callanan7f27d602011-11-19 02:54:21 +0000125 std::string name = llvm_function.getName().str();
Sean Callanan79763a42011-05-23 21:40:23 +0000126
127 return true;
128}
129
Sean Callanand1e5b432010-08-12 01:56:52 +0000130bool
Sean Callanan79763a42011-05-23 21:40:23 +0000131IRForTarget::HasSideEffects (llvm::Function &llvm_function)
Sean Callanane4ec90e2010-12-16 03:17:46 +0000132{
133 llvm::Function::iterator bbi;
134 BasicBlock::iterator ii;
Sean Callanan63697e52011-05-07 01:06:41 +0000135
Sean Callanane4ec90e2010-12-16 03:17:46 +0000136 for (bbi = llvm_function.begin();
137 bbi != llvm_function.end();
138 ++bbi)
139 {
140 BasicBlock &basic_block = *bbi;
141
142 for (ii = basic_block.begin();
143 ii != basic_block.end();
144 ++ii)
145 {
146 switch (ii->getOpcode())
147 {
148 default:
149 return true;
150 case Instruction::Store:
151 {
152 StoreInst *store_inst = dyn_cast<StoreInst>(ii);
153
154 Value *store_ptr = store_inst->getPointerOperand();
155
Sean Callanan63697e52011-05-07 01:06:41 +0000156 std::string ptr_name;
157
158 if (store_ptr->hasName())
Sean Callanan7f27d602011-11-19 02:54:21 +0000159 ptr_name = store_ptr->getName().str();
Sean Callanan63697e52011-05-07 01:06:41 +0000160
161 if (isa <AllocaInst> (store_ptr))
Sean Callanane4ec90e2010-12-16 03:17:46 +0000162 break;
Sean Callanan63697e52011-05-07 01:06:41 +0000163
164 if (ptr_name.find("$__lldb_expr_result") != std::string::npos)
165 {
166 if (ptr_name.find("GV") == std::string::npos)
167 m_result_store = store_inst;
168 }
169 else
170 {
171 return true;
172 }
173
174 break;
Sean Callanane4ec90e2010-12-16 03:17:46 +0000175 }
176 case Instruction::Load:
177 case Instruction::Alloca:
178 case Instruction::GetElementPtr:
Sean Callanan63697e52011-05-07 01:06:41 +0000179 case Instruction::BitCast:
Sean Callanane4ec90e2010-12-16 03:17:46 +0000180 case Instruction::Ret:
Sean Callanan63697e52011-05-07 01:06:41 +0000181 case Instruction::ICmp:
182 case Instruction::Br:
Sean Callanane4ec90e2010-12-16 03:17:46 +0000183 break;
184 }
185 }
186 }
187
188 return false;
189}
190
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000191bool
192IRForTarget::GetFunctionAddress (llvm::Function *fun,
193 uint64_t &fun_addr,
194 lldb_private::ConstString &name,
195 Constant **&value_ptr)
196{
Greg Clayton5160ce52013-03-27 23:08:40 +0000197 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000198
199 fun_addr = LLDB_INVALID_ADDRESS;
200 name.Clear();
201 value_ptr = NULL;
202
203 if (fun->isIntrinsic())
204 {
205 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
206
207 switch (intrinsic_id)
208 {
209 default:
210 if (log)
211 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
212
213 if (m_error_stream)
214 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
215
216 return false;
217 case Intrinsic::memcpy:
218 {
219 static lldb_private::ConstString g_memcpy_str ("memcpy");
220 name = g_memcpy_str;
221 }
222 break;
Sean Callanana6cbf062011-11-16 00:20:50 +0000223 case Intrinsic::memset:
224 {
225 static lldb_private::ConstString g_memset_str ("memset");
226 name = g_memset_str;
227 }
228 break;
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000229 }
230
231 if (log && name)
232 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
233 }
234 else
235 {
236 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
237 }
238
239 // Find the address of the function.
240
241 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000242
243 if (fun_decl)
244 {
Sean Callananc70ed462011-10-25 18:36:40 +0000245 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000246 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000247 lldb_private::ConstString altnernate_name;
Greg Claytonf0705c82011-10-22 03:33:13 +0000248 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
249 if (!found_it)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000250 {
Greg Claytonf0705c82011-10-22 03:33:13 +0000251 // Check for an alternate mangling for "std::basic_string<char>"
252 // that is part of the itanium C++ name mangling scheme
253 const char *name_cstr = name.GetCString();
Jim Ingham28eb5712012-10-12 17:34:26 +0000254 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
Greg Claytonf0705c82011-10-22 03:33:13 +0000255 {
256 std::string alternate_mangling("_ZNKSs");
257 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000258 altnernate_name.SetCString(alternate_mangling.c_str());
259 found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
Greg Claytonf0705c82011-10-22 03:33:13 +0000260 }
261 }
262
263 if (!found_it)
264 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000265 lldb_private::Mangled mangled_name(name);
266 lldb_private::Mangled alt_mangled_name(altnernate_name);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000267 if (log)
Greg Claytonf0705c82011-10-22 03:33:13 +0000268 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000269 if (alt_mangled_name)
270 log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
271 mangled_name.GetName().GetCString(),
272 alt_mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000273 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000274 log->Printf("Function \"%s\" had no address",
275 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000276 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000277
278 if (m_error_stream)
Greg Claytonf0705c82011-10-22 03:33:13 +0000279 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000280 if (alt_mangled_name)
281 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
282 mangled_name.GetName().GetCString(),
283 alt_mangled_name.GetName().GetCString());
Greg Claytonda1eb042013-04-23 21:48:38 +0000284 else if (mangled_name.GetMangledName())
285 m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
286 mangled_name.GetName().GetCString(),
287 mangled_name.GetMangledName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000288 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000289 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
290 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000291 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000292 return false;
293 }
294 }
295 }
296 else
297 {
298 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
299 {
300 if (log)
301 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
302
303 if (m_error_stream)
304 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
305
306 return false;
307 }
308 }
309
310 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000311 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000312
313 return true;
314}
315
316llvm::Constant *
317IRForTarget::BuildFunctionPointer (llvm::Type *type,
318 uint64_t ptr)
319{
320 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +0000321 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000322 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
323 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
324 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
325}
326
Sean Callananfc8feb82011-10-31 22:11:40 +0000327void
328IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
329 llvm::Value *function_ptr,
330 const char *name)
331{
Sean Callananfc8feb82011-10-31 22:11:40 +0000332 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
333 i != e;
334 ++i)
335 {
336 Value *user = *i;
337
338 if (Instruction *user_inst = dyn_cast<Instruction>(user))
339 {
Sean Callanand2b465f2012-02-09 03:22:41 +0000340 Constant *name_array = ConstantDataArray::getString(context, StringRef(name));
Sean Callananfc8feb82011-10-31 22:11:40 +0000341
342 ArrayRef<Value *> md_values(name_array);
343
344 MDNode *metadata = MDNode::get(context, md_values);
345
346 user_inst->setMetadata("lldb.call.realName", metadata);
347 }
348 else
349 {
350 RegisterFunctionMetadata (context, user, name);
351 }
352 }
353}
354
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000355bool
356IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module,
357 llvm::Function &llvm_function)
358{
Greg Clayton5160ce52013-03-27 23:08:40 +0000359 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000360
361 for (llvm::Module::iterator fi = llvm_module.begin();
362 fi != llvm_module.end();
363 ++fi)
364 {
365 Function *fun = fi;
366
367 bool is_decl = fun->isDeclaration();
368
369 if (log)
Sean Callanan7f27d602011-11-19 02:54:21 +0000370 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000371
372 if (!is_decl)
373 continue;
374
375 if (fun->hasNUses(0))
376 continue; // ignore
377
378 uint64_t addr = LLDB_INVALID_ADDRESS;
379 lldb_private::ConstString name;
380 Constant **value_ptr = NULL;
381
382 if (!GetFunctionAddress(fun,
383 addr,
384 name,
385 value_ptr))
386 return false; // GetFunctionAddress reports its own errors
387
388 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
389
Sean Callananfc8feb82011-10-31 22:11:40 +0000390 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
391
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000392 if (value_ptr)
393 *value_ptr = value;
394
395 fun->replaceAllUsesWith(value);
396 }
397
398 return true;
399}
400
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000401
Sean Callanan63697e52011-05-07 01:06:41 +0000402clang::NamedDecl *
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000403IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan63697e52011-05-07 01:06:41 +0000404{
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000405 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan63697e52011-05-07 01:06:41 +0000406
407 if (!named_metadata)
408 return NULL;
409
410 unsigned num_nodes = named_metadata->getNumOperands();
411 unsigned node_index;
412
413 for (node_index = 0;
414 node_index < num_nodes;
415 ++node_index)
416 {
417 MDNode *metadata_node = named_metadata->getOperand(node_index);
418
419 if (!metadata_node)
420 return NULL;
421
422 if (metadata_node->getNumOperands() != 2)
423 continue;
424
425 if (metadata_node->getOperand(0) != global_val)
426 continue;
427
428 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
429
430 if (!constant_int)
431 return NULL;
432
433 uintptr_t ptr = constant_int->getZExtValue();
434
435 return reinterpret_cast<clang::NamedDecl *>(ptr);
436 }
437
438 return NULL;
439}
440
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000441clang::NamedDecl *
442IRForTarget::DeclForGlobal (GlobalValue *global_val)
443{
444 return DeclForGlobal(global_val, m_module);
445}
446
Sean Callanane4ec90e2010-12-16 03:17:46 +0000447bool
Sean Callanan79763a42011-05-23 21:40:23 +0000448IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanand1e5b432010-08-12 01:56:52 +0000449{
Greg Clayton5160ce52013-03-27 23:08:40 +0000450 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand1e5b432010-08-12 01:56:52 +0000451
Sean Callanan9e6ed532010-09-13 21:34:21 +0000452 if (!m_resolve_vars)
453 return true;
454
455 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callananfc55f5d2010-09-21 00:44:12 +0000456
Sean Callanan79763a42011-05-23 21:40:23 +0000457 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananfc55f5d2010-09-21 00:44:12 +0000458
Sean Callanancc427fa2011-07-30 02:42:06 +0000459 std::string result_name_str;
Sean Callananfc55f5d2010-09-21 00:44:12 +0000460 const char *result_name = NULL;
461
462 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
463 vi != ve;
464 ++vi)
465 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000466 result_name_str = vi->first().str();
467 const char *value_name = result_name_str.c_str();
468
469 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000470 strncmp(value_name, "_ZGV", 4))
Sean Callanan92adcac2011-01-13 08:53:35 +0000471 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000472 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000473 m_result_is_pointer = true;
474 break;
475 }
476
Sean Callanancc427fa2011-07-30 02:42:06 +0000477 if (strstr(value_name, "$__lldb_expr_result") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000478 strncmp(value_name, "_ZGV", 4))
Sean Callanan46ae9e52010-09-28 21:13:03 +0000479 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000480 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000481 m_result_is_pointer = false;
Sean Callanan46ae9e52010-09-28 21:13:03 +0000482 break;
483 }
Sean Callananfc55f5d2010-09-21 00:44:12 +0000484 }
485
486 if (!result_name)
487 {
488 if (log)
489 log->PutCString("Couldn't find result variable");
490
491 return true;
492 }
493
Sean Callanan46ae9e52010-09-28 21:13:03 +0000494 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000495 log->Printf("Result name: \"%s\"", result_name);
Sean Callanan46ae9e52010-09-28 21:13:03 +0000496
Sean Callanan79763a42011-05-23 21:40:23 +0000497 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanand1e5b432010-08-12 01:56:52 +0000498
499 if (!result_value)
500 {
501 if (log)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000502 log->PutCString("Result variable had no data");
Sean Callanan92adcac2011-01-13 08:53:35 +0000503
Sean Callanan3989fb92011-01-27 01:07:04 +0000504 if (m_error_stream)
505 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
506
Sean Callananfc55f5d2010-09-21 00:44:12 +0000507 return false;
Sean Callanand1e5b432010-08-12 01:56:52 +0000508 }
Sean Callanan9e6ed532010-09-13 21:34:21 +0000509
Sean Callanand1e5b432010-08-12 01:56:52 +0000510 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000511 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000512
513 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
514
515 if (!result_global)
516 {
517 if (log)
518 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000519
520 if (m_error_stream)
521 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
522
Sean Callanand1e5b432010-08-12 01:56:52 +0000523 return false;
524 }
525
Sean Callanan79763a42011-05-23 21:40:23 +0000526 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan63697e52011-05-07 01:06:41 +0000527 if (!result_decl)
Sean Callanand1e5b432010-08-12 01:56:52 +0000528 {
529 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000530 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanand1e5b432010-08-12 01:56:52 +0000531
Sean Callanan3989fb92011-01-27 01:07:04 +0000532 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000533 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 +0000534
Sean Callanand1e5b432010-08-12 01:56:52 +0000535 return false;
536 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000537
Sean Callanan63697e52011-05-07 01:06:41 +0000538 if (log)
Sean Callanand1e5b432010-08-12 01:56:52 +0000539 {
Sean Callanan63697e52011-05-07 01:06:41 +0000540 std::string decl_desc_str;
541 raw_string_ostream decl_desc_stream(decl_desc_str);
542 result_decl->print(decl_desc_stream);
543 decl_desc_stream.flush();
Sean Callanand1e5b432010-08-12 01:56:52 +0000544
Sean Callanan63697e52011-05-07 01:06:41 +0000545 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000546 }
547
Sean Callanan63697e52011-05-07 01:06:41 +0000548 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
549 if (!result_var)
Sean Callanand1e5b432010-08-12 01:56:52 +0000550 {
551 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000552 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan3989fb92011-01-27 01:07:04 +0000553
554 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000555 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 +0000556
Sean Callanand1e5b432010-08-12 01:56:52 +0000557 return false;
558 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000559
Sean Callanand1e5b432010-08-12 01:56:52 +0000560 // Get the next available result name from m_decl_map and create the persistent
561 // variable for it
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000562
Sean Callanan63697e52011-05-07 01:06:41 +0000563 // If the result is an Lvalue, it is emitted as a pointer; see
564 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan92adcac2011-01-13 08:53:35 +0000565 if (m_result_is_pointer)
566 {
Sean Callanan63697e52011-05-07 01:06:41 +0000567 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanan78e37602011-01-27 04:42:51 +0000568 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
Sean Callanan92adcac2011-01-13 08:53:35 +0000569
Sean Callananfc4f2fb2011-12-14 01:13:04 +0000570 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
571 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
Sean Callanan5780f9d2011-12-08 19:04:34 +0000572
573 if (pointer_pointertype)
574 {
575 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
576
577 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
578 &result_decl->getASTContext());
579 }
580 else if (pointer_objcobjpointertype)
581 {
582 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
583
584 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
585 &result_decl->getASTContext());
586 }
587 else
Sean Callanan92adcac2011-01-13 08:53:35 +0000588 {
589 if (log)
590 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan3989fb92011-01-27 01:07:04 +0000591
592 if (m_error_stream)
593 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
594
Sean Callanan92adcac2011-01-13 08:53:35 +0000595 return false;
596 }
Sean Callanan92adcac2011-01-13 08:53:35 +0000597 }
598 else
599 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000600 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan00f43622011-11-18 03:28:09 +0000601 &result_decl->getASTContext());
602 }
603
604 if (m_result_type.GetClangTypeBitWidth() == 0)
605 {
606 lldb_private::StreamString type_desc_stream;
607 m_result_type.DumpTypeDescription(&type_desc_stream);
608
609 if (log)
610 log->Printf("Result type has size 0");
611
612 if (m_error_stream)
Sean Callanan960534c2011-12-21 23:44:05 +0000613 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
Sean Callanan00f43622011-11-18 03:28:09 +0000614 type_desc_stream.GetData());
Sean Callanan960534c2011-12-21 23:44:05 +0000615 return false;
Sean Callanan92adcac2011-01-13 08:53:35 +0000616 }
617
Sean Callanan63697e52011-05-07 01:06:41 +0000618 if (log)
619 {
620 lldb_private::StreamString type_desc_stream;
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000621 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan63697e52011-05-07 01:06:41 +0000622
Sean Callanan00f43622011-11-18 03:28:09 +0000623 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
Sean Callanan63697e52011-05-07 01:06:41 +0000624 }
625
Sean Callanan1582ee62013-04-18 22:06:33 +0000626 m_result_name = lldb_private::ConstString("$RESULT_NAME");
Sean Callanand1e5b432010-08-12 01:56:52 +0000627
628 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +0000629 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
Sean Callanan00f43622011-11-18 03:28:09 +0000630 m_result_name.GetCString(),
631 m_result_type.GetClangTypeBitWidth() / 8);
Sean Callanand1e5b432010-08-12 01:56:52 +0000632
633 // Construct a new result global and set up its metadata
634
Sean Callanan79763a42011-05-23 21:40:23 +0000635 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanand1e5b432010-08-12 01:56:52 +0000636 result_global->getType()->getElementType(),
637 false, /* not constant */
638 GlobalValue::ExternalLinkage,
639 NULL, /* no initializer */
Sean Callanan92adcac2011-01-13 08:53:35 +0000640 m_result_name.GetCString ());
Sean Callanand1e5b432010-08-12 01:56:52 +0000641
642 // It's too late in compilation to create a new VarDecl for this, but we don't
643 // need to. We point the metadata at the old VarDecl. This creates an odd
644 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton7b462cc2010-10-15 22:48:33 +0000645 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanand1e5b432010-08-12 01:56:52 +0000646 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
647 // fixed up.
648
Sean Callanan79763a42011-05-23 21:40:23 +0000649 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan63697e52011-05-07 01:06:41 +0000650 reinterpret_cast<uint64_t>(result_decl),
Sean Callanand1e5b432010-08-12 01:56:52 +0000651 false);
652
653 llvm::Value* values[2];
654 values[0] = new_result_global;
655 values[1] = new_constant_int;
656
Sean Callanand12cf8bb2011-05-15 22:34:38 +0000657 ArrayRef<Value*> value_ref(values, 2);
658
Sean Callanan79763a42011-05-23 21:40:23 +0000659 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
660 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanand1e5b432010-08-12 01:56:52 +0000661 named_metadata->addOperand(persistent_global_md);
662
663 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000664 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan1e87fff2010-09-07 22:43:19 +0000665 PrintValue(result_global).c_str(),
Sean Callanand1e5b432010-08-12 01:56:52 +0000666 PrintValue(new_result_global).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000667
668 if (result_global->hasNUses(0))
669 {
670 // We need to synthesize a store for this variable, because otherwise
671 // there's nothing to put into its equivalent persistent variable.
Sean Callanand1e5b432010-08-12 01:56:52 +0000672
Greg Clayton7b462cc2010-10-15 22:48:33 +0000673 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000674 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
675
676 if (!first_entry_instruction)
677 return false;
678
679 if (!result_global->hasInitializer())
680 {
681 if (log)
682 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000683
684 if (m_error_stream)
685 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
686
Sean Callanan1e87fff2010-09-07 22:43:19 +0000687 return false;
688 }
689
690 Constant *initializer = result_global->getInitializer();
Sean Callanane4ec90e2010-12-16 03:17:46 +0000691
692 // Here we write the initializer into a result variable assuming it
693 // can be computed statically.
694
695 if (!m_has_side_effects)
696 {
Sean Callanan80c48c12011-10-21 05:18:02 +0000697 //MaybeSetConstantResult (initializer,
698 // m_result_name,
699 // m_result_type);
Sean Callanane4ec90e2010-12-16 03:17:46 +0000700 }
Sean Callanan1e87fff2010-09-07 22:43:19 +0000701
Greg Clayton9c139312011-02-05 02:28:58 +0000702 StoreInst *synthesized_store = new StoreInst(initializer,
703 new_result_global,
704 first_entry_instruction);
Sean Callanan1e87fff2010-09-07 22:43:19 +0000705
706 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000707 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000708 }
709 else
710 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000711 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (m_result_type.GetOpaqueQualType()))
Sean Callanan63697e52011-05-07 01:06:41 +0000712 {
Sean Callanan80c48c12011-10-21 05:18:02 +0000713 //MaybeSetCastResult (m_result_type);
Sean Callanan63697e52011-05-07 01:06:41 +0000714 }
715
Sean Callanan1e87fff2010-09-07 22:43:19 +0000716 result_global->replaceAllUsesWith(new_result_global);
717 }
718
Sean Callanan1582ee62013-04-18 22:06:33 +0000719 if (!m_decl_map->AddPersistentVariable(result_decl,
720 m_result_name,
721 m_result_type,
722 true,
723 m_result_is_pointer))
724 return false;
725
Sean Callanand1e5b432010-08-12 01:56:52 +0000726 result_global->eraseFromParent();
727
728 return true;
729}
730
Johnny Chenee7a3592011-08-09 23:10:20 +0000731#if 0
Greg Clayton5160ce52013-03-27 23:08:40 +0000732static void DebugUsers(Log *log, Value *value, uint8_t depth)
Sean Callananafe16a72010-11-17 23:00:36 +0000733{
734 if (!depth)
735 return;
736
737 depth--;
738
Johnny Chenee7a3592011-08-09 23:10:20 +0000739 if (log)
740 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callananafe16a72010-11-17 23:00:36 +0000741
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000742 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callananafe16a72010-11-17 23:00:36 +0000743 ui != ue;
744 ++ui)
745 {
Johnny Chenee7a3592011-08-09 23:10:20 +0000746 if (log)
747 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callananafe16a72010-11-17 23:00:36 +0000748 DebugUsers(log, *ui, depth);
749 }
750
Johnny Chenee7a3592011-08-09 23:10:20 +0000751 if (log)
752 log->Printf(" <End uses>");
Sean Callananafe16a72010-11-17 23:00:36 +0000753}
Johnny Chenee7a3592011-08-09 23:10:20 +0000754#endif
Sean Callananafe16a72010-11-17 23:00:36 +0000755
756bool
Sean Callanan79763a42011-05-23 21:40:23 +0000757IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000758 llvm::GlobalVariable *cstr,
759 Instruction *FirstEntryInstruction)
Sean Callananafe16a72010-11-17 23:00:36 +0000760{
Greg Clayton5160ce52013-03-27 23:08:40 +0000761 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000762
Sean Callanancc427fa2011-07-30 02:42:06 +0000763 Type *ns_str_ty = ns_str->getType();
Sean Callanan79763a42011-05-23 21:40:23 +0000764
Sean Callanancc427fa2011-07-30 02:42:06 +0000765 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
766 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +0000767 (m_module->getPointerSize()
Micah Villmow08318972012-10-11 17:21:41 +0000768 == Module::Pointer64) ? 64 : 32);
Sean Callanancc427fa2011-07-30 02:42:06 +0000769 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
770 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananafe16a72010-11-17 23:00:36 +0000771
772 if (!m_CFStringCreateWithBytes)
773 {
774 lldb::addr_t CFStringCreateWithBytes_addr;
775
776 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
777
778 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
779 {
780 if (log)
781 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
782
Sean Callanan3989fb92011-01-27 01:07:04 +0000783 if (m_error_stream)
784 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
785
Sean Callananafe16a72010-11-17 23:00:36 +0000786 return false;
787 }
788
789 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000790 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
Sean Callananafe16a72010-11-17 23:00:36 +0000791
792 // Build the function type:
793 //
794 // CFStringRef CFStringCreateWithBytes (
795 // CFAllocatorRef alloc,
796 // const UInt8 *bytes,
797 // CFIndex numBytes,
798 // CFStringEncoding encoding,
799 // Boolean isExternalRepresentation
800 // );
801 //
802 // We make the following substitutions:
803 //
804 // CFStringRef -> i8*
805 // CFAllocatorRef -> i8*
806 // UInt8 * -> i8*
807 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
808 // CFStringEncoding -> i32
809 // Boolean -> i8
810
Sean Callanancc427fa2011-07-30 02:42:06 +0000811 Type *arg_type_array[5];
812
813 arg_type_array[0] = i8_ptr_ty;
814 arg_type_array[1] = i8_ptr_ty;
815 arg_type_array[2] = intptr_ty;
816 arg_type_array[3] = i32_ty;
817 arg_type_array[4] = i8_ty;
818
819 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
820
Sean Callanan79763a42011-05-23 21:40:23 +0000821 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000822
823 // Build the constant containing the pointer to the function
824 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
825 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
826 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
827 }
828
Sean Callanand2b465f2012-02-09 03:22:41 +0000829 ConstantDataSequential *string_array = NULL;
Sean Callanan229ce2d2011-02-10 22:17:53 +0000830
831 if (cstr)
Sean Callanand2b465f2012-02-09 03:22:41 +0000832 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
Sean Callanancc427fa2011-07-30 02:42:06 +0000833
Sean Callananafe16a72010-11-17 23:00:36 +0000834 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan229ce2d2011-02-10 22:17:53 +0000835 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
Sean Callanand2b465f2012-02-09 03:22:41 +0000836 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000837 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
838 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
839
Sean Callanancc427fa2011-07-30 02:42:06 +0000840 Value *argument_array[5];
841
842 argument_array[0] = alloc_arg;
843 argument_array[1] = bytes_arg;
844 argument_array[2] = numBytes_arg;
845 argument_array[3] = encoding_arg;
846 argument_array[4] = isExternal_arg;
847
848 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callananafe16a72010-11-17 23:00:36 +0000849
850 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanancc427fa2011-07-30 02:42:06 +0000851 CFSCWB_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +0000852 "CFStringCreateWithBytes",
853 FirstEntryInstruction);
Sean Callanan7a55a322010-11-18 22:21:58 +0000854
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000855 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callananafe16a72010-11-17 23:00:36 +0000856 {
857 if (log)
858 log->PutCString("Couldn't replace the NSString with the result of the call");
859
Sean Callanan3989fb92011-01-27 01:07:04 +0000860 if (m_error_stream)
861 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
862
Sean Callananafe16a72010-11-17 23:00:36 +0000863 return false;
864 }
865
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000866 ns_str->eraseFromParent();
Sean Callananafe16a72010-11-17 23:00:36 +0000867
868 return true;
869}
870
871bool
Sean Callanan79763a42011-05-23 21:40:23 +0000872IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callananafe16a72010-11-17 23:00:36 +0000873{
Greg Clayton5160ce52013-03-27 23:08:40 +0000874 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000875
Sean Callanan79763a42011-05-23 21:40:23 +0000876 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananafe16a72010-11-17 23:00:36 +0000877
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000878 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +0000879 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
880
881 if (!FirstEntryInstruction)
882 {
883 if (log)
884 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
885
Sean Callanan3989fb92011-01-27 01:07:04 +0000886 if (m_error_stream)
887 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
888
Sean Callananafe16a72010-11-17 23:00:36 +0000889 return false;
890 }
891
892 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
893 vi != ve;
894 ++vi)
895 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000896 std::string value_name = vi->first().str();
897 const char *value_name_cstr = value_name.c_str();
898
899 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callananafe16a72010-11-17 23:00:36 +0000900 {
901 Value *nsstring_value = vi->second;
902
903 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
904
905 if (!nsstring_global)
906 {
907 if (log)
908 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000909
910 if (m_error_stream)
911 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
912
Sean Callananafe16a72010-11-17 23:00:36 +0000913 return false;
914 }
915
916 if (!nsstring_global->hasInitializer())
917 {
918 if (log)
919 log->PutCString("NSString variable does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000920
921 if (m_error_stream)
922 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
923
Sean Callananafe16a72010-11-17 23:00:36 +0000924 return false;
925 }
926
927 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
928
929 if (!nsstring_struct)
930 {
931 if (log)
932 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan3989fb92011-01-27 01:07:04 +0000933
934 if (m_error_stream)
935 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
936
Sean Callananafe16a72010-11-17 23:00:36 +0000937 return false;
938 }
939
940 // We expect the following structure:
941 //
942 // struct {
943 // int *isa;
944 // int flags;
945 // char *str;
946 // long length;
947 // };
948
949 if (nsstring_struct->getNumOperands() != 4)
950 {
951 if (log)
952 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 +0000953
954 if (m_error_stream)
955 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
956
Sean Callananafe16a72010-11-17 23:00:36 +0000957 return false;
958 }
959
960 Constant *nsstring_member = nsstring_struct->getOperand(2);
961
962 if (!nsstring_member)
963 {
964 if (log)
965 log->PutCString("NSString initializer's str element was empty");
Sean Callanan3989fb92011-01-27 01:07:04 +0000966
967 if (m_error_stream)
968 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
969
Sean Callananafe16a72010-11-17 23:00:36 +0000970 return false;
971 }
972
973 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
974
975 if (!nsstring_expr)
976 {
977 if (log)
978 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan3989fb92011-01-27 01:07:04 +0000979
980 if (m_error_stream)
981 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
982
Sean Callananafe16a72010-11-17 23:00:36 +0000983 return false;
984 }
985
986 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
987 {
988 if (log)
989 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 +0000990
991 if (m_error_stream)
992 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
993
Sean Callananafe16a72010-11-17 23:00:36 +0000994 return false;
995 }
996
997 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
998
999 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
1000
1001 if (!cstr_global)
1002 {
1003 if (log)
1004 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001005
1006 if (m_error_stream)
1007 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
Sean Callanan80eee3a2010-11-20 02:06:01 +00001008
Sean Callananafe16a72010-11-17 23:00:36 +00001009 return false;
1010 }
1011
1012 if (!cstr_global->hasInitializer())
1013 {
1014 if (log)
1015 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +00001016
1017 if (m_error_stream)
1018 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
1019
Sean Callananafe16a72010-11-17 23:00:36 +00001020 return false;
1021 }
Sean Callanan229ce2d2011-02-10 22:17:53 +00001022
1023 /*
Sean Callananafe16a72010-11-17 23:00:36 +00001024 if (!cstr_array)
1025 {
1026 if (log)
1027 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan3989fb92011-01-27 01:07:04 +00001028
1029 if (m_error_stream)
1030 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
1031
Sean Callananafe16a72010-11-17 23:00:36 +00001032 return false;
1033 }
1034
1035 if (!cstr_array->isCString())
1036 {
1037 if (log)
1038 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan3989fb92011-01-27 01:07:04 +00001039
1040 if (m_error_stream)
1041 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
1042
Sean Callananafe16a72010-11-17 23:00:36 +00001043 return false;
1044 }
Sean Callanan229ce2d2011-02-10 22:17:53 +00001045 */
1046
Sean Callanand2b465f2012-02-09 03:22:41 +00001047 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
Sean Callananafe16a72010-11-17 23:00:36 +00001048
1049 if (log)
Sean Callanan229ce2d2011-02-10 22:17:53 +00001050 {
1051 if (cstr_array)
Sean Callanand2b465f2012-02-09 03:22:41 +00001052 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 +00001053 else
Sean Callanancc427fa2011-07-30 02:42:06 +00001054 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan229ce2d2011-02-10 22:17:53 +00001055 }
1056
1057 if (!cstr_array)
1058 cstr_global = NULL;
Sean Callananafe16a72010-11-17 23:00:36 +00001059
Sean Callanan79763a42011-05-23 21:40:23 +00001060 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan3989fb92011-01-27 01:07:04 +00001061 {
Sean Callananafe16a72010-11-17 23:00:36 +00001062 if (log)
1063 log->PutCString("Error rewriting the constant string");
Sean Callanan3989fb92011-01-27 01:07:04 +00001064
1065 // We don't print an error message here because RewriteObjCConstString has done so for us.
1066
Sean Callananafe16a72010-11-17 23:00:36 +00001067 return false;
1068 }
Sean Callananafe16a72010-11-17 23:00:36 +00001069 }
1070 }
1071
1072 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1073 vi != ve;
1074 ++vi)
1075 {
Sean Callanancc427fa2011-07-30 02:42:06 +00001076 std::string value_name = vi->first().str();
1077 const char *value_name_cstr = value_name.c_str();
1078
1079 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callananafe16a72010-11-17 23:00:36 +00001080 {
1081 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1082
1083 if (!gv)
1084 {
1085 if (log)
1086 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001087
1088 if (m_error_stream)
1089 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1090
Sean Callananafe16a72010-11-17 23:00:36 +00001091 return false;
1092 }
1093
1094 gv->eraseFromParent();
1095
1096 break;
1097 }
1098 }
1099
1100 return true;
1101}
1102
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001103static bool IsObjCSelectorRef (Value *value)
Sean Callanan5300d372010-07-31 01:32:05 +00001104{
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001105 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callanan5300d372010-07-31 01:32:05 +00001106
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001107 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callanan5300d372010-07-31 01:32:05 +00001108 return false;
1109
1110 return true;
1111}
1112
Sean Callanan3989fb92011-01-27 01:07:04 +00001113// This function does not report errors; its callers are responsible.
Sean Callanan5300d372010-07-31 01:32:05 +00001114bool
Sean Callanan79763a42011-05-23 21:40:23 +00001115IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callanan5300d372010-07-31 01:32:05 +00001116{
Greg Clayton5160ce52013-03-27 23:08:40 +00001117 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001118
1119 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1120
1121 if (!load)
1122 return false;
1123
1124 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1125 //
1126 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1127 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1128 //
1129 // where %obj is the object pointer and %tmp is the selector.
1130 //
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001131 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1132 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callanan5300d372010-07-31 01:32:05 +00001133
1134 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1135
1136 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1137
1138 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1139 return false;
1140
1141 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1142
1143 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1144
1145 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1146 return false;
1147
1148 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1149
1150 if (!osr_initializer_base)
1151 return false;
1152
1153 // Find the string's initializer (a ConstantArray) and get the string from it
1154
1155 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1156
1157 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1158 return false;
1159
1160 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1161
Sean Callanand2b465f2012-02-09 03:22:41 +00001162 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
Sean Callanan5300d372010-07-31 01:32:05 +00001163
1164 if (!omvn_initializer_array->isString())
1165 return false;
1166
1167 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1168
1169 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001170 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callanan5300d372010-07-31 01:32:05 +00001171
1172 // Construct a call to sel_registerName
1173
1174 if (!m_sel_registerName)
1175 {
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001176 lldb::addr_t sel_registerName_addr;
Sean Callanan5300d372010-07-31 01:32:05 +00001177
Greg Clayton7b462cc2010-10-15 22:48:33 +00001178 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001179 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callanan5300d372010-07-31 01:32:05 +00001180 return false;
1181
Sean Callananbe3a1b12010-10-26 00:31:56 +00001182 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001183 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
Sean Callananbe3a1b12010-10-26 00:31:56 +00001184
Sean Callanan5300d372010-07-31 01:32:05 +00001185 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1186
1187 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callanan79763a42011-05-23 21:40:23 +00001188 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001189 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanancc427fa2011-07-30 02:42:06 +00001190 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001191
Sean Callanancc427fa2011-07-30 02:42:06 +00001192 Type *type_array[1];
1193
1194 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1195
1196 ArrayRef<Type *> srN_arg_types(type_array, 1);
1197
Sean Callanan5300d372010-07-31 01:32:05 +00001198 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1199
1200 // Build the constant containing the pointer to the function
Sean Callanancc427fa2011-07-30 02:42:06 +00001201 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001202 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan5300d372010-07-31 01:32:05 +00001203 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001204 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callanan5300d372010-07-31 01:32:05 +00001205 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1206 }
1207
Sean Callanancc427fa2011-07-30 02:42:06 +00001208 Value *argument_array[1];
1209
Sean Callanan79763a42011-05-23 21:40:23 +00001210 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callanan5300d372010-07-31 01:32:05 +00001211
Sean Callanancc427fa2011-07-30 02:42:06 +00001212 argument_array[0] = omvn_pointer;
Sean Callanan5300d372010-07-31 01:32:05 +00001213
Sean Callanancc427fa2011-07-30 02:42:06 +00001214 ArrayRef<Value *> srN_arguments(argument_array, 1);
1215
Sean Callanan5300d372010-07-31 01:32:05 +00001216 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanancc427fa2011-07-30 02:42:06 +00001217 srN_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +00001218 "sel_registerName",
Sean Callanan5300d372010-07-31 01:32:05 +00001219 selector_load);
1220
1221 // Replace the load with the call in all users
1222
1223 selector_load->replaceAllUsesWith(srN_call);
1224
1225 selector_load->eraseFromParent();
1226
1227 return true;
1228}
1229
1230bool
Sean Callanan79763a42011-05-23 21:40:23 +00001231IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callanan5300d372010-07-31 01:32:05 +00001232{
Greg Clayton5160ce52013-03-27 23:08:40 +00001233 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001234
1235 BasicBlock::iterator ii;
1236
1237 typedef SmallVector <Instruction*, 2> InstrList;
1238 typedef InstrList::iterator InstrIterator;
1239
1240 InstrList selector_loads;
1241
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001242 for (ii = basic_block.begin();
1243 ii != basic_block.end();
Sean Callanan5300d372010-07-31 01:32:05 +00001244 ++ii)
1245 {
1246 Instruction &inst = *ii;
1247
1248 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001249 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callanan5300d372010-07-31 01:32:05 +00001250 selector_loads.push_back(&inst);
1251 }
1252
1253 InstrIterator iter;
1254
1255 for (iter = selector_loads.begin();
1256 iter != selector_loads.end();
1257 ++iter)
1258 {
Sean Callanan79763a42011-05-23 21:40:23 +00001259 if (!RewriteObjCSelector(*iter))
Sean Callanan5300d372010-07-31 01:32:05 +00001260 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001261 if (m_error_stream)
1262 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1263
Enrico Granata20edcdb2011-07-19 18:03:25 +00001264 if (log)
Sean Callanan5300d372010-07-31 01:32:05 +00001265 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan3989fb92011-01-27 01:07:04 +00001266
Sean Callanan5300d372010-07-31 01:32:05 +00001267 return false;
1268 }
1269 }
1270
1271 return true;
1272}
1273
Sean Callanan3989fb92011-01-27 01:07:04 +00001274// This function does not report errors; its callers are responsible.
Sean Callanan2235f322010-08-11 03:57:18 +00001275bool
Sean Callanan79763a42011-05-23 21:40:23 +00001276IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanan2235f322010-08-11 03:57:18 +00001277{
Greg Clayton5160ce52013-03-27 23:08:40 +00001278 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanane1175b72011-01-13 21:23:32 +00001279
Sean Callanan2235f322010-08-11 03:57:18 +00001280 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1281
1282 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1283
1284 if (!alloc_md || !alloc_md->getNumOperands())
1285 return false;
1286
1287 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1288
1289 if (!constant_int)
1290 return false;
1291
1292 // We attempt to register this as a new persistent variable with the DeclMap.
1293
1294 uintptr_t ptr = constant_int->getZExtValue();
1295
Sean Callanand1e5b432010-08-12 01:56:52 +00001296 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanan2235f322010-08-11 03:57:18 +00001297
Sean Callanand1e5b432010-08-12 01:56:52 +00001298 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1299 &decl->getASTContext());
1300
Greg Clayton7b462cc2010-10-15 22:48:33 +00001301 StringRef decl_name (decl->getName());
1302 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan92adcac2011-01-13 08:53:35 +00001303 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanan2235f322010-08-11 03:57:18 +00001304 return false;
1305
Sean Callanan79763a42011-05-23 21:40:23 +00001306 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanane1175b72011-01-13 21:23:32 +00001307 alloc->getType(),
Sean Callanan2235f322010-08-11 03:57:18 +00001308 false, /* not constant */
1309 GlobalValue::ExternalLinkage,
1310 NULL, /* no initializer */
1311 alloc->getName().str().c_str());
1312
1313 // What we're going to do here is make believe this was a regular old external
1314 // variable. That means we need to make the metadata valid.
1315
Sean Callanan585c0ec82012-07-04 01:26:26 +00001316 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
Sean Callanan2235f322010-08-11 03:57:18 +00001317
1318 llvm::Value* values[2];
1319 values[0] = persistent_global;
1320 values[1] = constant_int;
Sean Callanand12cf8bb2011-05-15 22:34:38 +00001321
1322 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanan2235f322010-08-11 03:57:18 +00001323
Sean Callanan79763a42011-05-23 21:40:23 +00001324 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanan2235f322010-08-11 03:57:18 +00001325 named_metadata->addOperand(persistent_global_md);
1326
Sean Callanane1175b72011-01-13 21:23:32 +00001327 // Now, since the variable is a pointer variable, we will drop in a load of that
1328 // pointer variable.
1329
1330 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1331
1332 if (log)
1333 log->Printf("Replacing \"%s\" with \"%s\"",
1334 PrintValue(alloc).c_str(),
1335 PrintValue(persistent_load).c_str());
1336
1337 alloc->replaceAllUsesWith(persistent_load);
Sean Callanan2235f322010-08-11 03:57:18 +00001338 alloc->eraseFromParent();
1339
1340 return true;
1341}
1342
1343bool
Sean Callanan79763a42011-05-23 21:40:23 +00001344IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanan2235f322010-08-11 03:57:18 +00001345{
Sean Callanan9e6ed532010-09-13 21:34:21 +00001346 if (!m_resolve_vars)
1347 return true;
1348
Greg Clayton5160ce52013-03-27 23:08:40 +00001349 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2235f322010-08-11 03:57:18 +00001350
1351 BasicBlock::iterator ii;
1352
1353 typedef SmallVector <Instruction*, 2> InstrList;
1354 typedef InstrList::iterator InstrIterator;
1355
1356 InstrList pvar_allocs;
1357
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001358 for (ii = basic_block.begin();
1359 ii != basic_block.end();
Sean Callanan2235f322010-08-11 03:57:18 +00001360 ++ii)
1361 {
1362 Instruction &inst = *ii;
1363
1364 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callananf694a552011-01-21 22:30:25 +00001365 {
1366 llvm::StringRef alloc_name = alloc->getName();
1367
1368 if (alloc_name.startswith("$") &&
1369 !alloc_name.startswith("$__lldb"))
1370 {
1371 if (alloc_name.find_first_of("0123456789") == 1)
1372 {
1373 if (log)
1374 log->Printf("Rejecting a numeric persistent variable.");
1375
Sean Callanan3989fb92011-01-27 01:07:04 +00001376 if (m_error_stream)
1377 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1378
Sean Callananf694a552011-01-21 22:30:25 +00001379 return false;
1380 }
1381
Sean Callanan2235f322010-08-11 03:57:18 +00001382 pvar_allocs.push_back(alloc);
Sean Callananf694a552011-01-21 22:30:25 +00001383 }
1384 }
Sean Callanan2235f322010-08-11 03:57:18 +00001385 }
1386
1387 InstrIterator iter;
1388
1389 for (iter = pvar_allocs.begin();
1390 iter != pvar_allocs.end();
1391 ++iter)
1392 {
Sean Callanan79763a42011-05-23 21:40:23 +00001393 if (!RewritePersistentAlloc(*iter))
Sean Callanan2235f322010-08-11 03:57:18 +00001394 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001395 if (m_error_stream)
1396 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1397
Enrico Granata20edcdb2011-07-19 18:03:25 +00001398 if (log)
Sean Callanan2235f322010-08-11 03:57:18 +00001399 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001400
Sean Callanan2235f322010-08-11 03:57:18 +00001401 return false;
1402 }
1403 }
1404
1405 return true;
1406}
1407
Sean Callananc70ed462011-10-25 18:36:40 +00001408bool
1409IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1410{
1411 if (!initializer)
1412 return true;
1413
Greg Clayton5160ce52013-03-27 23:08:40 +00001414 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc70ed462011-10-25 18:36:40 +00001415
1416 if (log && log->GetVerbose())
1417 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1418
1419 Type *initializer_type = initializer->getType();
1420
1421 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1422 {
1423 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1424 return true;
1425 }
Sean Callanand2b465f2012-02-09 03:22:41 +00001426 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
Sean Callananc70ed462011-10-25 18:36:40 +00001427 {
1428 if (array_initializer->isString())
1429 {
1430 std::string array_initializer_string = array_initializer->getAsString();
1431 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1432 }
1433 else
1434 {
1435 ArrayType *array_initializer_type = array_initializer->getType();
1436 Type *array_element_type = array_initializer_type->getElementType();
1437
1438 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1439
1440 for (int i = 0; i < array_initializer->getNumOperands(); ++i)
1441 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001442 Value *operand_value = array_initializer->getOperand(i);
1443 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1444
1445 if (!operand_constant)
1446 return false;
1447
1448 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
Sean Callananc70ed462011-10-25 18:36:40 +00001449 return false;
1450 }
1451 }
1452 return true;
1453 }
1454 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1455 {
1456 StructType *struct_initializer_type = struct_initializer->getType();
1457 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1458
1459 for (int i = 0;
1460 i < struct_initializer->getNumOperands();
1461 ++i)
1462 {
1463 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1464 return false;
1465 }
1466 return true;
1467 }
Sean Callanan76ee3e72013-04-24 19:50:12 +00001468 else if (isa<ConstantAggregateZero>(initializer))
1469 {
1470 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1471 return true;
1472 }
Sean Callananc70ed462011-10-25 18:36:40 +00001473 return false;
1474}
1475
1476bool
1477IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1478{
1479 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1480 return false;
1481
Sean Callananfe5d1392011-11-15 19:13:54 +00001482 if (global_variable == m_reloc_placeholder)
1483 return true;
1484
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001485 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callananc70ed462011-10-25 18:36:40 +00001486
1487 llvm::Type *variable_type = global_variable->getType();
1488
1489 Constant *initializer = global_variable->getInitializer();
1490
1491 llvm::Type *initializer_type = initializer->getType();
1492
1493 size_t size = m_target_data->getTypeAllocSize(initializer_type);
Sean Callanane3333d62012-06-08 22:20:41 +00001494 size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1495
1496 const size_t mask = (align - 1);
1497 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001498 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00001499 offset = aligned_offset;
Sean Callananc70ed462011-10-25 18:36:40 +00001500
1501 lldb_private::DataBufferHeap data(size, '\0');
1502
1503 if (initializer)
1504 if (!MaterializeInitializer(data.GetBytes(), initializer))
1505 return false;
1506
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001507 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
Sean Callananc70ed462011-10-25 18:36:40 +00001508
1509 Constant *new_pointer = BuildRelocation(variable_type, offset);
1510
1511 global_variable->replaceAllUsesWith(new_pointer);
1512
1513 global_variable->eraseFromParent();
1514
1515 return true;
1516}
1517
Sean Callanan3989fb92011-01-27 01:07:04 +00001518// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001519bool
Sean Callanan79763a42011-05-23 21:40:23 +00001520IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001521{
Greg Clayton5160ce52013-03-27 23:08:40 +00001522 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001523
1524 if (log)
Sean Callanan88339f02010-12-06 22:16:55 +00001525 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callananaf8e96c2011-08-01 17:41:38 +00001526
Greg Clayton7b462cc2010-10-15 22:48:33 +00001527 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callanan4cf04d22010-08-03 00:23:29 +00001528 {
Sean Callanan5666b672010-08-04 01:02:13 +00001529 switch (constant_expr->getOpcode())
Sean Callanan4cf04d22010-08-03 00:23:29 +00001530 {
Sean Callanan5666b672010-08-04 01:02:13 +00001531 default:
1532 break;
1533 case Instruction::GetElementPtr:
1534 case Instruction::BitCast:
Sean Callanan4cf04d22010-08-03 00:23:29 +00001535 Value *s = constant_expr->getOperand(0);
Sean Callanan79763a42011-05-23 21:40:23 +00001536 if (!MaybeHandleVariable(s))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001537 return false;
Sean Callanan4cf04d22010-08-03 00:23:29 +00001538 }
1539 }
Sean Callanand6e04ae2010-12-03 19:51:05 +00001540 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001541 {
Sean Callananc70ed462011-10-25 18:36:40 +00001542 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1543 return MaterializeInternalVariable(global_variable);
1544
Sean Callanan79763a42011-05-23 21:40:23 +00001545 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan2ab712f22010-07-03 01:35:46 +00001546
Sean Callanan5300d372010-07-31 01:32:05 +00001547 if (!named_decl)
1548 {
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001549 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001550 return true;
1551
Sean Callanan14f0b0e2010-12-06 00:56:39 +00001552 if (!global_variable->hasExternalLinkage())
1553 return true;
1554
Sean Callanan5300d372010-07-31 01:32:05 +00001555 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001556 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001557
Sean Callanan5300d372010-07-31 01:32:05 +00001558 return false;
1559 }
1560
Greg Clayton7b462cc2010-10-15 22:48:33 +00001561 std::string name (named_decl->getName().str());
Sean Callananea22d422010-07-16 00:09:46 +00001562
Sean Callanan038df5032010-09-30 21:18:25 +00001563 void *opaque_type = NULL;
Sean Callanan1d180662010-07-20 23:31:16 +00001564 clang::ASTContext *ast_context = NULL;
Sean Callananea22d422010-07-16 00:09:46 +00001565
1566 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callanan1d180662010-07-20 23:31:16 +00001567 {
Sean Callanan038df5032010-09-30 21:18:25 +00001568 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callanan1d180662010-07-20 23:31:16 +00001569 ast_context = &value_decl->getASTContext();
1570 }
Sean Callananea22d422010-07-16 00:09:46 +00001571 else
Sean Callanan1d180662010-07-20 23:31:16 +00001572 {
Sean Callananea22d422010-07-16 00:09:46 +00001573 return false;
Sean Callanan1d180662010-07-20 23:31:16 +00001574 }
Sean Callanan038df5032010-09-30 21:18:25 +00001575
Sean Callanan92adcac2011-01-13 08:53:35 +00001576 clang::QualType qual_type;
Sean Callanan77eaf442011-07-08 00:39:14 +00001577 const Type *value_type = NULL;
Sean Callanan92adcac2011-01-13 08:53:35 +00001578
Sean Callanane1175b72011-01-13 21:23:32 +00001579 if (name[0] == '$')
Sean Callanan92adcac2011-01-13 08:53:35 +00001580 {
1581 // The $__lldb_expr_result name indicates the the return value has allocated as
1582 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1583 // accesses to this static variable need to be redirected to the result of dereferencing
1584 // a pointer that is passed in as one of the arguments.
1585 //
1586 // Consequently, when reporting the size of the type, we report a pointer type pointing
1587 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanane1175b72011-01-13 21:23:32 +00001588 //
1589 // We also do this for any user-declared persistent variables.
Sean Callanan1d180662010-07-20 23:31:16 +00001590
Sean Callanan92adcac2011-01-13 08:53:35 +00001591 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1592 value_type = PointerType::get(global_variable->getType(), 0);
1593 }
1594 else
1595 {
1596 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1597 value_type = global_variable->getType();
1598 }
Sean Callanan038df5032010-09-30 21:18:25 +00001599
Greg Claytonfaac1112013-03-14 18:31:44 +00001600 uint64_t value_size = (ast_context->getTypeSize(qual_type) + 7ull) / 8ull;
1601 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7ull) / 8ull;
Sean Callanan17827832010-12-13 22:46:15 +00001602
Sean Callanan038df5032010-09-30 21:18:25 +00001603 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +00001604 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
Sean Callanan038df5032010-09-30 21:18:25 +00001605 name.c_str(),
1606 qual_type.getAsString().c_str(),
1607 PrintType(value_type).c_str(),
1608 value_size,
1609 value_alignment);
Sean Callanan17827832010-12-13 22:46:15 +00001610
Sean Callanan549c9f72010-07-13 21:41:46 +00001611
Sean Callanan64dfc9a2010-08-23 23:09:38 +00001612 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton7b462cc2010-10-15 22:48:33 +00001613 lldb_private::ConstString (name.c_str()),
1614 llvm_value_ptr,
Sean Callanan4edba2d2010-07-27 02:07:53 +00001615 value_size,
1616 value_alignment))
Sean Callananaf8e96c2011-08-01 17:41:38 +00001617 {
1618 if (!global_variable->hasExternalLinkage())
1619 return true;
Sean Callanan0ff3bf92013-04-11 17:57:16 +00001620 else if (HandleSymbol (global_variable))
1621 return true;
Sean Callananaf8e96c2011-08-01 17:41:38 +00001622 else
1623 return false;
1624 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001625 }
Sean Callanan4a5fcbb2010-12-03 03:02:31 +00001626 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001627 {
1628 if (log)
1629 log->Printf("Function pointers aren't handled right now");
1630
1631 return false;
1632 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001633
1634 return true;
1635}
1636
Sean Callanan3989fb92011-01-27 01:07:04 +00001637// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001638bool
Sean Callanan79763a42011-05-23 21:40:23 +00001639IRForTarget::HandleSymbol (Value *symbol)
Sean Callanand9ca42a2011-05-08 02:21:26 +00001640{
Greg Clayton5160ce52013-03-27 23:08:40 +00001641 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc3a16002011-01-17 23:42:46 +00001642
1643 lldb_private::ConstString name(symbol->getName().str().c_str());
1644
Sean Callanan947ccc72011-12-01 02:04:16 +00001645 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
Sean Callananc3a16002011-01-17 23:42:46 +00001646
Greg Clayton084db102011-06-23 04:25:29 +00001647 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc3a16002011-01-17 23:42:46 +00001648 {
1649 if (log)
1650 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1651
1652 return false;
1653 }
1654
1655 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001656 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
Sean Callananc3a16002011-01-17 23:42:46 +00001657
Sean Callanancc427fa2011-07-30 02:42:06 +00001658 Type *symbol_type = symbol->getType();
Sean Callanancc427fa2011-07-30 02:42:06 +00001659 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001660 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc3a16002011-01-17 23:42:46 +00001661
1662 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1663
1664 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1665
1666 if (log)
1667 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1668
1669 symbol->replaceAllUsesWith(symbol_addr_ptr);
1670
1671 return true;
1672}
1673
1674bool
Sean Callanan79763a42011-05-23 21:40:23 +00001675IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanan85a0a832010-10-05 22:26:43 +00001676{
Greg Clayton5160ce52013-03-27 23:08:40 +00001677 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001678
1679 if (log)
1680 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanan85a0a832010-10-05 22:26:43 +00001681
Sean Callananafe16a72010-11-17 23:00:36 +00001682 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanan85a0a832010-10-05 22:26:43 +00001683 op_index < num_ops;
1684 ++op_index)
Sean Callanan79763a42011-05-23 21:40:23 +00001685 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan3989fb92011-01-27 01:07:04 +00001686 {
1687 if (m_error_stream)
1688 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1689
Sean Callanan85a0a832010-10-05 22:26:43 +00001690 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001691 }
1692
Sean Callanan85a0a832010-10-05 22:26:43 +00001693 return true;
1694}
1695
1696bool
Sean Callananfc89c142011-11-01 23:38:03 +00001697IRForTarget::HandleObjCClass(Value *classlist_reference)
1698{
Greg Clayton5160ce52013-03-27 23:08:40 +00001699 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananfc89c142011-11-01 23:38:03 +00001700
1701 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1702
1703 if (!global_variable)
1704 return false;
1705
1706 Constant *initializer = global_variable->getInitializer();
1707
1708 if (!initializer)
1709 return false;
1710
1711 if (!initializer->hasName())
1712 return false;
1713
1714 StringRef name(initializer->getName());
1715 lldb_private::ConstString name_cstr(name.str().c_str());
Greg Clayton1075aca2011-12-03 20:02:42 +00001716 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
Sean Callananfc89c142011-11-01 23:38:03 +00001717
1718 if (log)
1719 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1720
1721 if (class_ptr == LLDB_INVALID_ADDRESS)
1722 return false;
1723
1724 if (global_variable->use_begin() == global_variable->use_end())
1725 return false;
1726
Sean Callanan719a4d52013-03-23 01:01:16 +00001727 SmallVector<LoadInst *, 2> load_instructions;
1728
Sean Callananfc89c142011-11-01 23:38:03 +00001729 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1730 i != e;
1731 ++i)
1732 {
Sean Callanan719a4d52013-03-23 01:01:16 +00001733 if (LoadInst *load_instruction = dyn_cast<LoadInst>(*i))
1734 load_instructions.push_back(load_instruction);
Sean Callananfc89c142011-11-01 23:38:03 +00001735 }
1736
Sean Callanan719a4d52013-03-23 01:01:16 +00001737 if (load_instructions.empty())
Sean Callananfc89c142011-11-01 23:38:03 +00001738 return false;
1739
1740 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001741 (m_module->getPointerSize()
Micah Villmow08318972012-10-11 17:21:41 +00001742 == Module::Pointer64) ? 64 : 32);
Sean Callananfc89c142011-11-01 23:38:03 +00001743
1744 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
Sean Callananfc89c142011-11-01 23:38:03 +00001745
Sean Callanan719a4d52013-03-23 01:01:16 +00001746 for (LoadInst *load_instruction : load_instructions)
1747 {
1748 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
Sean Callananfc89c142011-11-01 23:38:03 +00001749
Sean Callanan719a4d52013-03-23 01:01:16 +00001750 load_instruction->replaceAllUsesWith(class_bitcast);
1751
1752 load_instruction->eraseFromParent();
1753 }
Sean Callananfc89c142011-11-01 23:38:03 +00001754
1755 return true;
1756}
1757
1758bool
Sean Callanan6e6d4a62012-07-21 02:02:15 +00001759IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1760{
1761 BasicBlock::iterator ii;
1762
1763 std::vector<CallInst *> calls_to_remove;
1764
1765 for (ii = basic_block.begin();
1766 ii != basic_block.end();
1767 ++ii)
1768 {
1769 Instruction &inst = *ii;
1770
1771 CallInst *call = dyn_cast<CallInst>(&inst);
1772
1773 // MaybeHandleCallArguments handles error reporting; we are silent here
1774 if (!call)
1775 continue;
1776
1777 bool remove = false;
1778
1779 llvm::Function *func = call->getCalledFunction();
1780
1781 if (func && func->getName() == "__cxa_atexit")
1782 remove = true;
1783
1784 llvm::Value *val = call->getCalledValue();
1785
1786 if (val && val->getName() == "__cxa_atexit")
1787 remove = true;
1788
1789 if (remove)
1790 calls_to_remove.push_back(call);
1791 }
1792
1793 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1794 ci != ce;
1795 ++ci)
1796 {
1797 (*ci)->eraseFromParent();
1798 }
1799
1800 return true;
1801}
1802
1803bool
Sean Callanan79763a42011-05-23 21:40:23 +00001804IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan549c9f72010-07-13 21:41:46 +00001805{
Sean Callanan2ab712f22010-07-03 01:35:46 +00001806 /////////////////////////////////////////////////////////////////////////
1807 // Prepare the current basic block for execution in the remote process
1808 //
1809
Sean Callanan7ea35012010-07-27 21:39:39 +00001810 BasicBlock::iterator ii;
Sean Callanan549c9f72010-07-13 21:41:46 +00001811
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001812 for (ii = basic_block.begin();
1813 ii != basic_block.end();
Sean Callanan549c9f72010-07-13 21:41:46 +00001814 ++ii)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001815 {
Sean Callanan549c9f72010-07-13 21:41:46 +00001816 Instruction &inst = *ii;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001817
Sean Callanana4e55172010-11-08 00:31:32 +00001818 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callanan4edba2d2010-07-27 02:07:53 +00001819
Sean Callanan3989fb92011-01-27 01:07:04 +00001820 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callanan79763a42011-05-23 21:40:23 +00001821 if (call && !MaybeHandleCallArguments(call))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001822 return false;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001823 }
1824
1825 return true;
1826}
1827
Sean Callanana4e55172010-11-08 00:31:32 +00001828bool
Sean Callanan79763a42011-05-23 21:40:23 +00001829IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanana4e55172010-11-08 00:31:32 +00001830{
Greg Clayton5160ce52013-03-27 23:08:40 +00001831 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7a55a322010-11-18 22:21:58 +00001832
Sean Callanan79763a42011-05-23 21:40:23 +00001833 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanana4e55172010-11-08 00:31:32 +00001834 global != end;
1835 ++global)
1836 {
Sean Callanan694e2442011-12-22 21:24:49 +00001837 if (!global)
1838 {
1839 if (m_error_stream)
1840 m_error_stream->Printf("Internal error [IRForTarget]: global variable is NULL");
1841
1842 return false;
1843 }
1844
1845 std::string global_name = (*global).getName().str();
1846
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001847 if (log)
1848 log->Printf("Examining %s, DeclForGlobalValue returns %p",
Sean Callanan694e2442011-12-22 21:24:49 +00001849 global_name.c_str(),
Sean Callanan79763a42011-05-23 21:40:23 +00001850 DeclForGlobal(global));
Sean Callananfc89c142011-11-01 23:38:03 +00001851
1852 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc3a16002011-01-17 23:42:46 +00001853 {
Sean Callanan79763a42011-05-23 21:40:23 +00001854 if (!HandleSymbol(global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001855 {
1856 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001857 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 +00001858
Sean Callananc3a16002011-01-17 23:42:46 +00001859 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001860 }
Sean Callananc3a16002011-01-17 23:42:46 +00001861 }
Sean Callananfc89c142011-11-01 23:38:03 +00001862 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1863 {
1864 if (!HandleObjCClass(global))
1865 {
1866 if (m_error_stream)
1867 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1868
1869 return false;
1870 }
1871 }
Sean Callanan79763a42011-05-23 21:40:23 +00001872 else if (DeclForGlobal(global))
Sean Callananc3a16002011-01-17 23:42:46 +00001873 {
Sean Callanan79763a42011-05-23 21:40:23 +00001874 if (!MaybeHandleVariable (global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001875 {
1876 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001877 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 +00001878
Sean Callananc3a16002011-01-17 23:42:46 +00001879 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001880 }
Sean Callananc3a16002011-01-17 23:42:46 +00001881 }
Sean Callanana4e55172010-11-08 00:31:32 +00001882 }
1883
1884 return true;
1885}
1886
Sean Callanan79763a42011-05-23 21:40:23 +00001887bool
1888IRForTarget::ReplaceStrings ()
1889{
Greg Clayton5160ce52013-03-27 23:08:40 +00001890 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001891
Sean Callanan79763a42011-05-23 21:40:23 +00001892 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1893
1894 OffsetsTy offsets;
1895
1896 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1897 gi != ge;
1898 ++gi)
1899 {
1900 GlobalVariable *gv = gi;
1901
1902 if (!gv->hasInitializer())
1903 continue;
1904
1905 Constant *gc = gv->getInitializer();
1906
Sean Callanan5207a342011-08-10 21:05:52 +00001907 std::string str;
Sean Callanan79763a42011-05-23 21:40:23 +00001908
Sean Callanan5207a342011-08-10 21:05:52 +00001909 if (gc->isNullValue())
1910 {
1911 Type *gc_type = gc->getType();
1912
1913 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1914
1915 if (!gc_array_type)
1916 continue;
1917
1918 Type *gc_element_type = gc_array_type->getElementType();
1919
1920 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1921
1922 if (gc_integer_type->getBitWidth() != 8)
1923 continue;
1924
1925 str = "";
1926 }
1927 else
1928 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001929 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
Sean Callanan5207a342011-08-10 21:05:52 +00001930
1931 if (!gc_array)
1932 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001933
Sean Callanan5207a342011-08-10 21:05:52 +00001934 if (!gc_array->isCString())
1935 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001936
Sean Callanan5207a342011-08-10 21:05:52 +00001937 if (log)
1938 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00001939
Sean Callanan5207a342011-08-10 21:05:52 +00001940 str = gc_array->getAsString();
1941 }
1942
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001943 offsets[gv] = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00001944
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001945 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
Sean Callanan79763a42011-05-23 21:40:23 +00001946 }
1947
Sean Callanancc427fa2011-07-30 02:42:06 +00001948 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00001949
1950 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1951 oi != oe;
1952 ++oi)
1953 {
1954 GlobalVariable *gv = oi->first;
1955 size_t offset = oi->second;
1956
1957 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1958
1959 if (log)
1960 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1961
1962 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1963 ui != ue;
1964 ++ui)
1965 {
1966 if (log)
1967 log->Printf("Found use %s", PrintValue(*ui).c_str());
1968
1969 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1970 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1971
1972 if (const_expr)
1973 {
1974 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1975 {
1976 if (log)
1977 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1978
1979 return false;
1980 }
1981
Sean Callanan5207a342011-08-10 21:05:52 +00001982 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1983 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1984
1985 const_expr->replaceAllUsesWith(new_gep);
Sean Callanan79763a42011-05-23 21:40:23 +00001986 }
1987 else if (store_inst)
1988 {
1989 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1990
1991 store_inst->setOperand(0, bit_cast);
1992 }
1993 else
1994 {
1995 if (log)
1996 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1997
1998 return false;
1999 }
2000 }
2001
2002 gv->eraseFromParent();
2003 }
2004
2005 return true;
2006}
2007
2008bool
2009IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
2010{
Greg Clayton5160ce52013-03-27 23:08:40 +00002011 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002012
2013 typedef SmallVector <Value*, 2> ConstantList;
2014 typedef SmallVector <llvm::Instruction*, 2> UserList;
2015 typedef ConstantList::iterator ConstantIterator;
2016 typedef UserList::iterator UserIterator;
2017
2018 ConstantList static_constants;
2019 UserList static_users;
2020
2021 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
2022 ii != ie;
2023 ++ii)
2024 {
2025 llvm::Instruction &inst = *ii;
2026
2027 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
2028 oi != oe;
2029 ++oi)
2030 {
2031 Value *operand_val = oi->get();
2032
2033 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2034
Sean Callanan822944c2012-04-26 20:51:20 +00002035 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
Sean Callanan79763a42011-05-23 21:40:23 +00002036 {
2037 static_constants.push_back(operand_val);
2038 static_users.push_back(ii);
2039 }
2040 }
2041 }
2042
2043 ConstantIterator constant_iter;
2044 UserIterator user_iter;
Greg Clayton9b72eb72011-05-24 23:06:02 +00002045
Sean Callanan79763a42011-05-23 21:40:23 +00002046 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
2047 constant_iter != static_constants.end();
2048 ++constant_iter, ++user_iter)
2049 {
2050 Value *operand_val = *constant_iter;
2051 llvm::Instruction *inst = *user_iter;
2052
2053 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2054
2055 if (operand_constant_fp)
2056 {
Sean Callanan1582ee62013-04-18 22:06:33 +00002057 Type *operand_type = operand_constant_fp->getType();
2058
Sean Callanan79763a42011-05-23 21:40:23 +00002059 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2060 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2061
2062 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2063 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2064
2065 if (log)
2066 {
2067 std::string s;
2068 raw_string_ostream ss(s);
2069 for (size_t index = 0;
2070 index < operand_data_size;
2071 ++index)
2072 {
2073 ss << (uint32_t)operand_raw_data[index];
2074 ss << " ";
2075 }
2076 ss.flush();
2077
Jason Molendafd54b362011-09-20 21:44:10 +00002078 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00002079 }
2080
2081 lldb_private::DataBufferHeap data(operand_data_size, 0);
2082
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002083 if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
Sean Callanan79763a42011-05-23 21:40:23 +00002084 {
2085 uint8_t *data_bytes = data.GetBytes();
2086
2087 for (size_t index = 0;
2088 index < operand_data_size;
2089 ++index)
2090 {
2091 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2092 }
2093 }
2094 else
2095 {
2096 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2097 }
2098
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002099 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00002100
Sean Callanane3333d62012-06-08 22:20:41 +00002101 size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2102
2103 const size_t mask = (align - 1);
2104 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002105 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00002106 offset = aligned_offset;
2107
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002108 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
Sean Callanan79763a42011-05-23 21:40:23 +00002109
Sean Callanancc427fa2011-07-30 02:42:06 +00002110 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callanan79763a42011-05-23 21:40:23 +00002111
Sean Callanan1582ee62013-04-18 22:06:33 +00002112 Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
Sean Callanan79763a42011-05-23 21:40:23 +00002113
2114 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2115
2116 operand_constant_fp->replaceAllUsesWith(fp_load);
2117 }
2118 }
2119
2120 return true;
2121}
2122
Sean Callanan7ea35012010-07-27 21:39:39 +00002123static bool isGuardVariableRef(Value *V)
Sean Callananddb46ef2010-07-24 01:37:44 +00002124{
Sean Callanan77eaf442011-07-08 00:39:14 +00002125 Constant *Old = NULL;
Sean Callananddb46ef2010-07-24 01:37:44 +00002126
Sean Callananafe16a72010-11-17 23:00:36 +00002127 if (!(Old = dyn_cast<Constant>(V)))
Sean Callananddb46ef2010-07-24 01:37:44 +00002128 return false;
2129
Sean Callanan77eaf442011-07-08 00:39:14 +00002130 ConstantExpr *CE = NULL;
Sean Callanane2ef6e32010-09-23 03:01:22 +00002131
2132 if ((CE = dyn_cast<ConstantExpr>(V)))
2133 {
2134 if (CE->getOpcode() != Instruction::BitCast)
2135 return false;
2136
Sean Callananafe16a72010-11-17 23:00:36 +00002137 Old = CE->getOperand(0);
Sean Callanane2ef6e32010-09-23 03:01:22 +00002138 }
2139
Sean Callananafe16a72010-11-17 23:00:36 +00002140 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callananddb46ef2010-07-24 01:37:44 +00002141
2142 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2143 return false;
2144
2145 return true;
2146}
2147
Sean Callanan79763a42011-05-23 21:40:23 +00002148void
2149IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callananddb46ef2010-07-24 01:37:44 +00002150{
Sean Callanan79763a42011-05-23 21:40:23 +00002151 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callananddb46ef2010-07-24 01:37:44 +00002152
2153 Value::use_iterator ui;
2154
2155 for (ui = guard_load->use_begin();
2156 ui != guard_load->use_end();
2157 ++ui)
Sean Callananb27a62f2010-07-27 01:17:28 +00002158 {
Greg Claytone6371122010-07-30 20:30:44 +00002159 if (isa<Constant>(*ui))
Sean Callananb27a62f2010-07-27 01:17:28 +00002160 {
2161 // do nothing for the moment
2162 }
2163 else
2164 {
2165 ui->replaceUsesOfWith(guard_load, zero);
2166 }
2167 }
Sean Callananddb46ef2010-07-24 01:37:44 +00002168
2169 guard_load->eraseFromParent();
2170}
2171
2172static void ExciseGuardStore(Instruction* guard_store)
2173{
2174 guard_store->eraseFromParent();
2175}
2176
2177bool
Sean Callanan79763a42011-05-23 21:40:23 +00002178IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callananddb46ef2010-07-24 01:37:44 +00002179{
2180 ///////////////////////////////////////////////////////
2181 // Eliminate any reference to guard variables found.
2182 //
2183
Sean Callanan7ea35012010-07-27 21:39:39 +00002184 BasicBlock::iterator ii;
Sean Callananddb46ef2010-07-24 01:37:44 +00002185
Sean Callanan7ea35012010-07-27 21:39:39 +00002186 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callananddb46ef2010-07-24 01:37:44 +00002187 typedef InstrList::iterator InstrIterator;
2188
2189 InstrList guard_loads;
2190 InstrList guard_stores;
2191
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002192 for (ii = basic_block.begin();
2193 ii != basic_block.end();
Sean Callananddb46ef2010-07-24 01:37:44 +00002194 ++ii)
2195 {
2196 Instruction &inst = *ii;
2197
2198 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2199 if (isGuardVariableRef(load->getPointerOperand()))
2200 guard_loads.push_back(&inst);
2201
2202 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2203 if (isGuardVariableRef(store->getPointerOperand()))
2204 guard_stores.push_back(&inst);
2205 }
2206
2207 InstrIterator iter;
2208
2209 for (iter = guard_loads.begin();
2210 iter != guard_loads.end();
2211 ++iter)
Sean Callanan79763a42011-05-23 21:40:23 +00002212 TurnGuardLoadIntoZero(*iter);
Sean Callananddb46ef2010-07-24 01:37:44 +00002213
2214 for (iter = guard_stores.begin();
2215 iter != guard_stores.end();
2216 ++iter)
2217 ExciseGuardStore(*iter);
2218
2219 return true;
2220}
2221
Sean Callanan3989fb92011-01-27 01:07:04 +00002222// This function does not report errors; its callers are responsible.
Sean Callananafe16a72010-11-17 23:00:36 +00002223bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002224IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callanan7618f4e2010-07-14 23:40:29 +00002225{
Greg Clayton5160ce52013-03-27 23:08:40 +00002226 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002227
2228 Value::use_iterator ui;
2229
Sean Callanan2235f322010-08-11 03:57:18 +00002230 SmallVector<User*, 16> users;
2231
2232 // We do this because the use list might change, invalidating our iterator.
2233 // Much better to keep a work list ourselves.
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002234 for (ui = old_constant->use_begin();
2235 ui != old_constant->use_end();
Sean Callanan7618f4e2010-07-14 23:40:29 +00002236 ++ui)
Sean Callanan2235f322010-08-11 03:57:18 +00002237 users.push_back(*ui);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002238
Johnny Chen44805302011-07-19 19:48:13 +00002239 for (size_t i = 0;
Sean Callanan2235f322010-08-11 03:57:18 +00002240 i < users.size();
2241 ++i)
2242 {
2243 User *user = users[i];
2244
Sean Callanan7618f4e2010-07-14 23:40:29 +00002245 if (Constant *constant = dyn_cast<Constant>(user))
2246 {
2247 // synthesize a new non-constant equivalent of the constant
2248
2249 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2250 {
2251 switch (constant_expr->getOpcode())
2252 {
2253 default:
2254 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002255 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002256 return false;
2257 case Instruction::BitCast:
2258 {
2259 // UnaryExpr
2260 // OperandList[0] is value
2261
2262 Value *s = constant_expr->getOperand(0);
2263
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002264 if (s == old_constant)
2265 s = new_constant;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002266
Sean Callanan79763a42011-05-23 21:40:23 +00002267 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002268
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002269 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002270 }
2271 break;
2272 case Instruction::GetElementPtr:
2273 {
2274 // GetElementPtrConstantExpr
2275 // OperandList[0] is base
2276 // OperandList[1]... are indices
2277
2278 Value *ptr = constant_expr->getOperand(0);
2279
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002280 if (ptr == old_constant)
2281 ptr = new_constant;
Sean Callanancc427fa2011-07-30 02:42:06 +00002282
2283 std::vector<Value*> index_vector;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002284
2285 unsigned operand_index;
2286 unsigned num_operands = constant_expr->getNumOperands();
2287
2288 for (operand_index = 1;
2289 operand_index < num_operands;
2290 ++operand_index)
2291 {
2292 Value *operand = constant_expr->getOperand(operand_index);
2293
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002294 if (operand == old_constant)
2295 operand = new_constant;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002296
Sean Callanancc427fa2011-07-30 02:42:06 +00002297 index_vector.push_back(operand);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002298 }
2299
Sean Callanancc427fa2011-07-30 02:42:06 +00002300 ArrayRef <Value*> indices(index_vector);
2301
2302 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002303
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002304 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002305 }
2306 break;
2307 }
2308 }
2309 else
2310 {
2311 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002312 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002313 return false;
2314 }
2315 }
2316 else
2317 {
2318 // simple fall-through case for non-constants
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002319 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002320 }
2321 }
2322
2323 return true;
2324}
2325
Sean Callanan549c9f72010-07-13 21:41:46 +00002326bool
Sean Callanan79763a42011-05-23 21:40:23 +00002327IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan549c9f72010-07-13 21:41:46 +00002328{
Sean Callanan9e6ed532010-09-13 21:34:21 +00002329 if (!m_resolve_vars)
2330 return true;
2331
Greg Clayton5160ce52013-03-27 23:08:40 +00002332 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan549c9f72010-07-13 21:41:46 +00002333
2334 m_decl_map->DoStructLayout();
2335
2336 if (log)
2337 log->Printf("Element arrangement:");
2338
2339 uint32_t num_elements;
2340 uint32_t element_index;
2341
2342 size_t size;
2343 off_t alignment;
2344
2345 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2346 return false;
2347
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002348 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan549c9f72010-07-13 21:41:46 +00002349
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002350 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002351 {
2352 if (m_error_stream)
2353 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2354
Sean Callanan549c9f72010-07-13 21:41:46 +00002355 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002356 }
2357
Sean Callanan7ea35012010-07-27 21:39:39 +00002358 Argument *argument = iter;
Sean Callanan549c9f72010-07-13 21:41:46 +00002359
Sean Callananfc55f5d2010-09-21 00:44:12 +00002360 if (argument->getName().equals("this"))
2361 {
2362 ++iter;
2363
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002364 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002365 {
2366 if (m_error_stream)
2367 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2368
Sean Callananfc55f5d2010-09-21 00:44:12 +00002369 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002370 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002371
2372 argument = iter;
2373 }
Sean Callanan17827832010-12-13 22:46:15 +00002374 else if (argument->getName().equals("self"))
2375 {
2376 ++iter;
2377
2378 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002379 {
2380 if (m_error_stream)
2381 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2382
Sean Callanan17827832010-12-13 22:46:15 +00002383 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002384 }
Sean Callanan17827832010-12-13 22:46:15 +00002385
2386 if (!iter->getName().equals("_cmd"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002387 {
2388 if (m_error_stream)
2389 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2390
Sean Callanan17827832010-12-13 22:46:15 +00002391 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002392 }
Sean Callanan17827832010-12-13 22:46:15 +00002393
2394 ++iter;
2395
2396 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002397 {
2398 if (m_error_stream)
2399 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2400
Sean Callanan17827832010-12-13 22:46:15 +00002401 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002402 }
Sean Callanan17827832010-12-13 22:46:15 +00002403
2404 argument = iter;
2405 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002406
Greg Clayton7b462cc2010-10-15 22:48:33 +00002407 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002408 {
2409 if (m_error_stream)
2410 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2411
Sean Callanan549c9f72010-07-13 21:41:46 +00002412 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002413 }
2414
Sean Callanan549c9f72010-07-13 21:41:46 +00002415 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002416 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan549c9f72010-07-13 21:41:46 +00002417
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002418 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +00002419 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan549c9f72010-07-13 21:41:46 +00002420
Sean Callananafe16a72010-11-17 23:00:36 +00002421 if (!FirstEntryInstruction)
Sean Callanan3989fb92011-01-27 01:07:04 +00002422 {
2423 if (m_error_stream)
2424 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2425
Sean Callanan549c9f72010-07-13 21:41:46 +00002426 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002427 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002428
Sean Callanan79763a42011-05-23 21:40:23 +00002429 LLVMContext &context(m_module->getContext());
Sean Callanancc427fa2011-07-30 02:42:06 +00002430 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan549c9f72010-07-13 21:41:46 +00002431
2432 if (!offset_type)
Sean Callanan3989fb92011-01-27 01:07:04 +00002433 {
2434 if (m_error_stream)
2435 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2436
Sean Callanan549c9f72010-07-13 21:41:46 +00002437 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002438 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002439
2440 for (element_index = 0; element_index < num_elements; ++element_index)
2441 {
Sean Callanan77eaf442011-07-08 00:39:14 +00002442 const clang::NamedDecl *decl = NULL;
2443 Value *value = NULL;
Sean Callanan549c9f72010-07-13 21:41:46 +00002444 off_t offset;
Greg Clayton7b462cc2010-10-15 22:48:33 +00002445 lldb_private::ConstString name;
Sean Callanan549c9f72010-07-13 21:41:46 +00002446
Sean Callanan823bb4c2010-08-30 22:17:16 +00002447 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan3989fb92011-01-27 01:07:04 +00002448 {
2449 if (m_error_stream)
2450 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2451
Sean Callanan549c9f72010-07-13 21:41:46 +00002452 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002453 }
2454
Sean Callanan549c9f72010-07-13 21:41:46 +00002455 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002456 log->Printf(" \"%s\" (\"%s\") placed at %" PRId64,
Greg Clayton7b462cc2010-10-15 22:48:33 +00002457 name.GetCString(),
Sean Callananc70ed462011-10-25 18:36:40 +00002458 decl->getNameAsString().c_str(),
Sean Callanan549c9f72010-07-13 21:41:46 +00002459 offset);
2460
Sean Callanancc427fa2011-07-30 02:42:06 +00002461 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callananafe16a72010-11-17 23:00:36 +00002462 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan92adcac2011-01-13 08:53:35 +00002463
Sean Callananc70ed462011-10-25 18:36:40 +00002464 if (value)
Sean Callanan92adcac2011-01-13 08:53:35 +00002465 {
Sean Callananc70ed462011-10-25 18:36:40 +00002466 Value *replacement = NULL;
Sean Callanan92adcac2011-01-13 08:53:35 +00002467
Sean Callananc70ed462011-10-25 18:36:40 +00002468 if (log)
2469 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan92adcac2011-01-13 08:53:35 +00002470
Sean Callananc70ed462011-10-25 18:36:40 +00002471 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2472 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2473 // entry in order to produce the static variable that the AST thinks it is accessing.
2474 if (name == m_result_name && !m_result_is_pointer)
2475 {
2476 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2477
2478 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2479
2480 replacement = load;
2481 }
2482 else
2483 {
2484 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2485
2486 replacement = bit_cast;
2487 }
2488
2489 if (Constant *constant = dyn_cast<Constant>(value))
2490 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2491 else
2492 value->replaceAllUsesWith(replacement);
2493
2494 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2495 var->eraseFromParent();
2496 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002497 }
2498
2499 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002500 log->Printf("Total structure [align %" PRId64 ", size %lu]", alignment, size);
Sean Callanan549c9f72010-07-13 21:41:46 +00002501
2502 return true;
2503}
2504
Sean Callanan79763a42011-05-23 21:40:23 +00002505llvm::Constant *
Greg Clayton5160ce52013-03-27 23:08:40 +00002506IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
Sean Callanan79763a42011-05-23 21:40:23 +00002507{
Sean Callanancc427fa2011-07-30 02:42:06 +00002508 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00002509 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan79763a42011-05-23 21:40:23 +00002510
2511 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanancc427fa2011-07-30 02:42:06 +00002512
2513 llvm::Constant *offset_array[1];
2514
2515 offset_array[0] = offset_int;
2516
2517 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2518
2519 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callanan79763a42011-05-23 21:40:23 +00002520 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2521
2522 return reloc_getbitcast;
2523}
2524
2525bool
2526IRForTarget::CompleteDataAllocation ()
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002527{
Greg Clayton5160ce52013-03-27 23:08:40 +00002528 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002529
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002530 if (!m_data_allocator.GetStream().GetSize())
Sean Callanan79763a42011-05-23 21:40:23 +00002531 return true;
2532
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002533 lldb::addr_t allocation = m_data_allocator.Allocate();
Sean Callanan79763a42011-05-23 21:40:23 +00002534
2535 if (log)
2536 {
2537 if (allocation)
2538 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2539 else
2540 log->Printf("Failed to allocate static data");
2541 }
2542
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002543 if (!allocation || allocation == LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +00002544 return false;
2545
Sean Callanancc427fa2011-07-30 02:42:06 +00002546 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00002547 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan79763a42011-05-23 21:40:23 +00002548
2549 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2550 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2551
2552 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2553
2554 m_reloc_placeholder->eraseFromParent();
2555
2556 return true;
2557}
2558
Sean Callanan2ab712f22010-07-03 01:35:46 +00002559bool
Sean Callanan3d654b32012-09-24 22:25:51 +00002560IRForTarget::StripAllGVs (Module &llvm_module)
2561{
Greg Clayton5160ce52013-03-27 23:08:40 +00002562 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3d654b32012-09-24 22:25:51 +00002563 std::vector<GlobalVariable *> global_vars;
2564 std::set<GlobalVariable *>erased_vars;
2565
2566 bool erased = true;
2567
2568 while (erased)
2569 {
2570 erased = false;
2571
2572 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2573 gi != ge;
2574 ++gi)
2575 {
2576 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2577
2578 global_var->removeDeadConstantUsers();
2579
2580 if (global_var->use_empty())
2581 {
2582 if (log)
2583 log->Printf("Did remove %s",
2584 PrintValue(global_var).c_str());
2585 global_var->eraseFromParent();
2586 erased = true;
2587 break;
2588 }
2589 }
2590 }
2591
2592 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2593 gi != ge;
2594 ++gi)
2595 {
2596 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2597
2598 GlobalValue::use_iterator ui = global_var->use_begin();
2599
Jim Inghamd77557d2012-11-26 19:54:04 +00002600 if (log)
2601 log->Printf("Couldn't remove %s because of %s",
2602 PrintValue(global_var).c_str(),
2603 PrintValue(*ui).c_str());
Sean Callanan3d654b32012-09-24 22:25:51 +00002604 }
2605
2606 return true;
2607}
2608
2609bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002610IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002611{
Greg Clayton5160ce52013-03-27 23:08:40 +00002612 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002613
Sean Callanan79763a42011-05-23 21:40:23 +00002614 m_module = &llvm_module;
Micah Villmow8468dbe2012-10-08 16:28:57 +00002615 m_target_data.reset(new DataLayout(m_module));
Sean Callanan79763a42011-05-23 21:40:23 +00002616
2617 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002618
2619 if (!function)
2620 {
2621 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002622 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00002623
2624 if (m_error_stream)
Sean Callanan79763a42011-05-23 21:40:23 +00002625 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 +00002626
Sean Callanan2ab712f22010-07-03 01:35:46 +00002627 return false;
2628 }
Sean Callanan79763a42011-05-23 21:40:23 +00002629
2630 if (!FixFunctionLinkage (*function))
2631 {
2632 if (log)
2633 log->Printf("Couldn't fix the linkage for the function");
2634
2635 return false;
2636 }
2637
Sean Callananc70ed462011-10-25 18:36:40 +00002638 if (log)
2639 {
2640 std::string s;
2641 raw_string_ostream oss(s);
2642
2643 m_module->print(oss, NULL);
2644
2645 oss.flush();
2646
2647 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2648 }
2649
Sean Callanancc427fa2011-07-30 02:42:06 +00002650 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00002651
2652 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2653 intptr_ty,
Sean Callanan3d654b32012-09-24 22:25:51 +00002654 false /* IsConstant */,
Sean Callanan79763a42011-05-23 21:40:23 +00002655 GlobalVariable::InternalLinkage,
2656 Constant::getNullValue(intptr_ty),
2657 "reloc_placeholder",
2658 NULL /* InsertBefore */,
Sean Callanan3d654b32012-09-24 22:25:51 +00002659 GlobalVariable::NotThreadLocal /* ThreadLocal */,
Sean Callanan79763a42011-05-23 21:40:23 +00002660 0 /* AddressSpace */);
Sean Callanan2ab712f22010-07-03 01:35:46 +00002661
Sean Callanan7ea35012010-07-27 21:39:39 +00002662 Function::iterator bbi;
Sean Callanan2ab712f22010-07-03 01:35:46 +00002663
Sean Callanan79763a42011-05-23 21:40:23 +00002664 m_has_side_effects = HasSideEffects(*function);
Sean Callanane4ec90e2010-12-16 03:17:46 +00002665
Sean Callanand1e5b432010-08-12 01:56:52 +00002666 ////////////////////////////////////////////////////////////
Greg Clayton7b462cc2010-10-15 22:48:33 +00002667 // Replace $__lldb_expr_result with a persistent variable
Sean Callanand1e5b432010-08-12 01:56:52 +00002668 //
2669
Sean Callanan79763a42011-05-23 21:40:23 +00002670 if (!CreateResultVariable(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002671 {
2672 if (log)
2673 log->Printf("CreateResultVariable() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002674
2675 // CreateResultVariable() reports its own errors, so we don't do so here
2676
Sean Callanand1e5b432010-08-12 01:56:52 +00002677 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002678 }
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002679
2680 for (bbi = function->begin();
2681 bbi != function->end();
2682 ++bbi)
2683 {
2684 if (!RemoveGuards(*bbi))
2685 {
2686 if (log)
2687 log->Printf("RemoveGuards() failed");
2688
2689 // RemoveGuards() reports its own errors, so we don't do so here
2690
2691 return false;
2692 }
2693
2694 if (!RewritePersistentAllocs(*bbi))
2695 {
2696 if (log)
2697 log->Printf("RewritePersistentAllocs() failed");
2698
2699 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2700
2701 return false;
2702 }
Sean Callanan6e6d4a62012-07-21 02:02:15 +00002703
2704 if (!RemoveCXAAtExit(*bbi))
2705 {
2706 if (log)
2707 log->Printf("RemoveCXAAtExit() failed");
2708
2709 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2710
2711 return false;
2712 }
Sean Callanan3bfdaa22011-09-15 02:13:07 +00002713 }
2714
Sean Callananea685ae2011-11-01 17:33:54 +00002715 if (log && log->GetVerbose())
Sean Callanan79763a42011-05-23 21:40:23 +00002716 {
2717 std::string s;
2718 raw_string_ostream oss(s);
2719
2720 m_module->print(oss, NULL);
2721
2722 oss.flush();
2723
2724 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2725 }
2726
Sean Callananafe16a72010-11-17 23:00:36 +00002727 ///////////////////////////////////////////////////////////////////////////////
2728 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2729 //
Sean Callananafe16a72010-11-17 23:00:36 +00002730
Sean Callanan79763a42011-05-23 21:40:23 +00002731 if (!RewriteObjCConstStrings(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002732 {
2733 if (log)
2734 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002735
2736 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2737
Sean Callananafe16a72010-11-17 23:00:36 +00002738 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002739 }
Sean Callananafe16a72010-11-17 23:00:36 +00002740
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002741 ///////////////////////////////
2742 // Resolve function pointers
2743 //
2744
2745 if (!ResolveFunctionPointers(llvm_module, *function))
2746 {
2747 if (log)
2748 log->Printf("ResolveFunctionPointers() failed");
2749
2750 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2751
2752 return false;
2753 }
2754
Sean Callanan2ab712f22010-07-03 01:35:46 +00002755 for (bbi = function->begin();
2756 bbi != function->end();
2757 ++bbi)
2758 {
Sean Callanan79763a42011-05-23 21:40:23 +00002759 if (!RewriteObjCSelectors(*bbi))
Sean Callanan17827832010-12-13 22:46:15 +00002760 {
2761 if (log)
2762 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002763
2764 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2765
Sean Callanan2235f322010-08-11 03:57:18 +00002766 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002767 }
Sean Callananbad134f2012-07-27 19:25:24 +00002768 }
Sean Callanan2235f322010-08-11 03:57:18 +00002769
Sean Callananbad134f2012-07-27 19:25:24 +00002770 for (bbi = function->begin();
2771 bbi != function->end();
2772 ++bbi)
2773 {
Sean Callanan79763a42011-05-23 21:40:23 +00002774 if (!ResolveCalls(*bbi))
Sean Callanan17827832010-12-13 22:46:15 +00002775 {
2776 if (log)
2777 log->Printf("ResolveCalls() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002778
2779 // ResolveCalls() reports its own errors, so we don't do so here
2780
Sean Callanan549c9f72010-07-13 21:41:46 +00002781 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002782 }
Sean Callanan79763a42011-05-23 21:40:23 +00002783
2784 if (!ReplaceStaticLiterals(*bbi))
2785 {
2786 if (log)
2787 log->Printf("ReplaceStaticLiterals() failed");
2788
2789 return false;
2790 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002791 }
2792
Sean Callanan038df5032010-09-30 21:18:25 +00002793 ///////////////////////////////
2794 // Run function-level passes
2795 //
2796
Sean Callanan79763a42011-05-23 21:40:23 +00002797 if (!ResolveExternals(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002798 {
2799 if (log)
2800 log->Printf("ResolveExternals() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002801
2802 // ResolveExternals() reports its own errors, so we don't do so here
2803
Sean Callanana4e55172010-11-08 00:31:32 +00002804 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002805 }
Sean Callanana4e55172010-11-08 00:31:32 +00002806
Sean Callanan79763a42011-05-23 21:40:23 +00002807 if (!ReplaceVariables(*function))
Sean Callanan17827832010-12-13 22:46:15 +00002808 {
2809 if (log)
2810 log->Printf("ReplaceVariables() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002811
2812 // ReplaceVariables() reports its own errors, so we don't do so here
2813
Sean Callanan038df5032010-09-30 21:18:25 +00002814 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002815 }
Sean Callanan038df5032010-09-30 21:18:25 +00002816
Sean Callanan79763a42011-05-23 21:40:23 +00002817 if (!ReplaceStrings())
2818 {
2819 if (log)
2820 log->Printf("ReplaceStrings() failed");
2821
2822 return false;
2823 }
2824
2825 if (!CompleteDataAllocation())
2826 {
2827 if (log)
2828 log->Printf("CompleteDataAllocation() failed");
2829
2830 return false;
2831 }
2832
Sean Callanan3d654b32012-09-24 22:25:51 +00002833 if (!StripAllGVs(llvm_module))
2834 {
2835 if (log)
2836 log->Printf("StripAllGVs() failed");
2837 }
2838
Sean Callananea685ae2011-11-01 17:33:54 +00002839 if (log && log->GetVerbose())
Sean Callanan549c9f72010-07-13 21:41:46 +00002840 {
Sean Callanancc54bd32010-07-28 01:00:59 +00002841 std::string s;
2842 raw_string_ostream oss(s);
Sean Callanan549c9f72010-07-13 21:41:46 +00002843
Sean Callanan79763a42011-05-23 21:40:23 +00002844 m_module->print(oss, NULL);
Sean Callanancc54bd32010-07-28 01:00:59 +00002845
2846 oss.flush();
2847
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002848 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan2ab712f22010-07-03 01:35:46 +00002849 }
2850
2851 return true;
2852}
2853
2854void
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002855IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002856{
2857}
2858
2859PassManagerType
2860IRForTarget::getPotentialPassManagerType() const
2861{
2862 return PMT_ModulePassManager;
2863}