blob: cac3fdf60dfae38c2f1cd321a1a5825a2ba37ed9 [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"
Greg Clayton57ee3062013-07-11 22:46:58 +000036#include "lldb/Symbol/ClangASTType.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000037
38#include <map>
39
40using namespace llvm;
41
Sean Callananeaacbc92010-08-18 18:50:51 +000042static char ID;
43
Sean Callanan8dfb68e2013-03-19 00:10:07 +000044IRForTarget::StaticDataAllocator::StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit) :
45 m_execution_unit(execution_unit),
Sean Callanan1582ee62013-04-18 22:06:33 +000046 m_stream_string(lldb_private::Stream::eBinary, execution_unit.GetAddressByteSize(), execution_unit.GetByteOrder()),
Sean Callanan8dfb68e2013-03-19 00:10:07 +000047 m_allocation(LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +000048{
49}
50
Sean Callanan1f9db3e2013-06-28 21:44:15 +000051IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) :
52 m_maker(maker),
53 m_values()
54{
55}
56
57IRForTarget::FunctionValueCache::~FunctionValueCache()
58{
59}
60
61llvm::Value *IRForTarget::FunctionValueCache::GetValue(llvm::Function *function)
62{
63 if (!m_values.count(function))
64 {
65 llvm::Value *ret = m_maker(function);
66 m_values[function] = ret;
67 return ret;
68 }
69 return m_values[function];
70}
71
Sean Callanan8dfb68e2013-03-19 00:10:07 +000072lldb::addr_t IRForTarget::StaticDataAllocator::Allocate()
Sean Callanan79763a42011-05-23 21:40:23 +000073{
Sean Callanan8dfb68e2013-03-19 00:10:07 +000074 lldb_private::Error err;
75
76 if (m_allocation != LLDB_INVALID_ADDRESS)
77 {
78 m_execution_unit.FreeNow(m_allocation);
79 m_allocation = LLDB_INVALID_ADDRESS;
80 }
81
82 m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
83
84 return m_allocation;
Sean Callanan79763a42011-05-23 21:40:23 +000085}
86
Sean Callanan1f9db3e2013-06-28 21:44:15 +000087static llvm::Value *FindEntryInstruction (llvm::Function *function)
88{
89 if (function->empty())
90 return NULL;
91
92 return function->getEntryBlock().getFirstNonPHIOrDbg();
93}
94
Greg Clayton1b95a6f2010-11-19 01:05:25 +000095IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
96 bool resolve_vars,
Sean Callanan8dfb68e2013-03-19 00:10:07 +000097 lldb_private::IRExecutionUnit &execution_unit,
Sean Callanan3989fb92011-01-27 01:07:04 +000098 lldb_private::Stream *error_stream,
Greg Clayton1b95a6f2010-11-19 01:05:25 +000099 const char *func_name) :
Sean Callanane2ef6e32010-09-23 03:01:22 +0000100 ModulePass(ID),
Stephen Wilson71c21d12011-04-11 19:41:40 +0000101 m_resolve_vars(resolve_vars),
102 m_func_name(func_name),
Sean Callanan79763a42011-05-23 21:40:23 +0000103 m_module(NULL),
Johnny Chen44805302011-07-19 19:48:13 +0000104 m_decl_map(decl_map),
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000105 m_data_allocator(execution_unit),
Sean Callananafe16a72010-11-17 23:00:36 +0000106 m_CFStringCreateWithBytes(NULL),
Sean Callanan1a8d4092010-08-27 01:01:44 +0000107 m_sel_registerName(NULL),
Stephen Wilson71c21d12011-04-11 19:41:40 +0000108 m_error_stream(error_stream),
Sean Callanan63697e52011-05-07 01:06:41 +0000109 m_result_store(NULL),
110 m_result_is_pointer(false),
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000111 m_reloc_placeholder(NULL),
112 m_entry_instruction_finder (FindEntryInstruction)
Sean Callanan2ab712f22010-07-03 01:35:46 +0000113{
114}
115
Sean Callanan038df5032010-09-30 21:18:25 +0000116/* Handy utility functions used at several places in the code */
Sean Callanan2235f322010-08-11 03:57:18 +0000117
118static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000119PrintValue(const Value *value, bool truncate = false)
Sean Callanan2235f322010-08-11 03:57:18 +0000120{
121 std::string s;
Jim Ingham28eb5712012-10-12 17:34:26 +0000122 if (value)
123 {
124 raw_string_ostream rso(s);
125 value->print(rso);
126 rso.flush();
127 if (truncate)
128 s.resize(s.length() - 1);
129 }
Sean Callanan2235f322010-08-11 03:57:18 +0000130 return s;
131}
132
Sean Callanan038df5032010-09-30 21:18:25 +0000133static std::string
Greg Clayton57ee3062013-07-11 22:46:58 +0000134PrintType(const llvm::Type *type, bool truncate = false)
Sean Callanan038df5032010-09-30 21:18:25 +0000135{
136 std::string s;
137 raw_string_ostream rso(s);
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000138 type->print(rso);
Sean Callanan038df5032010-09-30 21:18:25 +0000139 rso.flush();
140 if (truncate)
141 s.resize(s.length() - 1);
142 return s;
143}
144
Sean Callanan2ab712f22010-07-03 01:35:46 +0000145IRForTarget::~IRForTarget()
146{
147}
148
Sean Callanan79763a42011-05-23 21:40:23 +0000149bool
150IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
151{
Sean Callanan79763a42011-05-23 21:40:23 +0000152 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
153
Sean Callanan7f27d602011-11-19 02:54:21 +0000154 std::string name = llvm_function.getName().str();
Sean Callanan79763a42011-05-23 21:40:23 +0000155
156 return true;
157}
158
Sean Callanand1e5b432010-08-12 01:56:52 +0000159bool
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000160IRForTarget::GetFunctionAddress (llvm::Function *fun,
161 uint64_t &fun_addr,
162 lldb_private::ConstString &name,
163 Constant **&value_ptr)
164{
Greg Clayton5160ce52013-03-27 23:08:40 +0000165 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000166
167 fun_addr = LLDB_INVALID_ADDRESS;
168 name.Clear();
169 value_ptr = NULL;
170
171 if (fun->isIntrinsic())
172 {
173 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
174
175 switch (intrinsic_id)
176 {
177 default:
178 if (log)
179 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
180
181 if (m_error_stream)
182 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
183
184 return false;
185 case Intrinsic::memcpy:
186 {
187 static lldb_private::ConstString g_memcpy_str ("memcpy");
188 name = g_memcpy_str;
189 }
190 break;
Sean Callanana6cbf062011-11-16 00:20:50 +0000191 case Intrinsic::memset:
192 {
193 static lldb_private::ConstString g_memset_str ("memset");
194 name = g_memset_str;
195 }
196 break;
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000197 }
198
199 if (log && name)
200 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
201 }
202 else
203 {
204 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
205 }
206
207 // Find the address of the function.
208
209 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000210
211 if (fun_decl)
212 {
Sean Callananc70ed462011-10-25 18:36:40 +0000213 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000214 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000215 lldb_private::ConstString altnernate_name;
Greg Claytonf0705c82011-10-22 03:33:13 +0000216 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
217 if (!found_it)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000218 {
Greg Claytonf0705c82011-10-22 03:33:13 +0000219 // Check for an alternate mangling for "std::basic_string<char>"
220 // that is part of the itanium C++ name mangling scheme
221 const char *name_cstr = name.GetCString();
Jim Ingham28eb5712012-10-12 17:34:26 +0000222 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
Greg Claytonf0705c82011-10-22 03:33:13 +0000223 {
224 std::string alternate_mangling("_ZNKSs");
225 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000226 altnernate_name.SetCString(alternate_mangling.c_str());
227 found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
Greg Claytonf0705c82011-10-22 03:33:13 +0000228 }
229 }
230
231 if (!found_it)
232 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000233 lldb_private::Mangled mangled_name(name);
234 lldb_private::Mangled alt_mangled_name(altnernate_name);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000235 if (log)
Greg Claytonf0705c82011-10-22 03:33:13 +0000236 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000237 if (alt_mangled_name)
238 log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
239 mangled_name.GetName().GetCString(),
240 alt_mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000241 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000242 log->Printf("Function \"%s\" had no address",
243 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000244 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000245
246 if (m_error_stream)
Greg Claytonf0705c82011-10-22 03:33:13 +0000247 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000248 if (alt_mangled_name)
249 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
250 mangled_name.GetName().GetCString(),
251 alt_mangled_name.GetName().GetCString());
Greg Claytonda1eb042013-04-23 21:48:38 +0000252 else if (mangled_name.GetMangledName())
253 m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
254 mangled_name.GetName().GetCString(),
255 mangled_name.GetMangledName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000256 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000257 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
258 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000259 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000260 return false;
261 }
262 }
263 }
264 else
265 {
266 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
267 {
268 if (log)
269 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
270
271 if (m_error_stream)
272 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
273
274 return false;
275 }
276 }
277
278 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000279 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000280
281 return true;
282}
283
284llvm::Constant *
285IRForTarget::BuildFunctionPointer (llvm::Type *type,
286 uint64_t ptr)
287{
288 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +0000289 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000290 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
291 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
292 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
293}
294
Sean Callananfc8feb82011-10-31 22:11:40 +0000295void
296IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
297 llvm::Value *function_ptr,
298 const char *name)
299{
Sean Callananfc8feb82011-10-31 22:11:40 +0000300 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
301 i != e;
302 ++i)
303 {
304 Value *user = *i;
305
306 if (Instruction *user_inst = dyn_cast<Instruction>(user))
307 {
Daniel Maleaf051dbc2013-06-03 20:45:54 +0000308 MDString* md_name = MDString::get(context, StringRef(name));
309
310 MDNode *metadata = MDNode::get(context, md_name);
311
Sean Callananfc8feb82011-10-31 22:11:40 +0000312 user_inst->setMetadata("lldb.call.realName", metadata);
313 }
314 else
315 {
316 RegisterFunctionMetadata (context, user, name);
317 }
318 }
319}
320
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000321bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000322IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000323{
Greg Clayton5160ce52013-03-27 23:08:40 +0000324 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000325
326 for (llvm::Module::iterator fi = llvm_module.begin();
327 fi != llvm_module.end();
328 ++fi)
329 {
330 Function *fun = fi;
331
332 bool is_decl = fun->isDeclaration();
333
334 if (log)
Sean Callanan7f27d602011-11-19 02:54:21 +0000335 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000336
337 if (!is_decl)
338 continue;
339
340 if (fun->hasNUses(0))
341 continue; // ignore
342
343 uint64_t addr = LLDB_INVALID_ADDRESS;
344 lldb_private::ConstString name;
345 Constant **value_ptr = NULL;
346
347 if (!GetFunctionAddress(fun,
348 addr,
349 name,
350 value_ptr))
351 return false; // GetFunctionAddress reports its own errors
352
353 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
354
Sean Callananfc8feb82011-10-31 22:11:40 +0000355 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
356
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000357 if (value_ptr)
358 *value_ptr = value;
Stefanus Du Toitfc6b7a02013-07-23 21:34:03 +0000359
360 // If we are replacing a function with the nobuiltin attribute, it may
361 // be called with the builtin attribute on call sites. Remove any such
362 // attributes since it's illegal to have a builtin call to something
363 // other than a nobuiltin function.
364 if (fun->hasFnAttribute(Attribute::NoBuiltin)) {
365 Attribute builtin = Attribute::get(fun->getContext(), Attribute::Builtin);
366
367 for (auto u = fun->use_begin(), e = fun->use_end(); u != e; ++u) {
368 if (auto call = dyn_cast<CallInst>(*u)) {
369 call->removeAttribute(AttributeSet::FunctionIndex, builtin);
370 }
371 }
372 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000373
374 fun->replaceAllUsesWith(value);
375 }
376
377 return true;
378}
379
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000380
Sean Callanan63697e52011-05-07 01:06:41 +0000381clang::NamedDecl *
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000382IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan63697e52011-05-07 01:06:41 +0000383{
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000384 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan63697e52011-05-07 01:06:41 +0000385
386 if (!named_metadata)
387 return NULL;
388
389 unsigned num_nodes = named_metadata->getNumOperands();
390 unsigned node_index;
391
392 for (node_index = 0;
393 node_index < num_nodes;
394 ++node_index)
395 {
396 MDNode *metadata_node = named_metadata->getOperand(node_index);
397
398 if (!metadata_node)
399 return NULL;
400
401 if (metadata_node->getNumOperands() != 2)
402 continue;
403
404 if (metadata_node->getOperand(0) != global_val)
405 continue;
406
407 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
408
409 if (!constant_int)
410 return NULL;
411
412 uintptr_t ptr = constant_int->getZExtValue();
413
414 return reinterpret_cast<clang::NamedDecl *>(ptr);
415 }
416
417 return NULL;
418}
419
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000420clang::NamedDecl *
421IRForTarget::DeclForGlobal (GlobalValue *global_val)
422{
423 return DeclForGlobal(global_val, m_module);
424}
425
Sean Callanane4ec90e2010-12-16 03:17:46 +0000426bool
Sean Callanan79763a42011-05-23 21:40:23 +0000427IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanand1e5b432010-08-12 01:56:52 +0000428{
Greg Clayton5160ce52013-03-27 23:08:40 +0000429 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand1e5b432010-08-12 01:56:52 +0000430
Sean Callanan9e6ed532010-09-13 21:34:21 +0000431 if (!m_resolve_vars)
432 return true;
433
434 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callananfc55f5d2010-09-21 00:44:12 +0000435
Sean Callanan79763a42011-05-23 21:40:23 +0000436 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananfc55f5d2010-09-21 00:44:12 +0000437
Sean Callanancc427fa2011-07-30 02:42:06 +0000438 std::string result_name_str;
Sean Callananfc55f5d2010-09-21 00:44:12 +0000439 const char *result_name = NULL;
440
441 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
442 vi != ve;
443 ++vi)
444 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000445 result_name_str = vi->first().str();
446 const char *value_name = result_name_str.c_str();
447
448 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000449 strncmp(value_name, "_ZGV", 4))
Sean Callanan92adcac2011-01-13 08:53:35 +0000450 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000451 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000452 m_result_is_pointer = true;
453 break;
454 }
455
Sean Callanancc427fa2011-07-30 02:42:06 +0000456 if (strstr(value_name, "$__lldb_expr_result") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000457 strncmp(value_name, "_ZGV", 4))
Sean Callanan46ae9e52010-09-28 21:13:03 +0000458 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000459 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000460 m_result_is_pointer = false;
Sean Callanan46ae9e52010-09-28 21:13:03 +0000461 break;
462 }
Sean Callananfc55f5d2010-09-21 00:44:12 +0000463 }
464
465 if (!result_name)
466 {
467 if (log)
468 log->PutCString("Couldn't find result variable");
469
470 return true;
471 }
472
Sean Callanan46ae9e52010-09-28 21:13:03 +0000473 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000474 log->Printf("Result name: \"%s\"", result_name);
Sean Callanan46ae9e52010-09-28 21:13:03 +0000475
Sean Callanan79763a42011-05-23 21:40:23 +0000476 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanand1e5b432010-08-12 01:56:52 +0000477
478 if (!result_value)
479 {
480 if (log)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000481 log->PutCString("Result variable had no data");
Sean Callanan92adcac2011-01-13 08:53:35 +0000482
Sean Callanan3989fb92011-01-27 01:07:04 +0000483 if (m_error_stream)
484 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
485
Sean Callananfc55f5d2010-09-21 00:44:12 +0000486 return false;
Sean Callanand1e5b432010-08-12 01:56:52 +0000487 }
Sean Callanan9e6ed532010-09-13 21:34:21 +0000488
Sean Callanand1e5b432010-08-12 01:56:52 +0000489 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000490 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000491
492 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
493
494 if (!result_global)
495 {
496 if (log)
497 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000498
499 if (m_error_stream)
500 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
501
Sean Callanand1e5b432010-08-12 01:56:52 +0000502 return false;
503 }
504
Sean Callanan79763a42011-05-23 21:40:23 +0000505 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan63697e52011-05-07 01:06:41 +0000506 if (!result_decl)
Sean Callanand1e5b432010-08-12 01:56:52 +0000507 {
508 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000509 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanand1e5b432010-08-12 01:56:52 +0000510
Sean Callanan3989fb92011-01-27 01:07:04 +0000511 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000512 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 +0000513
Sean Callanand1e5b432010-08-12 01:56:52 +0000514 return false;
515 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000516
Sean Callanan63697e52011-05-07 01:06:41 +0000517 if (log)
Sean Callanand1e5b432010-08-12 01:56:52 +0000518 {
Sean Callanan63697e52011-05-07 01:06:41 +0000519 std::string decl_desc_str;
520 raw_string_ostream decl_desc_stream(decl_desc_str);
521 result_decl->print(decl_desc_stream);
522 decl_desc_stream.flush();
Sean Callanand1e5b432010-08-12 01:56:52 +0000523
Sean Callanan63697e52011-05-07 01:06:41 +0000524 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000525 }
526
Sean Callanan63697e52011-05-07 01:06:41 +0000527 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
528 if (!result_var)
Sean Callanand1e5b432010-08-12 01:56:52 +0000529 {
530 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000531 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan3989fb92011-01-27 01:07:04 +0000532
533 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000534 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 +0000535
Sean Callanand1e5b432010-08-12 01:56:52 +0000536 return false;
537 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000538
Sean Callanand1e5b432010-08-12 01:56:52 +0000539 // Get the next available result name from m_decl_map and create the persistent
540 // variable for it
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000541
Sean Callanan63697e52011-05-07 01:06:41 +0000542 // If the result is an Lvalue, it is emitted as a pointer; see
543 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan92adcac2011-01-13 08:53:35 +0000544 if (m_result_is_pointer)
545 {
Sean Callanan63697e52011-05-07 01:06:41 +0000546 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanan78e37602011-01-27 04:42:51 +0000547 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
Sean Callanan92adcac2011-01-13 08:53:35 +0000548
Sean Callananfc4f2fb2011-12-14 01:13:04 +0000549 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
550 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
Sean Callanan5780f9d2011-12-08 19:04:34 +0000551
552 if (pointer_pointertype)
553 {
554 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
555
556 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
557 &result_decl->getASTContext());
558 }
559 else if (pointer_objcobjpointertype)
560 {
561 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
562
563 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
564 &result_decl->getASTContext());
565 }
566 else
Sean Callanan92adcac2011-01-13 08:53:35 +0000567 {
568 if (log)
569 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan3989fb92011-01-27 01:07:04 +0000570
571 if (m_error_stream)
572 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
573
Sean Callanan92adcac2011-01-13 08:53:35 +0000574 return false;
575 }
Sean Callanan92adcac2011-01-13 08:53:35 +0000576 }
577 else
578 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000579 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan00f43622011-11-18 03:28:09 +0000580 &result_decl->getASTContext());
581 }
582
Greg Clayton57ee3062013-07-11 22:46:58 +0000583 if (m_result_type.GetBitSize() == 0)
Sean Callanan00f43622011-11-18 03:28:09 +0000584 {
585 lldb_private::StreamString type_desc_stream;
586 m_result_type.DumpTypeDescription(&type_desc_stream);
587
588 if (log)
589 log->Printf("Result type has size 0");
590
591 if (m_error_stream)
Sean Callanan960534c2011-12-21 23:44:05 +0000592 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
Sean Callanan00f43622011-11-18 03:28:09 +0000593 type_desc_stream.GetData());
Sean Callanan960534c2011-12-21 23:44:05 +0000594 return false;
Sean Callanan92adcac2011-01-13 08:53:35 +0000595 }
596
Sean Callanan63697e52011-05-07 01:06:41 +0000597 if (log)
598 {
599 lldb_private::StreamString type_desc_stream;
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000600 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan63697e52011-05-07 01:06:41 +0000601
Sean Callanan00f43622011-11-18 03:28:09 +0000602 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
Sean Callanan63697e52011-05-07 01:06:41 +0000603 }
604
Sean Callanan1582ee62013-04-18 22:06:33 +0000605 m_result_name = lldb_private::ConstString("$RESULT_NAME");
Sean Callanand1e5b432010-08-12 01:56:52 +0000606
607 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +0000608 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
Sean Callanan00f43622011-11-18 03:28:09 +0000609 m_result_name.GetCString(),
Greg Clayton57ee3062013-07-11 22:46:58 +0000610 m_result_type.GetByteSize());
Sean Callanand1e5b432010-08-12 01:56:52 +0000611
612 // Construct a new result global and set up its metadata
613
Sean Callanan79763a42011-05-23 21:40:23 +0000614 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanand1e5b432010-08-12 01:56:52 +0000615 result_global->getType()->getElementType(),
616 false, /* not constant */
617 GlobalValue::ExternalLinkage,
618 NULL, /* no initializer */
Sean Callanan92adcac2011-01-13 08:53:35 +0000619 m_result_name.GetCString ());
Sean Callanand1e5b432010-08-12 01:56:52 +0000620
621 // It's too late in compilation to create a new VarDecl for this, but we don't
622 // need to. We point the metadata at the old VarDecl. This creates an odd
623 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton7b462cc2010-10-15 22:48:33 +0000624 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanand1e5b432010-08-12 01:56:52 +0000625 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
626 // fixed up.
627
Sean Callanan79763a42011-05-23 21:40:23 +0000628 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan63697e52011-05-07 01:06:41 +0000629 reinterpret_cast<uint64_t>(result_decl),
Sean Callanand1e5b432010-08-12 01:56:52 +0000630 false);
631
632 llvm::Value* values[2];
633 values[0] = new_result_global;
634 values[1] = new_constant_int;
635
Sean Callanand12cf8bb2011-05-15 22:34:38 +0000636 ArrayRef<Value*> value_ref(values, 2);
637
Sean Callanan79763a42011-05-23 21:40:23 +0000638 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
639 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanand1e5b432010-08-12 01:56:52 +0000640 named_metadata->addOperand(persistent_global_md);
641
642 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000643 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan1e87fff2010-09-07 22:43:19 +0000644 PrintValue(result_global).c_str(),
Sean Callanand1e5b432010-08-12 01:56:52 +0000645 PrintValue(new_result_global).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000646
647 if (result_global->hasNUses(0))
648 {
649 // We need to synthesize a store for this variable, because otherwise
650 // there's nothing to put into its equivalent persistent variable.
Sean Callanand1e5b432010-08-12 01:56:52 +0000651
Greg Clayton7b462cc2010-10-15 22:48:33 +0000652 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000653 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
654
655 if (!first_entry_instruction)
656 return false;
657
658 if (!result_global->hasInitializer())
659 {
660 if (log)
661 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000662
663 if (m_error_stream)
664 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
665
Sean Callanan1e87fff2010-09-07 22:43:19 +0000666 return false;
667 }
668
669 Constant *initializer = result_global->getInitializer();
Sean Callanane4ec90e2010-12-16 03:17:46 +0000670
Greg Clayton9c139312011-02-05 02:28:58 +0000671 StoreInst *synthesized_store = new StoreInst(initializer,
672 new_result_global,
673 first_entry_instruction);
Sean Callanan1e87fff2010-09-07 22:43:19 +0000674
675 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000676 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000677 }
678 else
679 {
680 result_global->replaceAllUsesWith(new_result_global);
681 }
682
Sean Callanan1582ee62013-04-18 22:06:33 +0000683 if (!m_decl_map->AddPersistentVariable(result_decl,
684 m_result_name,
685 m_result_type,
686 true,
687 m_result_is_pointer))
688 return false;
689
Sean Callanand1e5b432010-08-12 01:56:52 +0000690 result_global->eraseFromParent();
691
692 return true;
693}
694
Johnny Chenee7a3592011-08-09 23:10:20 +0000695#if 0
Greg Clayton5160ce52013-03-27 23:08:40 +0000696static void DebugUsers(Log *log, Value *value, uint8_t depth)
Sean Callananafe16a72010-11-17 23:00:36 +0000697{
698 if (!depth)
699 return;
700
701 depth--;
702
Johnny Chenee7a3592011-08-09 23:10:20 +0000703 if (log)
704 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callananafe16a72010-11-17 23:00:36 +0000705
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000706 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callananafe16a72010-11-17 23:00:36 +0000707 ui != ue;
708 ++ui)
709 {
Johnny Chenee7a3592011-08-09 23:10:20 +0000710 if (log)
711 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callananafe16a72010-11-17 23:00:36 +0000712 DebugUsers(log, *ui, depth);
713 }
714
Johnny Chenee7a3592011-08-09 23:10:20 +0000715 if (log)
716 log->Printf(" <End uses>");
Sean Callananafe16a72010-11-17 23:00:36 +0000717}
Johnny Chenee7a3592011-08-09 23:10:20 +0000718#endif
Sean Callananafe16a72010-11-17 23:00:36 +0000719
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000720bool
Sean Callanan79763a42011-05-23 21:40:23 +0000721IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000722 llvm::GlobalVariable *cstr)
Sean Callananafe16a72010-11-17 23:00:36 +0000723{
Greg Clayton5160ce52013-03-27 23:08:40 +0000724 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000725
Sean Callanancc427fa2011-07-30 02:42:06 +0000726 Type *ns_str_ty = ns_str->getType();
Sean Callanan79763a42011-05-23 21:40:23 +0000727
Sean Callanancc427fa2011-07-30 02:42:06 +0000728 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
729 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +0000730 (m_module->getPointerSize()
Micah Villmow08318972012-10-11 17:21:41 +0000731 == Module::Pointer64) ? 64 : 32);
Sean Callanancc427fa2011-07-30 02:42:06 +0000732 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
733 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananafe16a72010-11-17 23:00:36 +0000734
735 if (!m_CFStringCreateWithBytes)
736 {
737 lldb::addr_t CFStringCreateWithBytes_addr;
738
739 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
740
741 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
742 {
743 if (log)
744 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
745
Sean Callanan3989fb92011-01-27 01:07:04 +0000746 if (m_error_stream)
747 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
748
Sean Callananafe16a72010-11-17 23:00:36 +0000749 return false;
750 }
751
752 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000753 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
Sean Callananafe16a72010-11-17 23:00:36 +0000754
755 // Build the function type:
756 //
757 // CFStringRef CFStringCreateWithBytes (
758 // CFAllocatorRef alloc,
759 // const UInt8 *bytes,
760 // CFIndex numBytes,
761 // CFStringEncoding encoding,
762 // Boolean isExternalRepresentation
763 // );
764 //
765 // We make the following substitutions:
766 //
767 // CFStringRef -> i8*
768 // CFAllocatorRef -> i8*
769 // UInt8 * -> i8*
770 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
771 // CFStringEncoding -> i32
772 // Boolean -> i8
773
Sean Callanancc427fa2011-07-30 02:42:06 +0000774 Type *arg_type_array[5];
775
776 arg_type_array[0] = i8_ptr_ty;
777 arg_type_array[1] = i8_ptr_ty;
778 arg_type_array[2] = intptr_ty;
779 arg_type_array[3] = i32_ty;
780 arg_type_array[4] = i8_ty;
781
782 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
783
Sean Callanan79763a42011-05-23 21:40:23 +0000784 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000785
786 // Build the constant containing the pointer to the function
787 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
788 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
789 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
790 }
791
Sean Callanand2b465f2012-02-09 03:22:41 +0000792 ConstantDataSequential *string_array = NULL;
Sean Callanan229ce2d2011-02-10 22:17:53 +0000793
794 if (cstr)
Sean Callanand2b465f2012-02-09 03:22:41 +0000795 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
Sean Callanancc427fa2011-07-30 02:42:06 +0000796
Sean Callananafe16a72010-11-17 23:00:36 +0000797 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan229ce2d2011-02-10 22:17:53 +0000798 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
Sean Callanand2b465f2012-02-09 03:22:41 +0000799 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000800 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
801 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
802
Sean Callanancc427fa2011-07-30 02:42:06 +0000803 Value *argument_array[5];
804
805 argument_array[0] = alloc_arg;
806 argument_array[1] = bytes_arg;
807 argument_array[2] = numBytes_arg;
808 argument_array[3] = encoding_arg;
809 argument_array[4] = isExternal_arg;
810
811 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callananafe16a72010-11-17 23:00:36 +0000812
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000813 FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * {
814 return CallInst::Create(m_CFStringCreateWithBytes,
815 CFSCWB_arguments,
816 "CFStringCreateWithBytes",
817 llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)));
818 });
Sean Callanan7a55a322010-11-18 22:21:58 +0000819
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000820 if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder))
Sean Callananafe16a72010-11-17 23:00:36 +0000821 {
822 if (log)
823 log->PutCString("Couldn't replace the NSString with the result of the call");
824
Sean Callanan3989fb92011-01-27 01:07:04 +0000825 if (m_error_stream)
826 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
827
Sean Callananafe16a72010-11-17 23:00:36 +0000828 return false;
829 }
830
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000831 ns_str->eraseFromParent();
Sean Callananafe16a72010-11-17 23:00:36 +0000832
833 return true;
834}
835
836bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000837IRForTarget::RewriteObjCConstStrings()
Sean Callananafe16a72010-11-17 23:00:36 +0000838{
Greg Clayton5160ce52013-03-27 23:08:40 +0000839 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000840
Sean Callanan79763a42011-05-23 21:40:23 +0000841 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananafe16a72010-11-17 23:00:36 +0000842
Sean Callananafe16a72010-11-17 23:00:36 +0000843 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
844 vi != ve;
845 ++vi)
846 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000847 std::string value_name = vi->first().str();
848 const char *value_name_cstr = value_name.c_str();
849
850 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callananafe16a72010-11-17 23:00:36 +0000851 {
852 Value *nsstring_value = vi->second;
853
854 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
855
856 if (!nsstring_global)
857 {
858 if (log)
859 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000860
861 if (m_error_stream)
862 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
863
Sean Callananafe16a72010-11-17 23:00:36 +0000864 return false;
865 }
866
867 if (!nsstring_global->hasInitializer())
868 {
869 if (log)
870 log->PutCString("NSString variable does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000871
872 if (m_error_stream)
873 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
874
Sean Callananafe16a72010-11-17 23:00:36 +0000875 return false;
876 }
877
878 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
879
880 if (!nsstring_struct)
881 {
882 if (log)
883 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan3989fb92011-01-27 01:07:04 +0000884
885 if (m_error_stream)
886 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
887
Sean Callananafe16a72010-11-17 23:00:36 +0000888 return false;
889 }
890
891 // We expect the following structure:
892 //
893 // struct {
894 // int *isa;
895 // int flags;
896 // char *str;
897 // long length;
898 // };
899
900 if (nsstring_struct->getNumOperands() != 4)
901 {
902 if (log)
903 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 +0000904
905 if (m_error_stream)
906 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
907
Sean Callananafe16a72010-11-17 23:00:36 +0000908 return false;
909 }
910
911 Constant *nsstring_member = nsstring_struct->getOperand(2);
912
913 if (!nsstring_member)
914 {
915 if (log)
916 log->PutCString("NSString initializer's str element was empty");
Sean Callanan3989fb92011-01-27 01:07:04 +0000917
918 if (m_error_stream)
919 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
920
Sean Callananafe16a72010-11-17 23:00:36 +0000921 return false;
922 }
923
924 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
925
926 if (!nsstring_expr)
927 {
928 if (log)
929 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan3989fb92011-01-27 01:07:04 +0000930
931 if (m_error_stream)
932 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
933
Sean Callananafe16a72010-11-17 23:00:36 +0000934 return false;
935 }
936
937 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
938 {
939 if (log)
940 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 +0000941
942 if (m_error_stream)
943 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
944
Sean Callananafe16a72010-11-17 23:00:36 +0000945 return false;
946 }
947
948 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
949
950 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
951
952 if (!cstr_global)
953 {
954 if (log)
955 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000956
957 if (m_error_stream)
958 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
Sean Callanan80eee3a2010-11-20 02:06:01 +0000959
Sean Callananafe16a72010-11-17 23:00:36 +0000960 return false;
961 }
962
963 if (!cstr_global->hasInitializer())
964 {
965 if (log)
966 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000967
968 if (m_error_stream)
969 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
970
Sean Callananafe16a72010-11-17 23:00:36 +0000971 return false;
972 }
Sean Callanan229ce2d2011-02-10 22:17:53 +0000973
974 /*
Sean Callananafe16a72010-11-17 23:00:36 +0000975 if (!cstr_array)
976 {
977 if (log)
978 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan3989fb92011-01-27 01:07:04 +0000979
980 if (m_error_stream)
981 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
982
Sean Callananafe16a72010-11-17 23:00:36 +0000983 return false;
984 }
985
986 if (!cstr_array->isCString())
987 {
988 if (log)
989 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan3989fb92011-01-27 01:07:04 +0000990
991 if (m_error_stream)
992 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
993
Sean Callananafe16a72010-11-17 23:00:36 +0000994 return false;
995 }
Sean Callanan229ce2d2011-02-10 22:17:53 +0000996 */
997
Sean Callanand2b465f2012-02-09 03:22:41 +0000998 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
Sean Callananafe16a72010-11-17 23:00:36 +0000999
1000 if (log)
Sean Callanan229ce2d2011-02-10 22:17:53 +00001001 {
1002 if (cstr_array)
Sean Callanand2b465f2012-02-09 03:22:41 +00001003 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 +00001004 else
Sean Callanancc427fa2011-07-30 02:42:06 +00001005 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan229ce2d2011-02-10 22:17:53 +00001006 }
1007
1008 if (!cstr_array)
1009 cstr_global = NULL;
Sean Callananafe16a72010-11-17 23:00:36 +00001010
Sean Callanan1f9db3e2013-06-28 21:44:15 +00001011 if (!RewriteObjCConstString(nsstring_global, cstr_global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001012 {
Sean Callananafe16a72010-11-17 23:00:36 +00001013 if (log)
1014 log->PutCString("Error rewriting the constant string");
Sean Callanan3989fb92011-01-27 01:07:04 +00001015
1016 // We don't print an error message here because RewriteObjCConstString has done so for us.
1017
Sean Callananafe16a72010-11-17 23:00:36 +00001018 return false;
1019 }
Sean Callananafe16a72010-11-17 23:00:36 +00001020 }
1021 }
1022
1023 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1024 vi != ve;
1025 ++vi)
1026 {
Sean Callanancc427fa2011-07-30 02:42:06 +00001027 std::string value_name = vi->first().str();
1028 const char *value_name_cstr = value_name.c_str();
1029
1030 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callananafe16a72010-11-17 23:00:36 +00001031 {
1032 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1033
1034 if (!gv)
1035 {
1036 if (log)
1037 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001038
1039 if (m_error_stream)
1040 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1041
Sean Callananafe16a72010-11-17 23:00:36 +00001042 return false;
1043 }
1044
1045 gv->eraseFromParent();
1046
1047 break;
1048 }
1049 }
1050
1051 return true;
1052}
1053
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001054static bool IsObjCSelectorRef (Value *value)
Sean Callanan5300d372010-07-31 01:32:05 +00001055{
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001056 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callanan5300d372010-07-31 01:32:05 +00001057
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001058 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callanan5300d372010-07-31 01:32:05 +00001059 return false;
1060
1061 return true;
1062}
1063
Sean Callanan3989fb92011-01-27 01:07:04 +00001064// This function does not report errors; its callers are responsible.
Sean Callanan5300d372010-07-31 01:32:05 +00001065bool
Sean Callanan79763a42011-05-23 21:40:23 +00001066IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callanan5300d372010-07-31 01:32:05 +00001067{
Greg Clayton5160ce52013-03-27 23:08:40 +00001068 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001069
1070 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1071
1072 if (!load)
1073 return false;
1074
1075 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1076 //
1077 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1078 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1079 //
1080 // where %obj is the object pointer and %tmp is the selector.
1081 //
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001082 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1083 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callanan5300d372010-07-31 01:32:05 +00001084
1085 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1086
1087 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1088
1089 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1090 return false;
1091
1092 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1093
1094 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1095
1096 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1097 return false;
1098
1099 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1100
1101 if (!osr_initializer_base)
1102 return false;
1103
1104 // Find the string's initializer (a ConstantArray) and get the string from it
1105
1106 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1107
1108 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1109 return false;
1110
1111 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1112
Sean Callanand2b465f2012-02-09 03:22:41 +00001113 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
Sean Callanan5300d372010-07-31 01:32:05 +00001114
1115 if (!omvn_initializer_array->isString())
1116 return false;
1117
1118 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1119
1120 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001121 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callanan5300d372010-07-31 01:32:05 +00001122
1123 // Construct a call to sel_registerName
1124
1125 if (!m_sel_registerName)
1126 {
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001127 lldb::addr_t sel_registerName_addr;
Sean Callanan5300d372010-07-31 01:32:05 +00001128
Greg Clayton7b462cc2010-10-15 22:48:33 +00001129 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001130 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callanan5300d372010-07-31 01:32:05 +00001131 return false;
1132
Sean Callananbe3a1b12010-10-26 00:31:56 +00001133 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001134 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
Sean Callananbe3a1b12010-10-26 00:31:56 +00001135
Sean Callanan5300d372010-07-31 01:32:05 +00001136 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1137
1138 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callanan79763a42011-05-23 21:40:23 +00001139 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001140 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanancc427fa2011-07-30 02:42:06 +00001141 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001142
Sean Callanancc427fa2011-07-30 02:42:06 +00001143 Type *type_array[1];
1144
1145 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1146
1147 ArrayRef<Type *> srN_arg_types(type_array, 1);
1148
Sean Callanan5300d372010-07-31 01:32:05 +00001149 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1150
1151 // Build the constant containing the pointer to the function
Sean Callanancc427fa2011-07-30 02:42:06 +00001152 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001153 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan5300d372010-07-31 01:32:05 +00001154 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001155 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callanan5300d372010-07-31 01:32:05 +00001156 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1157 }
1158
Sean Callanancc427fa2011-07-30 02:42:06 +00001159 Value *argument_array[1];
1160
Sean Callanan79763a42011-05-23 21:40:23 +00001161 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callanan5300d372010-07-31 01:32:05 +00001162
Sean Callanancc427fa2011-07-30 02:42:06 +00001163 argument_array[0] = omvn_pointer;
Sean Callanan5300d372010-07-31 01:32:05 +00001164
Sean Callanancc427fa2011-07-30 02:42:06 +00001165 ArrayRef<Value *> srN_arguments(argument_array, 1);
1166
Sean Callanan5300d372010-07-31 01:32:05 +00001167 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanancc427fa2011-07-30 02:42:06 +00001168 srN_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +00001169 "sel_registerName",
Sean Callanan5300d372010-07-31 01:32:05 +00001170 selector_load);
1171
1172 // Replace the load with the call in all users
1173
1174 selector_load->replaceAllUsesWith(srN_call);
1175
1176 selector_load->eraseFromParent();
1177
1178 return true;
1179}
1180
1181bool
Sean Callanan79763a42011-05-23 21:40:23 +00001182IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callanan5300d372010-07-31 01:32:05 +00001183{
Greg Clayton5160ce52013-03-27 23:08:40 +00001184 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001185
1186 BasicBlock::iterator ii;
1187
1188 typedef SmallVector <Instruction*, 2> InstrList;
1189 typedef InstrList::iterator InstrIterator;
1190
1191 InstrList selector_loads;
1192
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001193 for (ii = basic_block.begin();
1194 ii != basic_block.end();
Sean Callanan5300d372010-07-31 01:32:05 +00001195 ++ii)
1196 {
1197 Instruction &inst = *ii;
1198
1199 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001200 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callanan5300d372010-07-31 01:32:05 +00001201 selector_loads.push_back(&inst);
1202 }
1203
1204 InstrIterator iter;
1205
1206 for (iter = selector_loads.begin();
1207 iter != selector_loads.end();
1208 ++iter)
1209 {
Sean Callanan79763a42011-05-23 21:40:23 +00001210 if (!RewriteObjCSelector(*iter))
Sean Callanan5300d372010-07-31 01:32:05 +00001211 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001212 if (m_error_stream)
1213 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1214
Enrico Granata20edcdb2011-07-19 18:03:25 +00001215 if (log)
Sean Callanan5300d372010-07-31 01:32:05 +00001216 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan3989fb92011-01-27 01:07:04 +00001217
Sean Callanan5300d372010-07-31 01:32:05 +00001218 return false;
1219 }
1220 }
1221
1222 return true;
1223}
1224
Sean Callanan3989fb92011-01-27 01:07:04 +00001225// This function does not report errors; its callers are responsible.
Sean Callanan2235f322010-08-11 03:57:18 +00001226bool
Sean Callanan79763a42011-05-23 21:40:23 +00001227IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanan2235f322010-08-11 03:57:18 +00001228{
Greg Clayton5160ce52013-03-27 23:08:40 +00001229 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanane1175b72011-01-13 21:23:32 +00001230
Sean Callanan2235f322010-08-11 03:57:18 +00001231 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1232
1233 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1234
1235 if (!alloc_md || !alloc_md->getNumOperands())
1236 return false;
1237
1238 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1239
1240 if (!constant_int)
1241 return false;
1242
1243 // We attempt to register this as a new persistent variable with the DeclMap.
1244
1245 uintptr_t ptr = constant_int->getZExtValue();
1246
Sean Callanand1e5b432010-08-12 01:56:52 +00001247 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanan2235f322010-08-11 03:57:18 +00001248
Sean Callanand1e5b432010-08-12 01:56:52 +00001249 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1250 &decl->getASTContext());
1251
Greg Clayton7b462cc2010-10-15 22:48:33 +00001252 StringRef decl_name (decl->getName());
1253 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan92adcac2011-01-13 08:53:35 +00001254 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanan2235f322010-08-11 03:57:18 +00001255 return false;
1256
Sean Callanan79763a42011-05-23 21:40:23 +00001257 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanane1175b72011-01-13 21:23:32 +00001258 alloc->getType(),
Sean Callanan2235f322010-08-11 03:57:18 +00001259 false, /* not constant */
1260 GlobalValue::ExternalLinkage,
1261 NULL, /* no initializer */
1262 alloc->getName().str().c_str());
1263
1264 // What we're going to do here is make believe this was a regular old external
1265 // variable. That means we need to make the metadata valid.
1266
Sean Callanan585c0ec82012-07-04 01:26:26 +00001267 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
Sean Callanan2235f322010-08-11 03:57:18 +00001268
1269 llvm::Value* values[2];
1270 values[0] = persistent_global;
1271 values[1] = constant_int;
Sean Callanand12cf8bb2011-05-15 22:34:38 +00001272
1273 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanan2235f322010-08-11 03:57:18 +00001274
Sean Callanan79763a42011-05-23 21:40:23 +00001275 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanan2235f322010-08-11 03:57:18 +00001276 named_metadata->addOperand(persistent_global_md);
1277
Sean Callanane1175b72011-01-13 21:23:32 +00001278 // Now, since the variable is a pointer variable, we will drop in a load of that
1279 // pointer variable.
1280
1281 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1282
1283 if (log)
1284 log->Printf("Replacing \"%s\" with \"%s\"",
1285 PrintValue(alloc).c_str(),
1286 PrintValue(persistent_load).c_str());
1287
1288 alloc->replaceAllUsesWith(persistent_load);
Sean Callanan2235f322010-08-11 03:57:18 +00001289 alloc->eraseFromParent();
1290
1291 return true;
1292}
1293
1294bool
Sean Callanan79763a42011-05-23 21:40:23 +00001295IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanan2235f322010-08-11 03:57:18 +00001296{
Sean Callanan9e6ed532010-09-13 21:34:21 +00001297 if (!m_resolve_vars)
1298 return true;
1299
Greg Clayton5160ce52013-03-27 23:08:40 +00001300 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2235f322010-08-11 03:57:18 +00001301
1302 BasicBlock::iterator ii;
1303
1304 typedef SmallVector <Instruction*, 2> InstrList;
1305 typedef InstrList::iterator InstrIterator;
1306
1307 InstrList pvar_allocs;
1308
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001309 for (ii = basic_block.begin();
1310 ii != basic_block.end();
Sean Callanan2235f322010-08-11 03:57:18 +00001311 ++ii)
1312 {
1313 Instruction &inst = *ii;
1314
1315 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callananf694a552011-01-21 22:30:25 +00001316 {
1317 llvm::StringRef alloc_name = alloc->getName();
1318
1319 if (alloc_name.startswith("$") &&
1320 !alloc_name.startswith("$__lldb"))
1321 {
1322 if (alloc_name.find_first_of("0123456789") == 1)
1323 {
1324 if (log)
1325 log->Printf("Rejecting a numeric persistent variable.");
1326
Sean Callanan3989fb92011-01-27 01:07:04 +00001327 if (m_error_stream)
1328 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1329
Sean Callananf694a552011-01-21 22:30:25 +00001330 return false;
1331 }
1332
Sean Callanan2235f322010-08-11 03:57:18 +00001333 pvar_allocs.push_back(alloc);
Sean Callananf694a552011-01-21 22:30:25 +00001334 }
1335 }
Sean Callanan2235f322010-08-11 03:57:18 +00001336 }
1337
1338 InstrIterator iter;
1339
1340 for (iter = pvar_allocs.begin();
1341 iter != pvar_allocs.end();
1342 ++iter)
1343 {
Sean Callanan79763a42011-05-23 21:40:23 +00001344 if (!RewritePersistentAlloc(*iter))
Sean Callanan2235f322010-08-11 03:57:18 +00001345 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001346 if (m_error_stream)
1347 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1348
Enrico Granata20edcdb2011-07-19 18:03:25 +00001349 if (log)
Sean Callanan2235f322010-08-11 03:57:18 +00001350 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001351
Sean Callanan2235f322010-08-11 03:57:18 +00001352 return false;
1353 }
1354 }
1355
1356 return true;
1357}
1358
Sean Callananc70ed462011-10-25 18:36:40 +00001359bool
1360IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1361{
1362 if (!initializer)
1363 return true;
1364
Greg Clayton5160ce52013-03-27 23:08:40 +00001365 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc70ed462011-10-25 18:36:40 +00001366
1367 if (log && log->GetVerbose())
1368 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1369
1370 Type *initializer_type = initializer->getType();
1371
1372 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1373 {
1374 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1375 return true;
1376 }
Sean Callanand2b465f2012-02-09 03:22:41 +00001377 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
Sean Callananc70ed462011-10-25 18:36:40 +00001378 {
1379 if (array_initializer->isString())
1380 {
1381 std::string array_initializer_string = array_initializer->getAsString();
1382 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1383 }
1384 else
1385 {
1386 ArrayType *array_initializer_type = array_initializer->getType();
1387 Type *array_element_type = array_initializer_type->getElementType();
1388
1389 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1390
Andy Gibbsa297a972013-06-19 19:04:53 +00001391 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i)
Sean Callananc70ed462011-10-25 18:36:40 +00001392 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001393 Value *operand_value = array_initializer->getOperand(i);
1394 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1395
1396 if (!operand_constant)
1397 return false;
1398
1399 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
Sean Callananc70ed462011-10-25 18:36:40 +00001400 return false;
1401 }
1402 }
1403 return true;
1404 }
1405 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1406 {
1407 StructType *struct_initializer_type = struct_initializer->getType();
1408 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1409
Andy Gibbsa297a972013-06-19 19:04:53 +00001410 for (unsigned i = 0;
Sean Callananc70ed462011-10-25 18:36:40 +00001411 i < struct_initializer->getNumOperands();
1412 ++i)
1413 {
1414 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1415 return false;
1416 }
1417 return true;
1418 }
Sean Callanan76ee3e72013-04-24 19:50:12 +00001419 else if (isa<ConstantAggregateZero>(initializer))
1420 {
1421 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1422 return true;
1423 }
Sean Callananc70ed462011-10-25 18:36:40 +00001424 return false;
1425}
1426
1427bool
1428IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1429{
1430 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1431 return false;
1432
Sean Callananfe5d1392011-11-15 19:13:54 +00001433 if (global_variable == m_reloc_placeholder)
1434 return true;
1435
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001436 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callananc70ed462011-10-25 18:36:40 +00001437
1438 llvm::Type *variable_type = global_variable->getType();
1439
1440 Constant *initializer = global_variable->getInitializer();
1441
1442 llvm::Type *initializer_type = initializer->getType();
1443
1444 size_t size = m_target_data->getTypeAllocSize(initializer_type);
Sean Callanane3333d62012-06-08 22:20:41 +00001445 size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1446
1447 const size_t mask = (align - 1);
1448 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001449 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00001450 offset = aligned_offset;
Sean Callananc70ed462011-10-25 18:36:40 +00001451
1452 lldb_private::DataBufferHeap data(size, '\0');
1453
1454 if (initializer)
1455 if (!MaterializeInitializer(data.GetBytes(), initializer))
1456 return false;
1457
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001458 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
Sean Callananc70ed462011-10-25 18:36:40 +00001459
1460 Constant *new_pointer = BuildRelocation(variable_type, offset);
1461
1462 global_variable->replaceAllUsesWith(new_pointer);
1463
1464 global_variable->eraseFromParent();
1465
1466 return true;
1467}
1468
Sean Callanan3989fb92011-01-27 01:07:04 +00001469// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001470bool
Sean Callanan79763a42011-05-23 21:40:23 +00001471IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001472{
Greg Clayton5160ce52013-03-27 23:08:40 +00001473 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001474
1475 if (log)
Sean Callanan88339f02010-12-06 22:16:55 +00001476 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callananaf8e96c2011-08-01 17:41:38 +00001477
Greg Clayton7b462cc2010-10-15 22:48:33 +00001478 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callanan4cf04d22010-08-03 00:23:29 +00001479 {
Sean Callanan5666b672010-08-04 01:02:13 +00001480 switch (constant_expr->getOpcode())
Sean Callanan4cf04d22010-08-03 00:23:29 +00001481 {
Sean Callanan5666b672010-08-04 01:02:13 +00001482 default:
1483 break;
1484 case Instruction::GetElementPtr:
1485 case Instruction::BitCast:
Sean Callanan4cf04d22010-08-03 00:23:29 +00001486 Value *s = constant_expr->getOperand(0);
Sean Callanan79763a42011-05-23 21:40:23 +00001487 if (!MaybeHandleVariable(s))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001488 return false;
Sean Callanan4cf04d22010-08-03 00:23:29 +00001489 }
1490 }
Sean Callanand6e04ae2010-12-03 19:51:05 +00001491 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001492 {
Sean Callananc70ed462011-10-25 18:36:40 +00001493 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1494 return MaterializeInternalVariable(global_variable);
1495
Sean Callanan79763a42011-05-23 21:40:23 +00001496 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan2ab712f22010-07-03 01:35:46 +00001497
Sean Callanan5300d372010-07-31 01:32:05 +00001498 if (!named_decl)
1499 {
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001500 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001501 return true;
1502
Sean Callanan14f0b0e2010-12-06 00:56:39 +00001503 if (!global_variable->hasExternalLinkage())
1504 return true;
1505
Sean Callanan5300d372010-07-31 01:32:05 +00001506 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001507 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001508
Sean Callanan5300d372010-07-31 01:32:05 +00001509 return false;
1510 }
1511
Greg Clayton7b462cc2010-10-15 22:48:33 +00001512 std::string name (named_decl->getName().str());
Sean Callananea22d422010-07-16 00:09:46 +00001513
Greg Clayton57ee3062013-07-11 22:46:58 +00001514 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1515 if (value_decl == NULL)
Sean Callananea22d422010-07-16 00:09:46 +00001516 return false;
Greg Clayton57ee3062013-07-11 22:46:58 +00001517
1518 lldb_private::ClangASTType clang_type(&value_decl->getASTContext(), value_decl->getType());
Sean Callanan038df5032010-09-30 21:18:25 +00001519
Sean Callanan77eaf442011-07-08 00:39:14 +00001520 const Type *value_type = NULL;
Greg Clayton57ee3062013-07-11 22:46:58 +00001521
Sean Callanane1175b72011-01-13 21:23:32 +00001522 if (name[0] == '$')
Sean Callanan92adcac2011-01-13 08:53:35 +00001523 {
1524 // The $__lldb_expr_result name indicates the the return value has allocated as
1525 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1526 // accesses to this static variable need to be redirected to the result of dereferencing
1527 // a pointer that is passed in as one of the arguments.
1528 //
1529 // Consequently, when reporting the size of the type, we report a pointer type pointing
1530 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanane1175b72011-01-13 21:23:32 +00001531 //
1532 // We also do this for any user-declared persistent variables.
Greg Clayton57ee3062013-07-11 22:46:58 +00001533 clang_type = clang_type.GetPointerType();
Sean Callanan92adcac2011-01-13 08:53:35 +00001534 value_type = PointerType::get(global_variable->getType(), 0);
1535 }
1536 else
1537 {
Sean Callanan92adcac2011-01-13 08:53:35 +00001538 value_type = global_variable->getType();
1539 }
Greg Clayton57ee3062013-07-11 22:46:58 +00001540
1541 const uint64_t value_size = clang_type.GetByteSize();
1542 off_t value_alignment = (clang_type.GetTypeBitAlign() + 7ull) / 8ull;
Sean Callanan17827832010-12-13 22:46:15 +00001543
Sean Callanan038df5032010-09-30 21:18:25 +00001544 if (log)
Greg Clayton57ee3062013-07-11 22:46:58 +00001545 {
Greg Claytonfaac1112013-03-14 18:31:44 +00001546 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
Sean Callanan038df5032010-09-30 21:18:25 +00001547 name.c_str(),
Greg Clayton57ee3062013-07-11 22:46:58 +00001548 clang_type.GetQualType().getAsString().c_str(),
1549 PrintType(value_type).c_str(),
Sean Callanan038df5032010-09-30 21:18:25 +00001550 value_size,
1551 value_alignment);
Greg Clayton57ee3062013-07-11 22:46:58 +00001552 }
Sean Callanan17827832010-12-13 22:46:15 +00001553
Sean Callanan549c9f72010-07-13 21:41:46 +00001554
Sean Callanan64dfc9a2010-08-23 23:09:38 +00001555 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton7b462cc2010-10-15 22:48:33 +00001556 lldb_private::ConstString (name.c_str()),
1557 llvm_value_ptr,
Sean Callanan4edba2d2010-07-27 02:07:53 +00001558 value_size,
1559 value_alignment))
Sean Callananaf8e96c2011-08-01 17:41:38 +00001560 {
1561 if (!global_variable->hasExternalLinkage())
1562 return true;
Sean Callanan0ff3bf92013-04-11 17:57:16 +00001563 else if (HandleSymbol (global_variable))
1564 return true;
Sean Callananaf8e96c2011-08-01 17:41:38 +00001565 else
1566 return false;
1567 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001568 }
Sean Callanan4a5fcbb2010-12-03 03:02:31 +00001569 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001570 {
1571 if (log)
1572 log->Printf("Function pointers aren't handled right now");
1573
1574 return false;
1575 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001576
1577 return true;
1578}
1579
Sean Callanan3989fb92011-01-27 01:07:04 +00001580// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001581bool
Sean Callanan79763a42011-05-23 21:40:23 +00001582IRForTarget::HandleSymbol (Value *symbol)
Sean Callanand9ca42a2011-05-08 02:21:26 +00001583{
Greg Clayton5160ce52013-03-27 23:08:40 +00001584 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc3a16002011-01-17 23:42:46 +00001585
1586 lldb_private::ConstString name(symbol->getName().str().c_str());
1587
Sean Callanan947ccc72011-12-01 02:04:16 +00001588 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
Sean Callananc3a16002011-01-17 23:42:46 +00001589
Greg Clayton084db102011-06-23 04:25:29 +00001590 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc3a16002011-01-17 23:42:46 +00001591 {
1592 if (log)
1593 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1594
1595 return false;
1596 }
1597
1598 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001599 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
Sean Callananc3a16002011-01-17 23:42:46 +00001600
Sean Callanancc427fa2011-07-30 02:42:06 +00001601 Type *symbol_type = symbol->getType();
Sean Callanancc427fa2011-07-30 02:42:06 +00001602 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001603 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc3a16002011-01-17 23:42:46 +00001604
1605 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1606
1607 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1608
1609 if (log)
1610 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1611
1612 symbol->replaceAllUsesWith(symbol_addr_ptr);
1613
1614 return true;
1615}
1616
1617bool
Sean Callanan79763a42011-05-23 21:40:23 +00001618IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanan85a0a832010-10-05 22:26:43 +00001619{
Greg Clayton5160ce52013-03-27 23:08:40 +00001620 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001621
1622 if (log)
1623 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanan85a0a832010-10-05 22:26:43 +00001624
Sean Callananafe16a72010-11-17 23:00:36 +00001625 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanan85a0a832010-10-05 22:26:43 +00001626 op_index < num_ops;
1627 ++op_index)
Sean Callanan79763a42011-05-23 21:40:23 +00001628 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan3989fb92011-01-27 01:07:04 +00001629 {
1630 if (m_error_stream)
1631 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1632
Sean Callanan85a0a832010-10-05 22:26:43 +00001633 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001634 }
1635
Sean Callanan85a0a832010-10-05 22:26:43 +00001636 return true;
1637}
1638
1639bool
Sean Callananfc89c142011-11-01 23:38:03 +00001640IRForTarget::HandleObjCClass(Value *classlist_reference)
1641{
Greg Clayton5160ce52013-03-27 23:08:40 +00001642 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananfc89c142011-11-01 23:38:03 +00001643
1644 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1645
1646 if (!global_variable)
1647 return false;
1648
1649 Constant *initializer = global_variable->getInitializer();
1650
1651 if (!initializer)
1652 return false;
1653
1654 if (!initializer->hasName())
1655 return false;
1656
1657 StringRef name(initializer->getName());
1658 lldb_private::ConstString name_cstr(name.str().c_str());
Greg Clayton1075aca2011-12-03 20:02:42 +00001659 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
Sean Callananfc89c142011-11-01 23:38:03 +00001660
1661 if (log)
1662 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1663
1664 if (class_ptr == LLDB_INVALID_ADDRESS)
1665 return false;
1666
1667 if (global_variable->use_begin() == global_variable->use_end())
1668 return false;
1669
Sean Callanan719a4d52013-03-23 01:01:16 +00001670 SmallVector<LoadInst *, 2> load_instructions;
1671
Sean Callananfc89c142011-11-01 23:38:03 +00001672 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1673 i != e;
1674 ++i)
1675 {
Sean Callanan719a4d52013-03-23 01:01:16 +00001676 if (LoadInst *load_instruction = dyn_cast<LoadInst>(*i))
1677 load_instructions.push_back(load_instruction);
Sean Callananfc89c142011-11-01 23:38:03 +00001678 }
1679
Sean Callanan719a4d52013-03-23 01:01:16 +00001680 if (load_instructions.empty())
Sean Callananfc89c142011-11-01 23:38:03 +00001681 return false;
1682
1683 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00001684 (m_module->getPointerSize()
Micah Villmow08318972012-10-11 17:21:41 +00001685 == Module::Pointer64) ? 64 : 32);
Sean Callananfc89c142011-11-01 23:38:03 +00001686
1687 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
Sean Callananfc89c142011-11-01 23:38:03 +00001688
Sean Callanan719a4d52013-03-23 01:01:16 +00001689 for (LoadInst *load_instruction : load_instructions)
1690 {
1691 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
Sean Callananfc89c142011-11-01 23:38:03 +00001692
Sean Callanan719a4d52013-03-23 01:01:16 +00001693 load_instruction->replaceAllUsesWith(class_bitcast);
1694
1695 load_instruction->eraseFromParent();
1696 }
Sean Callananfc89c142011-11-01 23:38:03 +00001697
1698 return true;
1699}
1700
1701bool
Sean Callanan6e6d4a62012-07-21 02:02:15 +00001702IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1703{
1704 BasicBlock::iterator ii;
1705
1706 std::vector<CallInst *> calls_to_remove;
1707
1708 for (ii = basic_block.begin();
1709 ii != basic_block.end();
1710 ++ii)
1711 {
1712 Instruction &inst = *ii;
1713
1714 CallInst *call = dyn_cast<CallInst>(&inst);
1715
1716 // MaybeHandleCallArguments handles error reporting; we are silent here
1717 if (!call)
1718 continue;
1719
1720 bool remove = false;
1721
1722 llvm::Function *func = call->getCalledFunction();
1723
1724 if (func && func->getName() == "__cxa_atexit")
1725 remove = true;
1726
1727 llvm::Value *val = call->getCalledValue();
1728
1729 if (val && val->getName() == "__cxa_atexit")
1730 remove = true;
1731
1732 if (remove)
1733 calls_to_remove.push_back(call);
1734 }
1735
1736 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1737 ci != ce;
1738 ++ci)
1739 {
1740 (*ci)->eraseFromParent();
1741 }
1742
1743 return true;
1744}
1745
1746bool
Sean Callanan79763a42011-05-23 21:40:23 +00001747IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan549c9f72010-07-13 21:41:46 +00001748{
Sean Callanan2ab712f22010-07-03 01:35:46 +00001749 /////////////////////////////////////////////////////////////////////////
1750 // Prepare the current basic block for execution in the remote process
1751 //
1752
Sean Callanan7ea35012010-07-27 21:39:39 +00001753 BasicBlock::iterator ii;
Sean Callanan549c9f72010-07-13 21:41:46 +00001754
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001755 for (ii = basic_block.begin();
1756 ii != basic_block.end();
Sean Callanan549c9f72010-07-13 21:41:46 +00001757 ++ii)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001758 {
Sean Callanan549c9f72010-07-13 21:41:46 +00001759 Instruction &inst = *ii;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001760
Sean Callanana4e55172010-11-08 00:31:32 +00001761 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callanan4edba2d2010-07-27 02:07:53 +00001762
Sean Callanan3989fb92011-01-27 01:07:04 +00001763 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callanan79763a42011-05-23 21:40:23 +00001764 if (call && !MaybeHandleCallArguments(call))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001765 return false;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001766 }
1767
1768 return true;
1769}
1770
Sean Callanana4e55172010-11-08 00:31:32 +00001771bool
Sean Callanan79763a42011-05-23 21:40:23 +00001772IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanana4e55172010-11-08 00:31:32 +00001773{
Greg Clayton5160ce52013-03-27 23:08:40 +00001774 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7a55a322010-11-18 22:21:58 +00001775
Sean Callanan79763a42011-05-23 21:40:23 +00001776 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanana4e55172010-11-08 00:31:32 +00001777 global != end;
1778 ++global)
1779 {
Sean Callanan694e2442011-12-22 21:24:49 +00001780 if (!global)
1781 {
1782 if (m_error_stream)
1783 m_error_stream->Printf("Internal error [IRForTarget]: global variable is NULL");
1784
1785 return false;
1786 }
1787
1788 std::string global_name = (*global).getName().str();
1789
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001790 if (log)
1791 log->Printf("Examining %s, DeclForGlobalValue returns %p",
Sean Callanan694e2442011-12-22 21:24:49 +00001792 global_name.c_str(),
Sean Callanan79763a42011-05-23 21:40:23 +00001793 DeclForGlobal(global));
Sean Callananfc89c142011-11-01 23:38:03 +00001794
1795 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc3a16002011-01-17 23:42:46 +00001796 {
Sean Callanan79763a42011-05-23 21:40:23 +00001797 if (!HandleSymbol(global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001798 {
1799 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001800 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 +00001801
Sean Callananc3a16002011-01-17 23:42:46 +00001802 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001803 }
Sean Callananc3a16002011-01-17 23:42:46 +00001804 }
Sean Callananfc89c142011-11-01 23:38:03 +00001805 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1806 {
1807 if (!HandleObjCClass(global))
1808 {
1809 if (m_error_stream)
1810 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1811
1812 return false;
1813 }
1814 }
Sean Callanan2ad66912013-04-24 21:25:20 +00001815 else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos)
1816 {
1817 if (!HandleObjCClass(global))
1818 {
1819 if (m_error_stream)
1820 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1821
1822 return false;
1823 }
1824 }
Sean Callanan79763a42011-05-23 21:40:23 +00001825 else if (DeclForGlobal(global))
Sean Callananc3a16002011-01-17 23:42:46 +00001826 {
Sean Callanan79763a42011-05-23 21:40:23 +00001827 if (!MaybeHandleVariable (global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001828 {
1829 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001830 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 +00001831
Sean Callananc3a16002011-01-17 23:42:46 +00001832 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001833 }
Sean Callananc3a16002011-01-17 23:42:46 +00001834 }
Sean Callanana4e55172010-11-08 00:31:32 +00001835 }
1836
1837 return true;
1838}
1839
Sean Callanan79763a42011-05-23 21:40:23 +00001840bool
1841IRForTarget::ReplaceStrings ()
1842{
Greg Clayton5160ce52013-03-27 23:08:40 +00001843 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001844
Sean Callanan79763a42011-05-23 21:40:23 +00001845 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1846
1847 OffsetsTy offsets;
1848
1849 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1850 gi != ge;
1851 ++gi)
1852 {
1853 GlobalVariable *gv = gi;
1854
1855 if (!gv->hasInitializer())
1856 continue;
1857
1858 Constant *gc = gv->getInitializer();
1859
Sean Callanan5207a342011-08-10 21:05:52 +00001860 std::string str;
Sean Callanan79763a42011-05-23 21:40:23 +00001861
Sean Callanan5207a342011-08-10 21:05:52 +00001862 if (gc->isNullValue())
1863 {
1864 Type *gc_type = gc->getType();
1865
1866 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1867
1868 if (!gc_array_type)
1869 continue;
1870
1871 Type *gc_element_type = gc_array_type->getElementType();
1872
1873 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1874
1875 if (gc_integer_type->getBitWidth() != 8)
1876 continue;
1877
1878 str = "";
1879 }
1880 else
1881 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001882 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
Sean Callanan5207a342011-08-10 21:05:52 +00001883
1884 if (!gc_array)
1885 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001886
Sean Callanan5207a342011-08-10 21:05:52 +00001887 if (!gc_array->isCString())
1888 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001889
Sean Callanan5207a342011-08-10 21:05:52 +00001890 if (log)
1891 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00001892
Sean Callanan5207a342011-08-10 21:05:52 +00001893 str = gc_array->getAsString();
1894 }
1895
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001896 offsets[gv] = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00001897
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001898 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
Sean Callanan79763a42011-05-23 21:40:23 +00001899 }
1900
Sean Callanancc427fa2011-07-30 02:42:06 +00001901 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00001902
1903 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1904 oi != oe;
1905 ++oi)
1906 {
1907 GlobalVariable *gv = oi->first;
1908 size_t offset = oi->second;
1909
1910 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1911
1912 if (log)
1913 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1914
1915 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1916 ui != ue;
1917 ++ui)
1918 {
1919 if (log)
1920 log->Printf("Found use %s", PrintValue(*ui).c_str());
1921
1922 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1923 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1924
1925 if (const_expr)
1926 {
1927 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1928 {
1929 if (log)
1930 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1931
1932 return false;
1933 }
1934
Sean Callanan5207a342011-08-10 21:05:52 +00001935 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1936 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1937
1938 const_expr->replaceAllUsesWith(new_gep);
Sean Callanan79763a42011-05-23 21:40:23 +00001939 }
1940 else if (store_inst)
1941 {
1942 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1943
1944 store_inst->setOperand(0, bit_cast);
1945 }
1946 else
1947 {
1948 if (log)
1949 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1950
1951 return false;
1952 }
1953 }
1954
1955 gv->eraseFromParent();
1956 }
1957
1958 return true;
1959}
1960
1961bool
1962IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1963{
Greg Clayton5160ce52013-03-27 23:08:40 +00001964 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001965
1966 typedef SmallVector <Value*, 2> ConstantList;
1967 typedef SmallVector <llvm::Instruction*, 2> UserList;
1968 typedef ConstantList::iterator ConstantIterator;
1969 typedef UserList::iterator UserIterator;
1970
1971 ConstantList static_constants;
1972 UserList static_users;
1973
1974 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1975 ii != ie;
1976 ++ii)
1977 {
1978 llvm::Instruction &inst = *ii;
1979
1980 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1981 oi != oe;
1982 ++oi)
1983 {
1984 Value *operand_val = oi->get();
1985
1986 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1987
Sean Callanan822944c2012-04-26 20:51:20 +00001988 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
Sean Callanan79763a42011-05-23 21:40:23 +00001989 {
1990 static_constants.push_back(operand_val);
1991 static_users.push_back(ii);
1992 }
1993 }
1994 }
1995
1996 ConstantIterator constant_iter;
1997 UserIterator user_iter;
Greg Clayton9b72eb72011-05-24 23:06:02 +00001998
Sean Callanan79763a42011-05-23 21:40:23 +00001999 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
2000 constant_iter != static_constants.end();
2001 ++constant_iter, ++user_iter)
2002 {
2003 Value *operand_val = *constant_iter;
2004 llvm::Instruction *inst = *user_iter;
2005
2006 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2007
2008 if (operand_constant_fp)
2009 {
Sean Callanan1582ee62013-04-18 22:06:33 +00002010 Type *operand_type = operand_constant_fp->getType();
2011
Sean Callanan79763a42011-05-23 21:40:23 +00002012 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2013 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2014
2015 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2016 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2017
2018 if (log)
2019 {
2020 std::string s;
2021 raw_string_ostream ss(s);
2022 for (size_t index = 0;
2023 index < operand_data_size;
2024 ++index)
2025 {
2026 ss << (uint32_t)operand_raw_data[index];
2027 ss << " ";
2028 }
2029 ss.flush();
2030
Jason Molendafd54b362011-09-20 21:44:10 +00002031 log->Printf("Found ConstantFP with size %lu and raw data %s", operand_data_size, s.c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00002032 }
2033
2034 lldb_private::DataBufferHeap data(operand_data_size, 0);
2035
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002036 if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
Sean Callanan79763a42011-05-23 21:40:23 +00002037 {
2038 uint8_t *data_bytes = data.GetBytes();
2039
2040 for (size_t index = 0;
2041 index < operand_data_size;
2042 ++index)
2043 {
2044 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2045 }
2046 }
2047 else
2048 {
2049 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2050 }
2051
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002052 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00002053
Sean Callanane3333d62012-06-08 22:20:41 +00002054 size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2055
2056 const size_t mask = (align - 1);
2057 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002058 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00002059 offset = aligned_offset;
2060
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002061 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
Sean Callanan79763a42011-05-23 21:40:23 +00002062
Sean Callanancc427fa2011-07-30 02:42:06 +00002063 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callanan79763a42011-05-23 21:40:23 +00002064
Sean Callanan1582ee62013-04-18 22:06:33 +00002065 Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
Sean Callanan79763a42011-05-23 21:40:23 +00002066
2067 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2068
2069 operand_constant_fp->replaceAllUsesWith(fp_load);
2070 }
2071 }
2072
2073 return true;
2074}
2075
Sean Callanan7ea35012010-07-27 21:39:39 +00002076static bool isGuardVariableRef(Value *V)
Sean Callananddb46ef2010-07-24 01:37:44 +00002077{
Sean Callanan77eaf442011-07-08 00:39:14 +00002078 Constant *Old = NULL;
Sean Callananddb46ef2010-07-24 01:37:44 +00002079
Sean Callananafe16a72010-11-17 23:00:36 +00002080 if (!(Old = dyn_cast<Constant>(V)))
Sean Callananddb46ef2010-07-24 01:37:44 +00002081 return false;
2082
Sean Callanan77eaf442011-07-08 00:39:14 +00002083 ConstantExpr *CE = NULL;
Sean Callanane2ef6e32010-09-23 03:01:22 +00002084
2085 if ((CE = dyn_cast<ConstantExpr>(V)))
2086 {
2087 if (CE->getOpcode() != Instruction::BitCast)
2088 return false;
2089
Sean Callananafe16a72010-11-17 23:00:36 +00002090 Old = CE->getOperand(0);
Sean Callanane2ef6e32010-09-23 03:01:22 +00002091 }
2092
Sean Callananafe16a72010-11-17 23:00:36 +00002093 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callananddb46ef2010-07-24 01:37:44 +00002094
2095 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2096 return false;
2097
2098 return true;
2099}
2100
Sean Callanan79763a42011-05-23 21:40:23 +00002101void
2102IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callananddb46ef2010-07-24 01:37:44 +00002103{
Sean Callanan79763a42011-05-23 21:40:23 +00002104 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callananddb46ef2010-07-24 01:37:44 +00002105
2106 Value::use_iterator ui;
2107
2108 for (ui = guard_load->use_begin();
2109 ui != guard_load->use_end();
2110 ++ui)
Sean Callananb27a62f2010-07-27 01:17:28 +00002111 {
Greg Claytone6371122010-07-30 20:30:44 +00002112 if (isa<Constant>(*ui))
Sean Callananb27a62f2010-07-27 01:17:28 +00002113 {
2114 // do nothing for the moment
2115 }
2116 else
2117 {
2118 ui->replaceUsesOfWith(guard_load, zero);
2119 }
2120 }
Sean Callananddb46ef2010-07-24 01:37:44 +00002121
2122 guard_load->eraseFromParent();
2123}
2124
2125static void ExciseGuardStore(Instruction* guard_store)
2126{
2127 guard_store->eraseFromParent();
2128}
2129
2130bool
Sean Callanan79763a42011-05-23 21:40:23 +00002131IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callananddb46ef2010-07-24 01:37:44 +00002132{
2133 ///////////////////////////////////////////////////////
2134 // Eliminate any reference to guard variables found.
2135 //
2136
Sean Callanan7ea35012010-07-27 21:39:39 +00002137 BasicBlock::iterator ii;
Sean Callananddb46ef2010-07-24 01:37:44 +00002138
Sean Callanan7ea35012010-07-27 21:39:39 +00002139 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callananddb46ef2010-07-24 01:37:44 +00002140 typedef InstrList::iterator InstrIterator;
2141
2142 InstrList guard_loads;
2143 InstrList guard_stores;
2144
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002145 for (ii = basic_block.begin();
2146 ii != basic_block.end();
Sean Callananddb46ef2010-07-24 01:37:44 +00002147 ++ii)
2148 {
2149 Instruction &inst = *ii;
2150
2151 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2152 if (isGuardVariableRef(load->getPointerOperand()))
2153 guard_loads.push_back(&inst);
2154
2155 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2156 if (isGuardVariableRef(store->getPointerOperand()))
2157 guard_stores.push_back(&inst);
2158 }
2159
2160 InstrIterator iter;
2161
2162 for (iter = guard_loads.begin();
2163 iter != guard_loads.end();
2164 ++iter)
Sean Callanan79763a42011-05-23 21:40:23 +00002165 TurnGuardLoadIntoZero(*iter);
Sean Callananddb46ef2010-07-24 01:37:44 +00002166
2167 for (iter = guard_stores.begin();
2168 iter != guard_stores.end();
2169 ++iter)
2170 ExciseGuardStore(*iter);
2171
2172 return true;
2173}
2174
Sean Callanan3989fb92011-01-27 01:07:04 +00002175// This function does not report errors; its callers are responsible.
Sean Callananafe16a72010-11-17 23:00:36 +00002176bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002177IRForTarget::UnfoldConstant(Constant *old_constant,
2178 FunctionValueCache &value_maker,
2179 FunctionValueCache &entry_instruction_finder)
Sean Callanan7618f4e2010-07-14 23:40:29 +00002180{
Greg Clayton5160ce52013-03-27 23:08:40 +00002181 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002182
2183 Value::use_iterator ui;
2184
Sean Callanan2235f322010-08-11 03:57:18 +00002185 SmallVector<User*, 16> users;
2186
2187 // We do this because the use list might change, invalidating our iterator.
2188 // Much better to keep a work list ourselves.
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002189 for (ui = old_constant->use_begin();
2190 ui != old_constant->use_end();
Sean Callanan7618f4e2010-07-14 23:40:29 +00002191 ++ui)
Sean Callanan2235f322010-08-11 03:57:18 +00002192 users.push_back(*ui);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002193
Johnny Chen44805302011-07-19 19:48:13 +00002194 for (size_t i = 0;
Sean Callanan2235f322010-08-11 03:57:18 +00002195 i < users.size();
2196 ++i)
2197 {
2198 User *user = users[i];
2199
Sean Callanan7618f4e2010-07-14 23:40:29 +00002200 if (Constant *constant = dyn_cast<Constant>(user))
2201 {
2202 // synthesize a new non-constant equivalent of the constant
2203
2204 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2205 {
2206 switch (constant_expr->getOpcode())
2207 {
2208 default:
2209 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002210 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002211 return false;
2212 case Instruction::BitCast:
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002213 {
2214 FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2215 // UnaryExpr
2216 // OperandList[0] is value
2217
2218 if (constant_expr->getOperand(0) != old_constant)
2219 return constant_expr;
2220
2221 return new BitCastInst(value_maker.GetValue(function),
2222 constant_expr->getType(),
2223 "",
2224 llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2225 });
Sean Callanan7618f4e2010-07-14 23:40:29 +00002226
Sean Callanan0e016fe2013-07-15 23:31:47 +00002227 if (!UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder))
2228 return false;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002229 }
2230 break;
2231 case Instruction::GetElementPtr:
2232 {
2233 // GetElementPtrConstantExpr
2234 // OperandList[0] is base
2235 // OperandList[1]... are indices
2236
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002237 FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2238 Value *ptr = constant_expr->getOperand(0);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002239
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002240 if (ptr == old_constant)
2241 ptr = value_maker.GetValue(function);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002242
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002243 std::vector<Value*> index_vector;
2244
2245 unsigned operand_index;
2246 unsigned num_operands = constant_expr->getNumOperands();
2247
2248 for (operand_index = 1;
2249 operand_index < num_operands;
2250 ++operand_index)
2251 {
2252 Value *operand = constant_expr->getOperand(operand_index);
2253
2254 if (operand == old_constant)
2255 operand = value_maker.GetValue(function);
2256
2257 index_vector.push_back(operand);
2258 }
2259
2260 ArrayRef <Value*> indices(index_vector);
2261
2262 return GetElementPtrInst::Create(ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2263 });
Sean Callanan7618f4e2010-07-14 23:40:29 +00002264
Sean Callanan0e016fe2013-07-15 23:31:47 +00002265 if (!UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder))
2266 return false;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002267 }
2268 break;
2269 }
2270 }
2271 else
2272 {
2273 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002274 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002275 return false;
2276 }
2277 }
2278 else
2279 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002280 if (Instruction *inst = llvm::dyn_cast<Instruction>(user))
2281 {
2282 inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent()));
2283 }
2284 else
2285 {
2286 if (log)
2287 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str());
2288 return false;
2289 }
Sean Callanan7618f4e2010-07-14 23:40:29 +00002290 }
2291 }
2292
Sean Callanan0e016fe2013-07-15 23:31:47 +00002293 if (!isa<GlobalValue>(old_constant))
2294 {
2295 old_constant->destroyConstant();
2296 }
2297
Sean Callanan7618f4e2010-07-14 23:40:29 +00002298 return true;
2299}
2300
Sean Callanan549c9f72010-07-13 21:41:46 +00002301bool
Sean Callanan79763a42011-05-23 21:40:23 +00002302IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan549c9f72010-07-13 21:41:46 +00002303{
Sean Callanan9e6ed532010-09-13 21:34:21 +00002304 if (!m_resolve_vars)
2305 return true;
2306
Greg Clayton5160ce52013-03-27 23:08:40 +00002307 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan549c9f72010-07-13 21:41:46 +00002308
2309 m_decl_map->DoStructLayout();
2310
2311 if (log)
2312 log->Printf("Element arrangement:");
2313
2314 uint32_t num_elements;
2315 uint32_t element_index;
2316
2317 size_t size;
2318 off_t alignment;
2319
2320 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2321 return false;
2322
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002323 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan549c9f72010-07-13 21:41:46 +00002324
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 no arguments (should take at least a struct pointer)");
2329
Sean Callanan549c9f72010-07-13 21:41:46 +00002330 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002331 }
2332
Sean Callanan7ea35012010-07-27 21:39:39 +00002333 Argument *argument = iter;
Sean Callanan549c9f72010-07-13 21:41:46 +00002334
Sean Callananfc55f5d2010-09-21 00:44:12 +00002335 if (argument->getName().equals("this"))
2336 {
2337 ++iter;
2338
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002339 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 'this' argument (should take a struct pointer too)");
2343
Sean Callananfc55f5d2010-09-21 00:44:12 +00002344 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002345 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002346
2347 argument = iter;
2348 }
Sean Callanan17827832010-12-13 22:46:15 +00002349 else if (argument->getName().equals("self"))
2350 {
2351 ++iter;
2352
2353 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002354 {
2355 if (m_error_stream)
2356 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2357
Sean Callanan17827832010-12-13 22:46:15 +00002358 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002359 }
Sean Callanan17827832010-12-13 22:46:15 +00002360
2361 if (!iter->getName().equals("_cmd"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002362 {
2363 if (m_error_stream)
2364 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2365
Sean Callanan17827832010-12-13 22:46:15 +00002366 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002367 }
Sean Callanan17827832010-12-13 22:46:15 +00002368
2369 ++iter;
2370
2371 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002372 {
2373 if (m_error_stream)
2374 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2375
Sean Callanan17827832010-12-13 22:46:15 +00002376 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002377 }
Sean Callanan17827832010-12-13 22:46:15 +00002378
2379 argument = iter;
2380 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002381
Greg Clayton7b462cc2010-10-15 22:48:33 +00002382 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002383 {
2384 if (m_error_stream)
2385 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2386
Sean Callanan549c9f72010-07-13 21:41:46 +00002387 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002388 }
2389
Sean Callanan549c9f72010-07-13 21:41:46 +00002390 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002391 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan549c9f72010-07-13 21:41:46 +00002392
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002393 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +00002394 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan549c9f72010-07-13 21:41:46 +00002395
Sean Callananafe16a72010-11-17 23:00:36 +00002396 if (!FirstEntryInstruction)
Sean Callanan3989fb92011-01-27 01:07:04 +00002397 {
2398 if (m_error_stream)
2399 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2400
Sean Callanan549c9f72010-07-13 21:41:46 +00002401 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002402 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002403
Sean Callanan79763a42011-05-23 21:40:23 +00002404 LLVMContext &context(m_module->getContext());
Sean Callanancc427fa2011-07-30 02:42:06 +00002405 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan549c9f72010-07-13 21:41:46 +00002406
2407 if (!offset_type)
Sean Callanan3989fb92011-01-27 01:07:04 +00002408 {
2409 if (m_error_stream)
2410 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2411
Sean Callanan549c9f72010-07-13 21:41:46 +00002412 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002413 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002414
2415 for (element_index = 0; element_index < num_elements; ++element_index)
2416 {
Sean Callanan77eaf442011-07-08 00:39:14 +00002417 const clang::NamedDecl *decl = NULL;
2418 Value *value = NULL;
Sean Callanan549c9f72010-07-13 21:41:46 +00002419 off_t offset;
Greg Clayton7b462cc2010-10-15 22:48:33 +00002420 lldb_private::ConstString name;
Sean Callanan549c9f72010-07-13 21:41:46 +00002421
Sean Callanan823bb4c2010-08-30 22:17:16 +00002422 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan3989fb92011-01-27 01:07:04 +00002423 {
2424 if (m_error_stream)
2425 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2426
Sean Callanan549c9f72010-07-13 21:41:46 +00002427 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002428 }
2429
Sean Callanan549c9f72010-07-13 21:41:46 +00002430 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002431 log->Printf(" \"%s\" (\"%s\") placed at %" PRId64,
Greg Clayton7b462cc2010-10-15 22:48:33 +00002432 name.GetCString(),
Sean Callananc70ed462011-10-25 18:36:40 +00002433 decl->getNameAsString().c_str(),
Sean Callanan549c9f72010-07-13 21:41:46 +00002434 offset);
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002435
Sean Callananc70ed462011-10-25 18:36:40 +00002436 if (value)
Sean Callanan92adcac2011-01-13 08:53:35 +00002437 {
Sean Callananc70ed462011-10-25 18:36:40 +00002438 if (log)
2439 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan92adcac2011-01-13 08:53:35 +00002440
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002441 FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * {
2442 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2443 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2444 // entry in order to produce the static variable that the AST thinks it is accessing.
Sean Callananc70ed462011-10-25 18:36:40 +00002445
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002446 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function));
Sean Callananc70ed462011-10-25 18:36:40 +00002447
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002448 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
2449 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument,
2450 offset_int,
2451 "",
2452 entry_instruction);
2453
2454 if (name == m_result_name && !m_result_is_pointer)
2455 {
2456 BitCastInst *bit_cast = new BitCastInst(get_element_ptr,
2457 value->getType()->getPointerTo(),
2458 "",
2459 entry_instruction);
2460
2461 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
2462
2463 return load;
2464 }
2465 else
2466 {
2467 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction);
2468
2469 return bit_cast;
2470 }
2471 });
Sean Callananc70ed462011-10-25 18:36:40 +00002472
2473 if (Constant *constant = dyn_cast<Constant>(value))
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002474 {
2475 UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder);
2476 }
2477 else if (Instruction *instruction = dyn_cast<Instruction>(value))
2478 {
2479 value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent()));
2480 }
Sean Callananc70ed462011-10-25 18:36:40 +00002481 else
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002482 {
2483 if (log)
2484 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str());
2485 return false;
2486 }
Sean Callananc70ed462011-10-25 18:36:40 +00002487
2488 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2489 var->eraseFromParent();
2490 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002491 }
2492
2493 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002494 log->Printf("Total structure [align %" PRId64 ", size %lu]", alignment, size);
Sean Callanan549c9f72010-07-13 21:41:46 +00002495
2496 return true;
2497}
2498
Sean Callanan79763a42011-05-23 21:40:23 +00002499llvm::Constant *
Greg Clayton5160ce52013-03-27 23:08:40 +00002500IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
Sean Callanan79763a42011-05-23 21:40:23 +00002501{
Sean Callanancc427fa2011-07-30 02:42:06 +00002502 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00002503 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan79763a42011-05-23 21:40:23 +00002504
2505 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanancc427fa2011-07-30 02:42:06 +00002506
2507 llvm::Constant *offset_array[1];
2508
2509 offset_array[0] = offset_int;
2510
2511 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2512
2513 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callanan79763a42011-05-23 21:40:23 +00002514 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2515
2516 return reloc_getbitcast;
2517}
2518
2519bool
2520IRForTarget::CompleteDataAllocation ()
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002521{
Greg Clayton5160ce52013-03-27 23:08:40 +00002522 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002523
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002524 if (!m_data_allocator.GetStream().GetSize())
Sean Callanan79763a42011-05-23 21:40:23 +00002525 return true;
2526
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002527 lldb::addr_t allocation = m_data_allocator.Allocate();
Sean Callanan79763a42011-05-23 21:40:23 +00002528
2529 if (log)
2530 {
2531 if (allocation)
2532 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2533 else
2534 log->Printf("Failed to allocate static data");
2535 }
2536
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002537 if (!allocation || allocation == LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +00002538 return false;
2539
Sean Callanancc427fa2011-07-30 02:42:06 +00002540 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callanan95769bf2012-10-11 22:00:52 +00002541 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan79763a42011-05-23 21:40:23 +00002542
2543 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2544 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2545
2546 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2547
2548 m_reloc_placeholder->eraseFromParent();
2549
2550 return true;
2551}
2552
Sean Callanan2ab712f22010-07-03 01:35:46 +00002553bool
Sean Callanan3d654b32012-09-24 22:25:51 +00002554IRForTarget::StripAllGVs (Module &llvm_module)
2555{
Greg Clayton5160ce52013-03-27 23:08:40 +00002556 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3d654b32012-09-24 22:25:51 +00002557 std::vector<GlobalVariable *> global_vars;
2558 std::set<GlobalVariable *>erased_vars;
2559
2560 bool erased = true;
2561
2562 while (erased)
2563 {
2564 erased = false;
2565
2566 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2567 gi != ge;
2568 ++gi)
2569 {
2570 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2571
2572 global_var->removeDeadConstantUsers();
2573
2574 if (global_var->use_empty())
2575 {
2576 if (log)
2577 log->Printf("Did remove %s",
2578 PrintValue(global_var).c_str());
2579 global_var->eraseFromParent();
2580 erased = true;
2581 break;
2582 }
2583 }
2584 }
2585
2586 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2587 gi != ge;
2588 ++gi)
2589 {
2590 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2591
2592 GlobalValue::use_iterator ui = global_var->use_begin();
2593
Jim Inghamd77557d2012-11-26 19:54:04 +00002594 if (log)
2595 log->Printf("Couldn't remove %s because of %s",
2596 PrintValue(global_var).c_str(),
2597 PrintValue(*ui).c_str());
Sean Callanan3d654b32012-09-24 22:25:51 +00002598 }
2599
2600 return true;
2601}
2602
2603bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002604IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002605{
Greg Clayton5160ce52013-03-27 23:08:40 +00002606 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002607
Sean Callanan79763a42011-05-23 21:40:23 +00002608 m_module = &llvm_module;
Micah Villmow8468dbe2012-10-08 16:28:57 +00002609 m_target_data.reset(new DataLayout(m_module));
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002610
Sean Callananc70ed462011-10-25 18:36:40 +00002611 if (log)
2612 {
2613 std::string s;
2614 raw_string_ostream oss(s);
2615
2616 m_module->print(oss, NULL);
2617
2618 oss.flush();
2619
2620 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2621 }
2622
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002623 Function* main_function = m_module->getFunction(StringRef(m_func_name.c_str()));
2624
2625 if (!main_function)
2626 {
2627 if (log)
2628 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
2629
2630 if (m_error_stream)
2631 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
2632
2633 return false;
2634 }
2635
2636 if (!FixFunctionLinkage (*main_function))
2637 {
2638 if (log)
2639 log->Printf("Couldn't fix the linkage for the function");
2640
2641 return false;
2642 }
2643
Sean Callanancc427fa2011-07-30 02:42:06 +00002644 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00002645
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002646 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
Sean Callanan79763a42011-05-23 21:40:23 +00002647 intptr_ty,
Sean Callanan3d654b32012-09-24 22:25:51 +00002648 false /* IsConstant */,
Sean Callanan79763a42011-05-23 21:40:23 +00002649 GlobalVariable::InternalLinkage,
2650 Constant::getNullValue(intptr_ty),
2651 "reloc_placeholder",
2652 NULL /* InsertBefore */,
Sean Callanan3d654b32012-09-24 22:25:51 +00002653 GlobalVariable::NotThreadLocal /* ThreadLocal */,
Sean Callanan79763a42011-05-23 21:40:23 +00002654 0 /* AddressSpace */);
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002655
Sean Callanand1e5b432010-08-12 01:56:52 +00002656 ////////////////////////////////////////////////////////////
Greg Clayton7b462cc2010-10-15 22:48:33 +00002657 // Replace $__lldb_expr_result with a persistent variable
Sean Callanand1e5b432010-08-12 01:56:52 +00002658 //
2659
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002660 if (!CreateResultVariable(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002661 {
2662 if (log)
2663 log->Printf("CreateResultVariable() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002664
2665 // CreateResultVariable() reports its own errors, so we don't do so here
2666
Sean Callanand1e5b432010-08-12 01:56:52 +00002667 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002668 }
Sean Callanan6e6d4a62012-07-21 02:02:15 +00002669
Sean Callananea685ae2011-11-01 17:33:54 +00002670 if (log && log->GetVerbose())
Sean Callanan79763a42011-05-23 21:40:23 +00002671 {
2672 std::string s;
2673 raw_string_ostream oss(s);
2674
2675 m_module->print(oss, NULL);
2676
2677 oss.flush();
2678
2679 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2680 }
2681
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002682 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2683 fi != fe;
2684 ++fi)
2685 {
2686 llvm::Function *function = fi;
2687
2688 if (function->begin() == function->end())
2689 continue;
2690
2691 Function::iterator bbi;
2692
2693 for (bbi = function->begin();
2694 bbi != function->end();
2695 ++bbi)
2696 {
2697 if (!RemoveGuards(*bbi))
2698 {
2699 if (log)
2700 log->Printf("RemoveGuards() failed");
2701
2702 // RemoveGuards() reports its own errors, so we don't do so here
2703
2704 return false;
2705 }
2706
2707 if (!RewritePersistentAllocs(*bbi))
2708 {
2709 if (log)
2710 log->Printf("RewritePersistentAllocs() failed");
2711
2712 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2713
2714 return false;
2715 }
2716
2717 if (!RemoveCXAAtExit(*bbi))
2718 {
2719 if (log)
2720 log->Printf("RemoveCXAAtExit() failed");
2721
2722 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2723
2724 return false;
2725 }
2726 }
2727 }
2728
Sean Callananafe16a72010-11-17 23:00:36 +00002729 ///////////////////////////////////////////////////////////////////////////////
2730 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2731 //
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002732
2733 if (!RewriteObjCConstStrings())
Sean Callanan17827832010-12-13 22:46:15 +00002734 {
2735 if (log)
2736 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002737
2738 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2739
Sean Callananafe16a72010-11-17 23:00:36 +00002740 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002741 }
Sean Callananafe16a72010-11-17 23:00:36 +00002742
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002743 ///////////////////////////////
2744 // Resolve function pointers
2745 //
2746
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002747 if (!ResolveFunctionPointers(llvm_module))
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002748 {
2749 if (log)
2750 log->Printf("ResolveFunctionPointers() failed");
2751
2752 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2753
2754 return false;
2755 }
2756
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002757 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2758 fi != fe;
2759 ++fi)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002760 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002761 llvm::Function *function = fi;
2762
2763 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2764 bbi != bbe;
2765 ++bbi)
Sean Callanan17827832010-12-13 22:46:15 +00002766 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002767 if (!RewriteObjCSelectors(*bbi))
2768 {
2769 if (log)
2770 log->Printf("RewriteObjCSelectors() failed");
2771
2772 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2773
2774 return false;
2775 }
Sean Callanan17827832010-12-13 22:46:15 +00002776 }
Sean Callananbad134f2012-07-27 19:25:24 +00002777 }
Sean Callanan2235f322010-08-11 03:57:18 +00002778
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002779 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2780 fi != fe;
2781 ++fi)
Sean Callananbad134f2012-07-27 19:25:24 +00002782 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002783 llvm::Function *function = fi;
Sean Callanan79763a42011-05-23 21:40:23 +00002784
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002785 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2786 bbi != bbe;
2787 ++bbi)
Sean Callanan79763a42011-05-23 21:40:23 +00002788 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002789 if (!ResolveCalls(*bbi))
2790 {
2791 if (log)
2792 log->Printf("ResolveCalls() failed");
2793
2794 // ResolveCalls() reports its own errors, so we don't do so here
2795
2796 return false;
2797 }
Sean Callanan79763a42011-05-23 21:40:23 +00002798
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002799 if (!ReplaceStaticLiterals(*bbi))
2800 {
2801 if (log)
2802 log->Printf("ReplaceStaticLiterals() failed");
2803
2804 return false;
2805 }
Sean Callanan79763a42011-05-23 21:40:23 +00002806 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002807 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002808
2809 ////////////////////////////////////////////////////////////////////////
2810 // Run function-level passes that only make sense on the main function
Sean Callanan038df5032010-09-30 21:18:25 +00002811 //
2812
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002813 if (!ResolveExternals(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002814 {
2815 if (log)
2816 log->Printf("ResolveExternals() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002817
2818 // ResolveExternals() reports its own errors, so we don't do so here
2819
Sean Callanana4e55172010-11-08 00:31:32 +00002820 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002821 }
Sean Callanana4e55172010-11-08 00:31:32 +00002822
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002823 if (!ReplaceVariables(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002824 {
2825 if (log)
2826 log->Printf("ReplaceVariables() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002827
2828 // ReplaceVariables() reports its own errors, so we don't do so here
2829
Sean Callanan038df5032010-09-30 21:18:25 +00002830 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002831 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002832
Sean Callanan79763a42011-05-23 21:40:23 +00002833 if (!ReplaceStrings())
2834 {
2835 if (log)
2836 log->Printf("ReplaceStrings() failed");
2837
2838 return false;
2839 }
2840
2841 if (!CompleteDataAllocation())
2842 {
2843 if (log)
2844 log->Printf("CompleteDataAllocation() failed");
2845
2846 return false;
2847 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002848
Sean Callanan3d654b32012-09-24 22:25:51 +00002849 if (!StripAllGVs(llvm_module))
2850 {
2851 if (log)
2852 log->Printf("StripAllGVs() failed");
2853 }
2854
Sean Callananea685ae2011-11-01 17:33:54 +00002855 if (log && log->GetVerbose())
Sean Callanan549c9f72010-07-13 21:41:46 +00002856 {
Sean Callanancc54bd32010-07-28 01:00:59 +00002857 std::string s;
2858 raw_string_ostream oss(s);
Sean Callanan549c9f72010-07-13 21:41:46 +00002859
Sean Callanan79763a42011-05-23 21:40:23 +00002860 m_module->print(oss, NULL);
Sean Callanancc54bd32010-07-28 01:00:59 +00002861
2862 oss.flush();
2863
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002864 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan2ab712f22010-07-03 01:35:46 +00002865 }
2866
2867 return true;
2868}
2869
2870void
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002871IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002872{
2873}
2874
2875PassManagerType
2876IRForTarget::getPotentialPassManagerType() const
2877{
2878 return PMT_ModulePassManager;
2879}