blob: 1d9faa690dc003477c2e23f91c5787653833caac [file] [log] [blame]
Sean Callanan3bfdaa22011-09-15 02:13:07 +00001//===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===//
Sean Callanan2ab712f22010-07-03 01:35:46 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Expression/IRForTarget.h"
11
12#include "llvm/Support/raw_ostream.h"
Chandler Carruth1e157582013-01-02 12:20:07 +000013#include "llvm/IR/Constants.h"
14#include "llvm/IR/DataLayout.h"
15#include "llvm/IR/InstrTypes.h"
16#include "llvm/IR/Instructions.h"
17#include "llvm/IR/Intrinsics.h"
18#include "llvm/IR/Module.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000019#include "llvm/PassManager.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000020#include "llvm/Transforms/IPO.h"
Chandler Carruth1e157582013-01-02 12:20:07 +000021#include "llvm/IR/ValueSymbolTable.h"
Sean Callanan549c9f72010-07-13 21:41:46 +000022
23#include "clang/AST/ASTContext.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000024
25#include "lldb/Core/dwarf.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000026#include "lldb/Core/ConstString.h"
27#include "lldb/Core/DataBufferHeap.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000028#include "lldb/Core/Log.h"
29#include "lldb/Core/Scalar.h"
30#include "lldb/Core/StreamString.h"
31#include "lldb/Expression/ClangExpressionDeclMap.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000032#include "lldb/Expression/IRExecutionUnit.h"
Sean Callanan3bfdaa22011-09-15 02:13:07 +000033#include "lldb/Expression/IRInterpreter.h"
Sean Callanan79763a42011-05-23 21:40:23 +000034#include "lldb/Host/Endian.h"
Sean Callanan63697e52011-05-07 01:06:41 +000035#include "lldb/Symbol/ClangASTContext.h"
Greg Clayton57ee3062013-07-11 22:46:58 +000036#include "lldb/Symbol/ClangASTType.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000037
38#include <map>
39
40using namespace llvm;
41
Sean Callananeaacbc92010-08-18 18:50:51 +000042static char ID;
43
Sean Callanan8dfb68e2013-03-19 00:10:07 +000044IRForTarget::StaticDataAllocator::StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit) :
45 m_execution_unit(execution_unit),
Sean Callanan1582ee62013-04-18 22:06:33 +000046 m_stream_string(lldb_private::Stream::eBinary, execution_unit.GetAddressByteSize(), execution_unit.GetByteOrder()),
Sean Callanan8dfb68e2013-03-19 00:10:07 +000047 m_allocation(LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +000048{
49}
50
Sean Callanan1f9db3e2013-06-28 21:44:15 +000051IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) :
52 m_maker(maker),
53 m_values()
54{
55}
56
57IRForTarget::FunctionValueCache::~FunctionValueCache()
58{
59}
60
61llvm::Value *IRForTarget::FunctionValueCache::GetValue(llvm::Function *function)
62{
63 if (!m_values.count(function))
64 {
65 llvm::Value *ret = m_maker(function);
66 m_values[function] = ret;
67 return ret;
68 }
69 return m_values[function];
70}
71
Sean Callanan8dfb68e2013-03-19 00:10:07 +000072lldb::addr_t IRForTarget::StaticDataAllocator::Allocate()
Sean Callanan79763a42011-05-23 21:40:23 +000073{
Sean Callanan8dfb68e2013-03-19 00:10:07 +000074 lldb_private::Error err;
75
76 if (m_allocation != LLDB_INVALID_ADDRESS)
77 {
78 m_execution_unit.FreeNow(m_allocation);
79 m_allocation = LLDB_INVALID_ADDRESS;
80 }
81
82 m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
83
84 return m_allocation;
Sean Callanan79763a42011-05-23 21:40:23 +000085}
86
Sean Callanan1f9db3e2013-06-28 21:44:15 +000087static llvm::Value *FindEntryInstruction (llvm::Function *function)
88{
89 if (function->empty())
90 return NULL;
91
92 return function->getEntryBlock().getFirstNonPHIOrDbg();
93}
94
Greg Clayton1b95a6f2010-11-19 01:05:25 +000095IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
96 bool resolve_vars,
Sean Callanan8dfb68e2013-03-19 00:10:07 +000097 lldb_private::IRExecutionUnit &execution_unit,
Sean Callanan3989fb92011-01-27 01:07:04 +000098 lldb_private::Stream *error_stream,
Greg Clayton1b95a6f2010-11-19 01:05:25 +000099 const char *func_name) :
Sean Callanane2ef6e32010-09-23 03:01:22 +0000100 ModulePass(ID),
Stephen Wilson71c21d12011-04-11 19:41:40 +0000101 m_resolve_vars(resolve_vars),
102 m_func_name(func_name),
Sean Callanan79763a42011-05-23 21:40:23 +0000103 m_module(NULL),
Johnny Chen44805302011-07-19 19:48:13 +0000104 m_decl_map(decl_map),
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000105 m_data_allocator(execution_unit),
Sean Callananafe16a72010-11-17 23:00:36 +0000106 m_CFStringCreateWithBytes(NULL),
Sean Callanan1a8d4092010-08-27 01:01:44 +0000107 m_sel_registerName(NULL),
Stephen Wilson71c21d12011-04-11 19:41:40 +0000108 m_error_stream(error_stream),
Sean Callanan63697e52011-05-07 01:06:41 +0000109 m_result_store(NULL),
110 m_result_is_pointer(false),
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000111 m_reloc_placeholder(NULL),
112 m_entry_instruction_finder (FindEntryInstruction)
Sean Callanan2ab712f22010-07-03 01:35:46 +0000113{
114}
115
Sean Callanan038df5032010-09-30 21:18:25 +0000116/* Handy utility functions used at several places in the code */
Sean Callanan2235f322010-08-11 03:57:18 +0000117
118static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000119PrintValue(const Value *value, bool truncate = false)
Sean Callanan2235f322010-08-11 03:57:18 +0000120{
121 std::string s;
Jim Ingham28eb5712012-10-12 17:34:26 +0000122 if (value)
123 {
124 raw_string_ostream rso(s);
125 value->print(rso);
126 rso.flush();
127 if (truncate)
128 s.resize(s.length() - 1);
129 }
Sean Callanan2235f322010-08-11 03:57:18 +0000130 return s;
131}
132
Sean Callanan038df5032010-09-30 21:18:25 +0000133static std::string
Greg Clayton57ee3062013-07-11 22:46:58 +0000134PrintType(const llvm::Type *type, bool truncate = false)
Sean Callanan038df5032010-09-30 21:18:25 +0000135{
136 std::string s;
137 raw_string_ostream rso(s);
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000138 type->print(rso);
Sean Callanan038df5032010-09-30 21:18:25 +0000139 rso.flush();
140 if (truncate)
141 s.resize(s.length() - 1);
142 return s;
143}
144
Sean Callanan2ab712f22010-07-03 01:35:46 +0000145IRForTarget::~IRForTarget()
146{
147}
148
Sean Callanan79763a42011-05-23 21:40:23 +0000149bool
150IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
151{
Sean Callanan79763a42011-05-23 21:40:23 +0000152 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
153
Sean Callanan7f27d602011-11-19 02:54:21 +0000154 std::string name = llvm_function.getName().str();
Sean Callanan79763a42011-05-23 21:40:23 +0000155
156 return true;
157}
158
Sean Callanand1e5b432010-08-12 01:56:52 +0000159bool
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000160IRForTarget::GetFunctionAddress (llvm::Function *fun,
161 uint64_t &fun_addr,
162 lldb_private::ConstString &name,
163 Constant **&value_ptr)
164{
Greg Clayton5160ce52013-03-27 23:08:40 +0000165 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000166
167 fun_addr = LLDB_INVALID_ADDRESS;
168 name.Clear();
169 value_ptr = NULL;
170
171 if (fun->isIntrinsic())
172 {
173 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
174
175 switch (intrinsic_id)
176 {
177 default:
178 if (log)
179 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
180
181 if (m_error_stream)
182 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
183
184 return false;
185 case Intrinsic::memcpy:
186 {
187 static lldb_private::ConstString g_memcpy_str ("memcpy");
188 name = g_memcpy_str;
189 }
190 break;
Sean Callanana6cbf062011-11-16 00:20:50 +0000191 case Intrinsic::memset:
192 {
193 static lldb_private::ConstString g_memset_str ("memset");
194 name = g_memset_str;
195 }
196 break;
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000197 }
198
199 if (log && name)
200 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
201 }
202 else
203 {
204 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
205 }
206
207 // Find the address of the function.
208
209 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000210
211 if (fun_decl)
212 {
Sean Callananc70ed462011-10-25 18:36:40 +0000213 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000214 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000215 lldb_private::ConstString altnernate_name;
Greg Claytonf0705c82011-10-22 03:33:13 +0000216 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
217 if (!found_it)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000218 {
Greg Claytonf0705c82011-10-22 03:33:13 +0000219 // Check for an alternate mangling for "std::basic_string<char>"
220 // that is part of the itanium C++ name mangling scheme
221 const char *name_cstr = name.GetCString();
Jim Ingham28eb5712012-10-12 17:34:26 +0000222 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
Greg Claytonf0705c82011-10-22 03:33:13 +0000223 {
224 std::string alternate_mangling("_ZNKSs");
225 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000226 altnernate_name.SetCString(alternate_mangling.c_str());
227 found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
Greg Claytonf0705c82011-10-22 03:33:13 +0000228 }
229 }
230
231 if (!found_it)
232 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000233 lldb_private::Mangled mangled_name(name);
234 lldb_private::Mangled alt_mangled_name(altnernate_name);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000235 if (log)
Greg Claytonf0705c82011-10-22 03:33:13 +0000236 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000237 if (alt_mangled_name)
238 log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
239 mangled_name.GetName().GetCString(),
240 alt_mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000241 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000242 log->Printf("Function \"%s\" had no address",
243 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000244 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000245
246 if (m_error_stream)
Greg Claytonf0705c82011-10-22 03:33:13 +0000247 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000248 if (alt_mangled_name)
249 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
250 mangled_name.GetName().GetCString(),
251 alt_mangled_name.GetName().GetCString());
Greg Claytonda1eb042013-04-23 21:48:38 +0000252 else if (mangled_name.GetMangledName())
253 m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
254 mangled_name.GetName().GetCString(),
255 mangled_name.GetMangledName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000256 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000257 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
258 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000259 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000260 return false;
261 }
262 }
263 }
264 else
265 {
266 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
267 {
268 if (log)
269 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
270
271 if (m_error_stream)
272 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
273
274 return false;
275 }
276 }
277
278 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000279 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000280
281 return true;
282}
283
284llvm::Constant *
285IRForTarget::BuildFunctionPointer (llvm::Type *type,
286 uint64_t ptr)
287{
Sean Callanan090e1192013-12-20 04:07:43 +0000288 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(), 64);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000289 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
290 Constant *fun_addr_int = ConstantInt::get(intptr_ty, ptr, false);
291 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
292}
293
Sean Callananfc8feb82011-10-31 22:11:40 +0000294void
295IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
296 llvm::Value *function_ptr,
297 const char *name)
298{
Sean Callananfc8feb82011-10-31 22:11:40 +0000299 for (Value::use_iterator i = function_ptr->use_begin(), e = function_ptr->use_end();
300 i != e;
301 ++i)
302 {
303 Value *user = *i;
304
305 if (Instruction *user_inst = dyn_cast<Instruction>(user))
306 {
Daniel Maleaf051dbc2013-06-03 20:45:54 +0000307 MDString* md_name = MDString::get(context, StringRef(name));
308
309 MDNode *metadata = MDNode::get(context, md_name);
310
Sean Callananfc8feb82011-10-31 22:11:40 +0000311 user_inst->setMetadata("lldb.call.realName", metadata);
312 }
313 else
314 {
315 RegisterFunctionMetadata (context, user, name);
316 }
317 }
318}
319
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000320bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000321IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000322{
Greg Clayton5160ce52013-03-27 23:08:40 +0000323 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000324
325 for (llvm::Module::iterator fi = llvm_module.begin();
326 fi != llvm_module.end();
327 ++fi)
328 {
329 Function *fun = fi;
330
331 bool is_decl = fun->isDeclaration();
332
333 if (log)
Sean Callanan7f27d602011-11-19 02:54:21 +0000334 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000335
336 if (!is_decl)
337 continue;
338
339 if (fun->hasNUses(0))
340 continue; // ignore
341
342 uint64_t addr = LLDB_INVALID_ADDRESS;
343 lldb_private::ConstString name;
344 Constant **value_ptr = NULL;
345
346 if (!GetFunctionAddress(fun,
347 addr,
348 name,
349 value_ptr))
350 return false; // GetFunctionAddress reports its own errors
351
352 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
353
Sean Callananfc8feb82011-10-31 22:11:40 +0000354 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
355
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000356 if (value_ptr)
357 *value_ptr = value;
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 Callanan090e1192013-12-20 04:07:43 +0000728 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(), 64);
Sean Callanancc427fa2011-07-30 02:42:06 +0000729 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
730 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananafe16a72010-11-17 23:00:36 +0000731
732 if (!m_CFStringCreateWithBytes)
733 {
734 lldb::addr_t CFStringCreateWithBytes_addr;
735
736 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
737
738 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
739 {
740 if (log)
741 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
742
Sean Callanan3989fb92011-01-27 01:07:04 +0000743 if (m_error_stream)
744 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
745
Sean Callananafe16a72010-11-17 23:00:36 +0000746 return false;
747 }
748
749 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000750 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
Sean Callananafe16a72010-11-17 23:00:36 +0000751
752 // Build the function type:
753 //
754 // CFStringRef CFStringCreateWithBytes (
755 // CFAllocatorRef alloc,
756 // const UInt8 *bytes,
757 // CFIndex numBytes,
758 // CFStringEncoding encoding,
759 // Boolean isExternalRepresentation
760 // );
761 //
762 // We make the following substitutions:
763 //
764 // CFStringRef -> i8*
765 // CFAllocatorRef -> i8*
766 // UInt8 * -> i8*
767 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
768 // CFStringEncoding -> i32
769 // Boolean -> i8
770
Sean Callanancc427fa2011-07-30 02:42:06 +0000771 Type *arg_type_array[5];
772
773 arg_type_array[0] = i8_ptr_ty;
774 arg_type_array[1] = i8_ptr_ty;
775 arg_type_array[2] = intptr_ty;
776 arg_type_array[3] = i32_ty;
777 arg_type_array[4] = i8_ty;
778
779 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
780
Sean Callanan79763a42011-05-23 21:40:23 +0000781 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000782
783 // Build the constant containing the pointer to the function
784 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
785 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
786 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
787 }
788
Sean Callanand2b465f2012-02-09 03:22:41 +0000789 ConstantDataSequential *string_array = NULL;
Sean Callanan229ce2d2011-02-10 22:17:53 +0000790
791 if (cstr)
Sean Callanand2b465f2012-02-09 03:22:41 +0000792 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
Sean Callanancc427fa2011-07-30 02:42:06 +0000793
Sean Callananafe16a72010-11-17 23:00:36 +0000794 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan229ce2d2011-02-10 22:17:53 +0000795 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
Sean Callanand2b465f2012-02-09 03:22:41 +0000796 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000797 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
798 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
799
Sean Callanancc427fa2011-07-30 02:42:06 +0000800 Value *argument_array[5];
801
802 argument_array[0] = alloc_arg;
803 argument_array[1] = bytes_arg;
804 argument_array[2] = numBytes_arg;
805 argument_array[3] = encoding_arg;
806 argument_array[4] = isExternal_arg;
807
808 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callananafe16a72010-11-17 23:00:36 +0000809
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000810 FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * {
811 return CallInst::Create(m_CFStringCreateWithBytes,
812 CFSCWB_arguments,
813 "CFStringCreateWithBytes",
814 llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)));
815 });
Sean Callanan7a55a322010-11-18 22:21:58 +0000816
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000817 if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder))
Sean Callananafe16a72010-11-17 23:00:36 +0000818 {
819 if (log)
820 log->PutCString("Couldn't replace the NSString with the result of the call");
821
Sean Callanan3989fb92011-01-27 01:07:04 +0000822 if (m_error_stream)
823 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
824
Sean Callananafe16a72010-11-17 23:00:36 +0000825 return false;
826 }
827
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000828 ns_str->eraseFromParent();
Sean Callananafe16a72010-11-17 23:00:36 +0000829
830 return true;
831}
832
833bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000834IRForTarget::RewriteObjCConstStrings()
Sean Callananafe16a72010-11-17 23:00:36 +0000835{
Greg Clayton5160ce52013-03-27 23:08:40 +0000836 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000837
Sean Callanan79763a42011-05-23 21:40:23 +0000838 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananafe16a72010-11-17 23:00:36 +0000839
Sean Callananafe16a72010-11-17 23:00:36 +0000840 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
841 vi != ve;
842 ++vi)
843 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000844 std::string value_name = vi->first().str();
845 const char *value_name_cstr = value_name.c_str();
846
847 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callananafe16a72010-11-17 23:00:36 +0000848 {
849 Value *nsstring_value = vi->second;
850
851 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
852
853 if (!nsstring_global)
854 {
855 if (log)
856 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000857
858 if (m_error_stream)
859 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
860
Sean Callananafe16a72010-11-17 23:00:36 +0000861 return false;
862 }
863
864 if (!nsstring_global->hasInitializer())
865 {
866 if (log)
867 log->PutCString("NSString variable does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000868
869 if (m_error_stream)
870 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
871
Sean Callananafe16a72010-11-17 23:00:36 +0000872 return false;
873 }
874
875 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
876
877 if (!nsstring_struct)
878 {
879 if (log)
880 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan3989fb92011-01-27 01:07:04 +0000881
882 if (m_error_stream)
883 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
884
Sean Callananafe16a72010-11-17 23:00:36 +0000885 return false;
886 }
887
888 // We expect the following structure:
889 //
890 // struct {
891 // int *isa;
892 // int flags;
893 // char *str;
894 // long length;
895 // };
896
897 if (nsstring_struct->getNumOperands() != 4)
898 {
899 if (log)
900 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 +0000901
902 if (m_error_stream)
903 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
904
Sean Callananafe16a72010-11-17 23:00:36 +0000905 return false;
906 }
907
908 Constant *nsstring_member = nsstring_struct->getOperand(2);
909
910 if (!nsstring_member)
911 {
912 if (log)
913 log->PutCString("NSString initializer's str element was empty");
Sean Callanan3989fb92011-01-27 01:07:04 +0000914
915 if (m_error_stream)
916 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
917
Sean Callananafe16a72010-11-17 23:00:36 +0000918 return false;
919 }
920
921 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
922
923 if (!nsstring_expr)
924 {
925 if (log)
926 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan3989fb92011-01-27 01:07:04 +0000927
928 if (m_error_stream)
929 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
930
Sean Callananafe16a72010-11-17 23:00:36 +0000931 return false;
932 }
933
934 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
935 {
936 if (log)
937 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 +0000938
939 if (m_error_stream)
940 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
941
Sean Callananafe16a72010-11-17 23:00:36 +0000942 return false;
943 }
944
945 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
946
947 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
948
949 if (!cstr_global)
950 {
951 if (log)
952 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000953
954 if (m_error_stream)
955 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 +0000956
Sean Callananafe16a72010-11-17 23:00:36 +0000957 return false;
958 }
959
960 if (!cstr_global->hasInitializer())
961 {
962 if (log)
963 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000964
965 if (m_error_stream)
966 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
967
Sean Callananafe16a72010-11-17 23:00:36 +0000968 return false;
969 }
Sean Callanan229ce2d2011-02-10 22:17:53 +0000970
971 /*
Sean Callananafe16a72010-11-17 23:00:36 +0000972 if (!cstr_array)
973 {
974 if (log)
975 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan3989fb92011-01-27 01:07:04 +0000976
977 if (m_error_stream)
978 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
979
Sean Callananafe16a72010-11-17 23:00:36 +0000980 return false;
981 }
982
983 if (!cstr_array->isCString())
984 {
985 if (log)
986 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan3989fb92011-01-27 01:07:04 +0000987
988 if (m_error_stream)
989 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
990
Sean Callananafe16a72010-11-17 23:00:36 +0000991 return false;
992 }
Sean Callanan229ce2d2011-02-10 22:17:53 +0000993 */
994
Sean Callanand2b465f2012-02-09 03:22:41 +0000995 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
Sean Callananafe16a72010-11-17 23:00:36 +0000996
997 if (log)
Sean Callanan229ce2d2011-02-10 22:17:53 +0000998 {
999 if (cstr_array)
Sean Callanand2b465f2012-02-09 03:22:41 +00001000 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 +00001001 else
Sean Callanancc427fa2011-07-30 02:42:06 +00001002 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan229ce2d2011-02-10 22:17:53 +00001003 }
1004
1005 if (!cstr_array)
1006 cstr_global = NULL;
Sean Callananafe16a72010-11-17 23:00:36 +00001007
Sean Callanan1f9db3e2013-06-28 21:44:15 +00001008 if (!RewriteObjCConstString(nsstring_global, cstr_global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001009 {
Sean Callananafe16a72010-11-17 23:00:36 +00001010 if (log)
1011 log->PutCString("Error rewriting the constant string");
Sean Callanan3989fb92011-01-27 01:07:04 +00001012
1013 // We don't print an error message here because RewriteObjCConstString has done so for us.
1014
Sean Callananafe16a72010-11-17 23:00:36 +00001015 return false;
1016 }
Sean Callananafe16a72010-11-17 23:00:36 +00001017 }
1018 }
1019
1020 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1021 vi != ve;
1022 ++vi)
1023 {
Sean Callanancc427fa2011-07-30 02:42:06 +00001024 std::string value_name = vi->first().str();
1025 const char *value_name_cstr = value_name.c_str();
1026
1027 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callananafe16a72010-11-17 23:00:36 +00001028 {
1029 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1030
1031 if (!gv)
1032 {
1033 if (log)
1034 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001035
1036 if (m_error_stream)
1037 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1038
Sean Callananafe16a72010-11-17 23:00:36 +00001039 return false;
1040 }
1041
1042 gv->eraseFromParent();
1043
1044 break;
1045 }
1046 }
1047
1048 return true;
1049}
1050
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001051static bool IsObjCSelectorRef (Value *value)
Sean Callanan5300d372010-07-31 01:32:05 +00001052{
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001053 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callanan5300d372010-07-31 01:32:05 +00001054
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001055 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callanan5300d372010-07-31 01:32:05 +00001056 return false;
1057
1058 return true;
1059}
1060
Sean Callanan3989fb92011-01-27 01:07:04 +00001061// This function does not report errors; its callers are responsible.
Sean Callanan5300d372010-07-31 01:32:05 +00001062bool
Sean Callanan79763a42011-05-23 21:40:23 +00001063IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callanan5300d372010-07-31 01:32:05 +00001064{
Greg Clayton5160ce52013-03-27 23:08:40 +00001065 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001066
1067 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1068
1069 if (!load)
1070 return false;
1071
1072 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1073 //
1074 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1075 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1076 //
1077 // where %obj is the object pointer and %tmp is the selector.
1078 //
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001079 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1080 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callanan5300d372010-07-31 01:32:05 +00001081
1082 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1083
1084 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1085
1086 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1087 return false;
1088
1089 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1090
1091 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1092
1093 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1094 return false;
1095
1096 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1097
1098 if (!osr_initializer_base)
1099 return false;
1100
1101 // Find the string's initializer (a ConstantArray) and get the string from it
1102
1103 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1104
1105 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1106 return false;
1107
1108 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1109
Sean Callanand2b465f2012-02-09 03:22:41 +00001110 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
Sean Callanan5300d372010-07-31 01:32:05 +00001111
1112 if (!omvn_initializer_array->isString())
1113 return false;
1114
1115 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1116
1117 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001118 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callanan5300d372010-07-31 01:32:05 +00001119
1120 // Construct a call to sel_registerName
1121
1122 if (!m_sel_registerName)
1123 {
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001124 lldb::addr_t sel_registerName_addr;
Sean Callanan5300d372010-07-31 01:32:05 +00001125
Greg Clayton7b462cc2010-10-15 22:48:33 +00001126 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001127 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callanan5300d372010-07-31 01:32:05 +00001128 return false;
1129
Sean Callananbe3a1b12010-10-26 00:31:56 +00001130 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001131 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
Sean Callananbe3a1b12010-10-26 00:31:56 +00001132
Sean Callanan5300d372010-07-31 01:32:05 +00001133 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1134
1135 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callanan79763a42011-05-23 21:40:23 +00001136 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001137 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanancc427fa2011-07-30 02:42:06 +00001138 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001139
Sean Callanancc427fa2011-07-30 02:42:06 +00001140 Type *type_array[1];
1141
1142 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1143
1144 ArrayRef<Type *> srN_arg_types(type_array, 1);
1145
Sean Callanan5300d372010-07-31 01:32:05 +00001146 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1147
1148 // Build the constant containing the pointer to the function
Sean Callanan090e1192013-12-20 04:07:43 +00001149 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(), 64);
Sean Callanan5300d372010-07-31 01:32:05 +00001150 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001151 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callanan5300d372010-07-31 01:32:05 +00001152 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1153 }
1154
Sean Callanancc427fa2011-07-30 02:42:06 +00001155 Value *argument_array[1];
1156
Sean Callanan79763a42011-05-23 21:40:23 +00001157 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callanan5300d372010-07-31 01:32:05 +00001158
Sean Callanancc427fa2011-07-30 02:42:06 +00001159 argument_array[0] = omvn_pointer;
Sean Callanan5300d372010-07-31 01:32:05 +00001160
Sean Callanancc427fa2011-07-30 02:42:06 +00001161 ArrayRef<Value *> srN_arguments(argument_array, 1);
1162
Sean Callanan5300d372010-07-31 01:32:05 +00001163 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanancc427fa2011-07-30 02:42:06 +00001164 srN_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +00001165 "sel_registerName",
Sean Callanan5300d372010-07-31 01:32:05 +00001166 selector_load);
1167
1168 // Replace the load with the call in all users
1169
1170 selector_load->replaceAllUsesWith(srN_call);
1171
1172 selector_load->eraseFromParent();
1173
1174 return true;
1175}
1176
1177bool
Sean Callanan79763a42011-05-23 21:40:23 +00001178IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callanan5300d372010-07-31 01:32:05 +00001179{
Greg Clayton5160ce52013-03-27 23:08:40 +00001180 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001181
1182 BasicBlock::iterator ii;
1183
1184 typedef SmallVector <Instruction*, 2> InstrList;
1185 typedef InstrList::iterator InstrIterator;
1186
1187 InstrList selector_loads;
1188
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001189 for (ii = basic_block.begin();
1190 ii != basic_block.end();
Sean Callanan5300d372010-07-31 01:32:05 +00001191 ++ii)
1192 {
1193 Instruction &inst = *ii;
1194
1195 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001196 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callanan5300d372010-07-31 01:32:05 +00001197 selector_loads.push_back(&inst);
1198 }
1199
1200 InstrIterator iter;
1201
1202 for (iter = selector_loads.begin();
1203 iter != selector_loads.end();
1204 ++iter)
1205 {
Sean Callanan79763a42011-05-23 21:40:23 +00001206 if (!RewriteObjCSelector(*iter))
Sean Callanan5300d372010-07-31 01:32:05 +00001207 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001208 if (m_error_stream)
1209 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1210
Enrico Granata20edcdb2011-07-19 18:03:25 +00001211 if (log)
Sean Callanan5300d372010-07-31 01:32:05 +00001212 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan3989fb92011-01-27 01:07:04 +00001213
Sean Callanan5300d372010-07-31 01:32:05 +00001214 return false;
1215 }
1216 }
1217
1218 return true;
1219}
1220
Sean Callanan3989fb92011-01-27 01:07:04 +00001221// This function does not report errors; its callers are responsible.
Sean Callanan2235f322010-08-11 03:57:18 +00001222bool
Sean Callanan79763a42011-05-23 21:40:23 +00001223IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanan2235f322010-08-11 03:57:18 +00001224{
Greg Clayton5160ce52013-03-27 23:08:40 +00001225 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanane1175b72011-01-13 21:23:32 +00001226
Sean Callanan2235f322010-08-11 03:57:18 +00001227 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1228
1229 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1230
1231 if (!alloc_md || !alloc_md->getNumOperands())
1232 return false;
1233
1234 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1235
1236 if (!constant_int)
1237 return false;
1238
1239 // We attempt to register this as a new persistent variable with the DeclMap.
1240
1241 uintptr_t ptr = constant_int->getZExtValue();
1242
Sean Callanand1e5b432010-08-12 01:56:52 +00001243 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanan2235f322010-08-11 03:57:18 +00001244
Sean Callanand1e5b432010-08-12 01:56:52 +00001245 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1246 &decl->getASTContext());
1247
Greg Clayton7b462cc2010-10-15 22:48:33 +00001248 StringRef decl_name (decl->getName());
1249 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan92adcac2011-01-13 08:53:35 +00001250 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanan2235f322010-08-11 03:57:18 +00001251 return false;
1252
Sean Callanan79763a42011-05-23 21:40:23 +00001253 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanane1175b72011-01-13 21:23:32 +00001254 alloc->getType(),
Sean Callanan2235f322010-08-11 03:57:18 +00001255 false, /* not constant */
1256 GlobalValue::ExternalLinkage,
1257 NULL, /* no initializer */
1258 alloc->getName().str().c_str());
1259
1260 // What we're going to do here is make believe this was a regular old external
1261 // variable. That means we need to make the metadata valid.
1262
Sean Callanan585c0ec82012-07-04 01:26:26 +00001263 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
Sean Callanan2235f322010-08-11 03:57:18 +00001264
1265 llvm::Value* values[2];
1266 values[0] = persistent_global;
1267 values[1] = constant_int;
Sean Callanand12cf8bb2011-05-15 22:34:38 +00001268
1269 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanan2235f322010-08-11 03:57:18 +00001270
Sean Callanan79763a42011-05-23 21:40:23 +00001271 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanan2235f322010-08-11 03:57:18 +00001272 named_metadata->addOperand(persistent_global_md);
1273
Sean Callanane1175b72011-01-13 21:23:32 +00001274 // Now, since the variable is a pointer variable, we will drop in a load of that
1275 // pointer variable.
1276
1277 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1278
1279 if (log)
1280 log->Printf("Replacing \"%s\" with \"%s\"",
1281 PrintValue(alloc).c_str(),
1282 PrintValue(persistent_load).c_str());
1283
1284 alloc->replaceAllUsesWith(persistent_load);
Sean Callanan2235f322010-08-11 03:57:18 +00001285 alloc->eraseFromParent();
1286
1287 return true;
1288}
1289
1290bool
Sean Callanan79763a42011-05-23 21:40:23 +00001291IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanan2235f322010-08-11 03:57:18 +00001292{
Sean Callanan9e6ed532010-09-13 21:34:21 +00001293 if (!m_resolve_vars)
1294 return true;
1295
Greg Clayton5160ce52013-03-27 23:08:40 +00001296 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2235f322010-08-11 03:57:18 +00001297
1298 BasicBlock::iterator ii;
1299
1300 typedef SmallVector <Instruction*, 2> InstrList;
1301 typedef InstrList::iterator InstrIterator;
1302
1303 InstrList pvar_allocs;
1304
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001305 for (ii = basic_block.begin();
1306 ii != basic_block.end();
Sean Callanan2235f322010-08-11 03:57:18 +00001307 ++ii)
1308 {
1309 Instruction &inst = *ii;
1310
1311 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callananf694a552011-01-21 22:30:25 +00001312 {
1313 llvm::StringRef alloc_name = alloc->getName();
1314
1315 if (alloc_name.startswith("$") &&
1316 !alloc_name.startswith("$__lldb"))
1317 {
1318 if (alloc_name.find_first_of("0123456789") == 1)
1319 {
1320 if (log)
1321 log->Printf("Rejecting a numeric persistent variable.");
1322
Sean Callanan3989fb92011-01-27 01:07:04 +00001323 if (m_error_stream)
1324 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1325
Sean Callananf694a552011-01-21 22:30:25 +00001326 return false;
1327 }
1328
Sean Callanan2235f322010-08-11 03:57:18 +00001329 pvar_allocs.push_back(alloc);
Sean Callananf694a552011-01-21 22:30:25 +00001330 }
1331 }
Sean Callanan2235f322010-08-11 03:57:18 +00001332 }
1333
1334 InstrIterator iter;
1335
1336 for (iter = pvar_allocs.begin();
1337 iter != pvar_allocs.end();
1338 ++iter)
1339 {
Sean Callanan79763a42011-05-23 21:40:23 +00001340 if (!RewritePersistentAlloc(*iter))
Sean Callanan2235f322010-08-11 03:57:18 +00001341 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001342 if (m_error_stream)
1343 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1344
Enrico Granata20edcdb2011-07-19 18:03:25 +00001345 if (log)
Sean Callanan2235f322010-08-11 03:57:18 +00001346 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001347
Sean Callanan2235f322010-08-11 03:57:18 +00001348 return false;
1349 }
1350 }
1351
1352 return true;
1353}
1354
Sean Callananc70ed462011-10-25 18:36:40 +00001355bool
1356IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1357{
1358 if (!initializer)
1359 return true;
1360
Greg Clayton5160ce52013-03-27 23:08:40 +00001361 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc70ed462011-10-25 18:36:40 +00001362
1363 if (log && log->GetVerbose())
1364 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1365
1366 Type *initializer_type = initializer->getType();
1367
1368 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1369 {
1370 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1371 return true;
1372 }
Sean Callanand2b465f2012-02-09 03:22:41 +00001373 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
Sean Callananc70ed462011-10-25 18:36:40 +00001374 {
1375 if (array_initializer->isString())
1376 {
1377 std::string array_initializer_string = array_initializer->getAsString();
1378 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1379 }
1380 else
1381 {
1382 ArrayType *array_initializer_type = array_initializer->getType();
1383 Type *array_element_type = array_initializer_type->getElementType();
1384
1385 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1386
Andy Gibbsa297a972013-06-19 19:04:53 +00001387 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i)
Sean Callananc70ed462011-10-25 18:36:40 +00001388 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001389 Value *operand_value = array_initializer->getOperand(i);
1390 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1391
1392 if (!operand_constant)
1393 return false;
1394
1395 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
Sean Callananc70ed462011-10-25 18:36:40 +00001396 return false;
1397 }
1398 }
1399 return true;
1400 }
1401 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1402 {
1403 StructType *struct_initializer_type = struct_initializer->getType();
1404 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1405
Andy Gibbsa297a972013-06-19 19:04:53 +00001406 for (unsigned i = 0;
Sean Callananc70ed462011-10-25 18:36:40 +00001407 i < struct_initializer->getNumOperands();
1408 ++i)
1409 {
1410 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1411 return false;
1412 }
1413 return true;
1414 }
Sean Callanan76ee3e72013-04-24 19:50:12 +00001415 else if (isa<ConstantAggregateZero>(initializer))
1416 {
1417 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1418 return true;
1419 }
Sean Callananc70ed462011-10-25 18:36:40 +00001420 return false;
1421}
1422
1423bool
1424IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1425{
1426 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1427 return false;
1428
Sean Callananfe5d1392011-11-15 19:13:54 +00001429 if (global_variable == m_reloc_placeholder)
1430 return true;
1431
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001432 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callananc70ed462011-10-25 18:36:40 +00001433
1434 llvm::Type *variable_type = global_variable->getType();
1435
1436 Constant *initializer = global_variable->getInitializer();
1437
1438 llvm::Type *initializer_type = initializer->getType();
1439
1440 size_t size = m_target_data->getTypeAllocSize(initializer_type);
Sean Callanane3333d62012-06-08 22:20:41 +00001441 size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1442
1443 const size_t mask = (align - 1);
1444 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001445 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00001446 offset = aligned_offset;
Sean Callananc70ed462011-10-25 18:36:40 +00001447
1448 lldb_private::DataBufferHeap data(size, '\0');
1449
1450 if (initializer)
1451 if (!MaterializeInitializer(data.GetBytes(), initializer))
1452 return false;
1453
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001454 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
Sean Callananc70ed462011-10-25 18:36:40 +00001455
1456 Constant *new_pointer = BuildRelocation(variable_type, offset);
1457
1458 global_variable->replaceAllUsesWith(new_pointer);
1459
1460 global_variable->eraseFromParent();
1461
1462 return true;
1463}
1464
Sean Callanan3989fb92011-01-27 01:07:04 +00001465// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001466bool
Sean Callanan79763a42011-05-23 21:40:23 +00001467IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001468{
Greg Clayton5160ce52013-03-27 23:08:40 +00001469 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001470
1471 if (log)
Sean Callanan88339f02010-12-06 22:16:55 +00001472 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callananaf8e96c2011-08-01 17:41:38 +00001473
Greg Clayton7b462cc2010-10-15 22:48:33 +00001474 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callanan4cf04d22010-08-03 00:23:29 +00001475 {
Sean Callanan5666b672010-08-04 01:02:13 +00001476 switch (constant_expr->getOpcode())
Sean Callanan4cf04d22010-08-03 00:23:29 +00001477 {
Sean Callanan5666b672010-08-04 01:02:13 +00001478 default:
1479 break;
1480 case Instruction::GetElementPtr:
1481 case Instruction::BitCast:
Sean Callanan4cf04d22010-08-03 00:23:29 +00001482 Value *s = constant_expr->getOperand(0);
Sean Callanan79763a42011-05-23 21:40:23 +00001483 if (!MaybeHandleVariable(s))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001484 return false;
Sean Callanan4cf04d22010-08-03 00:23:29 +00001485 }
1486 }
Sean Callanand6e04ae2010-12-03 19:51:05 +00001487 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001488 {
Sean Callananc70ed462011-10-25 18:36:40 +00001489 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1490 return MaterializeInternalVariable(global_variable);
1491
Sean Callanan79763a42011-05-23 21:40:23 +00001492 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan2ab712f22010-07-03 01:35:46 +00001493
Sean Callanan5300d372010-07-31 01:32:05 +00001494 if (!named_decl)
1495 {
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001496 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001497 return true;
1498
Sean Callanan14f0b0e2010-12-06 00:56:39 +00001499 if (!global_variable->hasExternalLinkage())
1500 return true;
1501
Sean Callanan5300d372010-07-31 01:32:05 +00001502 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001503 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001504
Sean Callanan5300d372010-07-31 01:32:05 +00001505 return false;
1506 }
1507
Greg Clayton7b462cc2010-10-15 22:48:33 +00001508 std::string name (named_decl->getName().str());
Sean Callananea22d422010-07-16 00:09:46 +00001509
Greg Clayton57ee3062013-07-11 22:46:58 +00001510 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1511 if (value_decl == NULL)
Sean Callananea22d422010-07-16 00:09:46 +00001512 return false;
Greg Clayton57ee3062013-07-11 22:46:58 +00001513
1514 lldb_private::ClangASTType clang_type(&value_decl->getASTContext(), value_decl->getType());
Sean Callanan038df5032010-09-30 21:18:25 +00001515
Sean Callanan77eaf442011-07-08 00:39:14 +00001516 const Type *value_type = NULL;
Greg Clayton57ee3062013-07-11 22:46:58 +00001517
Sean Callanane1175b72011-01-13 21:23:32 +00001518 if (name[0] == '$')
Sean Callanan92adcac2011-01-13 08:53:35 +00001519 {
1520 // The $__lldb_expr_result name indicates the the return value has allocated as
1521 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1522 // accesses to this static variable need to be redirected to the result of dereferencing
1523 // a pointer that is passed in as one of the arguments.
1524 //
1525 // Consequently, when reporting the size of the type, we report a pointer type pointing
1526 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanane1175b72011-01-13 21:23:32 +00001527 //
1528 // We also do this for any user-declared persistent variables.
Greg Clayton57ee3062013-07-11 22:46:58 +00001529 clang_type = clang_type.GetPointerType();
Sean Callanan92adcac2011-01-13 08:53:35 +00001530 value_type = PointerType::get(global_variable->getType(), 0);
1531 }
1532 else
1533 {
Sean Callanan92adcac2011-01-13 08:53:35 +00001534 value_type = global_variable->getType();
1535 }
Greg Clayton57ee3062013-07-11 22:46:58 +00001536
1537 const uint64_t value_size = clang_type.GetByteSize();
1538 off_t value_alignment = (clang_type.GetTypeBitAlign() + 7ull) / 8ull;
Sean Callanan17827832010-12-13 22:46:15 +00001539
Sean Callanan038df5032010-09-30 21:18:25 +00001540 if (log)
Greg Clayton57ee3062013-07-11 22:46:58 +00001541 {
Greg Claytonfaac1112013-03-14 18:31:44 +00001542 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
Sean Callanan038df5032010-09-30 21:18:25 +00001543 name.c_str(),
Greg Clayton57ee3062013-07-11 22:46:58 +00001544 clang_type.GetQualType().getAsString().c_str(),
1545 PrintType(value_type).c_str(),
Sean Callanan038df5032010-09-30 21:18:25 +00001546 value_size,
1547 value_alignment);
Greg Clayton57ee3062013-07-11 22:46:58 +00001548 }
Sean Callanan17827832010-12-13 22:46:15 +00001549
Sean Callanan549c9f72010-07-13 21:41:46 +00001550
Sean Callanan64dfc9a2010-08-23 23:09:38 +00001551 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton7b462cc2010-10-15 22:48:33 +00001552 lldb_private::ConstString (name.c_str()),
1553 llvm_value_ptr,
Sean Callanan4edba2d2010-07-27 02:07:53 +00001554 value_size,
1555 value_alignment))
Sean Callananaf8e96c2011-08-01 17:41:38 +00001556 {
1557 if (!global_variable->hasExternalLinkage())
1558 return true;
Sean Callanan0ff3bf92013-04-11 17:57:16 +00001559 else if (HandleSymbol (global_variable))
1560 return true;
Sean Callananaf8e96c2011-08-01 17:41:38 +00001561 else
1562 return false;
1563 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001564 }
Sean Callanan4a5fcbb2010-12-03 03:02:31 +00001565 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001566 {
1567 if (log)
1568 log->Printf("Function pointers aren't handled right now");
1569
1570 return false;
1571 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001572
1573 return true;
1574}
1575
Sean Callanan3989fb92011-01-27 01:07:04 +00001576// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001577bool
Sean Callanan79763a42011-05-23 21:40:23 +00001578IRForTarget::HandleSymbol (Value *symbol)
Sean Callanand9ca42a2011-05-08 02:21:26 +00001579{
Greg Clayton5160ce52013-03-27 23:08:40 +00001580 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc3a16002011-01-17 23:42:46 +00001581
1582 lldb_private::ConstString name(symbol->getName().str().c_str());
1583
Sean Callanan947ccc72011-12-01 02:04:16 +00001584 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
Sean Callananc3a16002011-01-17 23:42:46 +00001585
Greg Clayton084db102011-06-23 04:25:29 +00001586 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc3a16002011-01-17 23:42:46 +00001587 {
1588 if (log)
1589 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1590
1591 return false;
1592 }
1593
1594 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001595 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
Sean Callananc3a16002011-01-17 23:42:46 +00001596
Sean Callanancc427fa2011-07-30 02:42:06 +00001597 Type *symbol_type = symbol->getType();
Sean Callanan090e1192013-12-20 04:07:43 +00001598 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(), 64);
Sean Callananc3a16002011-01-17 23:42:46 +00001599
1600 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1601
1602 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1603
1604 if (log)
1605 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1606
1607 symbol->replaceAllUsesWith(symbol_addr_ptr);
1608
1609 return true;
1610}
1611
1612bool
Sean Callanan79763a42011-05-23 21:40:23 +00001613IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanan85a0a832010-10-05 22:26:43 +00001614{
Greg Clayton5160ce52013-03-27 23:08:40 +00001615 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001616
1617 if (log)
1618 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanan85a0a832010-10-05 22:26:43 +00001619
Sean Callananafe16a72010-11-17 23:00:36 +00001620 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanan85a0a832010-10-05 22:26:43 +00001621 op_index < num_ops;
1622 ++op_index)
Sean Callanan79763a42011-05-23 21:40:23 +00001623 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan3989fb92011-01-27 01:07:04 +00001624 {
1625 if (m_error_stream)
1626 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1627
Sean Callanan85a0a832010-10-05 22:26:43 +00001628 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001629 }
1630
Sean Callanan85a0a832010-10-05 22:26:43 +00001631 return true;
1632}
1633
1634bool
Sean Callananfc89c142011-11-01 23:38:03 +00001635IRForTarget::HandleObjCClass(Value *classlist_reference)
1636{
Greg Clayton5160ce52013-03-27 23:08:40 +00001637 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananfc89c142011-11-01 23:38:03 +00001638
1639 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1640
1641 if (!global_variable)
1642 return false;
1643
1644 Constant *initializer = global_variable->getInitializer();
1645
1646 if (!initializer)
1647 return false;
1648
1649 if (!initializer->hasName())
1650 return false;
1651
1652 StringRef name(initializer->getName());
1653 lldb_private::ConstString name_cstr(name.str().c_str());
Greg Clayton1075aca2011-12-03 20:02:42 +00001654 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
Sean Callananfc89c142011-11-01 23:38:03 +00001655
1656 if (log)
1657 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1658
1659 if (class_ptr == LLDB_INVALID_ADDRESS)
1660 return false;
1661
1662 if (global_variable->use_begin() == global_variable->use_end())
1663 return false;
1664
Sean Callanan719a4d52013-03-23 01:01:16 +00001665 SmallVector<LoadInst *, 2> load_instructions;
1666
Sean Callananfc89c142011-11-01 23:38:03 +00001667 for (Value::use_iterator i = global_variable->use_begin(), e = global_variable->use_end();
1668 i != e;
1669 ++i)
1670 {
Sean Callanan719a4d52013-03-23 01:01:16 +00001671 if (LoadInst *load_instruction = dyn_cast<LoadInst>(*i))
1672 load_instructions.push_back(load_instruction);
Sean Callananfc89c142011-11-01 23:38:03 +00001673 }
1674
Sean Callanan719a4d52013-03-23 01:01:16 +00001675 if (load_instructions.empty())
Sean Callananfc89c142011-11-01 23:38:03 +00001676 return false;
1677
Sean Callanan090e1192013-12-20 04:07:43 +00001678 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(), 64);
Sean Callananfc89c142011-11-01 23:38:03 +00001679
1680 Constant *class_addr = ConstantInt::get(intptr_ty, (uint64_t)class_ptr);
Sean Callananfc89c142011-11-01 23:38:03 +00001681
Sean Callanan719a4d52013-03-23 01:01:16 +00001682 for (LoadInst *load_instruction : load_instructions)
1683 {
1684 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
Sean Callananfc89c142011-11-01 23:38:03 +00001685
Sean Callanan719a4d52013-03-23 01:01:16 +00001686 load_instruction->replaceAllUsesWith(class_bitcast);
1687
1688 load_instruction->eraseFromParent();
1689 }
Sean Callananfc89c142011-11-01 23:38:03 +00001690
1691 return true;
1692}
1693
1694bool
Sean Callanan6e6d4a62012-07-21 02:02:15 +00001695IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1696{
1697 BasicBlock::iterator ii;
1698
1699 std::vector<CallInst *> calls_to_remove;
1700
1701 for (ii = basic_block.begin();
1702 ii != basic_block.end();
1703 ++ii)
1704 {
1705 Instruction &inst = *ii;
1706
1707 CallInst *call = dyn_cast<CallInst>(&inst);
1708
1709 // MaybeHandleCallArguments handles error reporting; we are silent here
1710 if (!call)
1711 continue;
1712
1713 bool remove = false;
1714
1715 llvm::Function *func = call->getCalledFunction();
1716
1717 if (func && func->getName() == "__cxa_atexit")
1718 remove = true;
1719
1720 llvm::Value *val = call->getCalledValue();
1721
1722 if (val && val->getName() == "__cxa_atexit")
1723 remove = true;
1724
1725 if (remove)
1726 calls_to_remove.push_back(call);
1727 }
1728
1729 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1730 ci != ce;
1731 ++ci)
1732 {
1733 (*ci)->eraseFromParent();
1734 }
1735
1736 return true;
1737}
1738
1739bool
Sean Callanan79763a42011-05-23 21:40:23 +00001740IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan549c9f72010-07-13 21:41:46 +00001741{
Sean Callanan2ab712f22010-07-03 01:35:46 +00001742 /////////////////////////////////////////////////////////////////////////
1743 // Prepare the current basic block for execution in the remote process
1744 //
1745
Sean Callanan7ea35012010-07-27 21:39:39 +00001746 BasicBlock::iterator ii;
Sean Callanan549c9f72010-07-13 21:41:46 +00001747
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001748 for (ii = basic_block.begin();
1749 ii != basic_block.end();
Sean Callanan549c9f72010-07-13 21:41:46 +00001750 ++ii)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001751 {
Sean Callanan549c9f72010-07-13 21:41:46 +00001752 Instruction &inst = *ii;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001753
Sean Callanana4e55172010-11-08 00:31:32 +00001754 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callanan4edba2d2010-07-27 02:07:53 +00001755
Sean Callanan3989fb92011-01-27 01:07:04 +00001756 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callanan79763a42011-05-23 21:40:23 +00001757 if (call && !MaybeHandleCallArguments(call))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001758 return false;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001759 }
1760
1761 return true;
1762}
1763
Sean Callanana4e55172010-11-08 00:31:32 +00001764bool
Sean Callanan79763a42011-05-23 21:40:23 +00001765IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanana4e55172010-11-08 00:31:32 +00001766{
Greg Clayton5160ce52013-03-27 23:08:40 +00001767 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7a55a322010-11-18 22:21:58 +00001768
Sean Callanan79763a42011-05-23 21:40:23 +00001769 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanana4e55172010-11-08 00:31:32 +00001770 global != end;
1771 ++global)
1772 {
Sean Callanan694e2442011-12-22 21:24:49 +00001773 if (!global)
1774 {
1775 if (m_error_stream)
1776 m_error_stream->Printf("Internal error [IRForTarget]: global variable is NULL");
1777
1778 return false;
1779 }
1780
1781 std::string global_name = (*global).getName().str();
1782
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001783 if (log)
1784 log->Printf("Examining %s, DeclForGlobalValue returns %p",
Sean Callanan694e2442011-12-22 21:24:49 +00001785 global_name.c_str(),
Sean Callanan79763a42011-05-23 21:40:23 +00001786 DeclForGlobal(global));
Sean Callananfc89c142011-11-01 23:38:03 +00001787
1788 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc3a16002011-01-17 23:42:46 +00001789 {
Sean Callanan79763a42011-05-23 21:40:23 +00001790 if (!HandleSymbol(global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001791 {
1792 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001793 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", global_name.c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001794
Sean Callananc3a16002011-01-17 23:42:46 +00001795 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001796 }
Sean Callananc3a16002011-01-17 23:42:46 +00001797 }
Sean Callananfc89c142011-11-01 23:38:03 +00001798 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1799 {
1800 if (!HandleObjCClass(global))
1801 {
1802 if (m_error_stream)
1803 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1804
1805 return false;
1806 }
1807 }
Sean Callanan2ad66912013-04-24 21:25:20 +00001808 else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos)
1809 {
1810 if (!HandleObjCClass(global))
1811 {
1812 if (m_error_stream)
1813 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1814
1815 return false;
1816 }
1817 }
Sean Callanan79763a42011-05-23 21:40:23 +00001818 else if (DeclForGlobal(global))
Sean Callananc3a16002011-01-17 23:42:46 +00001819 {
Sean Callanan79763a42011-05-23 21:40:23 +00001820 if (!MaybeHandleVariable (global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001821 {
1822 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001823 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", global_name.c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001824
Sean Callananc3a16002011-01-17 23:42:46 +00001825 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001826 }
Sean Callananc3a16002011-01-17 23:42:46 +00001827 }
Sean Callanana4e55172010-11-08 00:31:32 +00001828 }
1829
1830 return true;
1831}
1832
Sean Callanan79763a42011-05-23 21:40:23 +00001833bool
1834IRForTarget::ReplaceStrings ()
1835{
Greg Clayton5160ce52013-03-27 23:08:40 +00001836 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001837
Sean Callanan79763a42011-05-23 21:40:23 +00001838 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1839
1840 OffsetsTy offsets;
1841
1842 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1843 gi != ge;
1844 ++gi)
1845 {
1846 GlobalVariable *gv = gi;
1847
1848 if (!gv->hasInitializer())
1849 continue;
1850
1851 Constant *gc = gv->getInitializer();
1852
Sean Callanan5207a342011-08-10 21:05:52 +00001853 std::string str;
Sean Callanan79763a42011-05-23 21:40:23 +00001854
Sean Callanan5207a342011-08-10 21:05:52 +00001855 if (gc->isNullValue())
1856 {
1857 Type *gc_type = gc->getType();
1858
1859 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1860
1861 if (!gc_array_type)
1862 continue;
1863
1864 Type *gc_element_type = gc_array_type->getElementType();
1865
1866 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1867
1868 if (gc_integer_type->getBitWidth() != 8)
1869 continue;
1870
1871 str = "";
1872 }
1873 else
1874 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001875 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
Sean Callanan5207a342011-08-10 21:05:52 +00001876
1877 if (!gc_array)
1878 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001879
Sean Callanan5207a342011-08-10 21:05:52 +00001880 if (!gc_array->isCString())
1881 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001882
Sean Callanan5207a342011-08-10 21:05:52 +00001883 if (log)
1884 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00001885
Sean Callanan5207a342011-08-10 21:05:52 +00001886 str = gc_array->getAsString();
1887 }
1888
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001889 offsets[gv] = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00001890
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001891 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
Sean Callanan79763a42011-05-23 21:40:23 +00001892 }
1893
Sean Callanancc427fa2011-07-30 02:42:06 +00001894 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00001895
1896 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1897 oi != oe;
1898 ++oi)
1899 {
1900 GlobalVariable *gv = oi->first;
1901 size_t offset = oi->second;
1902
1903 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1904
1905 if (log)
1906 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1907
1908 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1909 ui != ue;
1910 ++ui)
1911 {
1912 if (log)
1913 log->Printf("Found use %s", PrintValue(*ui).c_str());
1914
1915 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1916 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1917
1918 if (const_expr)
1919 {
1920 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1921 {
1922 if (log)
1923 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1924
1925 return false;
1926 }
1927
Sean Callanan5207a342011-08-10 21:05:52 +00001928 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1929 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1930
1931 const_expr->replaceAllUsesWith(new_gep);
Sean Callanan79763a42011-05-23 21:40:23 +00001932 }
1933 else if (store_inst)
1934 {
1935 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1936
1937 store_inst->setOperand(0, bit_cast);
1938 }
1939 else
1940 {
1941 if (log)
1942 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1943
1944 return false;
1945 }
1946 }
1947
1948 gv->eraseFromParent();
1949 }
1950
1951 return true;
1952}
1953
1954bool
1955IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1956{
Greg Clayton5160ce52013-03-27 23:08:40 +00001957 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001958
1959 typedef SmallVector <Value*, 2> ConstantList;
1960 typedef SmallVector <llvm::Instruction*, 2> UserList;
1961 typedef ConstantList::iterator ConstantIterator;
1962 typedef UserList::iterator UserIterator;
1963
1964 ConstantList static_constants;
1965 UserList static_users;
1966
1967 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1968 ii != ie;
1969 ++ii)
1970 {
1971 llvm::Instruction &inst = *ii;
1972
1973 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1974 oi != oe;
1975 ++oi)
1976 {
1977 Value *operand_val = oi->get();
1978
1979 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1980
Sean Callanan822944c2012-04-26 20:51:20 +00001981 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
Sean Callanan79763a42011-05-23 21:40:23 +00001982 {
1983 static_constants.push_back(operand_val);
1984 static_users.push_back(ii);
1985 }
1986 }
1987 }
1988
1989 ConstantIterator constant_iter;
1990 UserIterator user_iter;
Greg Clayton9b72eb72011-05-24 23:06:02 +00001991
Sean Callanan79763a42011-05-23 21:40:23 +00001992 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1993 constant_iter != static_constants.end();
1994 ++constant_iter, ++user_iter)
1995 {
1996 Value *operand_val = *constant_iter;
1997 llvm::Instruction *inst = *user_iter;
1998
1999 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
2000
2001 if (operand_constant_fp)
2002 {
Sean Callanan1582ee62013-04-18 22:06:33 +00002003 Type *operand_type = operand_constant_fp->getType();
2004
Sean Callanan79763a42011-05-23 21:40:23 +00002005 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
2006 APInt operand_apint = operand_apfloat.bitcastToAPInt();
2007
2008 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
2009 size_t operand_data_size = operand_apint.getBitWidth() / 8;
2010
2011 if (log)
2012 {
2013 std::string s;
2014 raw_string_ostream ss(s);
2015 for (size_t index = 0;
2016 index < operand_data_size;
2017 ++index)
2018 {
2019 ss << (uint32_t)operand_raw_data[index];
2020 ss << " ";
2021 }
2022 ss.flush();
2023
Sylvestre Ledru779f9212013-10-31 23:55:19 +00002024 log->Printf("Found ConstantFP with size %zu and raw data %s", operand_data_size, s.c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00002025 }
2026
2027 lldb_private::DataBufferHeap data(operand_data_size, 0);
2028
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002029 if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
Sean Callanan79763a42011-05-23 21:40:23 +00002030 {
2031 uint8_t *data_bytes = data.GetBytes();
2032
2033 for (size_t index = 0;
2034 index < operand_data_size;
2035 ++index)
2036 {
2037 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2038 }
2039 }
2040 else
2041 {
2042 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2043 }
2044
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002045 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00002046
Sean Callanane3333d62012-06-08 22:20:41 +00002047 size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2048
2049 const size_t mask = (align - 1);
2050 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002051 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00002052 offset = aligned_offset;
2053
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002054 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
Sean Callanan79763a42011-05-23 21:40:23 +00002055
Sean Callanancc427fa2011-07-30 02:42:06 +00002056 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callanan79763a42011-05-23 21:40:23 +00002057
Sean Callanan1582ee62013-04-18 22:06:33 +00002058 Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
Sean Callanan79763a42011-05-23 21:40:23 +00002059
2060 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2061
2062 operand_constant_fp->replaceAllUsesWith(fp_load);
2063 }
2064 }
2065
2066 return true;
2067}
2068
Sean Callanan7ea35012010-07-27 21:39:39 +00002069static bool isGuardVariableRef(Value *V)
Sean Callananddb46ef2010-07-24 01:37:44 +00002070{
Sean Callanan77eaf442011-07-08 00:39:14 +00002071 Constant *Old = NULL;
Sean Callananddb46ef2010-07-24 01:37:44 +00002072
Sean Callananafe16a72010-11-17 23:00:36 +00002073 if (!(Old = dyn_cast<Constant>(V)))
Sean Callananddb46ef2010-07-24 01:37:44 +00002074 return false;
2075
Sean Callanan77eaf442011-07-08 00:39:14 +00002076 ConstantExpr *CE = NULL;
Sean Callanane2ef6e32010-09-23 03:01:22 +00002077
2078 if ((CE = dyn_cast<ConstantExpr>(V)))
2079 {
2080 if (CE->getOpcode() != Instruction::BitCast)
2081 return false;
2082
Sean Callananafe16a72010-11-17 23:00:36 +00002083 Old = CE->getOperand(0);
Sean Callanane2ef6e32010-09-23 03:01:22 +00002084 }
2085
Sean Callananafe16a72010-11-17 23:00:36 +00002086 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callananddb46ef2010-07-24 01:37:44 +00002087
2088 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2089 return false;
2090
2091 return true;
2092}
2093
Sean Callanan79763a42011-05-23 21:40:23 +00002094void
2095IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callananddb46ef2010-07-24 01:37:44 +00002096{
Sean Callanan79763a42011-05-23 21:40:23 +00002097 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callananddb46ef2010-07-24 01:37:44 +00002098
2099 Value::use_iterator ui;
2100
2101 for (ui = guard_load->use_begin();
2102 ui != guard_load->use_end();
2103 ++ui)
Sean Callananb27a62f2010-07-27 01:17:28 +00002104 {
Greg Claytone6371122010-07-30 20:30:44 +00002105 if (isa<Constant>(*ui))
Sean Callananb27a62f2010-07-27 01:17:28 +00002106 {
2107 // do nothing for the moment
2108 }
2109 else
2110 {
2111 ui->replaceUsesOfWith(guard_load, zero);
2112 }
2113 }
Sean Callananddb46ef2010-07-24 01:37:44 +00002114
2115 guard_load->eraseFromParent();
2116}
2117
2118static void ExciseGuardStore(Instruction* guard_store)
2119{
2120 guard_store->eraseFromParent();
2121}
2122
2123bool
Sean Callanan79763a42011-05-23 21:40:23 +00002124IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callananddb46ef2010-07-24 01:37:44 +00002125{
2126 ///////////////////////////////////////////////////////
2127 // Eliminate any reference to guard variables found.
2128 //
2129
Sean Callanan7ea35012010-07-27 21:39:39 +00002130 BasicBlock::iterator ii;
Sean Callananddb46ef2010-07-24 01:37:44 +00002131
Sean Callanan7ea35012010-07-27 21:39:39 +00002132 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callananddb46ef2010-07-24 01:37:44 +00002133 typedef InstrList::iterator InstrIterator;
2134
2135 InstrList guard_loads;
2136 InstrList guard_stores;
2137
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002138 for (ii = basic_block.begin();
2139 ii != basic_block.end();
Sean Callananddb46ef2010-07-24 01:37:44 +00002140 ++ii)
2141 {
2142 Instruction &inst = *ii;
2143
2144 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2145 if (isGuardVariableRef(load->getPointerOperand()))
2146 guard_loads.push_back(&inst);
2147
2148 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2149 if (isGuardVariableRef(store->getPointerOperand()))
2150 guard_stores.push_back(&inst);
2151 }
2152
2153 InstrIterator iter;
2154
2155 for (iter = guard_loads.begin();
2156 iter != guard_loads.end();
2157 ++iter)
Sean Callanan79763a42011-05-23 21:40:23 +00002158 TurnGuardLoadIntoZero(*iter);
Sean Callananddb46ef2010-07-24 01:37:44 +00002159
2160 for (iter = guard_stores.begin();
2161 iter != guard_stores.end();
2162 ++iter)
2163 ExciseGuardStore(*iter);
2164
2165 return true;
2166}
2167
Sean Callanan3989fb92011-01-27 01:07:04 +00002168// This function does not report errors; its callers are responsible.
Sean Callananafe16a72010-11-17 23:00:36 +00002169bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002170IRForTarget::UnfoldConstant(Constant *old_constant,
2171 FunctionValueCache &value_maker,
2172 FunctionValueCache &entry_instruction_finder)
Sean Callanan7618f4e2010-07-14 23:40:29 +00002173{
Greg Clayton5160ce52013-03-27 23:08:40 +00002174 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002175
2176 Value::use_iterator ui;
2177
Sean Callanan2235f322010-08-11 03:57:18 +00002178 SmallVector<User*, 16> users;
2179
2180 // We do this because the use list might change, invalidating our iterator.
2181 // Much better to keep a work list ourselves.
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002182 for (ui = old_constant->use_begin();
2183 ui != old_constant->use_end();
Sean Callanan7618f4e2010-07-14 23:40:29 +00002184 ++ui)
Sean Callanan2235f322010-08-11 03:57:18 +00002185 users.push_back(*ui);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002186
Johnny Chen44805302011-07-19 19:48:13 +00002187 for (size_t i = 0;
Sean Callanan2235f322010-08-11 03:57:18 +00002188 i < users.size();
2189 ++i)
2190 {
2191 User *user = users[i];
2192
Sean Callanan7618f4e2010-07-14 23:40:29 +00002193 if (Constant *constant = dyn_cast<Constant>(user))
2194 {
2195 // synthesize a new non-constant equivalent of the constant
2196
2197 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2198 {
2199 switch (constant_expr->getOpcode())
2200 {
2201 default:
2202 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002203 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002204 return false;
2205 case Instruction::BitCast:
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002206 {
2207 FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2208 // UnaryExpr
2209 // OperandList[0] is value
2210
2211 if (constant_expr->getOperand(0) != old_constant)
2212 return constant_expr;
2213
2214 return new BitCastInst(value_maker.GetValue(function),
2215 constant_expr->getType(),
2216 "",
2217 llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2218 });
Sean Callanan7618f4e2010-07-14 23:40:29 +00002219
Sean Callanan0e016fe2013-07-15 23:31:47 +00002220 if (!UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder))
2221 return false;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002222 }
2223 break;
2224 case Instruction::GetElementPtr:
2225 {
2226 // GetElementPtrConstantExpr
2227 // OperandList[0] is base
2228 // OperandList[1]... are indices
2229
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002230 FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2231 Value *ptr = constant_expr->getOperand(0);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002232
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002233 if (ptr == old_constant)
2234 ptr = value_maker.GetValue(function);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002235
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002236 std::vector<Value*> index_vector;
2237
2238 unsigned operand_index;
2239 unsigned num_operands = constant_expr->getNumOperands();
2240
2241 for (operand_index = 1;
2242 operand_index < num_operands;
2243 ++operand_index)
2244 {
2245 Value *operand = constant_expr->getOperand(operand_index);
2246
2247 if (operand == old_constant)
2248 operand = value_maker.GetValue(function);
2249
2250 index_vector.push_back(operand);
2251 }
2252
2253 ArrayRef <Value*> indices(index_vector);
2254
2255 return GetElementPtrInst::Create(ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2256 });
Sean Callanan7618f4e2010-07-14 23:40:29 +00002257
Sean Callanan0e016fe2013-07-15 23:31:47 +00002258 if (!UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder))
2259 return false;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002260 }
2261 break;
2262 }
2263 }
2264 else
2265 {
2266 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002267 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002268 return false;
2269 }
2270 }
2271 else
2272 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002273 if (Instruction *inst = llvm::dyn_cast<Instruction>(user))
2274 {
2275 inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent()));
2276 }
2277 else
2278 {
2279 if (log)
2280 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str());
2281 return false;
2282 }
Sean Callanan7618f4e2010-07-14 23:40:29 +00002283 }
2284 }
2285
Sean Callanan0e016fe2013-07-15 23:31:47 +00002286 if (!isa<GlobalValue>(old_constant))
2287 {
2288 old_constant->destroyConstant();
2289 }
2290
Sean Callanan7618f4e2010-07-14 23:40:29 +00002291 return true;
2292}
2293
Sean Callanan549c9f72010-07-13 21:41:46 +00002294bool
Sean Callanan79763a42011-05-23 21:40:23 +00002295IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan549c9f72010-07-13 21:41:46 +00002296{
Sean Callanan9e6ed532010-09-13 21:34:21 +00002297 if (!m_resolve_vars)
2298 return true;
2299
Greg Clayton5160ce52013-03-27 23:08:40 +00002300 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan549c9f72010-07-13 21:41:46 +00002301
2302 m_decl_map->DoStructLayout();
2303
2304 if (log)
2305 log->Printf("Element arrangement:");
2306
2307 uint32_t num_elements;
2308 uint32_t element_index;
2309
2310 size_t size;
2311 off_t alignment;
2312
2313 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2314 return false;
2315
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002316 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan549c9f72010-07-13 21:41:46 +00002317
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002318 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002319 {
2320 if (m_error_stream)
2321 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2322
Sean Callanan549c9f72010-07-13 21:41:46 +00002323 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002324 }
2325
Sean Callanan7ea35012010-07-27 21:39:39 +00002326 Argument *argument = iter;
Sean Callanan549c9f72010-07-13 21:41:46 +00002327
Sean Callananfc55f5d2010-09-21 00:44:12 +00002328 if (argument->getName().equals("this"))
2329 {
2330 ++iter;
2331
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002332 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002333 {
2334 if (m_error_stream)
2335 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2336
Sean Callananfc55f5d2010-09-21 00:44:12 +00002337 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002338 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002339
2340 argument = iter;
2341 }
Sean Callanan17827832010-12-13 22:46:15 +00002342 else if (argument->getName().equals("self"))
2343 {
2344 ++iter;
2345
2346 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002347 {
2348 if (m_error_stream)
2349 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2350
Sean Callanan17827832010-12-13 22:46:15 +00002351 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002352 }
Sean Callanan17827832010-12-13 22:46:15 +00002353
2354 if (!iter->getName().equals("_cmd"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002355 {
2356 if (m_error_stream)
2357 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2358
Sean Callanan17827832010-12-13 22:46:15 +00002359 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002360 }
Sean Callanan17827832010-12-13 22:46:15 +00002361
2362 ++iter;
2363
2364 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002365 {
2366 if (m_error_stream)
2367 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2368
Sean Callanan17827832010-12-13 22:46:15 +00002369 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002370 }
Sean Callanan17827832010-12-13 22:46:15 +00002371
2372 argument = iter;
2373 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002374
Greg Clayton7b462cc2010-10-15 22:48:33 +00002375 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002376 {
2377 if (m_error_stream)
2378 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2379
Sean Callanan549c9f72010-07-13 21:41:46 +00002380 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002381 }
2382
Sean Callanan549c9f72010-07-13 21:41:46 +00002383 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002384 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan549c9f72010-07-13 21:41:46 +00002385
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002386 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +00002387 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan549c9f72010-07-13 21:41:46 +00002388
Sean Callananafe16a72010-11-17 23:00:36 +00002389 if (!FirstEntryInstruction)
Sean Callanan3989fb92011-01-27 01:07:04 +00002390 {
2391 if (m_error_stream)
2392 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2393
Sean Callanan549c9f72010-07-13 21:41:46 +00002394 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002395 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002396
Sean Callanan79763a42011-05-23 21:40:23 +00002397 LLVMContext &context(m_module->getContext());
Sean Callanancc427fa2011-07-30 02:42:06 +00002398 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan549c9f72010-07-13 21:41:46 +00002399
2400 if (!offset_type)
Sean Callanan3989fb92011-01-27 01:07:04 +00002401 {
2402 if (m_error_stream)
2403 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2404
Sean Callanan549c9f72010-07-13 21:41:46 +00002405 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002406 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002407
2408 for (element_index = 0; element_index < num_elements; ++element_index)
2409 {
Sean Callanan77eaf442011-07-08 00:39:14 +00002410 const clang::NamedDecl *decl = NULL;
2411 Value *value = NULL;
Sean Callanan549c9f72010-07-13 21:41:46 +00002412 off_t offset;
Greg Clayton7b462cc2010-10-15 22:48:33 +00002413 lldb_private::ConstString name;
Sean Callanan549c9f72010-07-13 21:41:46 +00002414
Sean Callanan823bb4c2010-08-30 22:17:16 +00002415 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan3989fb92011-01-27 01:07:04 +00002416 {
2417 if (m_error_stream)
2418 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2419
Sean Callanan549c9f72010-07-13 21:41:46 +00002420 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002421 }
2422
Sean Callanan549c9f72010-07-13 21:41:46 +00002423 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002424 log->Printf(" \"%s\" (\"%s\") placed at %" PRId64,
Greg Clayton7b462cc2010-10-15 22:48:33 +00002425 name.GetCString(),
Sean Callananc70ed462011-10-25 18:36:40 +00002426 decl->getNameAsString().c_str(),
Sean Callanan549c9f72010-07-13 21:41:46 +00002427 offset);
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002428
Sean Callananc70ed462011-10-25 18:36:40 +00002429 if (value)
Sean Callanan92adcac2011-01-13 08:53:35 +00002430 {
Sean Callananc70ed462011-10-25 18:36:40 +00002431 if (log)
2432 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan92adcac2011-01-13 08:53:35 +00002433
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002434 FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * {
2435 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2436 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2437 // entry in order to produce the static variable that the AST thinks it is accessing.
Sean Callananc70ed462011-10-25 18:36:40 +00002438
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002439 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function));
Sean Callananc70ed462011-10-25 18:36:40 +00002440
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002441 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
2442 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument,
2443 offset_int,
2444 "",
2445 entry_instruction);
2446
2447 if (name == m_result_name && !m_result_is_pointer)
2448 {
2449 BitCastInst *bit_cast = new BitCastInst(get_element_ptr,
2450 value->getType()->getPointerTo(),
2451 "",
2452 entry_instruction);
2453
2454 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
2455
2456 return load;
2457 }
2458 else
2459 {
2460 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction);
2461
2462 return bit_cast;
2463 }
2464 });
Sean Callananc70ed462011-10-25 18:36:40 +00002465
2466 if (Constant *constant = dyn_cast<Constant>(value))
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002467 {
2468 UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder);
2469 }
2470 else if (Instruction *instruction = dyn_cast<Instruction>(value))
2471 {
2472 value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent()));
2473 }
Sean Callananc70ed462011-10-25 18:36:40 +00002474 else
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002475 {
2476 if (log)
2477 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str());
2478 return false;
2479 }
Sean Callananc70ed462011-10-25 18:36:40 +00002480
2481 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2482 var->eraseFromParent();
2483 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002484 }
2485
2486 if (log)
Sylvestre Ledru779f9212013-10-31 23:55:19 +00002487 log->Printf("Total structure [align %" PRId64 ", size %zu]", alignment, size);
Sean Callanan549c9f72010-07-13 21:41:46 +00002488
2489 return true;
2490}
2491
Sean Callanan79763a42011-05-23 21:40:23 +00002492llvm::Constant *
Greg Clayton5160ce52013-03-27 23:08:40 +00002493IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
Sean Callanan79763a42011-05-23 21:40:23 +00002494{
Sean Callanan090e1192013-12-20 04:07:43 +00002495 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(), 64);
Sean Callanan79763a42011-05-23 21:40:23 +00002496
2497 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanancc427fa2011-07-30 02:42:06 +00002498
2499 llvm::Constant *offset_array[1];
2500
2501 offset_array[0] = offset_int;
2502
2503 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2504
2505 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callanan79763a42011-05-23 21:40:23 +00002506 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2507
2508 return reloc_getbitcast;
2509}
2510
2511bool
2512IRForTarget::CompleteDataAllocation ()
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002513{
Greg Clayton5160ce52013-03-27 23:08:40 +00002514 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002515
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002516 if (!m_data_allocator.GetStream().GetSize())
Sean Callanan79763a42011-05-23 21:40:23 +00002517 return true;
2518
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002519 lldb::addr_t allocation = m_data_allocator.Allocate();
Sean Callanan79763a42011-05-23 21:40:23 +00002520
2521 if (log)
2522 {
2523 if (allocation)
2524 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2525 else
2526 log->Printf("Failed to allocate static data");
2527 }
2528
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002529 if (!allocation || allocation == LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +00002530 return false;
2531
Sean Callanan090e1192013-12-20 04:07:43 +00002532 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(), 64);
Sean Callanan79763a42011-05-23 21:40:23 +00002533
2534 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2535 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2536
2537 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2538
2539 m_reloc_placeholder->eraseFromParent();
2540
2541 return true;
2542}
2543
Sean Callanan2ab712f22010-07-03 01:35:46 +00002544bool
Sean Callanan3d654b32012-09-24 22:25:51 +00002545IRForTarget::StripAllGVs (Module &llvm_module)
2546{
Greg Clayton5160ce52013-03-27 23:08:40 +00002547 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3d654b32012-09-24 22:25:51 +00002548 std::vector<GlobalVariable *> global_vars;
2549 std::set<GlobalVariable *>erased_vars;
2550
2551 bool erased = true;
2552
2553 while (erased)
2554 {
2555 erased = false;
2556
2557 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2558 gi != ge;
2559 ++gi)
2560 {
2561 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2562
2563 global_var->removeDeadConstantUsers();
2564
2565 if (global_var->use_empty())
2566 {
2567 if (log)
2568 log->Printf("Did remove %s",
2569 PrintValue(global_var).c_str());
2570 global_var->eraseFromParent();
2571 erased = true;
2572 break;
2573 }
2574 }
2575 }
2576
2577 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2578 gi != ge;
2579 ++gi)
2580 {
2581 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2582
2583 GlobalValue::use_iterator ui = global_var->use_begin();
2584
Jim Inghamd77557d2012-11-26 19:54:04 +00002585 if (log)
2586 log->Printf("Couldn't remove %s because of %s",
2587 PrintValue(global_var).c_str(),
2588 PrintValue(*ui).c_str());
Sean Callanan3d654b32012-09-24 22:25:51 +00002589 }
2590
2591 return true;
2592}
2593
2594bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002595IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002596{
Greg Clayton5160ce52013-03-27 23:08:40 +00002597 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002598
Sean Callanan79763a42011-05-23 21:40:23 +00002599 m_module = &llvm_module;
Micah Villmow8468dbe2012-10-08 16:28:57 +00002600 m_target_data.reset(new DataLayout(m_module));
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002601
Sean Callananc70ed462011-10-25 18:36:40 +00002602 if (log)
2603 {
2604 std::string s;
2605 raw_string_ostream oss(s);
2606
2607 m_module->print(oss, NULL);
2608
2609 oss.flush();
2610
2611 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2612 }
2613
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002614 Function* main_function = m_module->getFunction(StringRef(m_func_name.c_str()));
2615
2616 if (!main_function)
2617 {
2618 if (log)
2619 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
2620
2621 if (m_error_stream)
2622 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
2623
2624 return false;
2625 }
2626
2627 if (!FixFunctionLinkage (*main_function))
2628 {
2629 if (log)
2630 log->Printf("Couldn't fix the linkage for the function");
2631
2632 return false;
2633 }
2634
Sean Callanancc427fa2011-07-30 02:42:06 +00002635 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00002636
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002637 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
Sean Callanan79763a42011-05-23 21:40:23 +00002638 intptr_ty,
Sean Callanan3d654b32012-09-24 22:25:51 +00002639 false /* IsConstant */,
Sean Callanan79763a42011-05-23 21:40:23 +00002640 GlobalVariable::InternalLinkage,
2641 Constant::getNullValue(intptr_ty),
2642 "reloc_placeholder",
2643 NULL /* InsertBefore */,
Sean Callanan3d654b32012-09-24 22:25:51 +00002644 GlobalVariable::NotThreadLocal /* ThreadLocal */,
Sean Callanan79763a42011-05-23 21:40:23 +00002645 0 /* AddressSpace */);
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002646
Sean Callanand1e5b432010-08-12 01:56:52 +00002647 ////////////////////////////////////////////////////////////
Greg Clayton7b462cc2010-10-15 22:48:33 +00002648 // Replace $__lldb_expr_result with a persistent variable
Sean Callanand1e5b432010-08-12 01:56:52 +00002649 //
2650
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002651 if (!CreateResultVariable(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002652 {
2653 if (log)
2654 log->Printf("CreateResultVariable() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002655
2656 // CreateResultVariable() reports its own errors, so we don't do so here
2657
Sean Callanand1e5b432010-08-12 01:56:52 +00002658 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002659 }
Sean Callanan6e6d4a62012-07-21 02:02:15 +00002660
Sean Callananea685ae2011-11-01 17:33:54 +00002661 if (log && log->GetVerbose())
Sean Callanan79763a42011-05-23 21:40:23 +00002662 {
2663 std::string s;
2664 raw_string_ostream oss(s);
2665
2666 m_module->print(oss, NULL);
2667
2668 oss.flush();
2669
2670 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2671 }
2672
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002673 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2674 fi != fe;
2675 ++fi)
2676 {
2677 llvm::Function *function = fi;
2678
2679 if (function->begin() == function->end())
2680 continue;
2681
2682 Function::iterator bbi;
2683
2684 for (bbi = function->begin();
2685 bbi != function->end();
2686 ++bbi)
2687 {
2688 if (!RemoveGuards(*bbi))
2689 {
2690 if (log)
2691 log->Printf("RemoveGuards() failed");
2692
2693 // RemoveGuards() reports its own errors, so we don't do so here
2694
2695 return false;
2696 }
2697
2698 if (!RewritePersistentAllocs(*bbi))
2699 {
2700 if (log)
2701 log->Printf("RewritePersistentAllocs() failed");
2702
2703 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2704
2705 return false;
2706 }
2707
2708 if (!RemoveCXAAtExit(*bbi))
2709 {
2710 if (log)
2711 log->Printf("RemoveCXAAtExit() failed");
2712
2713 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2714
2715 return false;
2716 }
2717 }
2718 }
2719
Sean Callananafe16a72010-11-17 23:00:36 +00002720 ///////////////////////////////////////////////////////////////////////////////
2721 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2722 //
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002723
2724 if (!RewriteObjCConstStrings())
Sean Callanan17827832010-12-13 22:46:15 +00002725 {
2726 if (log)
2727 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002728
2729 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2730
Sean Callananafe16a72010-11-17 23:00:36 +00002731 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002732 }
Sean Callananafe16a72010-11-17 23:00:36 +00002733
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002734 ///////////////////////////////
2735 // Resolve function pointers
2736 //
2737
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002738 if (!ResolveFunctionPointers(llvm_module))
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002739 {
2740 if (log)
2741 log->Printf("ResolveFunctionPointers() failed");
2742
2743 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2744
2745 return false;
2746 }
2747
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002748 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2749 fi != fe;
2750 ++fi)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002751 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002752 llvm::Function *function = fi;
2753
2754 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2755 bbi != bbe;
2756 ++bbi)
Sean Callanan17827832010-12-13 22:46:15 +00002757 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002758 if (!RewriteObjCSelectors(*bbi))
2759 {
2760 if (log)
2761 log->Printf("RewriteObjCSelectors() failed");
2762
2763 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2764
2765 return false;
2766 }
Sean Callanan17827832010-12-13 22:46:15 +00002767 }
Sean Callananbad134f2012-07-27 19:25:24 +00002768 }
Sean Callanan2235f322010-08-11 03:57:18 +00002769
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002770 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2771 fi != fe;
2772 ++fi)
Sean Callananbad134f2012-07-27 19:25:24 +00002773 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002774 llvm::Function *function = fi;
Sean Callanan79763a42011-05-23 21:40:23 +00002775
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002776 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2777 bbi != bbe;
2778 ++bbi)
Sean Callanan79763a42011-05-23 21:40:23 +00002779 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002780 if (!ResolveCalls(*bbi))
2781 {
2782 if (log)
2783 log->Printf("ResolveCalls() failed");
2784
2785 // ResolveCalls() reports its own errors, so we don't do so here
2786
2787 return false;
2788 }
Sean Callanan79763a42011-05-23 21:40:23 +00002789
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002790 if (!ReplaceStaticLiterals(*bbi))
2791 {
2792 if (log)
2793 log->Printf("ReplaceStaticLiterals() failed");
2794
2795 return false;
2796 }
Sean Callanan79763a42011-05-23 21:40:23 +00002797 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002798 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002799
2800 ////////////////////////////////////////////////////////////////////////
2801 // Run function-level passes that only make sense on the main function
Sean Callanan038df5032010-09-30 21:18:25 +00002802 //
2803
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002804 if (!ResolveExternals(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002805 {
2806 if (log)
2807 log->Printf("ResolveExternals() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002808
2809 // ResolveExternals() reports its own errors, so we don't do so here
2810
Sean Callanana4e55172010-11-08 00:31:32 +00002811 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002812 }
Sean Callanana4e55172010-11-08 00:31:32 +00002813
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002814 if (!ReplaceVariables(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002815 {
2816 if (log)
2817 log->Printf("ReplaceVariables() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002818
2819 // ReplaceVariables() reports its own errors, so we don't do so here
2820
Sean Callanan038df5032010-09-30 21:18:25 +00002821 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002822 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002823
Sean Callanan79763a42011-05-23 21:40:23 +00002824 if (!ReplaceStrings())
2825 {
2826 if (log)
2827 log->Printf("ReplaceStrings() failed");
2828
2829 return false;
2830 }
2831
2832 if (!CompleteDataAllocation())
2833 {
2834 if (log)
2835 log->Printf("CompleteDataAllocation() failed");
2836
2837 return false;
2838 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002839
Sean Callanan3d654b32012-09-24 22:25:51 +00002840 if (!StripAllGVs(llvm_module))
2841 {
2842 if (log)
2843 log->Printf("StripAllGVs() failed");
2844 }
2845
Sean Callananea685ae2011-11-01 17:33:54 +00002846 if (log && log->GetVerbose())
Sean Callanan549c9f72010-07-13 21:41:46 +00002847 {
Sean Callanancc54bd32010-07-28 01:00:59 +00002848 std::string s;
2849 raw_string_ostream oss(s);
Sean Callanan549c9f72010-07-13 21:41:46 +00002850
Sean Callanan79763a42011-05-23 21:40:23 +00002851 m_module->print(oss, NULL);
Sean Callanancc54bd32010-07-28 01:00:59 +00002852
2853 oss.flush();
2854
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002855 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan2ab712f22010-07-03 01:35:46 +00002856 }
2857
2858 return true;
2859}
2860
2861void
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002862IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002863{
2864}
2865
2866PassManagerType
2867IRForTarget::getPotentialPassManagerType() const
2868{
2869 return PMT_ModulePassManager;
2870}