blob: 37b424056e548cd80f79aee38dfb383ecd0b3367 [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 Callanan1f9db3e2013-06-28 21:44:15 +000050IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) :
51 m_maker(maker),
52 m_values()
53{
54}
55
56IRForTarget::FunctionValueCache::~FunctionValueCache()
57{
58}
59
60llvm::Value *IRForTarget::FunctionValueCache::GetValue(llvm::Function *function)
61{
62 if (!m_values.count(function))
63 {
64 llvm::Value *ret = m_maker(function);
65 m_values[function] = ret;
66 return ret;
67 }
68 return m_values[function];
69}
70
Sean Callanan8dfb68e2013-03-19 00:10:07 +000071lldb::addr_t IRForTarget::StaticDataAllocator::Allocate()
Sean Callanan79763a42011-05-23 21:40:23 +000072{
Sean Callanan8dfb68e2013-03-19 00:10:07 +000073 lldb_private::Error err;
74
75 if (m_allocation != LLDB_INVALID_ADDRESS)
76 {
77 m_execution_unit.FreeNow(m_allocation);
78 m_allocation = LLDB_INVALID_ADDRESS;
79 }
80
81 m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
82
83 return m_allocation;
Sean Callanan79763a42011-05-23 21:40:23 +000084}
85
Sean Callanan1f9db3e2013-06-28 21:44:15 +000086static llvm::Value *FindEntryInstruction (llvm::Function *function)
87{
88 if (function->empty())
89 return NULL;
90
91 return function->getEntryBlock().getFirstNonPHIOrDbg();
92}
93
Greg Clayton1b95a6f2010-11-19 01:05:25 +000094IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
95 bool resolve_vars,
Sean Callanan8dfb68e2013-03-19 00:10:07 +000096 lldb_private::IRExecutionUnit &execution_unit,
Sean Callanan3989fb92011-01-27 01:07:04 +000097 lldb_private::Stream *error_stream,
Greg Clayton1b95a6f2010-11-19 01:05:25 +000098 const char *func_name) :
Sean Callanane2ef6e32010-09-23 03:01:22 +000099 ModulePass(ID),
Stephen Wilson71c21d12011-04-11 19:41:40 +0000100 m_resolve_vars(resolve_vars),
101 m_func_name(func_name),
Sean Callanan79763a42011-05-23 21:40:23 +0000102 m_module(NULL),
Johnny Chen44805302011-07-19 19:48:13 +0000103 m_decl_map(decl_map),
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000104 m_data_allocator(execution_unit),
Sean Callananafe16a72010-11-17 23:00:36 +0000105 m_CFStringCreateWithBytes(NULL),
Sean Callanan1a8d4092010-08-27 01:01:44 +0000106 m_sel_registerName(NULL),
Stephen Wilson71c21d12011-04-11 19:41:40 +0000107 m_error_stream(error_stream),
Sean Callanan63697e52011-05-07 01:06:41 +0000108 m_result_store(NULL),
109 m_result_is_pointer(false),
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000110 m_reloc_placeholder(NULL),
111 m_entry_instruction_finder (FindEntryInstruction)
Sean Callanan2ab712f22010-07-03 01:35:46 +0000112{
113}
114
Sean Callanan038df5032010-09-30 21:18:25 +0000115/* Handy utility functions used at several places in the code */
Sean Callanan2235f322010-08-11 03:57:18 +0000116
117static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000118PrintValue(const Value *value, bool truncate = false)
Sean Callanan2235f322010-08-11 03:57:18 +0000119{
120 std::string s;
Jim Ingham28eb5712012-10-12 17:34:26 +0000121 if (value)
122 {
123 raw_string_ostream rso(s);
124 value->print(rso);
125 rso.flush();
126 if (truncate)
127 s.resize(s.length() - 1);
128 }
Sean Callanan2235f322010-08-11 03:57:18 +0000129 return s;
130}
131
Sean Callanan038df5032010-09-30 21:18:25 +0000132static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000133PrintType(const Type *type, bool truncate = false)
Sean Callanan038df5032010-09-30 21:18:25 +0000134{
135 std::string s;
136 raw_string_ostream rso(s);
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000137 type->print(rso);
Sean Callanan038df5032010-09-30 21:18:25 +0000138 rso.flush();
139 if (truncate)
140 s.resize(s.length() - 1);
141 return s;
142}
143
Sean Callanan2ab712f22010-07-03 01:35:46 +0000144IRForTarget::~IRForTarget()
145{
146}
147
Sean Callanan79763a42011-05-23 21:40:23 +0000148bool
149IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
150{
Sean Callanan79763a42011-05-23 21:40:23 +0000151 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
152
Sean Callanan7f27d602011-11-19 02:54:21 +0000153 std::string name = llvm_function.getName().str();
Sean Callanan79763a42011-05-23 21:40:23 +0000154
155 return true;
156}
157
Sean Callanand1e5b432010-08-12 01:56:52 +0000158bool
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000159IRForTarget::GetFunctionAddress (llvm::Function *fun,
160 uint64_t &fun_addr,
161 lldb_private::ConstString &name,
162 Constant **&value_ptr)
163{
Greg Clayton5160ce52013-03-27 23:08:40 +0000164 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000165
166 fun_addr = LLDB_INVALID_ADDRESS;
167 name.Clear();
168 value_ptr = NULL;
169
170 if (fun->isIntrinsic())
171 {
172 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
173
174 switch (intrinsic_id)
175 {
176 default:
177 if (log)
178 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
179
180 if (m_error_stream)
181 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
182
183 return false;
184 case Intrinsic::memcpy:
185 {
186 static lldb_private::ConstString g_memcpy_str ("memcpy");
187 name = g_memcpy_str;
188 }
189 break;
Sean Callanana6cbf062011-11-16 00:20:50 +0000190 case Intrinsic::memset:
191 {
192 static lldb_private::ConstString g_memset_str ("memset");
193 name = g_memset_str;
194 }
195 break;
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000196 }
197
198 if (log && name)
199 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
200 }
201 else
202 {
203 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
204 }
205
206 // Find the address of the function.
207
208 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000209
210 if (fun_decl)
211 {
Sean Callananc70ed462011-10-25 18:36:40 +0000212 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000213 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000214 lldb_private::ConstString altnernate_name;
Greg Claytonf0705c82011-10-22 03:33:13 +0000215 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
216 if (!found_it)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000217 {
Greg Claytonf0705c82011-10-22 03:33:13 +0000218 // Check for an alternate mangling for "std::basic_string<char>"
219 // that is part of the itanium C++ name mangling scheme
220 const char *name_cstr = name.GetCString();
Jim Ingham28eb5712012-10-12 17:34:26 +0000221 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
Greg Claytonf0705c82011-10-22 03:33:13 +0000222 {
223 std::string alternate_mangling("_ZNKSs");
224 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000225 altnernate_name.SetCString(alternate_mangling.c_str());
226 found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
Greg Claytonf0705c82011-10-22 03:33:13 +0000227 }
228 }
229
230 if (!found_it)
231 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000232 lldb_private::Mangled mangled_name(name);
233 lldb_private::Mangled alt_mangled_name(altnernate_name);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000234 if (log)
Greg Claytonf0705c82011-10-22 03:33:13 +0000235 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000236 if (alt_mangled_name)
237 log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
238 mangled_name.GetName().GetCString(),
239 alt_mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000240 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000241 log->Printf("Function \"%s\" had no address",
242 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000243 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000244
245 if (m_error_stream)
Greg Claytonf0705c82011-10-22 03:33:13 +0000246 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000247 if (alt_mangled_name)
248 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
249 mangled_name.GetName().GetCString(),
250 alt_mangled_name.GetName().GetCString());
Greg Claytonda1eb042013-04-23 21:48:38 +0000251 else if (mangled_name.GetMangledName())
252 m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
253 mangled_name.GetName().GetCString(),
254 mangled_name.GetMangledName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000255 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000256 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
257 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000258 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000259 return false;
260 }
261 }
262 }
263 else
264 {
265 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
266 {
267 if (log)
268 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
269
270 if (m_error_stream)
271 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
272
273 return false;
274 }
275 }
276
277 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000278 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000279
280 return true;
281}
282
283llvm::Constant *
284IRForTarget::BuildFunctionPointer (llvm::Type *type,
285 uint64_t ptr)
286{
287 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +0000288 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000289 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
290 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
291 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
292}
293
Sean Callananfc8feb82011-10-31 22:11:40 +0000294void
295IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
296 llvm::Value *function_ptr,
297 const char *name)
298{
Sean Callananfc8feb82011-10-31 22:11:40 +0000299 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
300 i != e;
301 ++i)
302 {
303 Value *user = *i;
304
305 if (Instruction *user_inst = dyn_cast<Instruction>(user))
306 {
Daniel Maleaf051dbc2013-06-03 20:45:54 +0000307 MDString* md_name = MDString::get(context, StringRef(name));
308
309 MDNode *metadata = MDNode::get(context, md_name);
310
Sean Callananfc8feb82011-10-31 22:11:40 +0000311 user_inst->setMetadata("lldb.call.realName", metadata);
312 }
313 else
314 {
315 RegisterFunctionMetadata (context, user, name);
316 }
317 }
318}
319
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000320bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000321IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000322{
Greg Clayton5160ce52013-03-27 23:08:40 +0000323 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000324
325 for (llvm::Module::iterator fi = llvm_module.begin();
326 fi != llvm_module.end();
327 ++fi)
328 {
329 Function *fun = fi;
330
331 bool is_decl = fun->isDeclaration();
332
333 if (log)
Sean Callanan7f27d602011-11-19 02:54:21 +0000334 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000335
336 if (!is_decl)
337 continue;
338
339 if (fun->hasNUses(0))
340 continue; // ignore
341
342 uint64_t addr = LLDB_INVALID_ADDRESS;
343 lldb_private::ConstString name;
344 Constant **value_ptr = NULL;
345
346 if (!GetFunctionAddress(fun,
347 addr,
348 name,
349 value_ptr))
350 return false; // GetFunctionAddress reports its own errors
351
352 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
353
Sean Callananfc8feb82011-10-31 22:11:40 +0000354 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
355
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000356 if (value_ptr)
357 *value_ptr = value;
358
359 fun->replaceAllUsesWith(value);
360 }
361
362 return true;
363}
364
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000365
Sean Callanan63697e52011-05-07 01:06:41 +0000366clang::NamedDecl *
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000367IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan63697e52011-05-07 01:06:41 +0000368{
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000369 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan63697e52011-05-07 01:06:41 +0000370
371 if (!named_metadata)
372 return NULL;
373
374 unsigned num_nodes = named_metadata->getNumOperands();
375 unsigned node_index;
376
377 for (node_index = 0;
378 node_index < num_nodes;
379 ++node_index)
380 {
381 MDNode *metadata_node = named_metadata->getOperand(node_index);
382
383 if (!metadata_node)
384 return NULL;
385
386 if (metadata_node->getNumOperands() != 2)
387 continue;
388
389 if (metadata_node->getOperand(0) != global_val)
390 continue;
391
392 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
393
394 if (!constant_int)
395 return NULL;
396
397 uintptr_t ptr = constant_int->getZExtValue();
398
399 return reinterpret_cast<clang::NamedDecl *>(ptr);
400 }
401
402 return NULL;
403}
404
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000405clang::NamedDecl *
406IRForTarget::DeclForGlobal (GlobalValue *global_val)
407{
408 return DeclForGlobal(global_val, m_module);
409}
410
Sean Callanane4ec90e2010-12-16 03:17:46 +0000411bool
Sean Callanan79763a42011-05-23 21:40:23 +0000412IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanand1e5b432010-08-12 01:56:52 +0000413{
Greg Clayton5160ce52013-03-27 23:08:40 +0000414 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand1e5b432010-08-12 01:56:52 +0000415
Sean Callanan9e6ed532010-09-13 21:34:21 +0000416 if (!m_resolve_vars)
417 return true;
418
419 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callananfc55f5d2010-09-21 00:44:12 +0000420
Sean Callanan79763a42011-05-23 21:40:23 +0000421 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananfc55f5d2010-09-21 00:44:12 +0000422
Sean Callanancc427fa2011-07-30 02:42:06 +0000423 std::string result_name_str;
Sean Callananfc55f5d2010-09-21 00:44:12 +0000424 const char *result_name = NULL;
425
426 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
427 vi != ve;
428 ++vi)
429 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000430 result_name_str = vi->first().str();
431 const char *value_name = result_name_str.c_str();
432
433 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000434 strncmp(value_name, "_ZGV", 4))
Sean Callanan92adcac2011-01-13 08:53:35 +0000435 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000436 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000437 m_result_is_pointer = true;
438 break;
439 }
440
Sean Callanancc427fa2011-07-30 02:42:06 +0000441 if (strstr(value_name, "$__lldb_expr_result") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000442 strncmp(value_name, "_ZGV", 4))
Sean Callanan46ae9e52010-09-28 21:13:03 +0000443 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000444 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000445 m_result_is_pointer = false;
Sean Callanan46ae9e52010-09-28 21:13:03 +0000446 break;
447 }
Sean Callananfc55f5d2010-09-21 00:44:12 +0000448 }
449
450 if (!result_name)
451 {
452 if (log)
453 log->PutCString("Couldn't find result variable");
454
455 return true;
456 }
457
Sean Callanan46ae9e52010-09-28 21:13:03 +0000458 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000459 log->Printf("Result name: \"%s\"", result_name);
Sean Callanan46ae9e52010-09-28 21:13:03 +0000460
Sean Callanan79763a42011-05-23 21:40:23 +0000461 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanand1e5b432010-08-12 01:56:52 +0000462
463 if (!result_value)
464 {
465 if (log)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000466 log->PutCString("Result variable had no data");
Sean Callanan92adcac2011-01-13 08:53:35 +0000467
Sean Callanan3989fb92011-01-27 01:07:04 +0000468 if (m_error_stream)
469 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
470
Sean Callananfc55f5d2010-09-21 00:44:12 +0000471 return false;
Sean Callanand1e5b432010-08-12 01:56:52 +0000472 }
Sean Callanan9e6ed532010-09-13 21:34:21 +0000473
Sean Callanand1e5b432010-08-12 01:56:52 +0000474 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000475 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000476
477 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
478
479 if (!result_global)
480 {
481 if (log)
482 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000483
484 if (m_error_stream)
485 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
486
Sean Callanand1e5b432010-08-12 01:56:52 +0000487 return false;
488 }
489
Sean Callanan79763a42011-05-23 21:40:23 +0000490 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan63697e52011-05-07 01:06:41 +0000491 if (!result_decl)
Sean Callanand1e5b432010-08-12 01:56:52 +0000492 {
493 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000494 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanand1e5b432010-08-12 01:56:52 +0000495
Sean Callanan3989fb92011-01-27 01:07:04 +0000496 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000497 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 +0000498
Sean Callanand1e5b432010-08-12 01:56:52 +0000499 return false;
500 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000501
Sean Callanan63697e52011-05-07 01:06:41 +0000502 if (log)
Sean Callanand1e5b432010-08-12 01:56:52 +0000503 {
Sean Callanan63697e52011-05-07 01:06:41 +0000504 std::string decl_desc_str;
505 raw_string_ostream decl_desc_stream(decl_desc_str);
506 result_decl->print(decl_desc_stream);
507 decl_desc_stream.flush();
Sean Callanand1e5b432010-08-12 01:56:52 +0000508
Sean Callanan63697e52011-05-07 01:06:41 +0000509 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000510 }
511
Sean Callanan63697e52011-05-07 01:06:41 +0000512 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
513 if (!result_var)
Sean Callanand1e5b432010-08-12 01:56:52 +0000514 {
515 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000516 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan3989fb92011-01-27 01:07:04 +0000517
518 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000519 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 +0000520
Sean Callanand1e5b432010-08-12 01:56:52 +0000521 return false;
522 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000523
Sean Callanand1e5b432010-08-12 01:56:52 +0000524 // Get the next available result name from m_decl_map and create the persistent
525 // variable for it
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000526
Sean Callanan63697e52011-05-07 01:06:41 +0000527 // If the result is an Lvalue, it is emitted as a pointer; see
528 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan92adcac2011-01-13 08:53:35 +0000529 if (m_result_is_pointer)
530 {
Sean Callanan63697e52011-05-07 01:06:41 +0000531 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanan78e37602011-01-27 04:42:51 +0000532 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
Sean Callanan92adcac2011-01-13 08:53:35 +0000533
Sean Callananfc4f2fb2011-12-14 01:13:04 +0000534 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
535 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
Sean Callanan5780f9d2011-12-08 19:04:34 +0000536
537 if (pointer_pointertype)
538 {
539 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
540
541 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
542 &result_decl->getASTContext());
543 }
544 else if (pointer_objcobjpointertype)
545 {
546 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
547
548 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
549 &result_decl->getASTContext());
550 }
551 else
Sean Callanan92adcac2011-01-13 08:53:35 +0000552 {
553 if (log)
554 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan3989fb92011-01-27 01:07:04 +0000555
556 if (m_error_stream)
557 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
558
Sean Callanan92adcac2011-01-13 08:53:35 +0000559 return false;
560 }
Sean Callanan92adcac2011-01-13 08:53:35 +0000561 }
562 else
563 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000564 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan00f43622011-11-18 03:28:09 +0000565 &result_decl->getASTContext());
566 }
567
568 if (m_result_type.GetClangTypeBitWidth() == 0)
569 {
570 lldb_private::StreamString type_desc_stream;
571 m_result_type.DumpTypeDescription(&type_desc_stream);
572
573 if (log)
574 log->Printf("Result type has size 0");
575
576 if (m_error_stream)
Sean Callanan960534c2011-12-21 23:44:05 +0000577 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
Sean Callanan00f43622011-11-18 03:28:09 +0000578 type_desc_stream.GetData());
Sean Callanan960534c2011-12-21 23:44:05 +0000579 return false;
Sean Callanan92adcac2011-01-13 08:53:35 +0000580 }
581
Sean Callanan63697e52011-05-07 01:06:41 +0000582 if (log)
583 {
584 lldb_private::StreamString type_desc_stream;
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000585 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan63697e52011-05-07 01:06:41 +0000586
Sean Callanan00f43622011-11-18 03:28:09 +0000587 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
Sean Callanan63697e52011-05-07 01:06:41 +0000588 }
589
Sean Callanan1582ee62013-04-18 22:06:33 +0000590 m_result_name = lldb_private::ConstString("$RESULT_NAME");
Sean Callanand1e5b432010-08-12 01:56:52 +0000591
592 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +0000593 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
Sean Callanan00f43622011-11-18 03:28:09 +0000594 m_result_name.GetCString(),
595 m_result_type.GetClangTypeBitWidth() / 8);
Sean Callanand1e5b432010-08-12 01:56:52 +0000596
597 // Construct a new result global and set up its metadata
598
Sean Callanan79763a42011-05-23 21:40:23 +0000599 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanand1e5b432010-08-12 01:56:52 +0000600 result_global->getType()->getElementType(),
601 false, /* not constant */
602 GlobalValue::ExternalLinkage,
603 NULL, /* no initializer */
Sean Callanan92adcac2011-01-13 08:53:35 +0000604 m_result_name.GetCString ());
Sean Callanand1e5b432010-08-12 01:56:52 +0000605
606 // It's too late in compilation to create a new VarDecl for this, but we don't
607 // need to. We point the metadata at the old VarDecl. This creates an odd
608 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton7b462cc2010-10-15 22:48:33 +0000609 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanand1e5b432010-08-12 01:56:52 +0000610 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
611 // fixed up.
612
Sean Callanan79763a42011-05-23 21:40:23 +0000613 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan63697e52011-05-07 01:06:41 +0000614 reinterpret_cast<uint64_t>(result_decl),
Sean Callanand1e5b432010-08-12 01:56:52 +0000615 false);
616
617 llvm::Value* values[2];
618 values[0] = new_result_global;
619 values[1] = new_constant_int;
620
Sean Callanand12cf8bb2011-05-15 22:34:38 +0000621 ArrayRef<Value*> value_ref(values, 2);
622
Sean Callanan79763a42011-05-23 21:40:23 +0000623 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
624 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanand1e5b432010-08-12 01:56:52 +0000625 named_metadata->addOperand(persistent_global_md);
626
627 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000628 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan1e87fff2010-09-07 22:43:19 +0000629 PrintValue(result_global).c_str(),
Sean Callanand1e5b432010-08-12 01:56:52 +0000630 PrintValue(new_result_global).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000631
632 if (result_global->hasNUses(0))
633 {
634 // We need to synthesize a store for this variable, because otherwise
635 // there's nothing to put into its equivalent persistent variable.
Sean Callanand1e5b432010-08-12 01:56:52 +0000636
Greg Clayton7b462cc2010-10-15 22:48:33 +0000637 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000638 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
639
640 if (!first_entry_instruction)
641 return false;
642
643 if (!result_global->hasInitializer())
644 {
645 if (log)
646 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000647
648 if (m_error_stream)
649 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
650
Sean Callanan1e87fff2010-09-07 22:43:19 +0000651 return false;
652 }
653
654 Constant *initializer = result_global->getInitializer();
Sean Callanane4ec90e2010-12-16 03:17:46 +0000655
Greg Clayton9c139312011-02-05 02:28:58 +0000656 StoreInst *synthesized_store = new StoreInst(initializer,
657 new_result_global,
658 first_entry_instruction);
Sean Callanan1e87fff2010-09-07 22:43:19 +0000659
660 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000661 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000662 }
663 else
664 {
665 result_global->replaceAllUsesWith(new_result_global);
666 }
667
Sean Callanan1582ee62013-04-18 22:06:33 +0000668 if (!m_decl_map->AddPersistentVariable(result_decl,
669 m_result_name,
670 m_result_type,
671 true,
672 m_result_is_pointer))
673 return false;
674
Sean Callanand1e5b432010-08-12 01:56:52 +0000675 result_global->eraseFromParent();
676
677 return true;
678}
679
Johnny Chenee7a3592011-08-09 23:10:20 +0000680#if 0
Greg Clayton5160ce52013-03-27 23:08:40 +0000681static void DebugUsers(Log *log, Value *value, uint8_t depth)
Sean Callananafe16a72010-11-17 23:00:36 +0000682{
683 if (!depth)
684 return;
685
686 depth--;
687
Johnny Chenee7a3592011-08-09 23:10:20 +0000688 if (log)
689 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callananafe16a72010-11-17 23:00:36 +0000690
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000691 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callananafe16a72010-11-17 23:00:36 +0000692 ui != ue;
693 ++ui)
694 {
Johnny Chenee7a3592011-08-09 23:10:20 +0000695 if (log)
696 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callananafe16a72010-11-17 23:00:36 +0000697 DebugUsers(log, *ui, depth);
698 }
699
Johnny Chenee7a3592011-08-09 23:10:20 +0000700 if (log)
701 log->Printf(" <End uses>");
Sean Callananafe16a72010-11-17 23:00:36 +0000702}
Johnny Chenee7a3592011-08-09 23:10:20 +0000703#endif
Sean Callananafe16a72010-11-17 23:00:36 +0000704
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000705bool
Sean Callanan79763a42011-05-23 21:40:23 +0000706IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000707 llvm::GlobalVariable *cstr)
Sean Callananafe16a72010-11-17 23:00:36 +0000708{
Greg Clayton5160ce52013-03-27 23:08:40 +0000709 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000710
Sean Callanancc427fa2011-07-30 02:42:06 +0000711 Type *ns_str_ty = ns_str->getType();
Sean Callanan79763a42011-05-23 21:40:23 +0000712
Sean Callanancc427fa2011-07-30 02:42:06 +0000713 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
714 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +0000715 (m_module->getPointerSize()
Micah Villmow08318972012-10-11 17:21:41 +0000716 == Module::Pointer64) ? 64 : 32);
Sean Callanancc427fa2011-07-30 02:42:06 +0000717 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
718 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananafe16a72010-11-17 23:00:36 +0000719
720 if (!m_CFStringCreateWithBytes)
721 {
722 lldb::addr_t CFStringCreateWithBytes_addr;
723
724 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
725
726 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
727 {
728 if (log)
729 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
730
Sean Callanan3989fb92011-01-27 01:07:04 +0000731 if (m_error_stream)
732 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
733
Sean Callananafe16a72010-11-17 23:00:36 +0000734 return false;
735 }
736
737 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000738 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
Sean Callananafe16a72010-11-17 23:00:36 +0000739
740 // Build the function type:
741 //
742 // CFStringRef CFStringCreateWithBytes (
743 // CFAllocatorRef alloc,
744 // const UInt8 *bytes,
745 // CFIndex numBytes,
746 // CFStringEncoding encoding,
747 // Boolean isExternalRepresentation
748 // );
749 //
750 // We make the following substitutions:
751 //
752 // CFStringRef -> i8*
753 // CFAllocatorRef -> i8*
754 // UInt8 * -> i8*
755 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
756 // CFStringEncoding -> i32
757 // Boolean -> i8
758
Sean Callanancc427fa2011-07-30 02:42:06 +0000759 Type *arg_type_array[5];
760
761 arg_type_array[0] = i8_ptr_ty;
762 arg_type_array[1] = i8_ptr_ty;
763 arg_type_array[2] = intptr_ty;
764 arg_type_array[3] = i32_ty;
765 arg_type_array[4] = i8_ty;
766
767 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
768
Sean Callanan79763a42011-05-23 21:40:23 +0000769 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000770
771 // Build the constant containing the pointer to the function
772 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
773 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
774 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
775 }
776
Sean Callanand2b465f2012-02-09 03:22:41 +0000777 ConstantDataSequential *string_array = NULL;
Sean Callanan229ce2d2011-02-10 22:17:53 +0000778
779 if (cstr)
Sean Callanand2b465f2012-02-09 03:22:41 +0000780 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
Sean Callanancc427fa2011-07-30 02:42:06 +0000781
Sean Callananafe16a72010-11-17 23:00:36 +0000782 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan229ce2d2011-02-10 22:17:53 +0000783 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
Sean Callanand2b465f2012-02-09 03:22:41 +0000784 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000785 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
786 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
787
Sean Callanancc427fa2011-07-30 02:42:06 +0000788 Value *argument_array[5];
789
790 argument_array[0] = alloc_arg;
791 argument_array[1] = bytes_arg;
792 argument_array[2] = numBytes_arg;
793 argument_array[3] = encoding_arg;
794 argument_array[4] = isExternal_arg;
795
796 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callananafe16a72010-11-17 23:00:36 +0000797
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000798 FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * {
799 return CallInst::Create(m_CFStringCreateWithBytes,
800 CFSCWB_arguments,
801 "CFStringCreateWithBytes",
802 llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)));
803 });
Sean Callanan7a55a322010-11-18 22:21:58 +0000804
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000805 if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder))
Sean Callananafe16a72010-11-17 23:00:36 +0000806 {
807 if (log)
808 log->PutCString("Couldn't replace the NSString with the result of the call");
809
Sean Callanan3989fb92011-01-27 01:07:04 +0000810 if (m_error_stream)
811 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
812
Sean Callananafe16a72010-11-17 23:00:36 +0000813 return false;
814 }
815
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000816 ns_str->eraseFromParent();
Sean Callananafe16a72010-11-17 23:00:36 +0000817
818 return true;
819}
820
821bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000822IRForTarget::RewriteObjCConstStrings()
Sean Callananafe16a72010-11-17 23:00:36 +0000823{
Greg Clayton5160ce52013-03-27 23:08:40 +0000824 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000825
Sean Callanan79763a42011-05-23 21:40:23 +0000826 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananafe16a72010-11-17 23:00:36 +0000827
Sean Callananafe16a72010-11-17 23:00:36 +0000828 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
829 vi != ve;
830 ++vi)
831 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000832 std::string value_name = vi->first().str();
833 const char *value_name_cstr = value_name.c_str();
834
835 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callananafe16a72010-11-17 23:00:36 +0000836 {
837 Value *nsstring_value = vi->second;
838
839 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
840
841 if (!nsstring_global)
842 {
843 if (log)
844 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000845
846 if (m_error_stream)
847 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
848
Sean Callananafe16a72010-11-17 23:00:36 +0000849 return false;
850 }
851
852 if (!nsstring_global->hasInitializer())
853 {
854 if (log)
855 log->PutCString("NSString variable does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000856
857 if (m_error_stream)
858 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
859
Sean Callananafe16a72010-11-17 23:00:36 +0000860 return false;
861 }
862
863 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
864
865 if (!nsstring_struct)
866 {
867 if (log)
868 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan3989fb92011-01-27 01:07:04 +0000869
870 if (m_error_stream)
871 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
872
Sean Callananafe16a72010-11-17 23:00:36 +0000873 return false;
874 }
875
876 // We expect the following structure:
877 //
878 // struct {
879 // int *isa;
880 // int flags;
881 // char *str;
882 // long length;
883 // };
884
885 if (nsstring_struct->getNumOperands() != 4)
886 {
887 if (log)
888 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 +0000889
890 if (m_error_stream)
891 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
892
Sean Callananafe16a72010-11-17 23:00:36 +0000893 return false;
894 }
895
896 Constant *nsstring_member = nsstring_struct->getOperand(2);
897
898 if (!nsstring_member)
899 {
900 if (log)
901 log->PutCString("NSString initializer's str element was empty");
Sean Callanan3989fb92011-01-27 01:07:04 +0000902
903 if (m_error_stream)
904 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
905
Sean Callananafe16a72010-11-17 23:00:36 +0000906 return false;
907 }
908
909 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
910
911 if (!nsstring_expr)
912 {
913 if (log)
914 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan3989fb92011-01-27 01:07:04 +0000915
916 if (m_error_stream)
917 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
918
Sean Callananafe16a72010-11-17 23:00:36 +0000919 return false;
920 }
921
922 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
923 {
924 if (log)
925 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 +0000926
927 if (m_error_stream)
928 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
929
Sean Callananafe16a72010-11-17 23:00:36 +0000930 return false;
931 }
932
933 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
934
935 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
936
937 if (!cstr_global)
938 {
939 if (log)
940 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000941
942 if (m_error_stream)
943 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 +0000944
Sean Callananafe16a72010-11-17 23:00:36 +0000945 return false;
946 }
947
948 if (!cstr_global->hasInitializer())
949 {
950 if (log)
951 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000952
953 if (m_error_stream)
954 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
955
Sean Callananafe16a72010-11-17 23:00:36 +0000956 return false;
957 }
Sean Callanan229ce2d2011-02-10 22:17:53 +0000958
959 /*
Sean Callananafe16a72010-11-17 23:00:36 +0000960 if (!cstr_array)
961 {
962 if (log)
963 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan3989fb92011-01-27 01:07:04 +0000964
965 if (m_error_stream)
966 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
967
Sean Callananafe16a72010-11-17 23:00:36 +0000968 return false;
969 }
970
971 if (!cstr_array->isCString())
972 {
973 if (log)
974 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan3989fb92011-01-27 01:07:04 +0000975
976 if (m_error_stream)
977 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
978
Sean Callananafe16a72010-11-17 23:00:36 +0000979 return false;
980 }
Sean Callanan229ce2d2011-02-10 22:17:53 +0000981 */
982
Sean Callanand2b465f2012-02-09 03:22:41 +0000983 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
Sean Callananafe16a72010-11-17 23:00:36 +0000984
985 if (log)
Sean Callanan229ce2d2011-02-10 22:17:53 +0000986 {
987 if (cstr_array)
Sean Callanand2b465f2012-02-09 03:22:41 +0000988 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 +0000989 else
Sean Callanancc427fa2011-07-30 02:42:06 +0000990 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan229ce2d2011-02-10 22:17:53 +0000991 }
992
993 if (!cstr_array)
994 cstr_global = NULL;
Sean Callananafe16a72010-11-17 23:00:36 +0000995
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000996 if (!RewriteObjCConstString(nsstring_global, cstr_global))
Sean Callanan3989fb92011-01-27 01:07:04 +0000997 {
Sean Callananafe16a72010-11-17 23:00:36 +0000998 if (log)
999 log->PutCString("Error rewriting the constant string");
Sean Callanan3989fb92011-01-27 01:07:04 +00001000
1001 // We don't print an error message here because RewriteObjCConstString has done so for us.
1002
Sean Callananafe16a72010-11-17 23:00:36 +00001003 return false;
1004 }
Sean Callananafe16a72010-11-17 23:00:36 +00001005 }
1006 }
1007
1008 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1009 vi != ve;
1010 ++vi)
1011 {
Sean Callanancc427fa2011-07-30 02:42:06 +00001012 std::string value_name = vi->first().str();
1013 const char *value_name_cstr = value_name.c_str();
1014
1015 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callananafe16a72010-11-17 23:00:36 +00001016 {
1017 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1018
1019 if (!gv)
1020 {
1021 if (log)
1022 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001023
1024 if (m_error_stream)
1025 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1026
Sean Callananafe16a72010-11-17 23:00:36 +00001027 return false;
1028 }
1029
1030 gv->eraseFromParent();
1031
1032 break;
1033 }
1034 }
1035
1036 return true;
1037}
1038
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001039static bool IsObjCSelectorRef (Value *value)
Sean Callanan5300d372010-07-31 01:32:05 +00001040{
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001041 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callanan5300d372010-07-31 01:32:05 +00001042
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001043 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callanan5300d372010-07-31 01:32:05 +00001044 return false;
1045
1046 return true;
1047}
1048
Sean Callanan3989fb92011-01-27 01:07:04 +00001049// This function does not report errors; its callers are responsible.
Sean Callanan5300d372010-07-31 01:32:05 +00001050bool
Sean Callanan79763a42011-05-23 21:40:23 +00001051IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callanan5300d372010-07-31 01:32:05 +00001052{
Greg Clayton5160ce52013-03-27 23:08:40 +00001053 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001054
1055 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1056
1057 if (!load)
1058 return false;
1059
1060 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1061 //
1062 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1063 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1064 //
1065 // where %obj is the object pointer and %tmp is the selector.
1066 //
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001067 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1068 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callanan5300d372010-07-31 01:32:05 +00001069
1070 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1071
1072 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1073
1074 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1075 return false;
1076
1077 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1078
1079 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1080
1081 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1082 return false;
1083
1084 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1085
1086 if (!osr_initializer_base)
1087 return false;
1088
1089 // Find the string's initializer (a ConstantArray) and get the string from it
1090
1091 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1092
1093 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1094 return false;
1095
1096 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1097
Sean Callanand2b465f2012-02-09 03:22:41 +00001098 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
Sean Callanan5300d372010-07-31 01:32:05 +00001099
1100 if (!omvn_initializer_array->isString())
1101 return false;
1102
1103 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1104
1105 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001106 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callanan5300d372010-07-31 01:32:05 +00001107
1108 // Construct a call to sel_registerName
1109
1110 if (!m_sel_registerName)
1111 {
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001112 lldb::addr_t sel_registerName_addr;
Sean Callanan5300d372010-07-31 01:32:05 +00001113
Greg Clayton7b462cc2010-10-15 22:48:33 +00001114 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001115 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callanan5300d372010-07-31 01:32:05 +00001116 return false;
1117
Sean Callananbe3a1b12010-10-26 00:31:56 +00001118 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001119 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
Sean Callananbe3a1b12010-10-26 00:31:56 +00001120
Sean Callanan5300d372010-07-31 01:32:05 +00001121 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1122
1123 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callanan79763a42011-05-23 21:40:23 +00001124 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001125 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanancc427fa2011-07-30 02:42:06 +00001126 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001127
Sean Callanancc427fa2011-07-30 02:42:06 +00001128 Type *type_array[1];
1129
1130 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1131
1132 ArrayRef<Type *> srN_arg_types(type_array, 1);
1133
Sean Callanan5300d372010-07-31 01:32:05 +00001134 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1135
1136 // Build the constant containing the pointer to the function
Sean Callanancc427fa2011-07-30 02:42:06 +00001137 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001138 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan5300d372010-07-31 01:32:05 +00001139 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001140 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callanan5300d372010-07-31 01:32:05 +00001141 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1142 }
1143
Sean Callanancc427fa2011-07-30 02:42:06 +00001144 Value *argument_array[1];
1145
Sean Callanan79763a42011-05-23 21:40:23 +00001146 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callanan5300d372010-07-31 01:32:05 +00001147
Sean Callanancc427fa2011-07-30 02:42:06 +00001148 argument_array[0] = omvn_pointer;
Sean Callanan5300d372010-07-31 01:32:05 +00001149
Sean Callanancc427fa2011-07-30 02:42:06 +00001150 ArrayRef<Value *> srN_arguments(argument_array, 1);
1151
Sean Callanan5300d372010-07-31 01:32:05 +00001152 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanancc427fa2011-07-30 02:42:06 +00001153 srN_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +00001154 "sel_registerName",
Sean Callanan5300d372010-07-31 01:32:05 +00001155 selector_load);
1156
1157 // Replace the load with the call in all users
1158
1159 selector_load->replaceAllUsesWith(srN_call);
1160
1161 selector_load->eraseFromParent();
1162
1163 return true;
1164}
1165
1166bool
Sean Callanan79763a42011-05-23 21:40:23 +00001167IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callanan5300d372010-07-31 01:32:05 +00001168{
Greg Clayton5160ce52013-03-27 23:08:40 +00001169 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001170
1171 BasicBlock::iterator ii;
1172
1173 typedef SmallVector <Instruction*, 2> InstrList;
1174 typedef InstrList::iterator InstrIterator;
1175
1176 InstrList selector_loads;
1177
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001178 for (ii = basic_block.begin();
1179 ii != basic_block.end();
Sean Callanan5300d372010-07-31 01:32:05 +00001180 ++ii)
1181 {
1182 Instruction &inst = *ii;
1183
1184 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001185 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callanan5300d372010-07-31 01:32:05 +00001186 selector_loads.push_back(&inst);
1187 }
1188
1189 InstrIterator iter;
1190
1191 for (iter = selector_loads.begin();
1192 iter != selector_loads.end();
1193 ++iter)
1194 {
Sean Callanan79763a42011-05-23 21:40:23 +00001195 if (!RewriteObjCSelector(*iter))
Sean Callanan5300d372010-07-31 01:32:05 +00001196 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001197 if (m_error_stream)
1198 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1199
Enrico Granata20edcdb2011-07-19 18:03:25 +00001200 if (log)
Sean Callanan5300d372010-07-31 01:32:05 +00001201 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan3989fb92011-01-27 01:07:04 +00001202
Sean Callanan5300d372010-07-31 01:32:05 +00001203 return false;
1204 }
1205 }
1206
1207 return true;
1208}
1209
Sean Callanan3989fb92011-01-27 01:07:04 +00001210// This function does not report errors; its callers are responsible.
Sean Callanan2235f322010-08-11 03:57:18 +00001211bool
Sean Callanan79763a42011-05-23 21:40:23 +00001212IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanan2235f322010-08-11 03:57:18 +00001213{
Greg Clayton5160ce52013-03-27 23:08:40 +00001214 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanane1175b72011-01-13 21:23:32 +00001215
Sean Callanan2235f322010-08-11 03:57:18 +00001216 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1217
1218 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1219
1220 if (!alloc_md || !alloc_md->getNumOperands())
1221 return false;
1222
1223 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1224
1225 if (!constant_int)
1226 return false;
1227
1228 // We attempt to register this as a new persistent variable with the DeclMap.
1229
1230 uintptr_t ptr = constant_int->getZExtValue();
1231
Sean Callanand1e5b432010-08-12 01:56:52 +00001232 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanan2235f322010-08-11 03:57:18 +00001233
Sean Callanand1e5b432010-08-12 01:56:52 +00001234 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1235 &decl->getASTContext());
1236
Greg Clayton7b462cc2010-10-15 22:48:33 +00001237 StringRef decl_name (decl->getName());
1238 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan92adcac2011-01-13 08:53:35 +00001239 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanan2235f322010-08-11 03:57:18 +00001240 return false;
1241
Sean Callanan79763a42011-05-23 21:40:23 +00001242 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanane1175b72011-01-13 21:23:32 +00001243 alloc->getType(),
Sean Callanan2235f322010-08-11 03:57:18 +00001244 false, /* not constant */
1245 GlobalValue::ExternalLinkage,
1246 NULL, /* no initializer */
1247 alloc->getName().str().c_str());
1248
1249 // What we're going to do here is make believe this was a regular old external
1250 // variable. That means we need to make the metadata valid.
1251
Sean Callanan585c0ec82012-07-04 01:26:26 +00001252 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
Sean Callanan2235f322010-08-11 03:57:18 +00001253
1254 llvm::Value* values[2];
1255 values[0] = persistent_global;
1256 values[1] = constant_int;
Sean Callanand12cf8bb2011-05-15 22:34:38 +00001257
1258 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanan2235f322010-08-11 03:57:18 +00001259
Sean Callanan79763a42011-05-23 21:40:23 +00001260 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanan2235f322010-08-11 03:57:18 +00001261 named_metadata->addOperand(persistent_global_md);
1262
Sean Callanane1175b72011-01-13 21:23:32 +00001263 // Now, since the variable is a pointer variable, we will drop in a load of that
1264 // pointer variable.
1265
1266 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1267
1268 if (log)
1269 log->Printf("Replacing \"%s\" with \"%s\"",
1270 PrintValue(alloc).c_str(),
1271 PrintValue(persistent_load).c_str());
1272
1273 alloc->replaceAllUsesWith(persistent_load);
Sean Callanan2235f322010-08-11 03:57:18 +00001274 alloc->eraseFromParent();
1275
1276 return true;
1277}
1278
1279bool
Sean Callanan79763a42011-05-23 21:40:23 +00001280IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanan2235f322010-08-11 03:57:18 +00001281{
Sean Callanan9e6ed532010-09-13 21:34:21 +00001282 if (!m_resolve_vars)
1283 return true;
1284
Greg Clayton5160ce52013-03-27 23:08:40 +00001285 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2235f322010-08-11 03:57:18 +00001286
1287 BasicBlock::iterator ii;
1288
1289 typedef SmallVector <Instruction*, 2> InstrList;
1290 typedef InstrList::iterator InstrIterator;
1291
1292 InstrList pvar_allocs;
1293
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001294 for (ii = basic_block.begin();
1295 ii != basic_block.end();
Sean Callanan2235f322010-08-11 03:57:18 +00001296 ++ii)
1297 {
1298 Instruction &inst = *ii;
1299
1300 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callananf694a552011-01-21 22:30:25 +00001301 {
1302 llvm::StringRef alloc_name = alloc->getName();
1303
1304 if (alloc_name.startswith("$") &&
1305 !alloc_name.startswith("$__lldb"))
1306 {
1307 if (alloc_name.find_first_of("0123456789") == 1)
1308 {
1309 if (log)
1310 log->Printf("Rejecting a numeric persistent variable.");
1311
Sean Callanan3989fb92011-01-27 01:07:04 +00001312 if (m_error_stream)
1313 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1314
Sean Callananf694a552011-01-21 22:30:25 +00001315 return false;
1316 }
1317
Sean Callanan2235f322010-08-11 03:57:18 +00001318 pvar_allocs.push_back(alloc);
Sean Callananf694a552011-01-21 22:30:25 +00001319 }
1320 }
Sean Callanan2235f322010-08-11 03:57:18 +00001321 }
1322
1323 InstrIterator iter;
1324
1325 for (iter = pvar_allocs.begin();
1326 iter != pvar_allocs.end();
1327 ++iter)
1328 {
Sean Callanan79763a42011-05-23 21:40:23 +00001329 if (!RewritePersistentAlloc(*iter))
Sean Callanan2235f322010-08-11 03:57:18 +00001330 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001331 if (m_error_stream)
1332 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1333
Enrico Granata20edcdb2011-07-19 18:03:25 +00001334 if (log)
Sean Callanan2235f322010-08-11 03:57:18 +00001335 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001336
Sean Callanan2235f322010-08-11 03:57:18 +00001337 return false;
1338 }
1339 }
1340
1341 return true;
1342}
1343
Sean Callananc70ed462011-10-25 18:36:40 +00001344bool
1345IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1346{
1347 if (!initializer)
1348 return true;
1349
Greg Clayton5160ce52013-03-27 23:08:40 +00001350 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc70ed462011-10-25 18:36:40 +00001351
1352 if (log && log->GetVerbose())
1353 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1354
1355 Type *initializer_type = initializer->getType();
1356
1357 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1358 {
1359 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1360 return true;
1361 }
Sean Callanand2b465f2012-02-09 03:22:41 +00001362 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
Sean Callananc70ed462011-10-25 18:36:40 +00001363 {
1364 if (array_initializer->isString())
1365 {
1366 std::string array_initializer_string = array_initializer->getAsString();
1367 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1368 }
1369 else
1370 {
1371 ArrayType *array_initializer_type = array_initializer->getType();
1372 Type *array_element_type = array_initializer_type->getElementType();
1373
1374 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1375
Andy Gibbsa297a972013-06-19 19:04:53 +00001376 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i)
Sean Callananc70ed462011-10-25 18:36:40 +00001377 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001378 Value *operand_value = array_initializer->getOperand(i);
1379 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1380
1381 if (!operand_constant)
1382 return false;
1383
1384 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
Sean Callananc70ed462011-10-25 18:36:40 +00001385 return false;
1386 }
1387 }
1388 return true;
1389 }
1390 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1391 {
1392 StructType *struct_initializer_type = struct_initializer->getType();
1393 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1394
Andy Gibbsa297a972013-06-19 19:04:53 +00001395 for (unsigned i = 0;
Sean Callananc70ed462011-10-25 18:36:40 +00001396 i < struct_initializer->getNumOperands();
1397 ++i)
1398 {
1399 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1400 return false;
1401 }
1402 return true;
1403 }
Sean Callanan76ee3e72013-04-24 19:50:12 +00001404 else if (isa<ConstantAggregateZero>(initializer))
1405 {
1406 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1407 return true;
1408 }
Sean Callananc70ed462011-10-25 18:36:40 +00001409 return false;
1410}
1411
1412bool
1413IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1414{
1415 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1416 return false;
1417
Sean Callananfe5d1392011-11-15 19:13:54 +00001418 if (global_variable == m_reloc_placeholder)
1419 return true;
1420
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001421 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callananc70ed462011-10-25 18:36:40 +00001422
1423 llvm::Type *variable_type = global_variable->getType();
1424
1425 Constant *initializer = global_variable->getInitializer();
1426
1427 llvm::Type *initializer_type = initializer->getType();
1428
1429 size_t size = m_target_data->getTypeAllocSize(initializer_type);
Sean Callanane3333d62012-06-08 22:20:41 +00001430 size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1431
1432 const size_t mask = (align - 1);
1433 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001434 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00001435 offset = aligned_offset;
Sean Callananc70ed462011-10-25 18:36:40 +00001436
1437 lldb_private::DataBufferHeap data(size, '\0');
1438
1439 if (initializer)
1440 if (!MaterializeInitializer(data.GetBytes(), initializer))
1441 return false;
1442
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001443 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
Sean Callananc70ed462011-10-25 18:36:40 +00001444
1445 Constant *new_pointer = BuildRelocation(variable_type, offset);
1446
1447 global_variable->replaceAllUsesWith(new_pointer);
1448
1449 global_variable->eraseFromParent();
1450
1451 return true;
1452}
1453
Sean Callanan3989fb92011-01-27 01:07:04 +00001454// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001455bool
Sean Callanan79763a42011-05-23 21:40:23 +00001456IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001457{
Greg Clayton5160ce52013-03-27 23:08:40 +00001458 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001459
1460 if (log)
Sean Callanan88339f02010-12-06 22:16:55 +00001461 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callananaf8e96c2011-08-01 17:41:38 +00001462
Greg Clayton7b462cc2010-10-15 22:48:33 +00001463 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callanan4cf04d22010-08-03 00:23:29 +00001464 {
Sean Callanan5666b672010-08-04 01:02:13 +00001465 switch (constant_expr->getOpcode())
Sean Callanan4cf04d22010-08-03 00:23:29 +00001466 {
Sean Callanan5666b672010-08-04 01:02:13 +00001467 default:
1468 break;
1469 case Instruction::GetElementPtr:
1470 case Instruction::BitCast:
Sean Callanan4cf04d22010-08-03 00:23:29 +00001471 Value *s = constant_expr->getOperand(0);
Sean Callanan79763a42011-05-23 21:40:23 +00001472 if (!MaybeHandleVariable(s))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001473 return false;
Sean Callanan4cf04d22010-08-03 00:23:29 +00001474 }
1475 }
Sean Callanand6e04ae2010-12-03 19:51:05 +00001476 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001477 {
Sean Callananc70ed462011-10-25 18:36:40 +00001478 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1479 return MaterializeInternalVariable(global_variable);
1480
Sean Callanan79763a42011-05-23 21:40:23 +00001481 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan2ab712f22010-07-03 01:35:46 +00001482
Sean Callanan5300d372010-07-31 01:32:05 +00001483 if (!named_decl)
1484 {
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001485 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001486 return true;
1487
Sean Callanan14f0b0e2010-12-06 00:56:39 +00001488 if (!global_variable->hasExternalLinkage())
1489 return true;
1490
Sean Callanan5300d372010-07-31 01:32:05 +00001491 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001492 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001493
Sean Callanan5300d372010-07-31 01:32:05 +00001494 return false;
1495 }
1496
Greg Clayton7b462cc2010-10-15 22:48:33 +00001497 std::string name (named_decl->getName().str());
Sean Callananea22d422010-07-16 00:09:46 +00001498
Sean Callanan038df5032010-09-30 21:18:25 +00001499 void *opaque_type = NULL;
Sean Callanan1d180662010-07-20 23:31:16 +00001500 clang::ASTContext *ast_context = NULL;
Sean Callananea22d422010-07-16 00:09:46 +00001501
1502 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callanan1d180662010-07-20 23:31:16 +00001503 {
Sean Callanan038df5032010-09-30 21:18:25 +00001504 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callanan1d180662010-07-20 23:31:16 +00001505 ast_context = &value_decl->getASTContext();
1506 }
Sean Callananea22d422010-07-16 00:09:46 +00001507 else
Sean Callanan1d180662010-07-20 23:31:16 +00001508 {
Sean Callananea22d422010-07-16 00:09:46 +00001509 return false;
Sean Callanan1d180662010-07-20 23:31:16 +00001510 }
Sean Callanan038df5032010-09-30 21:18:25 +00001511
Sean Callanan92adcac2011-01-13 08:53:35 +00001512 clang::QualType qual_type;
Sean Callanan77eaf442011-07-08 00:39:14 +00001513 const Type *value_type = NULL;
Sean Callanan92adcac2011-01-13 08:53:35 +00001514
Sean Callanane1175b72011-01-13 21:23:32 +00001515 if (name[0] == '$')
Sean Callanan92adcac2011-01-13 08:53:35 +00001516 {
1517 // The $__lldb_expr_result name indicates the the return value has allocated as
1518 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1519 // accesses to this static variable need to be redirected to the result of dereferencing
1520 // a pointer that is passed in as one of the arguments.
1521 //
1522 // Consequently, when reporting the size of the type, we report a pointer type pointing
1523 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanane1175b72011-01-13 21:23:32 +00001524 //
1525 // We also do this for any user-declared persistent variables.
Sean Callanan1d180662010-07-20 23:31:16 +00001526
Sean Callanan92adcac2011-01-13 08:53:35 +00001527 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1528 value_type = PointerType::get(global_variable->getType(), 0);
1529 }
1530 else
1531 {
1532 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1533 value_type = global_variable->getType();
1534 }
Sean Callanan038df5032010-09-30 21:18:25 +00001535
Greg Claytonfaac1112013-03-14 18:31:44 +00001536 uint64_t value_size = (ast_context->getTypeSize(qual_type) + 7ull) / 8ull;
1537 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7ull) / 8ull;
Sean Callanan17827832010-12-13 22:46:15 +00001538
Sean Callanan038df5032010-09-30 21:18:25 +00001539 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +00001540 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
Sean Callanan038df5032010-09-30 21:18:25 +00001541 name.c_str(),
1542 qual_type.getAsString().c_str(),
1543 PrintType(value_type).c_str(),
1544 value_size,
1545 value_alignment);
Sean Callanan17827832010-12-13 22:46:15 +00001546
Sean Callanan549c9f72010-07-13 21:41:46 +00001547
Sean Callanan64dfc9a2010-08-23 23:09:38 +00001548 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton7b462cc2010-10-15 22:48:33 +00001549 lldb_private::ConstString (name.c_str()),
1550 llvm_value_ptr,
Sean Callanan4edba2d2010-07-27 02:07:53 +00001551 value_size,
1552 value_alignment))
Sean Callananaf8e96c2011-08-01 17:41:38 +00001553 {
1554 if (!global_variable->hasExternalLinkage())
1555 return true;
Sean Callanan0ff3bf92013-04-11 17:57:16 +00001556 else if (HandleSymbol (global_variable))
1557 return true;
Sean Callananaf8e96c2011-08-01 17:41:38 +00001558 else
1559 return false;
1560 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001561 }
Sean Callanan4a5fcbb2010-12-03 03:02:31 +00001562 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001563 {
1564 if (log)
1565 log->Printf("Function pointers aren't handled right now");
1566
1567 return false;
1568 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001569
1570 return true;
1571}
1572
Sean Callanan3989fb92011-01-27 01:07:04 +00001573// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001574bool
Sean Callanan79763a42011-05-23 21:40:23 +00001575IRForTarget::HandleSymbol (Value *symbol)
Sean Callanand9ca42a2011-05-08 02:21:26 +00001576{
Greg Clayton5160ce52013-03-27 23:08:40 +00001577 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc3a16002011-01-17 23:42:46 +00001578
1579 lldb_private::ConstString name(symbol->getName().str().c_str());
1580
Sean Callanan947ccc72011-12-01 02:04:16 +00001581 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
Sean Callananc3a16002011-01-17 23:42:46 +00001582
Greg Clayton084db102011-06-23 04:25:29 +00001583 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc3a16002011-01-17 23:42:46 +00001584 {
1585 if (log)
1586 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1587
1588 return false;
1589 }
1590
1591 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001592 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
Sean Callananc3a16002011-01-17 23:42:46 +00001593
Sean Callanancc427fa2011-07-30 02:42:06 +00001594 Type *symbol_type = symbol->getType();
Sean Callanancc427fa2011-07-30 02:42:06 +00001595 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001596 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc3a16002011-01-17 23:42:46 +00001597
1598 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1599
1600 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1601
1602 if (log)
1603 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1604
1605 symbol->replaceAllUsesWith(symbol_addr_ptr);
1606
1607 return true;
1608}
1609
1610bool
Sean Callanan79763a42011-05-23 21:40:23 +00001611IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanan85a0a832010-10-05 22:26:43 +00001612{
Greg Clayton5160ce52013-03-27 23:08:40 +00001613 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001614
1615 if (log)
1616 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanan85a0a832010-10-05 22:26:43 +00001617
Sean Callananafe16a72010-11-17 23:00:36 +00001618 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanan85a0a832010-10-05 22:26:43 +00001619 op_index < num_ops;
1620 ++op_index)
Sean Callanan79763a42011-05-23 21:40:23 +00001621 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan3989fb92011-01-27 01:07:04 +00001622 {
1623 if (m_error_stream)
1624 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1625
Sean Callanan85a0a832010-10-05 22:26:43 +00001626 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001627 }
1628
Sean Callanan85a0a832010-10-05 22:26:43 +00001629 return true;
1630}
1631
1632bool
Sean Callananfc89c142011-11-01 23:38:03 +00001633IRForTarget::HandleObjCClass(Value *classlist_reference)
1634{
Greg Clayton5160ce52013-03-27 23:08:40 +00001635 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananfc89c142011-11-01 23:38:03 +00001636
1637 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1638
1639 if (!global_variable)
1640 return false;
1641
1642 Constant *initializer = global_variable->getInitializer();
1643
1644 if (!initializer)
1645 return false;
1646
1647 if (!initializer->hasName())
1648 return false;
1649
1650 StringRef name(initializer->getName());
1651 lldb_private::ConstString name_cstr(name.str().c_str());
Greg Clayton1075aca2011-12-03 20:02:42 +00001652 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
Sean Callananfc89c142011-11-01 23:38:03 +00001653
1654 if (log)
1655 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1656
1657 if (class_ptr == LLDB_INVALID_ADDRESS)
1658 return false;
1659
1660 if (global_variable->use_begin() == global_variable->use_end())
1661 return false;
1662
Sean Callanan719a4d52013-03-23 01:01:16 +00001663 SmallVector<LoadInst *, 2> load_instructions;
1664
Sean Callananfc89c142011-11-01 23:38:03 +00001665 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1666 i != e;
1667 ++i)
1668 {
Sean Callanan719a4d52013-03-23 01:01:16 +00001669 if (LoadInst *load_instruction = dyn_cast<LoadInst>(*i))
1670 load_instructions.push_back(load_instruction);
Sean Callananfc89c142011-11-01 23:38:03 +00001671 }
1672
Sean Callanan719a4d52013-03-23 01:01:16 +00001673 if (load_instructions.empty())
Sean Callananfc89c142011-11-01 23:38:03 +00001674 return false;
1675
1676 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001677 (m_module->getPointerSize()
Micah Villmow08318972012-10-11 17:21:41 +00001678 == Module::Pointer64) ? 64 : 32);
Sean Callananfc89c142011-11-01 23:38:03 +00001679
1680 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
Sean Callananfc89c142011-11-01 23:38:03 +00001681
Sean Callanan719a4d52013-03-23 01:01:16 +00001682 for (LoadInst *load_instruction : load_instructions)
1683 {
1684 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
Sean Callananfc89c142011-11-01 23:38:03 +00001685
Sean Callanan719a4d52013-03-23 01:01:16 +00001686 load_instruction->replaceAllUsesWith(class_bitcast);
1687
1688 load_instruction->eraseFromParent();
1689 }
Sean Callananfc89c142011-11-01 23:38:03 +00001690
1691 return true;
1692}
1693
1694bool
Sean Callanan6e6d4a62012-07-21 02:02:15 +00001695IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1696{
1697 BasicBlock::iterator ii;
1698
1699 std::vector<CallInst *> calls_to_remove;
1700
1701 for (ii = basic_block.begin();
1702 ii != basic_block.end();
1703 ++ii)
1704 {
1705 Instruction &inst = *ii;
1706
1707 CallInst *call = dyn_cast<CallInst>(&inst);
1708
1709 // MaybeHandleCallArguments handles error reporting; we are silent here
1710 if (!call)
1711 continue;
1712
1713 bool remove = false;
1714
1715 llvm::Function *func = call->getCalledFunction();
1716
1717 if (func && func->getName() == "__cxa_atexit")
1718 remove = true;
1719
1720 llvm::Value *val = call->getCalledValue();
1721
1722 if (val && val->getName() == "__cxa_atexit")
1723 remove = true;
1724
1725 if (remove)
1726 calls_to_remove.push_back(call);
1727 }
1728
1729 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1730 ci != ce;
1731 ++ci)
1732 {
1733 (*ci)->eraseFromParent();
1734 }
1735
1736 return true;
1737}
1738
1739bool
Sean Callanan79763a42011-05-23 21:40:23 +00001740IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan549c9f72010-07-13 21:41:46 +00001741{
Sean Callanan2ab712f22010-07-03 01:35:46 +00001742 /////////////////////////////////////////////////////////////////////////
1743 // Prepare the current basic block for execution in the remote process
1744 //
1745
Sean Callanan7ea35012010-07-27 21:39:39 +00001746 BasicBlock::iterator ii;
Sean Callanan549c9f72010-07-13 21:41:46 +00001747
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001748 for (ii = basic_block.begin();
1749 ii != basic_block.end();
Sean Callanan549c9f72010-07-13 21:41:46 +00001750 ++ii)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001751 {
Sean Callanan549c9f72010-07-13 21:41:46 +00001752 Instruction &inst = *ii;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001753
Sean Callanana4e55172010-11-08 00:31:32 +00001754 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callanan4edba2d2010-07-27 02:07:53 +00001755
Sean Callanan3989fb92011-01-27 01:07:04 +00001756 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callanan79763a42011-05-23 21:40:23 +00001757 if (call && !MaybeHandleCallArguments(call))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001758 return false;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001759 }
1760
1761 return true;
1762}
1763
Sean Callanana4e55172010-11-08 00:31:32 +00001764bool
Sean Callanan79763a42011-05-23 21:40:23 +00001765IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanana4e55172010-11-08 00:31:32 +00001766{
Greg Clayton5160ce52013-03-27 23:08:40 +00001767 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7a55a322010-11-18 22:21:58 +00001768
Sean Callanan79763a42011-05-23 21:40:23 +00001769 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanana4e55172010-11-08 00:31:32 +00001770 global != end;
1771 ++global)
1772 {
Sean Callanan694e2442011-12-22 21:24:49 +00001773 if (!global)
1774 {
1775 if (m_error_stream)
1776 m_error_stream->Printf("Internal error [IRForTarget]: global variable is NULL");
1777
1778 return false;
1779 }
1780
1781 std::string global_name = (*global).getName().str();
1782
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001783 if (log)
1784 log->Printf("Examining %s, DeclForGlobalValue returns %p",
Sean Callanan694e2442011-12-22 21:24:49 +00001785 global_name.c_str(),
Sean Callanan79763a42011-05-23 21:40:23 +00001786 DeclForGlobal(global));
Sean Callananfc89c142011-11-01 23:38:03 +00001787
1788 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc3a16002011-01-17 23:42:46 +00001789 {
Sean Callanan79763a42011-05-23 21:40:23 +00001790 if (!HandleSymbol(global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001791 {
1792 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001793 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 +00001794
Sean Callananc3a16002011-01-17 23:42:46 +00001795 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001796 }
Sean Callananc3a16002011-01-17 23:42:46 +00001797 }
Sean Callananfc89c142011-11-01 23:38:03 +00001798 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1799 {
1800 if (!HandleObjCClass(global))
1801 {
1802 if (m_error_stream)
1803 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1804
1805 return false;
1806 }
1807 }
Sean Callanan2ad66912013-04-24 21:25:20 +00001808 else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos)
1809 {
1810 if (!HandleObjCClass(global))
1811 {
1812 if (m_error_stream)
1813 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1814
1815 return false;
1816 }
1817 }
Sean Callanan79763a42011-05-23 21:40:23 +00001818 else if (DeclForGlobal(global))
Sean Callananc3a16002011-01-17 23:42:46 +00001819 {
Sean Callanan79763a42011-05-23 21:40:23 +00001820 if (!MaybeHandleVariable (global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001821 {
1822 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001823 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 +00001824
Sean Callananc3a16002011-01-17 23:42:46 +00001825 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001826 }
Sean Callananc3a16002011-01-17 23:42:46 +00001827 }
Sean Callanana4e55172010-11-08 00:31:32 +00001828 }
1829
1830 return true;
1831}
1832
Sean Callanan79763a42011-05-23 21:40:23 +00001833bool
1834IRForTarget::ReplaceStrings ()
1835{
Greg Clayton5160ce52013-03-27 23:08:40 +00001836 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001837
Sean Callanan79763a42011-05-23 21:40:23 +00001838 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1839
1840 OffsetsTy offsets;
1841
1842 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1843 gi != ge;
1844 ++gi)
1845 {
1846 GlobalVariable *gv = gi;
1847
1848 if (!gv->hasInitializer())
1849 continue;
1850
1851 Constant *gc = gv->getInitializer();
1852
Sean Callanan5207a342011-08-10 21:05:52 +00001853 std::string str;
Sean Callanan79763a42011-05-23 21:40:23 +00001854
Sean Callanan5207a342011-08-10 21:05:52 +00001855 if (gc->isNullValue())
1856 {
1857 Type *gc_type = gc->getType();
1858
1859 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1860
1861 if (!gc_array_type)
1862 continue;
1863
1864 Type *gc_element_type = gc_array_type->getElementType();
1865
1866 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1867
1868 if (gc_integer_type->getBitWidth() != 8)
1869 continue;
1870
1871 str = "";
1872 }
1873 else
1874 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001875 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
Sean Callanan5207a342011-08-10 21:05:52 +00001876
1877 if (!gc_array)
1878 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001879
Sean Callanan5207a342011-08-10 21:05:52 +00001880 if (!gc_array->isCString())
1881 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001882
Sean Callanan5207a342011-08-10 21:05:52 +00001883 if (log)
1884 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00001885
Sean Callanan5207a342011-08-10 21:05:52 +00001886 str = gc_array->getAsString();
1887 }
1888
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001889 offsets[gv] = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00001890
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001891 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
Sean Callanan79763a42011-05-23 21:40:23 +00001892 }
1893
Sean Callanancc427fa2011-07-30 02:42:06 +00001894 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00001895
1896 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1897 oi != oe;
1898 ++oi)
1899 {
1900 GlobalVariable *gv = oi->first;
1901 size_t offset = oi->second;
1902
1903 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1904
1905 if (log)
1906 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1907
1908 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1909 ui != ue;
1910 ++ui)
1911 {
1912 if (log)
1913 log->Printf("Found use %s", PrintValue(*ui).c_str());
1914
1915 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1916 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1917
1918 if (const_expr)
1919 {
1920 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1921 {
1922 if (log)
1923 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1924
1925 return false;
1926 }
1927
Sean Callanan5207a342011-08-10 21:05:52 +00001928 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1929 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1930
1931 const_expr->replaceAllUsesWith(new_gep);
Sean Callanan79763a42011-05-23 21:40:23 +00001932 }
1933 else if (store_inst)
1934 {
1935 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1936
1937 store_inst->setOperand(0, bit_cast);
1938 }
1939 else
1940 {
1941 if (log)
1942 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1943
1944 return false;
1945 }
1946 }
1947
1948 gv->eraseFromParent();
1949 }
1950
1951 return true;
1952}
1953
1954bool
1955IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1956{
Greg Clayton5160ce52013-03-27 23:08:40 +00001957 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001958
1959 typedef SmallVector <Value*, 2> ConstantList;
1960 typedef SmallVector <llvm::Instruction*, 2> UserList;
1961 typedef ConstantList::iterator ConstantIterator;
1962 typedef UserList::iterator UserIterator;
1963
1964 ConstantList static_constants;
1965 UserList static_users;
1966
1967 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1968 ii != ie;
1969 ++ii)
1970 {
1971 llvm::Instruction &inst = *ii;
1972
1973 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1974 oi != oe;
1975 ++oi)
1976 {
1977 Value *operand_val = oi->get();
1978
1979 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1980
Sean Callanan822944c2012-04-26 20:51:20 +00001981 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
Sean Callanan79763a42011-05-23 21:40:23 +00001982 {
1983 static_constants.push_back(operand_val);
1984 static_users.push_back(ii);
1985 }
1986 }
1987 }
1988
1989 ConstantIterator constant_iter;
1990 UserIterator user_iter;
Greg Clayton9b72eb72011-05-24 23:06:02 +00001991
Sean Callanan79763a42011-05-23 21:40:23 +00001992 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1993 constant_iter != static_constants.end();
1994 ++constant_iter, ++user_iter)
1995 {
1996 Value *operand_val = *constant_iter;
1997 llvm::Instruction *inst = *user_iter;
1998
1999 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2000
2001 if (operand_constant_fp)
2002 {
Sean Callanan1582ee62013-04-18 22:06:33 +00002003 Type *operand_type = operand_constant_fp->getType();
2004
Sean Callanan79763a42011-05-23 21:40:23 +00002005 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2006 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2007
2008 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2009 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2010
2011 if (log)
2012 {
2013 std::string s;
2014 raw_string_ostream ss(s);
2015 for (size_t index = 0;
2016 index < operand_data_size;
2017 ++index)
2018 {
2019 ss << (uint32_t)operand_raw_data[index];
2020 ss << " ";
2021 }
2022 ss.flush();
2023
Jason Molendafd54b362011-09-20 21:44:10 +00002024 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00002025 }
2026
2027 lldb_private::DataBufferHeap data(operand_data_size, 0);
2028
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002029 if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
Sean Callanan79763a42011-05-23 21:40:23 +00002030 {
2031 uint8_t *data_bytes = data.GetBytes();
2032
2033 for (size_t index = 0;
2034 index < operand_data_size;
2035 ++index)
2036 {
2037 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2038 }
2039 }
2040 else
2041 {
2042 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2043 }
2044
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002045 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00002046
Sean Callanane3333d62012-06-08 22:20:41 +00002047 size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2048
2049 const size_t mask = (align - 1);
2050 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002051 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00002052 offset = aligned_offset;
2053
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002054 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
Sean Callanan79763a42011-05-23 21:40:23 +00002055
Sean Callanancc427fa2011-07-30 02:42:06 +00002056 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callanan79763a42011-05-23 21:40:23 +00002057
Sean Callanan1582ee62013-04-18 22:06:33 +00002058 Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
Sean Callanan79763a42011-05-23 21:40:23 +00002059
2060 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2061
2062 operand_constant_fp->replaceAllUsesWith(fp_load);
2063 }
2064 }
2065
2066 return true;
2067}
2068
Sean Callanan7ea35012010-07-27 21:39:39 +00002069static bool isGuardVariableRef(Value *V)
Sean Callananddb46ef2010-07-24 01:37:44 +00002070{
Sean Callanan77eaf442011-07-08 00:39:14 +00002071 Constant *Old = NULL;
Sean Callananddb46ef2010-07-24 01:37:44 +00002072
Sean Callananafe16a72010-11-17 23:00:36 +00002073 if (!(Old = dyn_cast<Constant>(V)))
Sean Callananddb46ef2010-07-24 01:37:44 +00002074 return false;
2075
Sean Callanan77eaf442011-07-08 00:39:14 +00002076 ConstantExpr *CE = NULL;
Sean Callanane2ef6e32010-09-23 03:01:22 +00002077
2078 if ((CE = dyn_cast<ConstantExpr>(V)))
2079 {
2080 if (CE->getOpcode() != Instruction::BitCast)
2081 return false;
2082
Sean Callananafe16a72010-11-17 23:00:36 +00002083 Old = CE->getOperand(0);
Sean Callanane2ef6e32010-09-23 03:01:22 +00002084 }
2085
Sean Callananafe16a72010-11-17 23:00:36 +00002086 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callananddb46ef2010-07-24 01:37:44 +00002087
2088 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2089 return false;
2090
2091 return true;
2092}
2093
Sean Callanan79763a42011-05-23 21:40:23 +00002094void
2095IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callananddb46ef2010-07-24 01:37:44 +00002096{
Sean Callanan79763a42011-05-23 21:40:23 +00002097 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callananddb46ef2010-07-24 01:37:44 +00002098
2099 Value::use_iterator ui;
2100
2101 for (ui = guard_load->use_begin();
2102 ui != guard_load->use_end();
2103 ++ui)
Sean Callananb27a62f2010-07-27 01:17:28 +00002104 {
Greg Claytone6371122010-07-30 20:30:44 +00002105 if (isa<Constant>(*ui))
Sean Callananb27a62f2010-07-27 01:17:28 +00002106 {
2107 // do nothing for the moment
2108 }
2109 else
2110 {
2111 ui->replaceUsesOfWith(guard_load, zero);
2112 }
2113 }
Sean Callananddb46ef2010-07-24 01:37:44 +00002114
2115 guard_load->eraseFromParent();
2116}
2117
2118static void ExciseGuardStore(Instruction* guard_store)
2119{
2120 guard_store->eraseFromParent();
2121}
2122
2123bool
Sean Callanan79763a42011-05-23 21:40:23 +00002124IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callananddb46ef2010-07-24 01:37:44 +00002125{
2126 ///////////////////////////////////////////////////////
2127 // Eliminate any reference to guard variables found.
2128 //
2129
Sean Callanan7ea35012010-07-27 21:39:39 +00002130 BasicBlock::iterator ii;
Sean Callananddb46ef2010-07-24 01:37:44 +00002131
Sean Callanan7ea35012010-07-27 21:39:39 +00002132 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callananddb46ef2010-07-24 01:37:44 +00002133 typedef InstrList::iterator InstrIterator;
2134
2135 InstrList guard_loads;
2136 InstrList guard_stores;
2137
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002138 for (ii = basic_block.begin();
2139 ii != basic_block.end();
Sean Callananddb46ef2010-07-24 01:37:44 +00002140 ++ii)
2141 {
2142 Instruction &inst = *ii;
2143
2144 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2145 if (isGuardVariableRef(load->getPointerOperand()))
2146 guard_loads.push_back(&inst);
2147
2148 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2149 if (isGuardVariableRef(store->getPointerOperand()))
2150 guard_stores.push_back(&inst);
2151 }
2152
2153 InstrIterator iter;
2154
2155 for (iter = guard_loads.begin();
2156 iter != guard_loads.end();
2157 ++iter)
Sean Callanan79763a42011-05-23 21:40:23 +00002158 TurnGuardLoadIntoZero(*iter);
Sean Callananddb46ef2010-07-24 01:37:44 +00002159
2160 for (iter = guard_stores.begin();
2161 iter != guard_stores.end();
2162 ++iter)
2163 ExciseGuardStore(*iter);
2164
2165 return true;
2166}
2167
Sean Callanan3989fb92011-01-27 01:07:04 +00002168// This function does not report errors; its callers are responsible.
Sean Callananafe16a72010-11-17 23:00:36 +00002169bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002170IRForTarget::UnfoldConstant(Constant *old_constant,
2171 FunctionValueCache &value_maker,
2172 FunctionValueCache &entry_instruction_finder)
Sean Callanan7618f4e2010-07-14 23:40:29 +00002173{
Greg Clayton5160ce52013-03-27 23:08:40 +00002174 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002175
2176 Value::use_iterator ui;
2177
Sean Callanan2235f322010-08-11 03:57:18 +00002178 SmallVector<User*, 16> users;
2179
2180 // We do this because the use list might change, invalidating our iterator.
2181 // Much better to keep a work list ourselves.
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002182 for (ui = old_constant->use_begin();
2183 ui != old_constant->use_end();
Sean Callanan7618f4e2010-07-14 23:40:29 +00002184 ++ui)
Sean Callanan2235f322010-08-11 03:57:18 +00002185 users.push_back(*ui);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002186
Johnny Chen44805302011-07-19 19:48:13 +00002187 for (size_t i = 0;
Sean Callanan2235f322010-08-11 03:57:18 +00002188 i < users.size();
2189 ++i)
2190 {
2191 User *user = users[i];
2192
Sean Callanan7618f4e2010-07-14 23:40:29 +00002193 if (Constant *constant = dyn_cast<Constant>(user))
2194 {
2195 // synthesize a new non-constant equivalent of the constant
2196
2197 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2198 {
2199 switch (constant_expr->getOpcode())
2200 {
2201 default:
2202 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002203 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002204 return false;
2205 case Instruction::BitCast:
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002206 {
2207 FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2208 // UnaryExpr
2209 // OperandList[0] is value
2210
2211 if (constant_expr->getOperand(0) != old_constant)
2212 return constant_expr;
2213
2214 return new BitCastInst(value_maker.GetValue(function),
2215 constant_expr->getType(),
2216 "",
2217 llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2218 });
Sean Callanan7618f4e2010-07-14 23:40:29 +00002219
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002220 return UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002221 }
2222 break;
2223 case Instruction::GetElementPtr:
2224 {
2225 // GetElementPtrConstantExpr
2226 // OperandList[0] is base
2227 // OperandList[1]... are indices
2228
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002229 FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2230 Value *ptr = constant_expr->getOperand(0);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002231
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002232 if (ptr == old_constant)
2233 ptr = value_maker.GetValue(function);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002234
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002235 std::vector<Value*> index_vector;
2236
2237 unsigned operand_index;
2238 unsigned num_operands = constant_expr->getNumOperands();
2239
2240 for (operand_index = 1;
2241 operand_index < num_operands;
2242 ++operand_index)
2243 {
2244 Value *operand = constant_expr->getOperand(operand_index);
2245
2246 if (operand == old_constant)
2247 operand = value_maker.GetValue(function);
2248
2249 index_vector.push_back(operand);
2250 }
2251
2252 ArrayRef <Value*> indices(index_vector);
2253
2254 return GetElementPtrInst::Create(ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2255 });
Sean Callanan7618f4e2010-07-14 23:40:29 +00002256
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002257 return UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002258 }
2259 break;
2260 }
2261 }
2262 else
2263 {
2264 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002265 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002266 return false;
2267 }
2268 }
2269 else
2270 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002271 if (Instruction *inst = llvm::dyn_cast<Instruction>(user))
2272 {
2273 inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent()));
2274 }
2275 else
2276 {
2277 if (log)
2278 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str());
2279 return false;
2280 }
Sean Callanan7618f4e2010-07-14 23:40:29 +00002281 }
2282 }
2283
2284 return true;
2285}
2286
Sean Callanan549c9f72010-07-13 21:41:46 +00002287bool
Sean Callanan79763a42011-05-23 21:40:23 +00002288IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan549c9f72010-07-13 21:41:46 +00002289{
Sean Callanan9e6ed532010-09-13 21:34:21 +00002290 if (!m_resolve_vars)
2291 return true;
2292
Greg Clayton5160ce52013-03-27 23:08:40 +00002293 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan549c9f72010-07-13 21:41:46 +00002294
2295 m_decl_map->DoStructLayout();
2296
2297 if (log)
2298 log->Printf("Element arrangement:");
2299
2300 uint32_t num_elements;
2301 uint32_t element_index;
2302
2303 size_t size;
2304 off_t alignment;
2305
2306 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2307 return false;
2308
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002309 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan549c9f72010-07-13 21:41:46 +00002310
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002311 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002312 {
2313 if (m_error_stream)
2314 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2315
Sean Callanan549c9f72010-07-13 21:41:46 +00002316 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002317 }
2318
Sean Callanan7ea35012010-07-27 21:39:39 +00002319 Argument *argument = iter;
Sean Callanan549c9f72010-07-13 21:41:46 +00002320
Sean Callananfc55f5d2010-09-21 00:44:12 +00002321 if (argument->getName().equals("this"))
2322 {
2323 ++iter;
2324
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002325 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002326 {
2327 if (m_error_stream)
2328 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2329
Sean Callananfc55f5d2010-09-21 00:44:12 +00002330 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002331 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002332
2333 argument = iter;
2334 }
Sean Callanan17827832010-12-13 22:46:15 +00002335 else if (argument->getName().equals("self"))
2336 {
2337 ++iter;
2338
2339 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002340 {
2341 if (m_error_stream)
2342 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2343
Sean Callanan17827832010-12-13 22:46:15 +00002344 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002345 }
Sean Callanan17827832010-12-13 22:46:15 +00002346
2347 if (!iter->getName().equals("_cmd"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002348 {
2349 if (m_error_stream)
2350 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2351
Sean Callanan17827832010-12-13 22:46:15 +00002352 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002353 }
Sean Callanan17827832010-12-13 22:46:15 +00002354
2355 ++iter;
2356
2357 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002358 {
2359 if (m_error_stream)
2360 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2361
Sean Callanan17827832010-12-13 22:46:15 +00002362 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002363 }
Sean Callanan17827832010-12-13 22:46:15 +00002364
2365 argument = iter;
2366 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002367
Greg Clayton7b462cc2010-10-15 22:48:33 +00002368 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002369 {
2370 if (m_error_stream)
2371 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2372
Sean Callanan549c9f72010-07-13 21:41:46 +00002373 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002374 }
2375
Sean Callanan549c9f72010-07-13 21:41:46 +00002376 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002377 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan549c9f72010-07-13 21:41:46 +00002378
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002379 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +00002380 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan549c9f72010-07-13 21:41:46 +00002381
Sean Callananafe16a72010-11-17 23:00:36 +00002382 if (!FirstEntryInstruction)
Sean Callanan3989fb92011-01-27 01:07:04 +00002383 {
2384 if (m_error_stream)
2385 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2386
Sean Callanan549c9f72010-07-13 21:41:46 +00002387 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002388 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002389
Sean Callanan79763a42011-05-23 21:40:23 +00002390 LLVMContext &context(m_module->getContext());
Sean Callanancc427fa2011-07-30 02:42:06 +00002391 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan549c9f72010-07-13 21:41:46 +00002392
2393 if (!offset_type)
Sean Callanan3989fb92011-01-27 01:07:04 +00002394 {
2395 if (m_error_stream)
2396 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2397
Sean Callanan549c9f72010-07-13 21:41:46 +00002398 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002399 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002400
2401 for (element_index = 0; element_index < num_elements; ++element_index)
2402 {
Sean Callanan77eaf442011-07-08 00:39:14 +00002403 const clang::NamedDecl *decl = NULL;
2404 Value *value = NULL;
Sean Callanan549c9f72010-07-13 21:41:46 +00002405 off_t offset;
Greg Clayton7b462cc2010-10-15 22:48:33 +00002406 lldb_private::ConstString name;
Sean Callanan549c9f72010-07-13 21:41:46 +00002407
Sean Callanan823bb4c2010-08-30 22:17:16 +00002408 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan3989fb92011-01-27 01:07:04 +00002409 {
2410 if (m_error_stream)
2411 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2412
Sean Callanan549c9f72010-07-13 21:41:46 +00002413 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002414 }
2415
Sean Callanan549c9f72010-07-13 21:41:46 +00002416 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002417 log->Printf(" \"%s\" (\"%s\") placed at %" PRId64,
Greg Clayton7b462cc2010-10-15 22:48:33 +00002418 name.GetCString(),
Sean Callananc70ed462011-10-25 18:36:40 +00002419 decl->getNameAsString().c_str(),
Sean Callanan549c9f72010-07-13 21:41:46 +00002420 offset);
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002421
Sean Callananc70ed462011-10-25 18:36:40 +00002422 if (value)
Sean Callanan92adcac2011-01-13 08:53:35 +00002423 {
Sean Callananc70ed462011-10-25 18:36:40 +00002424 if (log)
2425 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan92adcac2011-01-13 08:53:35 +00002426
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002427 FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * {
2428 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2429 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2430 // entry in order to produce the static variable that the AST thinks it is accessing.
Sean Callananc70ed462011-10-25 18:36:40 +00002431
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002432 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function));
Sean Callananc70ed462011-10-25 18:36:40 +00002433
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002434 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
2435 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument,
2436 offset_int,
2437 "",
2438 entry_instruction);
2439
2440 if (name == m_result_name && !m_result_is_pointer)
2441 {
2442 BitCastInst *bit_cast = new BitCastInst(get_element_ptr,
2443 value->getType()->getPointerTo(),
2444 "",
2445 entry_instruction);
2446
2447 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
2448
2449 return load;
2450 }
2451 else
2452 {
2453 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction);
2454
2455 return bit_cast;
2456 }
2457 });
Sean Callananc70ed462011-10-25 18:36:40 +00002458
2459 if (Constant *constant = dyn_cast<Constant>(value))
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002460 {
2461 UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder);
2462 }
2463 else if (Instruction *instruction = dyn_cast<Instruction>(value))
2464 {
2465 value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent()));
2466 }
Sean Callananc70ed462011-10-25 18:36:40 +00002467 else
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002468 {
2469 if (log)
2470 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str());
2471 return false;
2472 }
Sean Callananc70ed462011-10-25 18:36:40 +00002473
2474 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2475 var->eraseFromParent();
2476 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002477 }
2478
2479 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002480 log->Printf("Total structure [align %" PRId64 ", size %lu]", alignment, size);
Sean Callanan549c9f72010-07-13 21:41:46 +00002481
2482 return true;
2483}
2484
Sean Callanan79763a42011-05-23 21:40:23 +00002485llvm::Constant *
Greg Clayton5160ce52013-03-27 23:08:40 +00002486IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
Sean Callanan79763a42011-05-23 21:40:23 +00002487{
Sean Callanancc427fa2011-07-30 02:42:06 +00002488 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00002489 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan79763a42011-05-23 21:40:23 +00002490
2491 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanancc427fa2011-07-30 02:42:06 +00002492
2493 llvm::Constant *offset_array[1];
2494
2495 offset_array[0] = offset_int;
2496
2497 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2498
2499 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callanan79763a42011-05-23 21:40:23 +00002500 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2501
2502 return reloc_getbitcast;
2503}
2504
2505bool
2506IRForTarget::CompleteDataAllocation ()
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002507{
Greg Clayton5160ce52013-03-27 23:08:40 +00002508 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002509
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002510 if (!m_data_allocator.GetStream().GetSize())
Sean Callanan79763a42011-05-23 21:40:23 +00002511 return true;
2512
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002513 lldb::addr_t allocation = m_data_allocator.Allocate();
Sean Callanan79763a42011-05-23 21:40:23 +00002514
2515 if (log)
2516 {
2517 if (allocation)
2518 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2519 else
2520 log->Printf("Failed to allocate static data");
2521 }
2522
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002523 if (!allocation || allocation == LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +00002524 return false;
2525
Sean Callanancc427fa2011-07-30 02:42:06 +00002526 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00002527 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan79763a42011-05-23 21:40:23 +00002528
2529 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2530 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2531
2532 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2533
2534 m_reloc_placeholder->eraseFromParent();
2535
2536 return true;
2537}
2538
Sean Callanan2ab712f22010-07-03 01:35:46 +00002539bool
Sean Callanan3d654b32012-09-24 22:25:51 +00002540IRForTarget::StripAllGVs (Module &llvm_module)
2541{
Greg Clayton5160ce52013-03-27 23:08:40 +00002542 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3d654b32012-09-24 22:25:51 +00002543 std::vector<GlobalVariable *> global_vars;
2544 std::set<GlobalVariable *>erased_vars;
2545
2546 bool erased = true;
2547
2548 while (erased)
2549 {
2550 erased = false;
2551
2552 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2553 gi != ge;
2554 ++gi)
2555 {
2556 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2557
2558 global_var->removeDeadConstantUsers();
2559
2560 if (global_var->use_empty())
2561 {
2562 if (log)
2563 log->Printf("Did remove %s",
2564 PrintValue(global_var).c_str());
2565 global_var->eraseFromParent();
2566 erased = true;
2567 break;
2568 }
2569 }
2570 }
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 GlobalValue::use_iterator ui = global_var->use_begin();
2579
Jim Inghamd77557d2012-11-26 19:54:04 +00002580 if (log)
2581 log->Printf("Couldn't remove %s because of %s",
2582 PrintValue(global_var).c_str(),
2583 PrintValue(*ui).c_str());
Sean Callanan3d654b32012-09-24 22:25:51 +00002584 }
2585
2586 return true;
2587}
2588
2589bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002590IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002591{
Greg Clayton5160ce52013-03-27 23:08:40 +00002592 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002593
Sean Callanan79763a42011-05-23 21:40:23 +00002594 m_module = &llvm_module;
Micah Villmow8468dbe2012-10-08 16:28:57 +00002595 m_target_data.reset(new DataLayout(m_module));
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002596
Sean Callananc70ed462011-10-25 18:36:40 +00002597 if (log)
2598 {
2599 std::string s;
2600 raw_string_ostream oss(s);
2601
2602 m_module->print(oss, NULL);
2603
2604 oss.flush();
2605
2606 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2607 }
2608
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002609 Function* main_function = m_module->getFunction(StringRef(m_func_name.c_str()));
2610
2611 if (!main_function)
2612 {
2613 if (log)
2614 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
2615
2616 if (m_error_stream)
2617 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
2618
2619 return false;
2620 }
2621
2622 if (!FixFunctionLinkage (*main_function))
2623 {
2624 if (log)
2625 log->Printf("Couldn't fix the linkage for the function");
2626
2627 return false;
2628 }
2629
Sean Callanancc427fa2011-07-30 02:42:06 +00002630 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00002631
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002632 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
Sean Callanan79763a42011-05-23 21:40:23 +00002633 intptr_ty,
Sean Callanan3d654b32012-09-24 22:25:51 +00002634 false /* IsConstant */,
Sean Callanan79763a42011-05-23 21:40:23 +00002635 GlobalVariable::InternalLinkage,
2636 Constant::getNullValue(intptr_ty),
2637 "reloc_placeholder",
2638 NULL /* InsertBefore */,
Sean Callanan3d654b32012-09-24 22:25:51 +00002639 GlobalVariable::NotThreadLocal /* ThreadLocal */,
Sean Callanan79763a42011-05-23 21:40:23 +00002640 0 /* AddressSpace */);
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002641
Sean Callanand1e5b432010-08-12 01:56:52 +00002642 ////////////////////////////////////////////////////////////
Greg Clayton7b462cc2010-10-15 22:48:33 +00002643 // Replace $__lldb_expr_result with a persistent variable
Sean Callanand1e5b432010-08-12 01:56:52 +00002644 //
2645
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002646 if (!CreateResultVariable(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002647 {
2648 if (log)
2649 log->Printf("CreateResultVariable() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002650
2651 // CreateResultVariable() reports its own errors, so we don't do so here
2652
Sean Callanand1e5b432010-08-12 01:56:52 +00002653 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002654 }
Sean Callanan6e6d4a62012-07-21 02:02:15 +00002655
Sean Callananea685ae2011-11-01 17:33:54 +00002656 if (log && log->GetVerbose())
Sean Callanan79763a42011-05-23 21:40:23 +00002657 {
2658 std::string s;
2659 raw_string_ostream oss(s);
2660
2661 m_module->print(oss, NULL);
2662
2663 oss.flush();
2664
2665 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2666 }
2667
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002668 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2669 fi != fe;
2670 ++fi)
2671 {
2672 llvm::Function *function = fi;
2673
2674 if (function->begin() == function->end())
2675 continue;
2676
2677 Function::iterator bbi;
2678
2679 for (bbi = function->begin();
2680 bbi != function->end();
2681 ++bbi)
2682 {
2683 if (!RemoveGuards(*bbi))
2684 {
2685 if (log)
2686 log->Printf("RemoveGuards() failed");
2687
2688 // RemoveGuards() reports its own errors, so we don't do so here
2689
2690 return false;
2691 }
2692
2693 if (!RewritePersistentAllocs(*bbi))
2694 {
2695 if (log)
2696 log->Printf("RewritePersistentAllocs() failed");
2697
2698 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2699
2700 return false;
2701 }
2702
2703 if (!RemoveCXAAtExit(*bbi))
2704 {
2705 if (log)
2706 log->Printf("RemoveCXAAtExit() failed");
2707
2708 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2709
2710 return false;
2711 }
2712 }
2713 }
2714
Sean Callananafe16a72010-11-17 23:00:36 +00002715 ///////////////////////////////////////////////////////////////////////////////
2716 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2717 //
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002718
2719 if (!RewriteObjCConstStrings())
Sean Callanan17827832010-12-13 22:46:15 +00002720 {
2721 if (log)
2722 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002723
2724 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2725
Sean Callananafe16a72010-11-17 23:00:36 +00002726 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002727 }
Sean Callananafe16a72010-11-17 23:00:36 +00002728
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002729 ///////////////////////////////
2730 // Resolve function pointers
2731 //
2732
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002733 if (!ResolveFunctionPointers(llvm_module))
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002734 {
2735 if (log)
2736 log->Printf("ResolveFunctionPointers() failed");
2737
2738 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2739
2740 return false;
2741 }
2742
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002743 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2744 fi != fe;
2745 ++fi)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002746 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002747 llvm::Function *function = fi;
2748
2749 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2750 bbi != bbe;
2751 ++bbi)
Sean Callanan17827832010-12-13 22:46:15 +00002752 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002753 if (!RewriteObjCSelectors(*bbi))
2754 {
2755 if (log)
2756 log->Printf("RewriteObjCSelectors() failed");
2757
2758 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2759
2760 return false;
2761 }
Sean Callanan17827832010-12-13 22:46:15 +00002762 }
Sean Callananbad134f2012-07-27 19:25:24 +00002763 }
Sean Callanan2235f322010-08-11 03:57:18 +00002764
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002765 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2766 fi != fe;
2767 ++fi)
Sean Callananbad134f2012-07-27 19:25:24 +00002768 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002769 llvm::Function *function = fi;
Sean Callanan79763a42011-05-23 21:40:23 +00002770
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002771 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2772 bbi != bbe;
2773 ++bbi)
Sean Callanan79763a42011-05-23 21:40:23 +00002774 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002775 if (!ResolveCalls(*bbi))
2776 {
2777 if (log)
2778 log->Printf("ResolveCalls() failed");
2779
2780 // ResolveCalls() reports its own errors, so we don't do so here
2781
2782 return false;
2783 }
Sean Callanan79763a42011-05-23 21:40:23 +00002784
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002785 if (!ReplaceStaticLiterals(*bbi))
2786 {
2787 if (log)
2788 log->Printf("ReplaceStaticLiterals() failed");
2789
2790 return false;
2791 }
Sean Callanan79763a42011-05-23 21:40:23 +00002792 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002793 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002794
2795 ////////////////////////////////////////////////////////////////////////
2796 // Run function-level passes that only make sense on the main function
Sean Callanan038df5032010-09-30 21:18:25 +00002797 //
2798
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002799 if (!ResolveExternals(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002800 {
2801 if (log)
2802 log->Printf("ResolveExternals() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002803
2804 // ResolveExternals() reports its own errors, so we don't do so here
2805
Sean Callanana4e55172010-11-08 00:31:32 +00002806 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002807 }
Sean Callanana4e55172010-11-08 00:31:32 +00002808
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002809 if (!ReplaceVariables(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002810 {
2811 if (log)
2812 log->Printf("ReplaceVariables() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002813
2814 // ReplaceVariables() reports its own errors, so we don't do so here
2815
Sean Callanan038df5032010-09-30 21:18:25 +00002816 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002817 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002818
Sean Callanan79763a42011-05-23 21:40:23 +00002819 if (!ReplaceStrings())
2820 {
2821 if (log)
2822 log->Printf("ReplaceStrings() failed");
2823
2824 return false;
2825 }
2826
2827 if (!CompleteDataAllocation())
2828 {
2829 if (log)
2830 log->Printf("CompleteDataAllocation() failed");
2831
2832 return false;
2833 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002834
Sean Callanan3d654b32012-09-24 22:25:51 +00002835 if (!StripAllGVs(llvm_module))
2836 {
2837 if (log)
2838 log->Printf("StripAllGVs() failed");
2839 }
2840
Sean Callananea685ae2011-11-01 17:33:54 +00002841 if (log && log->GetVerbose())
Sean Callanan549c9f72010-07-13 21:41:46 +00002842 {
Sean Callanancc54bd32010-07-28 01:00:59 +00002843 std::string s;
2844 raw_string_ostream oss(s);
Sean Callanan549c9f72010-07-13 21:41:46 +00002845
Sean Callanan79763a42011-05-23 21:40:23 +00002846 m_module->print(oss, NULL);
Sean Callanancc54bd32010-07-28 01:00:59 +00002847
2848 oss.flush();
2849
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002850 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan2ab712f22010-07-03 01:35:46 +00002851 }
2852
2853 return true;
2854}
2855
2856void
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002857IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002858{
2859}
2860
2861PassManagerType
2862IRForTarget::getPotentialPassManagerType() const
2863{
2864 return PMT_ModulePassManager;
2865}