blob: 6de244648a2e9528b29c9de03a828138846f4704 [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),
Sean Callanan439dcae2013-12-20 19:55:02 +0000108 m_intptr_ty(NULL),
Stephen Wilson71c21d12011-04-11 19:41:40 +0000109 m_error_stream(error_stream),
Sean Callanan63697e52011-05-07 01:06:41 +0000110 m_result_store(NULL),
111 m_result_is_pointer(false),
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000112 m_reloc_placeholder(NULL),
113 m_entry_instruction_finder (FindEntryInstruction)
Sean Callanan2ab712f22010-07-03 01:35:46 +0000114{
115}
116
Sean Callanan038df5032010-09-30 21:18:25 +0000117/* Handy utility functions used at several places in the code */
Sean Callanan2235f322010-08-11 03:57:18 +0000118
119static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000120PrintValue(const Value *value, bool truncate = false)
Sean Callanan2235f322010-08-11 03:57:18 +0000121{
122 std::string s;
Jim Ingham28eb5712012-10-12 17:34:26 +0000123 if (value)
124 {
125 raw_string_ostream rso(s);
126 value->print(rso);
127 rso.flush();
128 if (truncate)
129 s.resize(s.length() - 1);
130 }
Sean Callanan2235f322010-08-11 03:57:18 +0000131 return s;
132}
133
Sean Callanan038df5032010-09-30 21:18:25 +0000134static std::string
Greg Clayton57ee3062013-07-11 22:46:58 +0000135PrintType(const llvm::Type *type, bool truncate = false)
Sean Callanan038df5032010-09-30 21:18:25 +0000136{
137 std::string s;
138 raw_string_ostream rso(s);
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000139 type->print(rso);
Sean Callanan038df5032010-09-30 21:18:25 +0000140 rso.flush();
141 if (truncate)
142 s.resize(s.length() - 1);
143 return s;
144}
145
Sean Callanan2ab712f22010-07-03 01:35:46 +0000146IRForTarget::~IRForTarget()
147{
148}
149
Sean Callanan79763a42011-05-23 21:40:23 +0000150bool
151IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
152{
Sean Callanan79763a42011-05-23 21:40:23 +0000153 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
154
Sean Callanan7f27d602011-11-19 02:54:21 +0000155 std::string name = llvm_function.getName().str();
Sean Callanan79763a42011-05-23 21:40:23 +0000156
157 return true;
158}
159
Sean Callanand1e5b432010-08-12 01:56:52 +0000160bool
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000161IRForTarget::GetFunctionAddress (llvm::Function *fun,
162 uint64_t &fun_addr,
163 lldb_private::ConstString &name,
164 Constant **&value_ptr)
165{
Greg Clayton5160ce52013-03-27 23:08:40 +0000166 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000167
168 fun_addr = LLDB_INVALID_ADDRESS;
169 name.Clear();
170 value_ptr = NULL;
171
172 if (fun->isIntrinsic())
173 {
174 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
175
176 switch (intrinsic_id)
177 {
178 default:
179 if (log)
180 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
181
182 if (m_error_stream)
183 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
184
185 return false;
186 case Intrinsic::memcpy:
187 {
188 static lldb_private::ConstString g_memcpy_str ("memcpy");
189 name = g_memcpy_str;
190 }
191 break;
Sean Callanana6cbf062011-11-16 00:20:50 +0000192 case Intrinsic::memset:
193 {
194 static lldb_private::ConstString g_memset_str ("memset");
195 name = g_memset_str;
196 }
197 break;
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000198 }
199
200 if (log && name)
201 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
202 }
203 else
204 {
205 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
206 }
207
208 // Find the address of the function.
209
210 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000211
212 if (fun_decl)
213 {
Sean Callananc70ed462011-10-25 18:36:40 +0000214 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000215 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000216 lldb_private::ConstString altnernate_name;
Greg Claytonf0705c82011-10-22 03:33:13 +0000217 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
218 if (!found_it)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000219 {
Greg Claytonf0705c82011-10-22 03:33:13 +0000220 // Check for an alternate mangling for "std::basic_string<char>"
221 // that is part of the itanium C++ name mangling scheme
222 const char *name_cstr = name.GetCString();
Jim Ingham28eb5712012-10-12 17:34:26 +0000223 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
Greg Claytonf0705c82011-10-22 03:33:13 +0000224 {
225 std::string alternate_mangling("_ZNKSs");
226 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000227 altnernate_name.SetCString(alternate_mangling.c_str());
228 found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
Greg Claytonf0705c82011-10-22 03:33:13 +0000229 }
230 }
231
232 if (!found_it)
233 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000234 lldb_private::Mangled mangled_name(name);
235 lldb_private::Mangled alt_mangled_name(altnernate_name);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000236 if (log)
Greg Claytonf0705c82011-10-22 03:33:13 +0000237 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000238 if (alt_mangled_name)
239 log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
240 mangled_name.GetName().GetCString(),
241 alt_mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000242 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000243 log->Printf("Function \"%s\" had no address",
244 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000245 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000246
247 if (m_error_stream)
Greg Claytonf0705c82011-10-22 03:33:13 +0000248 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000249 if (alt_mangled_name)
250 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
251 mangled_name.GetName().GetCString(),
252 alt_mangled_name.GetName().GetCString());
Greg Claytonda1eb042013-04-23 21:48:38 +0000253 else if (mangled_name.GetMangledName())
254 m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
255 mangled_name.GetName().GetCString(),
256 mangled_name.GetMangledName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000257 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000258 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
259 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000260 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000261 return false;
262 }
263 }
264 }
265 else
266 {
267 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
268 {
269 if (log)
270 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
271
272 if (m_error_stream)
273 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
274
275 return false;
276 }
277 }
278
279 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000280 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000281
282 return true;
283}
284
285llvm::Constant *
286IRForTarget::BuildFunctionPointer (llvm::Type *type,
287 uint64_t ptr)
288{
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000289 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
Sean Callanan439dcae2013-12-20 19:55:02 +0000290 Constant *fun_addr_int = ConstantInt::get(m_intptr_ty, ptr, false);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000291 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
292}
293
Sean Callananfc8feb82011-10-31 22:11:40 +0000294void
295IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
296 llvm::Value *function_ptr,
297 const char *name)
298{
Sean Callananfc8feb82011-10-31 22:11:40 +0000299 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
300 i != e;
301 ++i)
302 {
303 Value *user = *i;
304
305 if (Instruction *user_inst = dyn_cast<Instruction>(user))
306 {
Daniel Maleaf051dbc2013-06-03 20:45:54 +0000307 MDString* md_name = MDString::get(context, StringRef(name));
308
309 MDNode *metadata = MDNode::get(context, md_name);
310
Sean Callananfc8feb82011-10-31 22:11:40 +0000311 user_inst->setMetadata("lldb.call.realName", metadata);
312 }
313 else
314 {
315 RegisterFunctionMetadata (context, user, name);
316 }
317 }
318}
319
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000320bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000321IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000322{
Greg Clayton5160ce52013-03-27 23:08:40 +0000323 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000324
325 for (llvm::Module::iterator fi = llvm_module.begin();
326 fi != llvm_module.end();
327 ++fi)
328 {
329 Function *fun = fi;
330
331 bool is_decl = fun->isDeclaration();
332
333 if (log)
Sean Callanan7f27d602011-11-19 02:54:21 +0000334 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000335
336 if (!is_decl)
337 continue;
338
339 if (fun->hasNUses(0))
340 continue; // ignore
341
342 uint64_t addr = LLDB_INVALID_ADDRESS;
343 lldb_private::ConstString name;
344 Constant **value_ptr = NULL;
345
346 if (!GetFunctionAddress(fun,
347 addr,
348 name,
349 value_ptr))
350 return false; // GetFunctionAddress reports its own errors
351
352 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
353
Sean Callananfc8feb82011-10-31 22:11:40 +0000354 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
355
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000356 if (value_ptr)
357 *value_ptr = value;
Stefanus Du Toitfc6b7a02013-07-23 21:34:03 +0000358
359 // If we are replacing a function with the nobuiltin attribute, it may
360 // be called with the builtin attribute on call sites. Remove any such
361 // attributes since it's illegal to have a builtin call to something
362 // other than a nobuiltin function.
Jason Molenda12075f72013-10-22 03:11:55 +0000363 if (fun->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
364 llvm::Attribute builtin = llvm::Attribute::get(fun->getContext(), llvm::Attribute::Builtin);
Stefanus Du Toitfc6b7a02013-07-23 21:34:03 +0000365
366 for (auto u = fun->use_begin(), e = fun->use_end(); u != e; ++u) {
367 if (auto call = dyn_cast<CallInst>(*u)) {
368 call->removeAttribute(AttributeSet::FunctionIndex, builtin);
369 }
370 }
371 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000372
373 fun->replaceAllUsesWith(value);
374 }
375
376 return true;
377}
378
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000379
Sean Callanan63697e52011-05-07 01:06:41 +0000380clang::NamedDecl *
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000381IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan63697e52011-05-07 01:06:41 +0000382{
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000383 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan63697e52011-05-07 01:06:41 +0000384
385 if (!named_metadata)
386 return NULL;
387
388 unsigned num_nodes = named_metadata->getNumOperands();
389 unsigned node_index;
390
391 for (node_index = 0;
392 node_index < num_nodes;
393 ++node_index)
394 {
395 MDNode *metadata_node = named_metadata->getOperand(node_index);
396
397 if (!metadata_node)
398 return NULL;
399
400 if (metadata_node->getNumOperands() != 2)
401 continue;
402
403 if (metadata_node->getOperand(0) != global_val)
404 continue;
405
406 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
407
408 if (!constant_int)
409 return NULL;
410
411 uintptr_t ptr = constant_int->getZExtValue();
412
413 return reinterpret_cast<clang::NamedDecl *>(ptr);
414 }
415
416 return NULL;
417}
418
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000419clang::NamedDecl *
420IRForTarget::DeclForGlobal (GlobalValue *global_val)
421{
422 return DeclForGlobal(global_val, m_module);
423}
424
Sean Callanane4ec90e2010-12-16 03:17:46 +0000425bool
Sean Callanan79763a42011-05-23 21:40:23 +0000426IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanand1e5b432010-08-12 01:56:52 +0000427{
Greg Clayton5160ce52013-03-27 23:08:40 +0000428 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand1e5b432010-08-12 01:56:52 +0000429
Sean Callanan9e6ed532010-09-13 21:34:21 +0000430 if (!m_resolve_vars)
431 return true;
432
433 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callananfc55f5d2010-09-21 00:44:12 +0000434
Sean Callanan79763a42011-05-23 21:40:23 +0000435 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananfc55f5d2010-09-21 00:44:12 +0000436
Sean Callanancc427fa2011-07-30 02:42:06 +0000437 std::string result_name_str;
Sean Callananfc55f5d2010-09-21 00:44:12 +0000438 const char *result_name = NULL;
439
440 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
441 vi != ve;
442 ++vi)
443 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000444 result_name_str = vi->first().str();
445 const char *value_name = result_name_str.c_str();
446
447 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000448 strncmp(value_name, "_ZGV", 4))
Sean Callanan92adcac2011-01-13 08:53:35 +0000449 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000450 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000451 m_result_is_pointer = true;
452 break;
453 }
454
Sean Callanancc427fa2011-07-30 02:42:06 +0000455 if (strstr(value_name, "$__lldb_expr_result") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000456 strncmp(value_name, "_ZGV", 4))
Sean Callanan46ae9e52010-09-28 21:13:03 +0000457 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000458 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000459 m_result_is_pointer = false;
Sean Callanan46ae9e52010-09-28 21:13:03 +0000460 break;
461 }
Sean Callananfc55f5d2010-09-21 00:44:12 +0000462 }
463
464 if (!result_name)
465 {
466 if (log)
467 log->PutCString("Couldn't find result variable");
468
Richard Mitton00dec202013-10-11 19:44:23 +0000469 return true;
Sean Callananfc55f5d2010-09-21 00:44:12 +0000470 }
471
Sean Callanan46ae9e52010-09-28 21:13:03 +0000472 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000473 log->Printf("Result name: \"%s\"", result_name);
Sean Callanan46ae9e52010-09-28 21:13:03 +0000474
Sean Callanan79763a42011-05-23 21:40:23 +0000475 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanand1e5b432010-08-12 01:56:52 +0000476
477 if (!result_value)
478 {
479 if (log)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000480 log->PutCString("Result variable had no data");
Sean Callanan92adcac2011-01-13 08:53:35 +0000481
Sean Callanan3989fb92011-01-27 01:07:04 +0000482 if (m_error_stream)
483 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
484
Sean Callananfc55f5d2010-09-21 00:44:12 +0000485 return false;
Sean Callanand1e5b432010-08-12 01:56:52 +0000486 }
Sean Callanan9e6ed532010-09-13 21:34:21 +0000487
Sean Callanand1e5b432010-08-12 01:56:52 +0000488 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000489 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000490
491 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
492
493 if (!result_global)
494 {
495 if (log)
496 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000497
498 if (m_error_stream)
499 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
500
Sean Callanand1e5b432010-08-12 01:56:52 +0000501 return false;
502 }
503
Sean Callanan79763a42011-05-23 21:40:23 +0000504 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan63697e52011-05-07 01:06:41 +0000505 if (!result_decl)
Sean Callanand1e5b432010-08-12 01:56:52 +0000506 {
507 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000508 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanand1e5b432010-08-12 01:56:52 +0000509
Sean Callanan3989fb92011-01-27 01:07:04 +0000510 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000511 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 +0000512
Sean Callanand1e5b432010-08-12 01:56:52 +0000513 return false;
514 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000515
Sean Callanan63697e52011-05-07 01:06:41 +0000516 if (log)
Sean Callanand1e5b432010-08-12 01:56:52 +0000517 {
Sean Callanan63697e52011-05-07 01:06:41 +0000518 std::string decl_desc_str;
519 raw_string_ostream decl_desc_stream(decl_desc_str);
520 result_decl->print(decl_desc_stream);
521 decl_desc_stream.flush();
Sean Callanand1e5b432010-08-12 01:56:52 +0000522
Sean Callanan63697e52011-05-07 01:06:41 +0000523 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000524 }
525
Sean Callanan63697e52011-05-07 01:06:41 +0000526 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
527 if (!result_var)
Sean Callanand1e5b432010-08-12 01:56:52 +0000528 {
529 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000530 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan3989fb92011-01-27 01:07:04 +0000531
532 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000533 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 +0000534
Sean Callanand1e5b432010-08-12 01:56:52 +0000535 return false;
536 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000537
Sean Callanand1e5b432010-08-12 01:56:52 +0000538 // Get the next available result name from m_decl_map and create the persistent
539 // variable for it
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000540
Sean Callanan63697e52011-05-07 01:06:41 +0000541 // If the result is an Lvalue, it is emitted as a pointer; see
542 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan92adcac2011-01-13 08:53:35 +0000543 if (m_result_is_pointer)
544 {
Sean Callanan63697e52011-05-07 01:06:41 +0000545 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanan78e37602011-01-27 04:42:51 +0000546 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
Sean Callanan92adcac2011-01-13 08:53:35 +0000547
Sean Callananfc4f2fb2011-12-14 01:13:04 +0000548 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
549 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
Sean Callanan5780f9d2011-12-08 19:04:34 +0000550
551 if (pointer_pointertype)
552 {
553 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
554
555 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
556 &result_decl->getASTContext());
557 }
558 else if (pointer_objcobjpointertype)
559 {
560 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
561
562 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
563 &result_decl->getASTContext());
564 }
565 else
Sean Callanan92adcac2011-01-13 08:53:35 +0000566 {
567 if (log)
568 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan3989fb92011-01-27 01:07:04 +0000569
570 if (m_error_stream)
571 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
572
Sean Callanan92adcac2011-01-13 08:53:35 +0000573 return false;
574 }
Sean Callanan92adcac2011-01-13 08:53:35 +0000575 }
576 else
577 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000578 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan00f43622011-11-18 03:28:09 +0000579 &result_decl->getASTContext());
580 }
581
Greg Clayton57ee3062013-07-11 22:46:58 +0000582 if (m_result_type.GetBitSize() == 0)
Sean Callanan00f43622011-11-18 03:28:09 +0000583 {
584 lldb_private::StreamString type_desc_stream;
585 m_result_type.DumpTypeDescription(&type_desc_stream);
586
587 if (log)
588 log->Printf("Result type has size 0");
589
590 if (m_error_stream)
Sean Callanan960534c2011-12-21 23:44:05 +0000591 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
Sean Callanan00f43622011-11-18 03:28:09 +0000592 type_desc_stream.GetData());
Sean Callanan960534c2011-12-21 23:44:05 +0000593 return false;
Sean Callanan92adcac2011-01-13 08:53:35 +0000594 }
595
Sean Callanan63697e52011-05-07 01:06:41 +0000596 if (log)
597 {
598 lldb_private::StreamString type_desc_stream;
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000599 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan63697e52011-05-07 01:06:41 +0000600
Sean Callanan00f43622011-11-18 03:28:09 +0000601 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
Sean Callanan63697e52011-05-07 01:06:41 +0000602 }
603
Sean Callanan1582ee62013-04-18 22:06:33 +0000604 m_result_name = lldb_private::ConstString("$RESULT_NAME");
Sean Callanand1e5b432010-08-12 01:56:52 +0000605
606 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +0000607 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
Sean Callanan00f43622011-11-18 03:28:09 +0000608 m_result_name.GetCString(),
Greg Clayton57ee3062013-07-11 22:46:58 +0000609 m_result_type.GetByteSize());
Sean Callanand1e5b432010-08-12 01:56:52 +0000610
611 // Construct a new result global and set up its metadata
612
Sean Callanan79763a42011-05-23 21:40:23 +0000613 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanand1e5b432010-08-12 01:56:52 +0000614 result_global->getType()->getElementType(),
615 false, /* not constant */
616 GlobalValue::ExternalLinkage,
617 NULL, /* no initializer */
Sean Callanan92adcac2011-01-13 08:53:35 +0000618 m_result_name.GetCString ());
Sean Callanand1e5b432010-08-12 01:56:52 +0000619
620 // It's too late in compilation to create a new VarDecl for this, but we don't
621 // need to. We point the metadata at the old VarDecl. This creates an odd
622 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton7b462cc2010-10-15 22:48:33 +0000623 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanand1e5b432010-08-12 01:56:52 +0000624 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
625 // fixed up.
626
Sean Callanan79763a42011-05-23 21:40:23 +0000627 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan63697e52011-05-07 01:06:41 +0000628 reinterpret_cast<uint64_t>(result_decl),
Sean Callanand1e5b432010-08-12 01:56:52 +0000629 false);
630
631 llvm::Value* values[2];
632 values[0] = new_result_global;
633 values[1] = new_constant_int;
634
Sean Callanand12cf8bb2011-05-15 22:34:38 +0000635 ArrayRef<Value*> value_ref(values, 2);
636
Sean Callanan79763a42011-05-23 21:40:23 +0000637 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
638 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanand1e5b432010-08-12 01:56:52 +0000639 named_metadata->addOperand(persistent_global_md);
640
641 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000642 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan1e87fff2010-09-07 22:43:19 +0000643 PrintValue(result_global).c_str(),
Sean Callanand1e5b432010-08-12 01:56:52 +0000644 PrintValue(new_result_global).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000645
646 if (result_global->hasNUses(0))
647 {
648 // We need to synthesize a store for this variable, because otherwise
649 // there's nothing to put into its equivalent persistent variable.
Sean Callanand1e5b432010-08-12 01:56:52 +0000650
Greg Clayton7b462cc2010-10-15 22:48:33 +0000651 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000652 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
653
654 if (!first_entry_instruction)
655 return false;
656
657 if (!result_global->hasInitializer())
658 {
659 if (log)
660 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000661
662 if (m_error_stream)
663 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
664
Sean Callanan1e87fff2010-09-07 22:43:19 +0000665 return false;
666 }
667
668 Constant *initializer = result_global->getInitializer();
Sean Callanane4ec90e2010-12-16 03:17:46 +0000669
Greg Clayton9c139312011-02-05 02:28:58 +0000670 StoreInst *synthesized_store = new StoreInst(initializer,
671 new_result_global,
672 first_entry_instruction);
Sean Callanan1e87fff2010-09-07 22:43:19 +0000673
674 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000675 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000676 }
677 else
678 {
679 result_global->replaceAllUsesWith(new_result_global);
680 }
681
Sean Callanan1582ee62013-04-18 22:06:33 +0000682 if (!m_decl_map->AddPersistentVariable(result_decl,
683 m_result_name,
684 m_result_type,
685 true,
686 m_result_is_pointer))
687 return false;
688
Sean Callanand1e5b432010-08-12 01:56:52 +0000689 result_global->eraseFromParent();
690
691 return true;
692}
693
Johnny Chenee7a3592011-08-09 23:10:20 +0000694#if 0
Greg Clayton5160ce52013-03-27 23:08:40 +0000695static void DebugUsers(Log *log, Value *value, uint8_t depth)
Sean Callananafe16a72010-11-17 23:00:36 +0000696{
697 if (!depth)
698 return;
699
700 depth--;
701
Johnny Chenee7a3592011-08-09 23:10:20 +0000702 if (log)
703 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callananafe16a72010-11-17 23:00:36 +0000704
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000705 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callananafe16a72010-11-17 23:00:36 +0000706 ui != ue;
707 ++ui)
708 {
Johnny Chenee7a3592011-08-09 23:10:20 +0000709 if (log)
710 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
Sean Callananafe16a72010-11-17 23:00:36 +0000711 DebugUsers(log, *ui, depth);
712 }
713
Johnny Chenee7a3592011-08-09 23:10:20 +0000714 if (log)
715 log->Printf(" <End uses>");
Sean Callananafe16a72010-11-17 23:00:36 +0000716}
Johnny Chenee7a3592011-08-09 23:10:20 +0000717#endif
Sean Callananafe16a72010-11-17 23:00:36 +0000718
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000719bool
Sean Callanan79763a42011-05-23 21:40:23 +0000720IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000721 llvm::GlobalVariable *cstr)
Sean Callananafe16a72010-11-17 23:00:36 +0000722{
Greg Clayton5160ce52013-03-27 23:08:40 +0000723 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000724
Sean Callanancc427fa2011-07-30 02:42:06 +0000725 Type *ns_str_ty = ns_str->getType();
Sean Callanan79763a42011-05-23 21:40:23 +0000726
Sean Callanancc427fa2011-07-30 02:42:06 +0000727 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callanancc427fa2011-07-30 02:42:06 +0000728 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
729 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananafe16a72010-11-17 23:00:36 +0000730
731 if (!m_CFStringCreateWithBytes)
732 {
733 lldb::addr_t CFStringCreateWithBytes_addr;
734
735 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
736
737 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
738 {
739 if (log)
740 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
741
Sean Callanan3989fb92011-01-27 01:07:04 +0000742 if (m_error_stream)
743 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
744
Sean Callananafe16a72010-11-17 23:00:36 +0000745 return false;
746 }
747
748 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000749 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
Sean Callananafe16a72010-11-17 23:00:36 +0000750
751 // Build the function type:
752 //
753 // CFStringRef CFStringCreateWithBytes (
754 // CFAllocatorRef alloc,
755 // const UInt8 *bytes,
756 // CFIndex numBytes,
757 // CFStringEncoding encoding,
758 // Boolean isExternalRepresentation
759 // );
760 //
761 // We make the following substitutions:
762 //
763 // CFStringRef -> i8*
764 // CFAllocatorRef -> i8*
765 // UInt8 * -> i8*
766 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
767 // CFStringEncoding -> i32
768 // Boolean -> i8
769
Sean Callanancc427fa2011-07-30 02:42:06 +0000770 Type *arg_type_array[5];
771
772 arg_type_array[0] = i8_ptr_ty;
773 arg_type_array[1] = i8_ptr_ty;
Sean Callanan439dcae2013-12-20 19:55:02 +0000774 arg_type_array[2] = m_intptr_ty;
Sean Callanancc427fa2011-07-30 02:42:06 +0000775 arg_type_array[3] = i32_ty;
776 arg_type_array[4] = i8_ty;
777
778 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
779
Sean Callanan79763a42011-05-23 21:40:23 +0000780 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000781
782 // Build the constant containing the pointer to the function
783 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
Sean Callanan439dcae2013-12-20 19:55:02 +0000784 Constant *CFSCWB_addr_int = ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000785 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
786 }
787
Sean Callanand2b465f2012-02-09 03:22:41 +0000788 ConstantDataSequential *string_array = NULL;
Sean Callanan229ce2d2011-02-10 22:17:53 +0000789
790 if (cstr)
Sean Callanand2b465f2012-02-09 03:22:41 +0000791 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
Sean Callanancc427fa2011-07-30 02:42:06 +0000792
Sean Callananafe16a72010-11-17 23:00:36 +0000793 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan229ce2d2011-02-10 22:17:53 +0000794 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
Sean Callanan439dcae2013-12-20 19:55:02 +0000795 Constant *numBytes_arg = ConstantInt::get(m_intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000796 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
797 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
798
Sean Callanancc427fa2011-07-30 02:42:06 +0000799 Value *argument_array[5];
800
801 argument_array[0] = alloc_arg;
802 argument_array[1] = bytes_arg;
803 argument_array[2] = numBytes_arg;
804 argument_array[3] = encoding_arg;
805 argument_array[4] = isExternal_arg;
806
807 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callananafe16a72010-11-17 23:00:36 +0000808
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000809 FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * {
810 return CallInst::Create(m_CFStringCreateWithBytes,
811 CFSCWB_arguments,
812 "CFStringCreateWithBytes",
813 llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)));
814 });
Sean Callanan7a55a322010-11-18 22:21:58 +0000815
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000816 if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder))
Sean Callananafe16a72010-11-17 23:00:36 +0000817 {
818 if (log)
819 log->PutCString("Couldn't replace the NSString with the result of the call");
820
Sean Callanan3989fb92011-01-27 01:07:04 +0000821 if (m_error_stream)
822 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
823
Sean Callananafe16a72010-11-17 23:00:36 +0000824 return false;
825 }
826
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000827 ns_str->eraseFromParent();
Sean Callananafe16a72010-11-17 23:00:36 +0000828
829 return true;
830}
831
832bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000833IRForTarget::RewriteObjCConstStrings()
Sean Callananafe16a72010-11-17 23:00:36 +0000834{
Greg Clayton5160ce52013-03-27 23:08:40 +0000835 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000836
Sean Callanan79763a42011-05-23 21:40:23 +0000837 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananafe16a72010-11-17 23:00:36 +0000838
Sean Callananafe16a72010-11-17 23:00:36 +0000839 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
840 vi != ve;
841 ++vi)
842 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000843 std::string value_name = vi->first().str();
844 const char *value_name_cstr = value_name.c_str();
845
846 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callananafe16a72010-11-17 23:00:36 +0000847 {
848 Value *nsstring_value = vi->second;
849
850 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
851
852 if (!nsstring_global)
853 {
854 if (log)
855 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000856
857 if (m_error_stream)
858 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
859
Sean Callananafe16a72010-11-17 23:00:36 +0000860 return false;
861 }
862
863 if (!nsstring_global->hasInitializer())
864 {
865 if (log)
866 log->PutCString("NSString variable does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000867
868 if (m_error_stream)
869 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
870
Sean Callananafe16a72010-11-17 23:00:36 +0000871 return false;
872 }
873
874 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
875
876 if (!nsstring_struct)
877 {
878 if (log)
879 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan3989fb92011-01-27 01:07:04 +0000880
881 if (m_error_stream)
882 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
883
Sean Callananafe16a72010-11-17 23:00:36 +0000884 return false;
885 }
886
887 // We expect the following structure:
888 //
889 // struct {
890 // int *isa;
891 // int flags;
892 // char *str;
893 // long length;
894 // };
895
896 if (nsstring_struct->getNumOperands() != 4)
897 {
898 if (log)
899 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 +0000900
901 if (m_error_stream)
902 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
903
Sean Callananafe16a72010-11-17 23:00:36 +0000904 return false;
905 }
906
907 Constant *nsstring_member = nsstring_struct->getOperand(2);
908
909 if (!nsstring_member)
910 {
911 if (log)
912 log->PutCString("NSString initializer's str element was empty");
Sean Callanan3989fb92011-01-27 01:07:04 +0000913
914 if (m_error_stream)
915 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
916
Sean Callananafe16a72010-11-17 23:00:36 +0000917 return false;
918 }
919
920 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
921
922 if (!nsstring_expr)
923 {
924 if (log)
925 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan3989fb92011-01-27 01:07:04 +0000926
927 if (m_error_stream)
928 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
929
Sean Callananafe16a72010-11-17 23:00:36 +0000930 return false;
931 }
932
933 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
934 {
935 if (log)
936 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 +0000937
938 if (m_error_stream)
939 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
940
Sean Callananafe16a72010-11-17 23:00:36 +0000941 return false;
942 }
943
944 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
945
946 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
947
948 if (!cstr_global)
949 {
950 if (log)
951 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000952
953 if (m_error_stream)
954 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
Sean Callanan80eee3a2010-11-20 02:06:01 +0000955
Sean Callananafe16a72010-11-17 23:00:36 +0000956 return false;
957 }
958
959 if (!cstr_global->hasInitializer())
960 {
961 if (log)
962 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000963
964 if (m_error_stream)
965 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
966
Sean Callananafe16a72010-11-17 23:00:36 +0000967 return false;
968 }
Sean Callanan229ce2d2011-02-10 22:17:53 +0000969
970 /*
Sean Callananafe16a72010-11-17 23:00:36 +0000971 if (!cstr_array)
972 {
973 if (log)
974 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan3989fb92011-01-27 01:07:04 +0000975
976 if (m_error_stream)
977 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
978
Sean Callananafe16a72010-11-17 23:00:36 +0000979 return false;
980 }
981
982 if (!cstr_array->isCString())
983 {
984 if (log)
985 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan3989fb92011-01-27 01:07:04 +0000986
987 if (m_error_stream)
988 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
989
Sean Callananafe16a72010-11-17 23:00:36 +0000990 return false;
991 }
Sean Callanan229ce2d2011-02-10 22:17:53 +0000992 */
993
Sean Callanand2b465f2012-02-09 03:22:41 +0000994 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
Sean Callananafe16a72010-11-17 23:00:36 +0000995
996 if (log)
Sean Callanan229ce2d2011-02-10 22:17:53 +0000997 {
998 if (cstr_array)
Sean Callanand2b465f2012-02-09 03:22:41 +0000999 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 +00001000 else
Sean Callanancc427fa2011-07-30 02:42:06 +00001001 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan229ce2d2011-02-10 22:17:53 +00001002 }
1003
1004 if (!cstr_array)
1005 cstr_global = NULL;
Sean Callananafe16a72010-11-17 23:00:36 +00001006
Sean Callanan1f9db3e2013-06-28 21:44:15 +00001007 if (!RewriteObjCConstString(nsstring_global, cstr_global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001008 {
Sean Callananafe16a72010-11-17 23:00:36 +00001009 if (log)
1010 log->PutCString("Error rewriting the constant string");
Sean Callanan3989fb92011-01-27 01:07:04 +00001011
1012 // We don't print an error message here because RewriteObjCConstString has done so for us.
1013
Sean Callananafe16a72010-11-17 23:00:36 +00001014 return false;
1015 }
Sean Callananafe16a72010-11-17 23:00:36 +00001016 }
1017 }
1018
1019 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1020 vi != ve;
1021 ++vi)
1022 {
Sean Callanancc427fa2011-07-30 02:42:06 +00001023 std::string value_name = vi->first().str();
1024 const char *value_name_cstr = value_name.c_str();
1025
1026 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callananafe16a72010-11-17 23:00:36 +00001027 {
1028 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1029
1030 if (!gv)
1031 {
1032 if (log)
1033 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001034
1035 if (m_error_stream)
1036 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1037
Sean Callananafe16a72010-11-17 23:00:36 +00001038 return false;
1039 }
1040
1041 gv->eraseFromParent();
1042
1043 break;
1044 }
1045 }
1046
1047 return true;
1048}
1049
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001050static bool IsObjCSelectorRef (Value *value)
Sean Callanan5300d372010-07-31 01:32:05 +00001051{
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001052 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callanan5300d372010-07-31 01:32:05 +00001053
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001054 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callanan5300d372010-07-31 01:32:05 +00001055 return false;
1056
1057 return true;
1058}
1059
Sean Callanan3989fb92011-01-27 01:07:04 +00001060// This function does not report errors; its callers are responsible.
Sean Callanan5300d372010-07-31 01:32:05 +00001061bool
Sean Callanan79763a42011-05-23 21:40:23 +00001062IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callanan5300d372010-07-31 01:32:05 +00001063{
Greg Clayton5160ce52013-03-27 23:08:40 +00001064 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001065
1066 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1067
1068 if (!load)
1069 return false;
1070
1071 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1072 //
1073 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1074 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1075 //
1076 // where %obj is the object pointer and %tmp is the selector.
1077 //
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001078 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1079 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callanan5300d372010-07-31 01:32:05 +00001080
1081 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1082
1083 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1084
1085 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1086 return false;
1087
1088 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1089
1090 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1091
1092 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1093 return false;
1094
1095 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1096
1097 if (!osr_initializer_base)
1098 return false;
1099
1100 // Find the string's initializer (a ConstantArray) and get the string from it
1101
1102 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1103
1104 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1105 return false;
1106
1107 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1108
Sean Callanand2b465f2012-02-09 03:22:41 +00001109 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
Sean Callanan5300d372010-07-31 01:32:05 +00001110
1111 if (!omvn_initializer_array->isString())
1112 return false;
1113
1114 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1115
1116 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001117 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callanan5300d372010-07-31 01:32:05 +00001118
1119 // Construct a call to sel_registerName
1120
1121 if (!m_sel_registerName)
1122 {
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001123 lldb::addr_t sel_registerName_addr;
Sean Callanan5300d372010-07-31 01:32:05 +00001124
Greg Clayton7b462cc2010-10-15 22:48:33 +00001125 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001126 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callanan5300d372010-07-31 01:32:05 +00001127 return false;
1128
Sean Callananbe3a1b12010-10-26 00:31:56 +00001129 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001130 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
Sean Callananbe3a1b12010-10-26 00:31:56 +00001131
Sean Callanan5300d372010-07-31 01:32:05 +00001132 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1133
1134 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callanan79763a42011-05-23 21:40:23 +00001135 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001136 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanancc427fa2011-07-30 02:42:06 +00001137 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001138
Sean Callanancc427fa2011-07-30 02:42:06 +00001139 Type *type_array[1];
1140
1141 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1142
1143 ArrayRef<Type *> srN_arg_types(type_array, 1);
1144
Sean Callanan5300d372010-07-31 01:32:05 +00001145 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1146
1147 // Build the constant containing the pointer to the function
Sean Callanan5300d372010-07-31 01:32:05 +00001148 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Sean Callanan439dcae2013-12-20 19:55:02 +00001149 Constant *srN_addr_int = ConstantInt::get(m_intptr_ty, sel_registerName_addr, false);
Sean Callanan5300d372010-07-31 01:32:05 +00001150 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1151 }
1152
Sean Callanancc427fa2011-07-30 02:42:06 +00001153 Value *argument_array[1];
1154
Sean Callanan79763a42011-05-23 21:40:23 +00001155 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callanan5300d372010-07-31 01:32:05 +00001156
Sean Callanancc427fa2011-07-30 02:42:06 +00001157 argument_array[0] = omvn_pointer;
Sean Callanan5300d372010-07-31 01:32:05 +00001158
Sean Callanancc427fa2011-07-30 02:42:06 +00001159 ArrayRef<Value *> srN_arguments(argument_array, 1);
1160
Sean Callanan5300d372010-07-31 01:32:05 +00001161 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanancc427fa2011-07-30 02:42:06 +00001162 srN_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +00001163 "sel_registerName",
Sean Callanan5300d372010-07-31 01:32:05 +00001164 selector_load);
1165
1166 // Replace the load with the call in all users
1167
1168 selector_load->replaceAllUsesWith(srN_call);
1169
1170 selector_load->eraseFromParent();
1171
1172 return true;
1173}
1174
1175bool
Sean Callanan79763a42011-05-23 21:40:23 +00001176IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callanan5300d372010-07-31 01:32:05 +00001177{
Greg Clayton5160ce52013-03-27 23:08:40 +00001178 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001179
1180 BasicBlock::iterator ii;
1181
1182 typedef SmallVector <Instruction*, 2> InstrList;
1183 typedef InstrList::iterator InstrIterator;
1184
1185 InstrList selector_loads;
1186
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001187 for (ii = basic_block.begin();
1188 ii != basic_block.end();
Sean Callanan5300d372010-07-31 01:32:05 +00001189 ++ii)
1190 {
1191 Instruction &inst = *ii;
1192
1193 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001194 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callanan5300d372010-07-31 01:32:05 +00001195 selector_loads.push_back(&inst);
1196 }
1197
1198 InstrIterator iter;
1199
1200 for (iter = selector_loads.begin();
1201 iter != selector_loads.end();
1202 ++iter)
1203 {
Sean Callanan79763a42011-05-23 21:40:23 +00001204 if (!RewriteObjCSelector(*iter))
Sean Callanan5300d372010-07-31 01:32:05 +00001205 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001206 if (m_error_stream)
1207 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1208
Enrico Granata20edcdb2011-07-19 18:03:25 +00001209 if (log)
Sean Callanan5300d372010-07-31 01:32:05 +00001210 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan3989fb92011-01-27 01:07:04 +00001211
Sean Callanan5300d372010-07-31 01:32:05 +00001212 return false;
1213 }
1214 }
1215
1216 return true;
1217}
1218
Sean Callanan3989fb92011-01-27 01:07:04 +00001219// This function does not report errors; its callers are responsible.
Sean Callanan2235f322010-08-11 03:57:18 +00001220bool
Sean Callanan79763a42011-05-23 21:40:23 +00001221IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanan2235f322010-08-11 03:57:18 +00001222{
Greg Clayton5160ce52013-03-27 23:08:40 +00001223 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanane1175b72011-01-13 21:23:32 +00001224
Sean Callanan2235f322010-08-11 03:57:18 +00001225 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1226
1227 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1228
1229 if (!alloc_md || !alloc_md->getNumOperands())
1230 return false;
1231
1232 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1233
1234 if (!constant_int)
1235 return false;
1236
1237 // We attempt to register this as a new persistent variable with the DeclMap.
1238
1239 uintptr_t ptr = constant_int->getZExtValue();
1240
Sean Callanand1e5b432010-08-12 01:56:52 +00001241 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanan2235f322010-08-11 03:57:18 +00001242
Sean Callanand1e5b432010-08-12 01:56:52 +00001243 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1244 &decl->getASTContext());
1245
Greg Clayton7b462cc2010-10-15 22:48:33 +00001246 StringRef decl_name (decl->getName());
1247 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan92adcac2011-01-13 08:53:35 +00001248 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanan2235f322010-08-11 03:57:18 +00001249 return false;
1250
Sean Callanan79763a42011-05-23 21:40:23 +00001251 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanane1175b72011-01-13 21:23:32 +00001252 alloc->getType(),
Sean Callanan2235f322010-08-11 03:57:18 +00001253 false, /* not constant */
1254 GlobalValue::ExternalLinkage,
1255 NULL, /* no initializer */
1256 alloc->getName().str().c_str());
1257
1258 // What we're going to do here is make believe this was a regular old external
1259 // variable. That means we need to make the metadata valid.
1260
Sean Callanan585c0ec82012-07-04 01:26:26 +00001261 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
Sean Callanan2235f322010-08-11 03:57:18 +00001262
1263 llvm::Value* values[2];
1264 values[0] = persistent_global;
1265 values[1] = constant_int;
Sean Callanand12cf8bb2011-05-15 22:34:38 +00001266
1267 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanan2235f322010-08-11 03:57:18 +00001268
Sean Callanan79763a42011-05-23 21:40:23 +00001269 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanan2235f322010-08-11 03:57:18 +00001270 named_metadata->addOperand(persistent_global_md);
1271
Sean Callanane1175b72011-01-13 21:23:32 +00001272 // Now, since the variable is a pointer variable, we will drop in a load of that
1273 // pointer variable.
1274
1275 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1276
1277 if (log)
1278 log->Printf("Replacing \"%s\" with \"%s\"",
1279 PrintValue(alloc).c_str(),
1280 PrintValue(persistent_load).c_str());
1281
1282 alloc->replaceAllUsesWith(persistent_load);
Sean Callanan2235f322010-08-11 03:57:18 +00001283 alloc->eraseFromParent();
1284
1285 return true;
1286}
1287
1288bool
Sean Callanan79763a42011-05-23 21:40:23 +00001289IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanan2235f322010-08-11 03:57:18 +00001290{
Sean Callanan9e6ed532010-09-13 21:34:21 +00001291 if (!m_resolve_vars)
1292 return true;
1293
Greg Clayton5160ce52013-03-27 23:08:40 +00001294 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2235f322010-08-11 03:57:18 +00001295
1296 BasicBlock::iterator ii;
1297
1298 typedef SmallVector <Instruction*, 2> InstrList;
1299 typedef InstrList::iterator InstrIterator;
1300
1301 InstrList pvar_allocs;
1302
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001303 for (ii = basic_block.begin();
1304 ii != basic_block.end();
Sean Callanan2235f322010-08-11 03:57:18 +00001305 ++ii)
1306 {
1307 Instruction &inst = *ii;
1308
1309 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callananf694a552011-01-21 22:30:25 +00001310 {
1311 llvm::StringRef alloc_name = alloc->getName();
1312
1313 if (alloc_name.startswith("$") &&
1314 !alloc_name.startswith("$__lldb"))
1315 {
1316 if (alloc_name.find_first_of("0123456789") == 1)
1317 {
1318 if (log)
1319 log->Printf("Rejecting a numeric persistent variable.");
1320
Sean Callanan3989fb92011-01-27 01:07:04 +00001321 if (m_error_stream)
1322 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1323
Sean Callananf694a552011-01-21 22:30:25 +00001324 return false;
1325 }
1326
Sean Callanan2235f322010-08-11 03:57:18 +00001327 pvar_allocs.push_back(alloc);
Sean Callananf694a552011-01-21 22:30:25 +00001328 }
1329 }
Sean Callanan2235f322010-08-11 03:57:18 +00001330 }
1331
1332 InstrIterator iter;
1333
1334 for (iter = pvar_allocs.begin();
1335 iter != pvar_allocs.end();
1336 ++iter)
1337 {
Sean Callanan79763a42011-05-23 21:40:23 +00001338 if (!RewritePersistentAlloc(*iter))
Sean Callanan2235f322010-08-11 03:57:18 +00001339 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001340 if (m_error_stream)
1341 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1342
Enrico Granata20edcdb2011-07-19 18:03:25 +00001343 if (log)
Sean Callanan2235f322010-08-11 03:57:18 +00001344 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001345
Sean Callanan2235f322010-08-11 03:57:18 +00001346 return false;
1347 }
1348 }
1349
1350 return true;
1351}
1352
Sean Callananc70ed462011-10-25 18:36:40 +00001353bool
1354IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1355{
1356 if (!initializer)
1357 return true;
1358
Greg Clayton5160ce52013-03-27 23:08:40 +00001359 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc70ed462011-10-25 18:36:40 +00001360
1361 if (log && log->GetVerbose())
1362 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1363
1364 Type *initializer_type = initializer->getType();
1365
1366 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1367 {
1368 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1369 return true;
1370 }
Sean Callanand2b465f2012-02-09 03:22:41 +00001371 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
Sean Callananc70ed462011-10-25 18:36:40 +00001372 {
1373 if (array_initializer->isString())
1374 {
1375 std::string array_initializer_string = array_initializer->getAsString();
1376 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1377 }
1378 else
1379 {
1380 ArrayType *array_initializer_type = array_initializer->getType();
1381 Type *array_element_type = array_initializer_type->getElementType();
1382
1383 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1384
Andy Gibbsa297a972013-06-19 19:04:53 +00001385 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i)
Sean Callananc70ed462011-10-25 18:36:40 +00001386 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001387 Value *operand_value = array_initializer->getOperand(i);
1388 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1389
1390 if (!operand_constant)
1391 return false;
1392
1393 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
Sean Callananc70ed462011-10-25 18:36:40 +00001394 return false;
1395 }
1396 }
1397 return true;
1398 }
1399 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1400 {
1401 StructType *struct_initializer_type = struct_initializer->getType();
1402 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1403
Andy Gibbsa297a972013-06-19 19:04:53 +00001404 for (unsigned i = 0;
Sean Callananc70ed462011-10-25 18:36:40 +00001405 i < struct_initializer->getNumOperands();
1406 ++i)
1407 {
1408 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1409 return false;
1410 }
1411 return true;
1412 }
Sean Callanan76ee3e72013-04-24 19:50:12 +00001413 else if (isa<ConstantAggregateZero>(initializer))
1414 {
1415 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1416 return true;
1417 }
Sean Callananc70ed462011-10-25 18:36:40 +00001418 return false;
1419}
1420
1421bool
1422IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1423{
1424 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1425 return false;
1426
Sean Callananfe5d1392011-11-15 19:13:54 +00001427 if (global_variable == m_reloc_placeholder)
1428 return true;
1429
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001430 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callananc70ed462011-10-25 18:36:40 +00001431
1432 llvm::Type *variable_type = global_variable->getType();
1433
1434 Constant *initializer = global_variable->getInitializer();
1435
1436 llvm::Type *initializer_type = initializer->getType();
1437
1438 size_t size = m_target_data->getTypeAllocSize(initializer_type);
Sean Callanane3333d62012-06-08 22:20:41 +00001439 size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1440
1441 const size_t mask = (align - 1);
1442 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001443 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00001444 offset = aligned_offset;
Sean Callananc70ed462011-10-25 18:36:40 +00001445
1446 lldb_private::DataBufferHeap data(size, '\0');
1447
1448 if (initializer)
1449 if (!MaterializeInitializer(data.GetBytes(), initializer))
1450 return false;
1451
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001452 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
Sean Callananc70ed462011-10-25 18:36:40 +00001453
1454 Constant *new_pointer = BuildRelocation(variable_type, offset);
1455
1456 global_variable->replaceAllUsesWith(new_pointer);
1457
1458 global_variable->eraseFromParent();
1459
1460 return true;
1461}
1462
Sean Callanan3989fb92011-01-27 01:07:04 +00001463// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001464bool
Sean Callanan79763a42011-05-23 21:40:23 +00001465IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001466{
Greg Clayton5160ce52013-03-27 23:08:40 +00001467 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001468
1469 if (log)
Sean Callanan88339f02010-12-06 22:16:55 +00001470 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callananaf8e96c2011-08-01 17:41:38 +00001471
Greg Clayton7b462cc2010-10-15 22:48:33 +00001472 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callanan4cf04d22010-08-03 00:23:29 +00001473 {
Sean Callanan5666b672010-08-04 01:02:13 +00001474 switch (constant_expr->getOpcode())
Sean Callanan4cf04d22010-08-03 00:23:29 +00001475 {
Sean Callanan5666b672010-08-04 01:02:13 +00001476 default:
1477 break;
1478 case Instruction::GetElementPtr:
1479 case Instruction::BitCast:
Sean Callanan4cf04d22010-08-03 00:23:29 +00001480 Value *s = constant_expr->getOperand(0);
Sean Callanan79763a42011-05-23 21:40:23 +00001481 if (!MaybeHandleVariable(s))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001482 return false;
Sean Callanan4cf04d22010-08-03 00:23:29 +00001483 }
1484 }
Sean Callanand6e04ae2010-12-03 19:51:05 +00001485 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001486 {
Sean Callananc70ed462011-10-25 18:36:40 +00001487 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1488 return MaterializeInternalVariable(global_variable);
1489
Sean Callanan79763a42011-05-23 21:40:23 +00001490 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan2ab712f22010-07-03 01:35:46 +00001491
Sean Callanan5300d372010-07-31 01:32:05 +00001492 if (!named_decl)
1493 {
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001494 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001495 return true;
1496
Sean Callanan14f0b0e2010-12-06 00:56:39 +00001497 if (!global_variable->hasExternalLinkage())
1498 return true;
1499
Sean Callanan5300d372010-07-31 01:32:05 +00001500 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001501 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001502
Sean Callanan5300d372010-07-31 01:32:05 +00001503 return false;
1504 }
1505
Greg Clayton7b462cc2010-10-15 22:48:33 +00001506 std::string name (named_decl->getName().str());
Sean Callananea22d422010-07-16 00:09:46 +00001507
Greg Clayton57ee3062013-07-11 22:46:58 +00001508 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1509 if (value_decl == NULL)
Sean Callananea22d422010-07-16 00:09:46 +00001510 return false;
Greg Clayton57ee3062013-07-11 22:46:58 +00001511
1512 lldb_private::ClangASTType clang_type(&value_decl->getASTContext(), value_decl->getType());
Sean Callanan038df5032010-09-30 21:18:25 +00001513
Sean Callanan77eaf442011-07-08 00:39:14 +00001514 const Type *value_type = NULL;
Greg Clayton57ee3062013-07-11 22:46:58 +00001515
Sean Callanane1175b72011-01-13 21:23:32 +00001516 if (name[0] == '$')
Sean Callanan92adcac2011-01-13 08:53:35 +00001517 {
1518 // The $__lldb_expr_result name indicates the the return value has allocated as
1519 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1520 // accesses to this static variable need to be redirected to the result of dereferencing
1521 // a pointer that is passed in as one of the arguments.
1522 //
1523 // Consequently, when reporting the size of the type, we report a pointer type pointing
1524 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanane1175b72011-01-13 21:23:32 +00001525 //
1526 // We also do this for any user-declared persistent variables.
Greg Clayton57ee3062013-07-11 22:46:58 +00001527 clang_type = clang_type.GetPointerType();
Sean Callanan92adcac2011-01-13 08:53:35 +00001528 value_type = PointerType::get(global_variable->getType(), 0);
1529 }
1530 else
1531 {
Sean Callanan92adcac2011-01-13 08:53:35 +00001532 value_type = global_variable->getType();
1533 }
Greg Clayton57ee3062013-07-11 22:46:58 +00001534
1535 const uint64_t value_size = clang_type.GetByteSize();
1536 off_t value_alignment = (clang_type.GetTypeBitAlign() + 7ull) / 8ull;
Sean Callanan17827832010-12-13 22:46:15 +00001537
Sean Callanan038df5032010-09-30 21:18:25 +00001538 if (log)
Greg Clayton57ee3062013-07-11 22:46:58 +00001539 {
Greg Claytonfaac1112013-03-14 18:31:44 +00001540 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
Sean Callanan038df5032010-09-30 21:18:25 +00001541 name.c_str(),
Greg Clayton57ee3062013-07-11 22:46:58 +00001542 clang_type.GetQualType().getAsString().c_str(),
1543 PrintType(value_type).c_str(),
Sean Callanan038df5032010-09-30 21:18:25 +00001544 value_size,
1545 value_alignment);
Greg Clayton57ee3062013-07-11 22:46:58 +00001546 }
Sean Callanan17827832010-12-13 22:46:15 +00001547
Sean Callanan549c9f72010-07-13 21:41:46 +00001548
Sean Callanan64dfc9a2010-08-23 23:09:38 +00001549 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton7b462cc2010-10-15 22:48:33 +00001550 lldb_private::ConstString (name.c_str()),
1551 llvm_value_ptr,
Sean Callanan4edba2d2010-07-27 02:07:53 +00001552 value_size,
1553 value_alignment))
Sean Callananaf8e96c2011-08-01 17:41:38 +00001554 {
1555 if (!global_variable->hasExternalLinkage())
1556 return true;
Sean Callanan0ff3bf92013-04-11 17:57:16 +00001557 else if (HandleSymbol (global_variable))
1558 return true;
Sean Callananaf8e96c2011-08-01 17:41:38 +00001559 else
1560 return false;
1561 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001562 }
Sean Callanan4a5fcbb2010-12-03 03:02:31 +00001563 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001564 {
1565 if (log)
1566 log->Printf("Function pointers aren't handled right now");
1567
1568 return false;
1569 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001570
1571 return true;
1572}
1573
Sean Callanan3989fb92011-01-27 01:07:04 +00001574// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001575bool
Sean Callanan79763a42011-05-23 21:40:23 +00001576IRForTarget::HandleSymbol (Value *symbol)
Sean Callanand9ca42a2011-05-08 02:21:26 +00001577{
Greg Clayton5160ce52013-03-27 23:08:40 +00001578 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc3a16002011-01-17 23:42:46 +00001579
1580 lldb_private::ConstString name(symbol->getName().str().c_str());
1581
Sean Callanan947ccc72011-12-01 02:04:16 +00001582 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
Sean Callananc3a16002011-01-17 23:42:46 +00001583
Greg Clayton084db102011-06-23 04:25:29 +00001584 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc3a16002011-01-17 23:42:46 +00001585 {
1586 if (log)
1587 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1588
1589 return false;
1590 }
1591
1592 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001593 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
Sean Callananc3a16002011-01-17 23:42:46 +00001594
Sean Callanancc427fa2011-07-30 02:42:06 +00001595 Type *symbol_type = symbol->getType();
Sean Callananc3a16002011-01-17 23:42:46 +00001596
Sean Callanan439dcae2013-12-20 19:55:02 +00001597 Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false);
Sean Callananc3a16002011-01-17 23:42:46 +00001598
1599 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1600
1601 if (log)
1602 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1603
1604 symbol->replaceAllUsesWith(symbol_addr_ptr);
1605
1606 return true;
1607}
1608
1609bool
Sean Callanan79763a42011-05-23 21:40:23 +00001610IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanan85a0a832010-10-05 22:26:43 +00001611{
Greg Clayton5160ce52013-03-27 23:08:40 +00001612 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001613
1614 if (log)
1615 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanan85a0a832010-10-05 22:26:43 +00001616
Sean Callananafe16a72010-11-17 23:00:36 +00001617 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanan85a0a832010-10-05 22:26:43 +00001618 op_index < num_ops;
1619 ++op_index)
Sean Callanan79763a42011-05-23 21:40:23 +00001620 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan3989fb92011-01-27 01:07:04 +00001621 {
1622 if (m_error_stream)
1623 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1624
Sean Callanan85a0a832010-10-05 22:26:43 +00001625 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001626 }
1627
Sean Callanan85a0a832010-10-05 22:26:43 +00001628 return true;
1629}
1630
1631bool
Sean Callananfc89c142011-11-01 23:38:03 +00001632IRForTarget::HandleObjCClass(Value *classlist_reference)
1633{
Greg Clayton5160ce52013-03-27 23:08:40 +00001634 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananfc89c142011-11-01 23:38:03 +00001635
1636 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1637
1638 if (!global_variable)
1639 return false;
1640
1641 Constant *initializer = global_variable->getInitializer();
1642
1643 if (!initializer)
1644 return false;
1645
1646 if (!initializer->hasName())
1647 return false;
1648
1649 StringRef name(initializer->getName());
1650 lldb_private::ConstString name_cstr(name.str().c_str());
Greg Clayton1075aca2011-12-03 20:02:42 +00001651 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
Sean Callananfc89c142011-11-01 23:38:03 +00001652
1653 if (log)
1654 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1655
1656 if (class_ptr == LLDB_INVALID_ADDRESS)
1657 return false;
1658
1659 if (global_variable->use_begin() == global_variable->use_end())
1660 return false;
1661
Sean Callanan719a4d52013-03-23 01:01:16 +00001662 SmallVector<LoadInst *, 2> load_instructions;
1663
Sean Callananfc89c142011-11-01 23:38:03 +00001664 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1665 i != e;
1666 ++i)
1667 {
Sean Callanan719a4d52013-03-23 01:01:16 +00001668 if (LoadInst *load_instruction = dyn_cast<LoadInst>(*i))
1669 load_instructions.push_back(load_instruction);
Sean Callananfc89c142011-11-01 23:38:03 +00001670 }
1671
Sean Callanan719a4d52013-03-23 01:01:16 +00001672 if (load_instructions.empty())
Sean Callananfc89c142011-11-01 23:38:03 +00001673 return false;
1674
Sean Callanan439dcae2013-12-20 19:55:02 +00001675 Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr);
Sean Callananfc89c142011-11-01 23:38:03 +00001676
Sean Callanan719a4d52013-03-23 01:01:16 +00001677 for (LoadInst *load_instruction : load_instructions)
1678 {
1679 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
Sean Callananfc89c142011-11-01 23:38:03 +00001680
Sean Callanan719a4d52013-03-23 01:01:16 +00001681 load_instruction->replaceAllUsesWith(class_bitcast);
1682
1683 load_instruction->eraseFromParent();
1684 }
Sean Callananfc89c142011-11-01 23:38:03 +00001685
1686 return true;
1687}
1688
1689bool
Sean Callanan6e6d4a62012-07-21 02:02:15 +00001690IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1691{
1692 BasicBlock::iterator ii;
1693
1694 std::vector<CallInst *> calls_to_remove;
1695
1696 for (ii = basic_block.begin();
1697 ii != basic_block.end();
1698 ++ii)
1699 {
1700 Instruction &inst = *ii;
1701
1702 CallInst *call = dyn_cast<CallInst>(&inst);
1703
1704 // MaybeHandleCallArguments handles error reporting; we are silent here
1705 if (!call)
1706 continue;
1707
1708 bool remove = false;
1709
1710 llvm::Function *func = call->getCalledFunction();
1711
1712 if (func && func->getName() == "__cxa_atexit")
1713 remove = true;
1714
1715 llvm::Value *val = call->getCalledValue();
1716
1717 if (val && val->getName() == "__cxa_atexit")
1718 remove = true;
1719
1720 if (remove)
1721 calls_to_remove.push_back(call);
1722 }
1723
1724 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1725 ci != ce;
1726 ++ci)
1727 {
1728 (*ci)->eraseFromParent();
1729 }
1730
1731 return true;
1732}
1733
1734bool
Sean Callanan79763a42011-05-23 21:40:23 +00001735IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan549c9f72010-07-13 21:41:46 +00001736{
Sean Callanan2ab712f22010-07-03 01:35:46 +00001737 /////////////////////////////////////////////////////////////////////////
1738 // Prepare the current basic block for execution in the remote process
1739 //
1740
Sean Callanan7ea35012010-07-27 21:39:39 +00001741 BasicBlock::iterator ii;
Sean Callanan549c9f72010-07-13 21:41:46 +00001742
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001743 for (ii = basic_block.begin();
1744 ii != basic_block.end();
Sean Callanan549c9f72010-07-13 21:41:46 +00001745 ++ii)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001746 {
Sean Callanan549c9f72010-07-13 21:41:46 +00001747 Instruction &inst = *ii;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001748
Sean Callanana4e55172010-11-08 00:31:32 +00001749 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callanan4edba2d2010-07-27 02:07:53 +00001750
Sean Callanan3989fb92011-01-27 01:07:04 +00001751 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callanan79763a42011-05-23 21:40:23 +00001752 if (call && !MaybeHandleCallArguments(call))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001753 return false;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001754 }
1755
1756 return true;
1757}
1758
Sean Callanana4e55172010-11-08 00:31:32 +00001759bool
Sean Callanan79763a42011-05-23 21:40:23 +00001760IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanana4e55172010-11-08 00:31:32 +00001761{
Greg Clayton5160ce52013-03-27 23:08:40 +00001762 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7a55a322010-11-18 22:21:58 +00001763
Sean Callanan79763a42011-05-23 21:40:23 +00001764 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanana4e55172010-11-08 00:31:32 +00001765 global != end;
1766 ++global)
1767 {
Sean Callanan694e2442011-12-22 21:24:49 +00001768 if (!global)
1769 {
1770 if (m_error_stream)
1771 m_error_stream->Printf("Internal error [IRForTarget]: global variable is NULL");
1772
1773 return false;
1774 }
1775
1776 std::string global_name = (*global).getName().str();
1777
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001778 if (log)
1779 log->Printf("Examining %s, DeclForGlobalValue returns %p",
Sean Callanan694e2442011-12-22 21:24:49 +00001780 global_name.c_str(),
Sean Callanan79763a42011-05-23 21:40:23 +00001781 DeclForGlobal(global));
Sean Callananfc89c142011-11-01 23:38:03 +00001782
1783 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc3a16002011-01-17 23:42:46 +00001784 {
Sean Callanan79763a42011-05-23 21:40:23 +00001785 if (!HandleSymbol(global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001786 {
1787 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001788 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 +00001789
Sean Callananc3a16002011-01-17 23:42:46 +00001790 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001791 }
Sean Callananc3a16002011-01-17 23:42:46 +00001792 }
Sean Callananfc89c142011-11-01 23:38:03 +00001793 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1794 {
1795 if (!HandleObjCClass(global))
1796 {
1797 if (m_error_stream)
1798 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1799
1800 return false;
1801 }
1802 }
Sean Callanan2ad66912013-04-24 21:25:20 +00001803 else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos)
1804 {
1805 if (!HandleObjCClass(global))
1806 {
1807 if (m_error_stream)
1808 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1809
1810 return false;
1811 }
1812 }
Sean Callanan79763a42011-05-23 21:40:23 +00001813 else if (DeclForGlobal(global))
Sean Callananc3a16002011-01-17 23:42:46 +00001814 {
Sean Callanan79763a42011-05-23 21:40:23 +00001815 if (!MaybeHandleVariable (global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001816 {
1817 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001818 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 +00001819
Sean Callananc3a16002011-01-17 23:42:46 +00001820 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001821 }
Sean Callananc3a16002011-01-17 23:42:46 +00001822 }
Sean Callanana4e55172010-11-08 00:31:32 +00001823 }
1824
1825 return true;
1826}
1827
Sean Callanan79763a42011-05-23 21:40:23 +00001828bool
1829IRForTarget::ReplaceStrings ()
1830{
Greg Clayton5160ce52013-03-27 23:08:40 +00001831 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001832
Sean Callanan79763a42011-05-23 21:40:23 +00001833 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1834
1835 OffsetsTy offsets;
1836
1837 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1838 gi != ge;
1839 ++gi)
1840 {
1841 GlobalVariable *gv = gi;
1842
1843 if (!gv->hasInitializer())
1844 continue;
1845
1846 Constant *gc = gv->getInitializer();
1847
Sean Callanan5207a342011-08-10 21:05:52 +00001848 std::string str;
Sean Callanan79763a42011-05-23 21:40:23 +00001849
Sean Callanan5207a342011-08-10 21:05:52 +00001850 if (gc->isNullValue())
1851 {
1852 Type *gc_type = gc->getType();
1853
1854 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1855
1856 if (!gc_array_type)
1857 continue;
1858
1859 Type *gc_element_type = gc_array_type->getElementType();
1860
1861 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1862
1863 if (gc_integer_type->getBitWidth() != 8)
1864 continue;
1865
1866 str = "";
1867 }
1868 else
1869 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001870 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
Sean Callanan5207a342011-08-10 21:05:52 +00001871
1872 if (!gc_array)
1873 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001874
Sean Callanan5207a342011-08-10 21:05:52 +00001875 if (!gc_array->isCString())
1876 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001877
Sean Callanan5207a342011-08-10 21:05:52 +00001878 if (log)
1879 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00001880
Sean Callanan5207a342011-08-10 21:05:52 +00001881 str = gc_array->getAsString();
1882 }
1883
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001884 offsets[gv] = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00001885
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001886 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
Sean Callanan79763a42011-05-23 21:40:23 +00001887 }
1888
Sean Callanancc427fa2011-07-30 02:42:06 +00001889 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00001890
1891 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1892 oi != oe;
1893 ++oi)
1894 {
1895 GlobalVariable *gv = oi->first;
1896 size_t offset = oi->second;
1897
1898 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1899
1900 if (log)
1901 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1902
1903 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1904 ui != ue;
1905 ++ui)
1906 {
1907 if (log)
1908 log->Printf("Found use %s", PrintValue(*ui).c_str());
1909
1910 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1911 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1912
1913 if (const_expr)
1914 {
1915 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1916 {
1917 if (log)
1918 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1919
1920 return false;
1921 }
1922
Sean Callanan5207a342011-08-10 21:05:52 +00001923 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1924 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1925
1926 const_expr->replaceAllUsesWith(new_gep);
Sean Callanan79763a42011-05-23 21:40:23 +00001927 }
1928 else if (store_inst)
1929 {
1930 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1931
1932 store_inst->setOperand(0, bit_cast);
1933 }
1934 else
1935 {
1936 if (log)
1937 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1938
1939 return false;
1940 }
1941 }
1942
1943 gv->eraseFromParent();
1944 }
1945
1946 return true;
1947}
1948
1949bool
1950IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1951{
Greg Clayton5160ce52013-03-27 23:08:40 +00001952 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001953
1954 typedef SmallVector <Value*, 2> ConstantList;
1955 typedef SmallVector <llvm::Instruction*, 2> UserList;
1956 typedef ConstantList::iterator ConstantIterator;
1957 typedef UserList::iterator UserIterator;
1958
1959 ConstantList static_constants;
1960 UserList static_users;
1961
1962 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1963 ii != ie;
1964 ++ii)
1965 {
1966 llvm::Instruction &inst = *ii;
1967
1968 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1969 oi != oe;
1970 ++oi)
1971 {
1972 Value *operand_val = oi->get();
1973
1974 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1975
Sean Callanan822944c2012-04-26 20:51:20 +00001976 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
Sean Callanan79763a42011-05-23 21:40:23 +00001977 {
1978 static_constants.push_back(operand_val);
1979 static_users.push_back(ii);
1980 }
1981 }
1982 }
1983
1984 ConstantIterator constant_iter;
1985 UserIterator user_iter;
Greg Clayton9b72eb72011-05-24 23:06:02 +00001986
Sean Callanan79763a42011-05-23 21:40:23 +00001987 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1988 constant_iter != static_constants.end();
1989 ++constant_iter, ++user_iter)
1990 {
1991 Value *operand_val = *constant_iter;
1992 llvm::Instruction *inst = *user_iter;
1993
1994 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1995
1996 if (operand_constant_fp)
1997 {
Sean Callanan1582ee62013-04-18 22:06:33 +00001998 Type *operand_type = operand_constant_fp->getType();
1999
Sean Callanan79763a42011-05-23 21:40:23 +00002000 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2001 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2002
2003 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2004 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2005
2006 if (log)
2007 {
2008 std::string s;
2009 raw_string_ostream ss(s);
2010 for (size_t index = 0;
2011 index < operand_data_size;
2012 ++index)
2013 {
2014 ss << (uint32_t)operand_raw_data[index];
2015 ss << " ";
2016 }
2017 ss.flush();
2018
Greg Clayton6fea17e2014-03-03 19:15:20 +00002019 log->Printf("Found ConstantFP with size %" PRIu64 " and raw data %s", (uint64_t)operand_data_size, s.c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00002020 }
2021
2022 lldb_private::DataBufferHeap data(operand_data_size, 0);
2023
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002024 if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
Sean Callanan79763a42011-05-23 21:40:23 +00002025 {
2026 uint8_t *data_bytes = data.GetBytes();
2027
2028 for (size_t index = 0;
2029 index < operand_data_size;
2030 ++index)
2031 {
2032 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2033 }
2034 }
2035 else
2036 {
2037 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2038 }
2039
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002040 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00002041
Sean Callanane3333d62012-06-08 22:20:41 +00002042 size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2043
2044 const size_t mask = (align - 1);
2045 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002046 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00002047 offset = aligned_offset;
2048
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002049 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
Sean Callanan79763a42011-05-23 21:40:23 +00002050
Sean Callanancc427fa2011-07-30 02:42:06 +00002051 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callanan79763a42011-05-23 21:40:23 +00002052
Sean Callanan1582ee62013-04-18 22:06:33 +00002053 Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
Sean Callanan79763a42011-05-23 21:40:23 +00002054
2055 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2056
2057 operand_constant_fp->replaceAllUsesWith(fp_load);
2058 }
2059 }
2060
2061 return true;
2062}
2063
Sean Callanan7ea35012010-07-27 21:39:39 +00002064static bool isGuardVariableRef(Value *V)
Sean Callananddb46ef2010-07-24 01:37:44 +00002065{
Sean Callanan77eaf442011-07-08 00:39:14 +00002066 Constant *Old = NULL;
Sean Callananddb46ef2010-07-24 01:37:44 +00002067
Sean Callananafe16a72010-11-17 23:00:36 +00002068 if (!(Old = dyn_cast<Constant>(V)))
Sean Callananddb46ef2010-07-24 01:37:44 +00002069 return false;
2070
Sean Callanan77eaf442011-07-08 00:39:14 +00002071 ConstantExpr *CE = NULL;
Sean Callanane2ef6e32010-09-23 03:01:22 +00002072
2073 if ((CE = dyn_cast<ConstantExpr>(V)))
2074 {
2075 if (CE->getOpcode() != Instruction::BitCast)
2076 return false;
2077
Sean Callananafe16a72010-11-17 23:00:36 +00002078 Old = CE->getOperand(0);
Sean Callanane2ef6e32010-09-23 03:01:22 +00002079 }
2080
Sean Callananafe16a72010-11-17 23:00:36 +00002081 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callananddb46ef2010-07-24 01:37:44 +00002082
2083 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2084 return false;
2085
2086 return true;
2087}
2088
Sean Callanan79763a42011-05-23 21:40:23 +00002089void
2090IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callananddb46ef2010-07-24 01:37:44 +00002091{
Sean Callanan79763a42011-05-23 21:40:23 +00002092 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callananddb46ef2010-07-24 01:37:44 +00002093
2094 Value::use_iterator ui;
2095
2096 for (ui = guard_load->use_begin();
2097 ui != guard_load->use_end();
2098 ++ui)
Sean Callananb27a62f2010-07-27 01:17:28 +00002099 {
Greg Claytone6371122010-07-30 20:30:44 +00002100 if (isa<Constant>(*ui))
Sean Callananb27a62f2010-07-27 01:17:28 +00002101 {
2102 // do nothing for the moment
2103 }
2104 else
2105 {
2106 ui->replaceUsesOfWith(guard_load, zero);
2107 }
2108 }
Sean Callananddb46ef2010-07-24 01:37:44 +00002109
2110 guard_load->eraseFromParent();
2111}
2112
2113static void ExciseGuardStore(Instruction* guard_store)
2114{
2115 guard_store->eraseFromParent();
2116}
2117
2118bool
Sean Callanan79763a42011-05-23 21:40:23 +00002119IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callananddb46ef2010-07-24 01:37:44 +00002120{
2121 ///////////////////////////////////////////////////////
2122 // Eliminate any reference to guard variables found.
2123 //
2124
Sean Callanan7ea35012010-07-27 21:39:39 +00002125 BasicBlock::iterator ii;
Sean Callananddb46ef2010-07-24 01:37:44 +00002126
Sean Callanan7ea35012010-07-27 21:39:39 +00002127 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callananddb46ef2010-07-24 01:37:44 +00002128 typedef InstrList::iterator InstrIterator;
2129
2130 InstrList guard_loads;
2131 InstrList guard_stores;
2132
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002133 for (ii = basic_block.begin();
2134 ii != basic_block.end();
Sean Callananddb46ef2010-07-24 01:37:44 +00002135 ++ii)
2136 {
2137 Instruction &inst = *ii;
2138
2139 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2140 if (isGuardVariableRef(load->getPointerOperand()))
2141 guard_loads.push_back(&inst);
2142
2143 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2144 if (isGuardVariableRef(store->getPointerOperand()))
2145 guard_stores.push_back(&inst);
2146 }
2147
2148 InstrIterator iter;
2149
2150 for (iter = guard_loads.begin();
2151 iter != guard_loads.end();
2152 ++iter)
Sean Callanan79763a42011-05-23 21:40:23 +00002153 TurnGuardLoadIntoZero(*iter);
Sean Callananddb46ef2010-07-24 01:37:44 +00002154
2155 for (iter = guard_stores.begin();
2156 iter != guard_stores.end();
2157 ++iter)
2158 ExciseGuardStore(*iter);
2159
2160 return true;
2161}
2162
Sean Callanan3989fb92011-01-27 01:07:04 +00002163// This function does not report errors; its callers are responsible.
Sean Callananafe16a72010-11-17 23:00:36 +00002164bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002165IRForTarget::UnfoldConstant(Constant *old_constant,
2166 FunctionValueCache &value_maker,
2167 FunctionValueCache &entry_instruction_finder)
Sean Callanan7618f4e2010-07-14 23:40:29 +00002168{
Greg Clayton5160ce52013-03-27 23:08:40 +00002169 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002170
2171 Value::use_iterator ui;
2172
Sean Callanan2235f322010-08-11 03:57:18 +00002173 SmallVector<User*, 16> users;
2174
2175 // We do this because the use list might change, invalidating our iterator.
2176 // Much better to keep a work list ourselves.
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002177 for (ui = old_constant->use_begin();
2178 ui != old_constant->use_end();
Sean Callanan7618f4e2010-07-14 23:40:29 +00002179 ++ui)
Sean Callanan2235f322010-08-11 03:57:18 +00002180 users.push_back(*ui);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002181
Johnny Chen44805302011-07-19 19:48:13 +00002182 for (size_t i = 0;
Sean Callanan2235f322010-08-11 03:57:18 +00002183 i < users.size();
2184 ++i)
2185 {
2186 User *user = users[i];
2187
Sean Callanan7618f4e2010-07-14 23:40:29 +00002188 if (Constant *constant = dyn_cast<Constant>(user))
2189 {
2190 // synthesize a new non-constant equivalent of the constant
2191
2192 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2193 {
2194 switch (constant_expr->getOpcode())
2195 {
2196 default:
2197 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002198 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002199 return false;
2200 case Instruction::BitCast:
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002201 {
2202 FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2203 // UnaryExpr
2204 // OperandList[0] is value
2205
2206 if (constant_expr->getOperand(0) != old_constant)
2207 return constant_expr;
2208
2209 return new BitCastInst(value_maker.GetValue(function),
2210 constant_expr->getType(),
2211 "",
2212 llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2213 });
Sean Callanan7618f4e2010-07-14 23:40:29 +00002214
Sean Callanan0e016fe2013-07-15 23:31:47 +00002215 if (!UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder))
2216 return false;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002217 }
2218 break;
2219 case Instruction::GetElementPtr:
2220 {
2221 // GetElementPtrConstantExpr
2222 // OperandList[0] is base
2223 // OperandList[1]... are indices
2224
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002225 FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2226 Value *ptr = constant_expr->getOperand(0);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002227
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002228 if (ptr == old_constant)
2229 ptr = value_maker.GetValue(function);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002230
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002231 std::vector<Value*> index_vector;
2232
2233 unsigned operand_index;
2234 unsigned num_operands = constant_expr->getNumOperands();
2235
2236 for (operand_index = 1;
2237 operand_index < num_operands;
2238 ++operand_index)
2239 {
2240 Value *operand = constant_expr->getOperand(operand_index);
2241
2242 if (operand == old_constant)
2243 operand = value_maker.GetValue(function);
2244
2245 index_vector.push_back(operand);
2246 }
2247
2248 ArrayRef <Value*> indices(index_vector);
2249
2250 return GetElementPtrInst::Create(ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2251 });
Sean Callanan7618f4e2010-07-14 23:40:29 +00002252
Sean Callanan0e016fe2013-07-15 23:31:47 +00002253 if (!UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder))
2254 return false;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002255 }
2256 break;
2257 }
2258 }
2259 else
2260 {
2261 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002262 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002263 return false;
2264 }
2265 }
2266 else
2267 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002268 if (Instruction *inst = llvm::dyn_cast<Instruction>(user))
2269 {
2270 inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent()));
2271 }
2272 else
2273 {
2274 if (log)
2275 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str());
2276 return false;
2277 }
Sean Callanan7618f4e2010-07-14 23:40:29 +00002278 }
2279 }
2280
Sean Callanan0e016fe2013-07-15 23:31:47 +00002281 if (!isa<GlobalValue>(old_constant))
2282 {
2283 old_constant->destroyConstant();
2284 }
2285
Sean Callanan7618f4e2010-07-14 23:40:29 +00002286 return true;
2287}
2288
Sean Callanan549c9f72010-07-13 21:41:46 +00002289bool
Sean Callanan79763a42011-05-23 21:40:23 +00002290IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan549c9f72010-07-13 21:41:46 +00002291{
Sean Callanan9e6ed532010-09-13 21:34:21 +00002292 if (!m_resolve_vars)
2293 return true;
2294
Greg Clayton5160ce52013-03-27 23:08:40 +00002295 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan549c9f72010-07-13 21:41:46 +00002296
2297 m_decl_map->DoStructLayout();
2298
2299 if (log)
2300 log->Printf("Element arrangement:");
2301
2302 uint32_t num_elements;
2303 uint32_t element_index;
2304
2305 size_t size;
2306 off_t alignment;
2307
2308 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2309 return false;
2310
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002311 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan549c9f72010-07-13 21:41:46 +00002312
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002313 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002314 {
2315 if (m_error_stream)
2316 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2317
Sean Callanan549c9f72010-07-13 21:41:46 +00002318 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002319 }
2320
Sean Callanan7ea35012010-07-27 21:39:39 +00002321 Argument *argument = iter;
Sean Callanan549c9f72010-07-13 21:41:46 +00002322
Sean Callananfc55f5d2010-09-21 00:44:12 +00002323 if (argument->getName().equals("this"))
2324 {
2325 ++iter;
2326
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002327 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002328 {
2329 if (m_error_stream)
2330 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2331
Sean Callananfc55f5d2010-09-21 00:44:12 +00002332 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002333 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002334
2335 argument = iter;
2336 }
Sean Callanan17827832010-12-13 22:46:15 +00002337 else if (argument->getName().equals("self"))
2338 {
2339 ++iter;
2340
2341 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002342 {
2343 if (m_error_stream)
2344 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2345
Sean Callanan17827832010-12-13 22:46:15 +00002346 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002347 }
Sean Callanan17827832010-12-13 22:46:15 +00002348
2349 if (!iter->getName().equals("_cmd"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002350 {
2351 if (m_error_stream)
2352 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2353
Sean Callanan17827832010-12-13 22:46:15 +00002354 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002355 }
Sean Callanan17827832010-12-13 22:46:15 +00002356
2357 ++iter;
2358
2359 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002360 {
2361 if (m_error_stream)
2362 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2363
Sean Callanan17827832010-12-13 22:46:15 +00002364 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002365 }
Sean Callanan17827832010-12-13 22:46:15 +00002366
2367 argument = iter;
2368 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002369
Greg Clayton7b462cc2010-10-15 22:48:33 +00002370 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002371 {
2372 if (m_error_stream)
2373 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2374
Sean Callanan549c9f72010-07-13 21:41:46 +00002375 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002376 }
2377
Sean Callanan549c9f72010-07-13 21:41:46 +00002378 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002379 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan549c9f72010-07-13 21:41:46 +00002380
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002381 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +00002382 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan549c9f72010-07-13 21:41:46 +00002383
Sean Callananafe16a72010-11-17 23:00:36 +00002384 if (!FirstEntryInstruction)
Sean Callanan3989fb92011-01-27 01:07:04 +00002385 {
2386 if (m_error_stream)
2387 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2388
Sean Callanan549c9f72010-07-13 21:41:46 +00002389 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002390 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002391
Sean Callanan79763a42011-05-23 21:40:23 +00002392 LLVMContext &context(m_module->getContext());
Sean Callanancc427fa2011-07-30 02:42:06 +00002393 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan549c9f72010-07-13 21:41:46 +00002394
2395 if (!offset_type)
Sean Callanan3989fb92011-01-27 01:07:04 +00002396 {
2397 if (m_error_stream)
2398 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2399
Sean Callanan549c9f72010-07-13 21:41:46 +00002400 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002401 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002402
2403 for (element_index = 0; element_index < num_elements; ++element_index)
2404 {
Sean Callanan77eaf442011-07-08 00:39:14 +00002405 const clang::NamedDecl *decl = NULL;
2406 Value *value = NULL;
Sean Callanan549c9f72010-07-13 21:41:46 +00002407 off_t offset;
Greg Clayton7b462cc2010-10-15 22:48:33 +00002408 lldb_private::ConstString name;
Sean Callanan549c9f72010-07-13 21:41:46 +00002409
Sean Callanan823bb4c2010-08-30 22:17:16 +00002410 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan3989fb92011-01-27 01:07:04 +00002411 {
2412 if (m_error_stream)
2413 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2414
Sean Callanan549c9f72010-07-13 21:41:46 +00002415 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002416 }
2417
Sean Callanan549c9f72010-07-13 21:41:46 +00002418 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002419 log->Printf(" \"%s\" (\"%s\") placed at %" PRId64,
Greg Clayton7b462cc2010-10-15 22:48:33 +00002420 name.GetCString(),
Sean Callananc70ed462011-10-25 18:36:40 +00002421 decl->getNameAsString().c_str(),
Sean Callanan549c9f72010-07-13 21:41:46 +00002422 offset);
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002423
Sean Callananc70ed462011-10-25 18:36:40 +00002424 if (value)
Sean Callanan92adcac2011-01-13 08:53:35 +00002425 {
Sean Callananc70ed462011-10-25 18:36:40 +00002426 if (log)
2427 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan92adcac2011-01-13 08:53:35 +00002428
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002429 FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * {
2430 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2431 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2432 // entry in order to produce the static variable that the AST thinks it is accessing.
Sean Callananc70ed462011-10-25 18:36:40 +00002433
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002434 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function));
Sean Callananc70ed462011-10-25 18:36:40 +00002435
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002436 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
2437 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument,
2438 offset_int,
2439 "",
2440 entry_instruction);
2441
2442 if (name == m_result_name && !m_result_is_pointer)
2443 {
2444 BitCastInst *bit_cast = new BitCastInst(get_element_ptr,
2445 value->getType()->getPointerTo(),
2446 "",
2447 entry_instruction);
2448
2449 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
2450
2451 return load;
2452 }
2453 else
2454 {
2455 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction);
2456
2457 return bit_cast;
2458 }
2459 });
Sean Callananc70ed462011-10-25 18:36:40 +00002460
2461 if (Constant *constant = dyn_cast<Constant>(value))
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002462 {
2463 UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder);
2464 }
2465 else if (Instruction *instruction = dyn_cast<Instruction>(value))
2466 {
2467 value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent()));
2468 }
Sean Callananc70ed462011-10-25 18:36:40 +00002469 else
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002470 {
2471 if (log)
2472 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str());
2473 return false;
2474 }
Sean Callananc70ed462011-10-25 18:36:40 +00002475
2476 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2477 var->eraseFromParent();
2478 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002479 }
2480
2481 if (log)
Greg Clayton6fea17e2014-03-03 19:15:20 +00002482 log->Printf("Total structure [align %" PRId64 ", size %" PRIu64 "]", (int64_t)alignment, (uint64_t)size);
Sean Callanan549c9f72010-07-13 21:41:46 +00002483
2484 return true;
2485}
2486
Sean Callanan79763a42011-05-23 21:40:23 +00002487llvm::Constant *
Greg Clayton5160ce52013-03-27 23:08:40 +00002488IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
Sean Callanan79763a42011-05-23 21:40:23 +00002489{
Sean Callanan439dcae2013-12-20 19:55:02 +00002490 llvm::Constant *offset_int = ConstantInt::get(m_intptr_ty, offset);
Sean Callanancc427fa2011-07-30 02:42:06 +00002491
2492 llvm::Constant *offset_array[1];
2493
2494 offset_array[0] = offset_int;
2495
2496 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2497
2498 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callanan79763a42011-05-23 21:40:23 +00002499 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2500
2501 return reloc_getbitcast;
2502}
2503
2504bool
2505IRForTarget::CompleteDataAllocation ()
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002506{
Greg Clayton5160ce52013-03-27 23:08:40 +00002507 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002508
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002509 if (!m_data_allocator.GetStream().GetSize())
Sean Callanan79763a42011-05-23 21:40:23 +00002510 return true;
2511
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002512 lldb::addr_t allocation = m_data_allocator.Allocate();
Sean Callanan79763a42011-05-23 21:40:23 +00002513
2514 if (log)
2515 {
2516 if (allocation)
2517 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2518 else
2519 log->Printf("Failed to allocate static data");
2520 }
2521
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002522 if (!allocation || allocation == LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +00002523 return false;
2524
Sean Callanan439dcae2013-12-20 19:55:02 +00002525 Constant *relocated_addr = ConstantInt::get(m_intptr_ty, (uint64_t)allocation);
Sean Callanan79763a42011-05-23 21:40:23 +00002526 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2527
2528 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2529
2530 m_reloc_placeholder->eraseFromParent();
2531
2532 return true;
2533}
2534
Sean Callanan2ab712f22010-07-03 01:35:46 +00002535bool
Sean Callanan3d654b32012-09-24 22:25:51 +00002536IRForTarget::StripAllGVs (Module &llvm_module)
2537{
Greg Clayton5160ce52013-03-27 23:08:40 +00002538 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3d654b32012-09-24 22:25:51 +00002539 std::vector<GlobalVariable *> global_vars;
2540 std::set<GlobalVariable *>erased_vars;
2541
2542 bool erased = true;
2543
2544 while (erased)
2545 {
2546 erased = false;
2547
2548 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2549 gi != ge;
2550 ++gi)
2551 {
2552 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2553
2554 global_var->removeDeadConstantUsers();
2555
2556 if (global_var->use_empty())
2557 {
2558 if (log)
2559 log->Printf("Did remove %s",
2560 PrintValue(global_var).c_str());
2561 global_var->eraseFromParent();
2562 erased = true;
2563 break;
2564 }
2565 }
2566 }
2567
2568 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2569 gi != ge;
2570 ++gi)
2571 {
2572 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2573
2574 GlobalValue::use_iterator ui = global_var->use_begin();
2575
Jim Inghamd77557d2012-11-26 19:54:04 +00002576 if (log)
2577 log->Printf("Couldn't remove %s because of %s",
2578 PrintValue(global_var).c_str(),
2579 PrintValue(*ui).c_str());
Sean Callanan3d654b32012-09-24 22:25:51 +00002580 }
2581
2582 return true;
2583}
2584
2585bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002586IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002587{
Greg Clayton5160ce52013-03-27 23:08:40 +00002588 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002589
Sean Callanan79763a42011-05-23 21:40:23 +00002590 m_module = &llvm_module;
Micah Villmow8468dbe2012-10-08 16:28:57 +00002591 m_target_data.reset(new DataLayout(m_module));
Sean Callanan439dcae2013-12-20 19:55:02 +00002592 m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(), m_target_data->getPointerSizeInBits());
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002593
Sean Callananc70ed462011-10-25 18:36:40 +00002594 if (log)
2595 {
2596 std::string s;
2597 raw_string_ostream oss(s);
2598
2599 m_module->print(oss, NULL);
2600
2601 oss.flush();
2602
2603 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2604 }
2605
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002606 Function* main_function = m_module->getFunction(StringRef(m_func_name.c_str()));
2607
2608 if (!main_function)
2609 {
2610 if (log)
2611 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
2612
2613 if (m_error_stream)
2614 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
2615
2616 return false;
2617 }
2618
2619 if (!FixFunctionLinkage (*main_function))
2620 {
2621 if (log)
2622 log->Printf("Couldn't fix the linkage for the function");
2623
2624 return false;
2625 }
2626
Sean Callanan439dcae2013-12-20 19:55:02 +00002627 llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00002628
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002629 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
Sean Callanan439dcae2013-12-20 19:55:02 +00002630 int8_ty,
Sean Callanan3d654b32012-09-24 22:25:51 +00002631 false /* IsConstant */,
Sean Callanan79763a42011-05-23 21:40:23 +00002632 GlobalVariable::InternalLinkage,
Sean Callanan439dcae2013-12-20 19:55:02 +00002633 Constant::getNullValue(int8_ty),
Sean Callanan79763a42011-05-23 21:40:23 +00002634 "reloc_placeholder",
2635 NULL /* InsertBefore */,
Sean Callanan3d654b32012-09-24 22:25:51 +00002636 GlobalVariable::NotThreadLocal /* ThreadLocal */,
Sean Callanan79763a42011-05-23 21:40:23 +00002637 0 /* AddressSpace */);
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002638
Sean Callanand1e5b432010-08-12 01:56:52 +00002639 ////////////////////////////////////////////////////////////
Greg Clayton7b462cc2010-10-15 22:48:33 +00002640 // Replace $__lldb_expr_result with a persistent variable
Sean Callanand1e5b432010-08-12 01:56:52 +00002641 //
2642
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002643 if (!CreateResultVariable(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002644 {
2645 if (log)
2646 log->Printf("CreateResultVariable() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002647
2648 // CreateResultVariable() reports its own errors, so we don't do so here
2649
Sean Callanand1e5b432010-08-12 01:56:52 +00002650 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002651 }
Sean Callanan6e6d4a62012-07-21 02:02:15 +00002652
Sean Callananea685ae2011-11-01 17:33:54 +00002653 if (log && log->GetVerbose())
Sean Callanan79763a42011-05-23 21:40:23 +00002654 {
2655 std::string s;
2656 raw_string_ostream oss(s);
2657
2658 m_module->print(oss, NULL);
2659
2660 oss.flush();
2661
2662 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2663 }
2664
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002665 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2666 fi != fe;
2667 ++fi)
2668 {
2669 llvm::Function *function = fi;
2670
2671 if (function->begin() == function->end())
2672 continue;
2673
2674 Function::iterator bbi;
2675
2676 for (bbi = function->begin();
2677 bbi != function->end();
2678 ++bbi)
2679 {
2680 if (!RemoveGuards(*bbi))
2681 {
2682 if (log)
2683 log->Printf("RemoveGuards() failed");
2684
2685 // RemoveGuards() reports its own errors, so we don't do so here
2686
2687 return false;
2688 }
2689
2690 if (!RewritePersistentAllocs(*bbi))
2691 {
2692 if (log)
2693 log->Printf("RewritePersistentAllocs() failed");
2694
2695 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2696
2697 return false;
2698 }
2699
2700 if (!RemoveCXAAtExit(*bbi))
2701 {
2702 if (log)
2703 log->Printf("RemoveCXAAtExit() failed");
2704
2705 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2706
2707 return false;
2708 }
2709 }
2710 }
2711
Sean Callananafe16a72010-11-17 23:00:36 +00002712 ///////////////////////////////////////////////////////////////////////////////
2713 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2714 //
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002715
2716 if (!RewriteObjCConstStrings())
Sean Callanan17827832010-12-13 22:46:15 +00002717 {
2718 if (log)
2719 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002720
2721 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2722
Sean Callananafe16a72010-11-17 23:00:36 +00002723 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002724 }
Sean Callananafe16a72010-11-17 23:00:36 +00002725
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002726 ///////////////////////////////
2727 // Resolve function pointers
2728 //
2729
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002730 if (!ResolveFunctionPointers(llvm_module))
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002731 {
2732 if (log)
2733 log->Printf("ResolveFunctionPointers() failed");
2734
2735 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2736
2737 return false;
2738 }
2739
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002740 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2741 fi != fe;
2742 ++fi)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002743 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002744 llvm::Function *function = fi;
2745
2746 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2747 bbi != bbe;
2748 ++bbi)
Sean Callanan17827832010-12-13 22:46:15 +00002749 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002750 if (!RewriteObjCSelectors(*bbi))
2751 {
2752 if (log)
2753 log->Printf("RewriteObjCSelectors() failed");
2754
2755 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2756
2757 return false;
2758 }
Sean Callanan17827832010-12-13 22:46:15 +00002759 }
Sean Callananbad134f2012-07-27 19:25:24 +00002760 }
Sean Callanan2235f322010-08-11 03:57:18 +00002761
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002762 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2763 fi != fe;
2764 ++fi)
Sean Callananbad134f2012-07-27 19:25:24 +00002765 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002766 llvm::Function *function = fi;
Sean Callanan79763a42011-05-23 21:40:23 +00002767
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002768 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2769 bbi != bbe;
2770 ++bbi)
Sean Callanan79763a42011-05-23 21:40:23 +00002771 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002772 if (!ResolveCalls(*bbi))
2773 {
2774 if (log)
2775 log->Printf("ResolveCalls() failed");
2776
2777 // ResolveCalls() reports its own errors, so we don't do so here
2778
2779 return false;
2780 }
Sean Callanan79763a42011-05-23 21:40:23 +00002781
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002782 if (!ReplaceStaticLiterals(*bbi))
2783 {
2784 if (log)
2785 log->Printf("ReplaceStaticLiterals() failed");
2786
2787 return false;
2788 }
Sean Callanan79763a42011-05-23 21:40:23 +00002789 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002790 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002791
2792 ////////////////////////////////////////////////////////////////////////
2793 // Run function-level passes that only make sense on the main function
Sean Callanan038df5032010-09-30 21:18:25 +00002794 //
2795
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002796 if (!ResolveExternals(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002797 {
2798 if (log)
2799 log->Printf("ResolveExternals() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002800
2801 // ResolveExternals() reports its own errors, so we don't do so here
2802
Sean Callanana4e55172010-11-08 00:31:32 +00002803 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002804 }
Sean Callanana4e55172010-11-08 00:31:32 +00002805
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002806 if (!ReplaceVariables(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002807 {
2808 if (log)
2809 log->Printf("ReplaceVariables() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002810
2811 // ReplaceVariables() reports its own errors, so we don't do so here
2812
Sean Callanan038df5032010-09-30 21:18:25 +00002813 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002814 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002815
Sean Callanan79763a42011-05-23 21:40:23 +00002816 if (!ReplaceStrings())
2817 {
2818 if (log)
2819 log->Printf("ReplaceStrings() failed");
2820
2821 return false;
2822 }
2823
2824 if (!CompleteDataAllocation())
2825 {
2826 if (log)
2827 log->Printf("CompleteDataAllocation() failed");
2828
2829 return false;
2830 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002831
Sean Callanan3d654b32012-09-24 22:25:51 +00002832 if (!StripAllGVs(llvm_module))
2833 {
2834 if (log)
2835 log->Printf("StripAllGVs() failed");
2836 }
2837
Sean Callananea685ae2011-11-01 17:33:54 +00002838 if (log && log->GetVerbose())
Sean Callanan549c9f72010-07-13 21:41:46 +00002839 {
Sean Callanancc54bd32010-07-28 01:00:59 +00002840 std::string s;
2841 raw_string_ostream oss(s);
Sean Callanan549c9f72010-07-13 21:41:46 +00002842
Sean Callanan79763a42011-05-23 21:40:23 +00002843 m_module->print(oss, NULL);
Sean Callanancc54bd32010-07-28 01:00:59 +00002844
2845 oss.flush();
2846
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002847 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan2ab712f22010-07-03 01:35:46 +00002848 }
2849
2850 return true;
2851}
2852
2853void
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002854IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002855{
2856}
2857
2858PassManagerType
2859IRForTarget::getPotentialPassManagerType() const
2860{
2861 return PMT_ModulePassManager;
2862}