blob: da9d3f47cfbbd2827a9b441bd874fa32fdd4b6e1 [file] [log] [blame]
Sean Callanan3bfdaa22011-09-15 02:13:07 +00001//===-- IRForTarget.cpp -----------------------------------------*- C++ -*-===//
Sean Callanan2ab712f22010-07-03 01:35:46 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Expression/IRForTarget.h"
11
12#include "llvm/Support/raw_ostream.h"
Chandler Carruth1e157582013-01-02 12:20:07 +000013#include "llvm/IR/Constants.h"
14#include "llvm/IR/DataLayout.h"
15#include "llvm/IR/InstrTypes.h"
16#include "llvm/IR/Instructions.h"
17#include "llvm/IR/Intrinsics.h"
18#include "llvm/IR/Module.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000019#include "llvm/PassManager.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000020#include "llvm/Transforms/IPO.h"
Chandler Carruth1e157582013-01-02 12:20:07 +000021#include "llvm/IR/ValueSymbolTable.h"
Sean Callanan549c9f72010-07-13 21:41:46 +000022
23#include "clang/AST/ASTContext.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000024
25#include "lldb/Core/dwarf.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000026#include "lldb/Core/ConstString.h"
27#include "lldb/Core/DataBufferHeap.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000028#include "lldb/Core/Log.h"
29#include "lldb/Core/Scalar.h"
30#include "lldb/Core/StreamString.h"
31#include "lldb/Expression/ClangExpressionDeclMap.h"
Sean Callanan8dfb68e2013-03-19 00:10:07 +000032#include "lldb/Expression/IRExecutionUnit.h"
Sean Callanan3bfdaa22011-09-15 02:13:07 +000033#include "lldb/Expression/IRInterpreter.h"
Sean Callanan79763a42011-05-23 21:40:23 +000034#include "lldb/Host/Endian.h"
Sean Callanan63697e52011-05-07 01:06:41 +000035#include "lldb/Symbol/ClangASTContext.h"
Greg Clayton57ee3062013-07-11 22:46:58 +000036#include "lldb/Symbol/ClangASTType.h"
Sean Callanan2ab712f22010-07-03 01:35:46 +000037
38#include <map>
39
40using namespace llvm;
41
Sean Callananeaacbc92010-08-18 18:50:51 +000042static char ID;
43
Sean Callanan8dfb68e2013-03-19 00:10:07 +000044IRForTarget::StaticDataAllocator::StaticDataAllocator(lldb_private::IRExecutionUnit &execution_unit) :
45 m_execution_unit(execution_unit),
Sean Callanan1582ee62013-04-18 22:06:33 +000046 m_stream_string(lldb_private::Stream::eBinary, execution_unit.GetAddressByteSize(), execution_unit.GetByteOrder()),
Sean Callanan8dfb68e2013-03-19 00:10:07 +000047 m_allocation(LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +000048{
49}
50
Sean Callanan1f9db3e2013-06-28 21:44:15 +000051IRForTarget::FunctionValueCache::FunctionValueCache(Maker const &maker) :
52 m_maker(maker),
53 m_values()
54{
55}
56
57IRForTarget::FunctionValueCache::~FunctionValueCache()
58{
59}
60
61llvm::Value *IRForTarget::FunctionValueCache::GetValue(llvm::Function *function)
62{
63 if (!m_values.count(function))
64 {
65 llvm::Value *ret = m_maker(function);
66 m_values[function] = ret;
67 return ret;
68 }
69 return m_values[function];
70}
71
Sean Callanan8dfb68e2013-03-19 00:10:07 +000072lldb::addr_t IRForTarget::StaticDataAllocator::Allocate()
Sean Callanan79763a42011-05-23 21:40:23 +000073{
Sean Callanan8dfb68e2013-03-19 00:10:07 +000074 lldb_private::Error err;
75
76 if (m_allocation != LLDB_INVALID_ADDRESS)
77 {
78 m_execution_unit.FreeNow(m_allocation);
79 m_allocation = LLDB_INVALID_ADDRESS;
80 }
81
82 m_allocation = m_execution_unit.WriteNow((const uint8_t*)m_stream_string.GetData(), m_stream_string.GetSize(), err);
83
84 return m_allocation;
Sean Callanan79763a42011-05-23 21:40:23 +000085}
86
Sean Callanan1f9db3e2013-06-28 21:44:15 +000087static llvm::Value *FindEntryInstruction (llvm::Function *function)
88{
89 if (function->empty())
90 return NULL;
91
92 return function->getEntryBlock().getFirstNonPHIOrDbg();
93}
94
Greg Clayton1b95a6f2010-11-19 01:05:25 +000095IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
96 bool resolve_vars,
Sean Callanan8dfb68e2013-03-19 00:10:07 +000097 lldb_private::IRExecutionUnit &execution_unit,
Sean Callanan3989fb92011-01-27 01:07:04 +000098 lldb_private::Stream *error_stream,
Greg Clayton1b95a6f2010-11-19 01:05:25 +000099 const char *func_name) :
Sean Callanane2ef6e32010-09-23 03:01:22 +0000100 ModulePass(ID),
Stephen Wilson71c21d12011-04-11 19:41:40 +0000101 m_resolve_vars(resolve_vars),
102 m_func_name(func_name),
Sean Callanan79763a42011-05-23 21:40:23 +0000103 m_module(NULL),
Johnny Chen44805302011-07-19 19:48:13 +0000104 m_decl_map(decl_map),
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000105 m_data_allocator(execution_unit),
Sean Callananafe16a72010-11-17 23:00:36 +0000106 m_CFStringCreateWithBytes(NULL),
Sean Callanan1a8d4092010-08-27 01:01:44 +0000107 m_sel_registerName(NULL),
Sean Callanan439dcae2013-12-20 19:55:02 +0000108 m_intptr_ty(NULL),
Stephen Wilson71c21d12011-04-11 19:41:40 +0000109 m_error_stream(error_stream),
Sean Callanan63697e52011-05-07 01:06:41 +0000110 m_result_store(NULL),
111 m_result_is_pointer(false),
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000112 m_reloc_placeholder(NULL),
113 m_entry_instruction_finder (FindEntryInstruction)
Sean Callanan2ab712f22010-07-03 01:35:46 +0000114{
115}
116
Sean Callanan038df5032010-09-30 21:18:25 +0000117/* Handy utility functions used at several places in the code */
Sean Callanan2235f322010-08-11 03:57:18 +0000118
119static std::string
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000120PrintValue(const Value *value, bool truncate = false)
Sean Callanan2235f322010-08-11 03:57:18 +0000121{
122 std::string s;
Jim Ingham28eb5712012-10-12 17:34:26 +0000123 if (value)
124 {
125 raw_string_ostream rso(s);
126 value->print(rso);
127 rso.flush();
128 if (truncate)
129 s.resize(s.length() - 1);
130 }
Sean Callanan2235f322010-08-11 03:57:18 +0000131 return s;
132}
133
Sean Callanan038df5032010-09-30 21:18:25 +0000134static std::string
Greg Clayton57ee3062013-07-11 22:46:58 +0000135PrintType(const llvm::Type *type, bool truncate = false)
Sean Callanan038df5032010-09-30 21:18:25 +0000136{
137 std::string s;
138 raw_string_ostream rso(s);
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000139 type->print(rso);
Sean Callanan038df5032010-09-30 21:18:25 +0000140 rso.flush();
141 if (truncate)
142 s.resize(s.length() - 1);
143 return s;
144}
145
Sean Callanan2ab712f22010-07-03 01:35:46 +0000146IRForTarget::~IRForTarget()
147{
148}
149
Sean Callanan79763a42011-05-23 21:40:23 +0000150bool
151IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
152{
Sean Callanan79763a42011-05-23 21:40:23 +0000153 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
154
Sean Callanan7f27d602011-11-19 02:54:21 +0000155 std::string name = llvm_function.getName().str();
Sean Callanan79763a42011-05-23 21:40:23 +0000156
157 return true;
158}
159
Sean Callanand1e5b432010-08-12 01:56:52 +0000160bool
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000161IRForTarget::GetFunctionAddress (llvm::Function *fun,
162 uint64_t &fun_addr,
163 lldb_private::ConstString &name,
164 Constant **&value_ptr)
165{
Greg Clayton5160ce52013-03-27 23:08:40 +0000166 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000167
168 fun_addr = LLDB_INVALID_ADDRESS;
169 name.Clear();
170 value_ptr = NULL;
171
172 if (fun->isIntrinsic())
173 {
174 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
175
176 switch (intrinsic_id)
177 {
178 default:
179 if (log)
180 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
181
182 if (m_error_stream)
183 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
184
185 return false;
186 case Intrinsic::memcpy:
187 {
188 static lldb_private::ConstString g_memcpy_str ("memcpy");
189 name = g_memcpy_str;
190 }
191 break;
Sean Callanana6cbf062011-11-16 00:20:50 +0000192 case Intrinsic::memset:
193 {
194 static lldb_private::ConstString g_memset_str ("memset");
195 name = g_memset_str;
196 }
197 break;
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000198 }
199
200 if (log && name)
201 log->Printf("Resolved intrinsic name \"%s\"", name.GetCString());
202 }
203 else
204 {
205 name.SetCStringWithLength (fun->getName().data(), fun->getName().size());
206 }
207
208 // Find the address of the function.
209
210 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000211
212 if (fun_decl)
213 {
Sean Callananc70ed462011-10-25 18:36:40 +0000214 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_addr))
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000215 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000216 lldb_private::ConstString altnernate_name;
Greg Claytonf0705c82011-10-22 03:33:13 +0000217 bool found_it = m_decl_map->GetFunctionAddress (name, fun_addr);
218 if (!found_it)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000219 {
Greg Claytonf0705c82011-10-22 03:33:13 +0000220 // Check for an alternate mangling for "std::basic_string<char>"
221 // that is part of the itanium C++ name mangling scheme
222 const char *name_cstr = name.GetCString();
Jim Ingham28eb5712012-10-12 17:34:26 +0000223 if (name_cstr && strncmp(name_cstr, "_ZNKSbIcE", strlen("_ZNKSbIcE")) == 0)
Greg Claytonf0705c82011-10-22 03:33:13 +0000224 {
225 std::string alternate_mangling("_ZNKSs");
226 alternate_mangling.append (name_cstr + strlen("_ZNKSbIcE"));
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000227 altnernate_name.SetCString(alternate_mangling.c_str());
228 found_it = m_decl_map->GetFunctionAddress (altnernate_name, fun_addr);
Greg Claytonf0705c82011-10-22 03:33:13 +0000229 }
230 }
231
232 if (!found_it)
233 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000234 lldb_private::Mangled mangled_name(name);
235 lldb_private::Mangled alt_mangled_name(altnernate_name);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000236 if (log)
Greg Claytonf0705c82011-10-22 03:33:13 +0000237 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000238 if (alt_mangled_name)
239 log->Printf("Function \"%s\" (alternate name \"%s\") has no address",
240 mangled_name.GetName().GetCString(),
241 alt_mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000242 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000243 log->Printf("Function \"%s\" had no address",
244 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000245 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000246
247 if (m_error_stream)
Greg Claytonf0705c82011-10-22 03:33:13 +0000248 {
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000249 if (alt_mangled_name)
250 m_error_stream->Printf("error: call to a function '%s' (alternate name '%s') that is not present in the target\n",
251 mangled_name.GetName().GetCString(),
252 alt_mangled_name.GetName().GetCString());
Greg Claytonda1eb042013-04-23 21:48:38 +0000253 else if (mangled_name.GetMangledName())
254 m_error_stream->Printf("error: call to a function '%s' ('%s') that is not present in the target\n",
255 mangled_name.GetName().GetCString(),
256 mangled_name.GetMangledName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000257 else
Greg Clayton5e0c5e82012-07-18 20:47:40 +0000258 m_error_stream->Printf("error: call to a function '%s' that is not present in the target\n",
259 mangled_name.GetName().GetCString());
Greg Claytonf0705c82011-10-22 03:33:13 +0000260 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000261 return false;
262 }
263 }
264 }
265 else
266 {
267 if (!m_decl_map->GetFunctionAddress (name, fun_addr))
268 {
269 if (log)
270 log->Printf ("Metadataless function \"%s\" had no address", name.GetCString());
271
272 if (m_error_stream)
273 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", name.GetCString());
274
275 return false;
276 }
277 }
278
279 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000280 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), fun_addr);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000281
282 return true;
283}
284
285llvm::Constant *
286IRForTarget::BuildFunctionPointer (llvm::Type *type,
287 uint64_t ptr)
288{
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000289 PointerType *fun_ptr_ty = PointerType::getUnqual(type);
Sean Callanan439dcae2013-12-20 19:55:02 +0000290 Constant *fun_addr_int = ConstantInt::get(m_intptr_ty, ptr, false);
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000291 return ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
292}
293
Sean Callananfc8feb82011-10-31 22:11:40 +0000294void
295IRForTarget::RegisterFunctionMetadata(LLVMContext &context,
296 llvm::Value *function_ptr,
297 const char *name)
298{
Ed Mastea8553092014-03-10 17:24:16 +0000299 for (llvm::User *user : function_ptr->users())
Sean Callananfc8feb82011-10-31 22:11:40 +0000300 {
Sean Callananfc8feb82011-10-31 22:11:40 +0000301 if (Instruction *user_inst = dyn_cast<Instruction>(user))
302 {
Daniel Maleaf051dbc2013-06-03 20:45:54 +0000303 MDString* md_name = MDString::get(context, StringRef(name));
304
305 MDNode *metadata = MDNode::get(context, md_name);
306
Sean Callananfc8feb82011-10-31 22:11:40 +0000307 user_inst->setMetadata("lldb.call.realName", metadata);
308 }
309 else
310 {
311 RegisterFunctionMetadata (context, user, name);
312 }
313 }
314}
315
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000316bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000317IRForTarget::ResolveFunctionPointers(llvm::Module &llvm_module)
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000318{
Greg Clayton5160ce52013-03-27 23:08:40 +0000319 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000320
321 for (llvm::Module::iterator fi = llvm_module.begin();
322 fi != llvm_module.end();
323 ++fi)
324 {
325 Function *fun = fi;
326
327 bool is_decl = fun->isDeclaration();
328
329 if (log)
Sean Callanan7f27d602011-11-19 02:54:21 +0000330 log->Printf("Examining %s function %s", (is_decl ? "declaration" : "non-declaration"), fun->getName().str().c_str());
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000331
332 if (!is_decl)
333 continue;
334
335 if (fun->hasNUses(0))
336 continue; // ignore
337
338 uint64_t addr = LLDB_INVALID_ADDRESS;
339 lldb_private::ConstString name;
340 Constant **value_ptr = NULL;
341
342 if (!GetFunctionAddress(fun,
343 addr,
344 name,
345 value_ptr))
346 return false; // GetFunctionAddress reports its own errors
347
348 Constant *value = BuildFunctionPointer(fun->getFunctionType(), addr);
349
Sean Callananfc8feb82011-10-31 22:11:40 +0000350 RegisterFunctionMetadata (llvm_module.getContext(), fun, name.AsCString());
351
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000352 if (value_ptr)
353 *value_ptr = value;
Stefanus Du Toitfc6b7a02013-07-23 21:34:03 +0000354
355 // If we are replacing a function with the nobuiltin attribute, it may
356 // be called with the builtin attribute on call sites. Remove any such
357 // attributes since it's illegal to have a builtin call to something
358 // other than a nobuiltin function.
Jason Molenda12075f72013-10-22 03:11:55 +0000359 if (fun->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
360 llvm::Attribute builtin = llvm::Attribute::get(fun->getContext(), llvm::Attribute::Builtin);
Stefanus Du Toitfc6b7a02013-07-23 21:34:03 +0000361
Ed Mastea8553092014-03-10 17:24:16 +0000362 for (auto u : fun->users()) {
363 if (auto call = dyn_cast<CallInst>(u)) {
Stefanus Du Toitfc6b7a02013-07-23 21:34:03 +0000364 call->removeAttribute(AttributeSet::FunctionIndex, builtin);
365 }
366 }
367 }
Sean Callanan0c4d8d22011-08-04 21:37:47 +0000368
369 fun->replaceAllUsesWith(value);
370 }
371
372 return true;
373}
374
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000375
Sean Callanan63697e52011-05-07 01:06:41 +0000376clang::NamedDecl *
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000377IRForTarget::DeclForGlobal (const GlobalValue *global_val, Module *module)
Sean Callanan63697e52011-05-07 01:06:41 +0000378{
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000379 NamedMDNode *named_metadata = module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan63697e52011-05-07 01:06:41 +0000380
381 if (!named_metadata)
382 return NULL;
383
384 unsigned num_nodes = named_metadata->getNumOperands();
385 unsigned node_index;
386
387 for (node_index = 0;
388 node_index < num_nodes;
389 ++node_index)
390 {
391 MDNode *metadata_node = named_metadata->getOperand(node_index);
392
393 if (!metadata_node)
394 return NULL;
395
396 if (metadata_node->getNumOperands() != 2)
397 continue;
398
399 if (metadata_node->getOperand(0) != global_val)
400 continue;
401
402 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
403
404 if (!constant_int)
405 return NULL;
406
407 uintptr_t ptr = constant_int->getZExtValue();
408
409 return reinterpret_cast<clang::NamedDecl *>(ptr);
410 }
411
412 return NULL;
413}
414
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000415clang::NamedDecl *
416IRForTarget::DeclForGlobal (GlobalValue *global_val)
417{
418 return DeclForGlobal(global_val, m_module);
419}
420
Sean Callanane4ec90e2010-12-16 03:17:46 +0000421bool
Sean Callanan79763a42011-05-23 21:40:23 +0000422IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanand1e5b432010-08-12 01:56:52 +0000423{
Greg Clayton5160ce52013-03-27 23:08:40 +0000424 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand1e5b432010-08-12 01:56:52 +0000425
Sean Callanan9e6ed532010-09-13 21:34:21 +0000426 if (!m_resolve_vars)
427 return true;
428
429 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callananfc55f5d2010-09-21 00:44:12 +0000430
Sean Callanan79763a42011-05-23 21:40:23 +0000431 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananfc55f5d2010-09-21 00:44:12 +0000432
Sean Callanancc427fa2011-07-30 02:42:06 +0000433 std::string result_name_str;
Sean Callananfc55f5d2010-09-21 00:44:12 +0000434 const char *result_name = NULL;
435
436 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
437 vi != ve;
438 ++vi)
439 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000440 result_name_str = vi->first().str();
441 const char *value_name = result_name_str.c_str();
442
443 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000444 strncmp(value_name, "_ZGV", 4))
Sean Callanan92adcac2011-01-13 08:53:35 +0000445 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000446 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000447 m_result_is_pointer = true;
448 break;
449 }
450
Sean Callanancc427fa2011-07-30 02:42:06 +0000451 if (strstr(value_name, "$__lldb_expr_result") &&
Sean Callanan7273e2d2012-11-02 22:28:08 +0000452 strncmp(value_name, "_ZGV", 4))
Sean Callanan46ae9e52010-09-28 21:13:03 +0000453 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000454 result_name = value_name;
Sean Callanan92adcac2011-01-13 08:53:35 +0000455 m_result_is_pointer = false;
Sean Callanan46ae9e52010-09-28 21:13:03 +0000456 break;
457 }
Sean Callananfc55f5d2010-09-21 00:44:12 +0000458 }
459
460 if (!result_name)
461 {
462 if (log)
463 log->PutCString("Couldn't find result variable");
464
Richard Mitton00dec202013-10-11 19:44:23 +0000465 return true;
Sean Callananfc55f5d2010-09-21 00:44:12 +0000466 }
467
Sean Callanan46ae9e52010-09-28 21:13:03 +0000468 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000469 log->Printf("Result name: \"%s\"", result_name);
Sean Callanan46ae9e52010-09-28 21:13:03 +0000470
Sean Callanan79763a42011-05-23 21:40:23 +0000471 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanand1e5b432010-08-12 01:56:52 +0000472
473 if (!result_value)
474 {
475 if (log)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000476 log->PutCString("Result variable had no data");
Sean Callanan92adcac2011-01-13 08:53:35 +0000477
Sean Callanan3989fb92011-01-27 01:07:04 +0000478 if (m_error_stream)
479 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
480
Sean Callananfc55f5d2010-09-21 00:44:12 +0000481 return false;
Sean Callanand1e5b432010-08-12 01:56:52 +0000482 }
Sean Callanan9e6ed532010-09-13 21:34:21 +0000483
Sean Callanand1e5b432010-08-12 01:56:52 +0000484 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000485 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000486
487 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
488
489 if (!result_global)
490 {
491 if (log)
492 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000493
494 if (m_error_stream)
495 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
496
Sean Callanand1e5b432010-08-12 01:56:52 +0000497 return false;
498 }
499
Sean Callanan79763a42011-05-23 21:40:23 +0000500 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan63697e52011-05-07 01:06:41 +0000501 if (!result_decl)
Sean Callanand1e5b432010-08-12 01:56:52 +0000502 {
503 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000504 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanand1e5b432010-08-12 01:56:52 +0000505
Sean Callanan3989fb92011-01-27 01:07:04 +0000506 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000507 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 +0000508
Sean Callanand1e5b432010-08-12 01:56:52 +0000509 return false;
510 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000511
Sean Callanan63697e52011-05-07 01:06:41 +0000512 if (log)
Sean Callanand1e5b432010-08-12 01:56:52 +0000513 {
Sean Callanan63697e52011-05-07 01:06:41 +0000514 std::string decl_desc_str;
515 raw_string_ostream decl_desc_stream(decl_desc_str);
516 result_decl->print(decl_desc_stream);
517 decl_desc_stream.flush();
Sean Callanand1e5b432010-08-12 01:56:52 +0000518
Sean Callanan63697e52011-05-07 01:06:41 +0000519 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanand1e5b432010-08-12 01:56:52 +0000520 }
521
Sean Callanan63697e52011-05-07 01:06:41 +0000522 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
523 if (!result_var)
Sean Callanand1e5b432010-08-12 01:56:52 +0000524 {
525 if (log)
Sean Callanan63697e52011-05-07 01:06:41 +0000526 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan3989fb92011-01-27 01:07:04 +0000527
528 if (m_error_stream)
Sean Callanan63697e52011-05-07 01:06:41 +0000529 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 +0000530
Sean Callanand1e5b432010-08-12 01:56:52 +0000531 return false;
532 }
Sean Callanand1e5b432010-08-12 01:56:52 +0000533
Sean Callanand1e5b432010-08-12 01:56:52 +0000534 // Get the next available result name from m_decl_map and create the persistent
535 // variable for it
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000536
Sean Callanan63697e52011-05-07 01:06:41 +0000537 // If the result is an Lvalue, it is emitted as a pointer; see
538 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan92adcac2011-01-13 08:53:35 +0000539 if (m_result_is_pointer)
540 {
Sean Callanan63697e52011-05-07 01:06:41 +0000541 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanan78e37602011-01-27 04:42:51 +0000542 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
Sean Callanan92adcac2011-01-13 08:53:35 +0000543
Sean Callananfc4f2fb2011-12-14 01:13:04 +0000544 const clang::PointerType *pointer_pointertype = pointer_type->getAs<clang::PointerType>();
545 const clang::ObjCObjectPointerType *pointer_objcobjpointertype = pointer_type->getAs<clang::ObjCObjectPointerType>();
Sean Callanan5780f9d2011-12-08 19:04:34 +0000546
547 if (pointer_pointertype)
548 {
549 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
550
551 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
552 &result_decl->getASTContext());
553 }
554 else if (pointer_objcobjpointertype)
555 {
556 clang::QualType element_qual_type = clang::QualType(pointer_objcobjpointertype->getObjectType(), 0);
557
558 m_result_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
559 &result_decl->getASTContext());
560 }
561 else
Sean Callanan92adcac2011-01-13 08:53:35 +0000562 {
563 if (log)
564 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan3989fb92011-01-27 01:07:04 +0000565
566 if (m_error_stream)
567 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
568
Sean Callanan92adcac2011-01-13 08:53:35 +0000569 return false;
570 }
Sean Callanan92adcac2011-01-13 08:53:35 +0000571 }
572 else
573 {
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000574 m_result_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan00f43622011-11-18 03:28:09 +0000575 &result_decl->getASTContext());
576 }
577
Greg Clayton57ee3062013-07-11 22:46:58 +0000578 if (m_result_type.GetBitSize() == 0)
Sean Callanan00f43622011-11-18 03:28:09 +0000579 {
580 lldb_private::StreamString type_desc_stream;
581 m_result_type.DumpTypeDescription(&type_desc_stream);
582
583 if (log)
584 log->Printf("Result type has size 0");
585
586 if (m_error_stream)
Sean Callanan960534c2011-12-21 23:44:05 +0000587 m_error_stream->Printf("Error [IRForTarget]: Size of result type '%s' couldn't be determined\n",
Sean Callanan00f43622011-11-18 03:28:09 +0000588 type_desc_stream.GetData());
Sean Callanan960534c2011-12-21 23:44:05 +0000589 return false;
Sean Callanan92adcac2011-01-13 08:53:35 +0000590 }
591
Sean Callanan63697e52011-05-07 01:06:41 +0000592 if (log)
593 {
594 lldb_private::StreamString type_desc_stream;
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000595 m_result_type.DumpTypeDescription(&type_desc_stream);
Sean Callanan63697e52011-05-07 01:06:41 +0000596
Sean Callanan00f43622011-11-18 03:28:09 +0000597 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetData());
Sean Callanan63697e52011-05-07 01:06:41 +0000598 }
599
Sean Callanan1582ee62013-04-18 22:06:33 +0000600 m_result_name = lldb_private::ConstString("$RESULT_NAME");
Sean Callanand1e5b432010-08-12 01:56:52 +0000601
602 if (log)
Greg Claytonfaac1112013-03-14 18:31:44 +0000603 log->Printf("Creating a new result global: \"%s\" with size 0x%" PRIx64,
Sean Callanan00f43622011-11-18 03:28:09 +0000604 m_result_name.GetCString(),
Greg Clayton57ee3062013-07-11 22:46:58 +0000605 m_result_type.GetByteSize());
Sean Callanand1e5b432010-08-12 01:56:52 +0000606
607 // Construct a new result global and set up its metadata
608
Sean Callanan79763a42011-05-23 21:40:23 +0000609 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanand1e5b432010-08-12 01:56:52 +0000610 result_global->getType()->getElementType(),
611 false, /* not constant */
612 GlobalValue::ExternalLinkage,
613 NULL, /* no initializer */
Sean Callanan92adcac2011-01-13 08:53:35 +0000614 m_result_name.GetCString ());
Sean Callanand1e5b432010-08-12 01:56:52 +0000615
616 // It's too late in compilation to create a new VarDecl for this, but we don't
617 // need to. We point the metadata at the old VarDecl. This creates an odd
618 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton7b462cc2010-10-15 22:48:33 +0000619 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanand1e5b432010-08-12 01:56:52 +0000620 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
621 // fixed up.
622
Sean Callanan79763a42011-05-23 21:40:23 +0000623 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan63697e52011-05-07 01:06:41 +0000624 reinterpret_cast<uint64_t>(result_decl),
Sean Callanand1e5b432010-08-12 01:56:52 +0000625 false);
626
627 llvm::Value* values[2];
628 values[0] = new_result_global;
629 values[1] = new_constant_int;
630
Sean Callanand12cf8bb2011-05-15 22:34:38 +0000631 ArrayRef<Value*> value_ref(values, 2);
632
Sean Callanan79763a42011-05-23 21:40:23 +0000633 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
634 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanand1e5b432010-08-12 01:56:52 +0000635 named_metadata->addOperand(persistent_global_md);
636
637 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000638 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan1e87fff2010-09-07 22:43:19 +0000639 PrintValue(result_global).c_str(),
Sean Callanand1e5b432010-08-12 01:56:52 +0000640 PrintValue(new_result_global).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000641
642 if (result_global->hasNUses(0))
643 {
644 // We need to synthesize a store for this variable, because otherwise
645 // there's nothing to put into its equivalent persistent variable.
Sean Callanand1e5b432010-08-12 01:56:52 +0000646
Greg Clayton7b462cc2010-10-15 22:48:33 +0000647 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000648 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
649
650 if (!first_entry_instruction)
651 return false;
652
653 if (!result_global->hasInitializer())
654 {
655 if (log)
656 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000657
658 if (m_error_stream)
659 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
660
Sean Callanan1e87fff2010-09-07 22:43:19 +0000661 return false;
662 }
663
664 Constant *initializer = result_global->getInitializer();
Sean Callanane4ec90e2010-12-16 03:17:46 +0000665
Greg Clayton9c139312011-02-05 02:28:58 +0000666 StoreInst *synthesized_store = new StoreInst(initializer,
667 new_result_global,
668 first_entry_instruction);
Sean Callanan1e87fff2010-09-07 22:43:19 +0000669
670 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +0000671 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan1e87fff2010-09-07 22:43:19 +0000672 }
673 else
674 {
675 result_global->replaceAllUsesWith(new_result_global);
676 }
677
Sean Callanan1582ee62013-04-18 22:06:33 +0000678 if (!m_decl_map->AddPersistentVariable(result_decl,
679 m_result_name,
680 m_result_type,
681 true,
682 m_result_is_pointer))
683 return false;
684
Sean Callanand1e5b432010-08-12 01:56:52 +0000685 result_global->eraseFromParent();
686
687 return true;
688}
689
Johnny Chenee7a3592011-08-09 23:10:20 +0000690#if 0
Greg Clayton5160ce52013-03-27 23:08:40 +0000691static void DebugUsers(Log *log, Value *value, uint8_t depth)
Sean Callananafe16a72010-11-17 23:00:36 +0000692{
693 if (!depth)
694 return;
695
696 depth--;
697
Johnny Chenee7a3592011-08-09 23:10:20 +0000698 if (log)
699 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callananafe16a72010-11-17 23:00:36 +0000700
Ed Mastea8553092014-03-10 17:24:16 +0000701 for (llvm::User *u : users())
Sean Callananafe16a72010-11-17 23:00:36 +0000702 {
Johnny Chenee7a3592011-08-09 23:10:20 +0000703 if (log)
Ed Mastea8553092014-03-10 17:24:16 +0000704 log->Printf(" <Use %p> %s", u, PrintValue(u).c_str());
705 DebugUsers(log, u, depth);
Sean Callananafe16a72010-11-17 23:00:36 +0000706 }
707
Johnny Chenee7a3592011-08-09 23:10:20 +0000708 if (log)
709 log->Printf(" <End uses>");
Sean Callananafe16a72010-11-17 23:00:36 +0000710}
Johnny Chenee7a3592011-08-09 23:10:20 +0000711#endif
Sean Callananafe16a72010-11-17 23:00:36 +0000712
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000713bool
Sean Callanan79763a42011-05-23 21:40:23 +0000714IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000715 llvm::GlobalVariable *cstr)
Sean Callananafe16a72010-11-17 23:00:36 +0000716{
Greg Clayton5160ce52013-03-27 23:08:40 +0000717 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000718
Sean Callanancc427fa2011-07-30 02:42:06 +0000719 Type *ns_str_ty = ns_str->getType();
Sean Callanan79763a42011-05-23 21:40:23 +0000720
Sean Callanancc427fa2011-07-30 02:42:06 +0000721 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callanancc427fa2011-07-30 02:42:06 +0000722 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
723 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananafe16a72010-11-17 23:00:36 +0000724
725 if (!m_CFStringCreateWithBytes)
726 {
727 lldb::addr_t CFStringCreateWithBytes_addr;
728
729 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
730
731 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
732 {
733 if (log)
734 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
735
Sean Callanan3989fb92011-01-27 01:07:04 +0000736 if (m_error_stream)
737 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
738
Sean Callananafe16a72010-11-17 23:00:36 +0000739 return false;
740 }
741
742 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000743 log->Printf("Found CFStringCreateWithBytes at 0x%" PRIx64, CFStringCreateWithBytes_addr);
Sean Callananafe16a72010-11-17 23:00:36 +0000744
745 // Build the function type:
746 //
747 // CFStringRef CFStringCreateWithBytes (
748 // CFAllocatorRef alloc,
749 // const UInt8 *bytes,
750 // CFIndex numBytes,
751 // CFStringEncoding encoding,
752 // Boolean isExternalRepresentation
753 // );
754 //
755 // We make the following substitutions:
756 //
757 // CFStringRef -> i8*
758 // CFAllocatorRef -> i8*
759 // UInt8 * -> i8*
760 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
761 // CFStringEncoding -> i32
762 // Boolean -> i8
763
Sean Callanancc427fa2011-07-30 02:42:06 +0000764 Type *arg_type_array[5];
765
766 arg_type_array[0] = i8_ptr_ty;
767 arg_type_array[1] = i8_ptr_ty;
Sean Callanan439dcae2013-12-20 19:55:02 +0000768 arg_type_array[2] = m_intptr_ty;
Sean Callanancc427fa2011-07-30 02:42:06 +0000769 arg_type_array[3] = i32_ty;
770 arg_type_array[4] = i8_ty;
771
772 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
773
Sean Callanan79763a42011-05-23 21:40:23 +0000774 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000775
776 // Build the constant containing the pointer to the function
777 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
Sean Callanan439dcae2013-12-20 19:55:02 +0000778 Constant *CFSCWB_addr_int = ConstantInt::get(m_intptr_ty, CFStringCreateWithBytes_addr, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000779 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
780 }
781
Sean Callanand2b465f2012-02-09 03:22:41 +0000782 ConstantDataSequential *string_array = NULL;
Sean Callanan229ce2d2011-02-10 22:17:53 +0000783
784 if (cstr)
Sean Callanand2b465f2012-02-09 03:22:41 +0000785 string_array = dyn_cast<ConstantDataSequential>(cstr->getInitializer());
Sean Callanancc427fa2011-07-30 02:42:06 +0000786
Sean Callananafe16a72010-11-17 23:00:36 +0000787 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan229ce2d2011-02-10 22:17:53 +0000788 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
Sean Callanan439dcae2013-12-20 19:55:02 +0000789 Constant *numBytes_arg = ConstantInt::get(m_intptr_ty, cstr ? string_array->getNumElements() - 1 : 0, false);
Sean Callananafe16a72010-11-17 23:00:36 +0000790 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
791 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
792
Sean Callanancc427fa2011-07-30 02:42:06 +0000793 Value *argument_array[5];
794
795 argument_array[0] = alloc_arg;
796 argument_array[1] = bytes_arg;
797 argument_array[2] = numBytes_arg;
798 argument_array[3] = encoding_arg;
799 argument_array[4] = isExternal_arg;
800
801 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callananafe16a72010-11-17 23:00:36 +0000802
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000803 FunctionValueCache CFSCWB_Caller ([this, &CFSCWB_arguments] (llvm::Function *function)->llvm::Value * {
804 return CallInst::Create(m_CFStringCreateWithBytes,
805 CFSCWB_arguments,
806 "CFStringCreateWithBytes",
807 llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function)));
808 });
Sean Callanan7a55a322010-11-18 22:21:58 +0000809
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000810 if (!UnfoldConstant(ns_str, CFSCWB_Caller, m_entry_instruction_finder))
Sean Callananafe16a72010-11-17 23:00:36 +0000811 {
812 if (log)
813 log->PutCString("Couldn't replace the NSString with the result of the call");
814
Sean Callanan3989fb92011-01-27 01:07:04 +0000815 if (m_error_stream)
816 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
817
Sean Callananafe16a72010-11-17 23:00:36 +0000818 return false;
819 }
820
Greg Clayton1b95a6f2010-11-19 01:05:25 +0000821 ns_str->eraseFromParent();
Sean Callananafe16a72010-11-17 23:00:36 +0000822
823 return true;
824}
825
826bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +0000827IRForTarget::RewriteObjCConstStrings()
Sean Callananafe16a72010-11-17 23:00:36 +0000828{
Greg Clayton5160ce52013-03-27 23:08:40 +0000829 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananafe16a72010-11-17 23:00:36 +0000830
Sean Callanan79763a42011-05-23 21:40:23 +0000831 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callananafe16a72010-11-17 23:00:36 +0000832
Sean Callananafe16a72010-11-17 23:00:36 +0000833 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
834 vi != ve;
835 ++vi)
836 {
Sean Callanancc427fa2011-07-30 02:42:06 +0000837 std::string value_name = vi->first().str();
838 const char *value_name_cstr = value_name.c_str();
839
840 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callananafe16a72010-11-17 23:00:36 +0000841 {
842 Value *nsstring_value = vi->second;
843
844 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
845
846 if (!nsstring_global)
847 {
848 if (log)
849 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000850
851 if (m_error_stream)
852 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
853
Sean Callananafe16a72010-11-17 23:00:36 +0000854 return false;
855 }
856
857 if (!nsstring_global->hasInitializer())
858 {
859 if (log)
860 log->PutCString("NSString variable does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000861
862 if (m_error_stream)
863 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
864
Sean Callananafe16a72010-11-17 23:00:36 +0000865 return false;
866 }
867
868 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
869
870 if (!nsstring_struct)
871 {
872 if (log)
873 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan3989fb92011-01-27 01:07:04 +0000874
875 if (m_error_stream)
876 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
877
Sean Callananafe16a72010-11-17 23:00:36 +0000878 return false;
879 }
880
881 // We expect the following structure:
882 //
883 // struct {
884 // int *isa;
885 // int flags;
886 // char *str;
887 // long length;
888 // };
889
890 if (nsstring_struct->getNumOperands() != 4)
891 {
892 if (log)
893 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 +0000894
895 if (m_error_stream)
896 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
897
Sean Callananafe16a72010-11-17 23:00:36 +0000898 return false;
899 }
900
901 Constant *nsstring_member = nsstring_struct->getOperand(2);
902
903 if (!nsstring_member)
904 {
905 if (log)
906 log->PutCString("NSString initializer's str element was empty");
Sean Callanan3989fb92011-01-27 01:07:04 +0000907
908 if (m_error_stream)
909 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
910
Sean Callananafe16a72010-11-17 23:00:36 +0000911 return false;
912 }
913
914 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
915
916 if (!nsstring_expr)
917 {
918 if (log)
919 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan3989fb92011-01-27 01:07:04 +0000920
921 if (m_error_stream)
922 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
923
Sean Callananafe16a72010-11-17 23:00:36 +0000924 return false;
925 }
926
927 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
928 {
929 if (log)
930 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 +0000931
932 if (m_error_stream)
933 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
934
Sean Callananafe16a72010-11-17 23:00:36 +0000935 return false;
936 }
937
938 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
939
940 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
941
942 if (!cstr_global)
943 {
944 if (log)
945 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan3989fb92011-01-27 01:07:04 +0000946
947 if (m_error_stream)
948 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 +0000949
Sean Callananafe16a72010-11-17 23:00:36 +0000950 return false;
951 }
952
953 if (!cstr_global->hasInitializer())
954 {
955 if (log)
956 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan3989fb92011-01-27 01:07:04 +0000957
958 if (m_error_stream)
959 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
960
Sean Callananafe16a72010-11-17 23:00:36 +0000961 return false;
962 }
Sean Callanan229ce2d2011-02-10 22:17:53 +0000963
964 /*
Sean Callananafe16a72010-11-17 23:00:36 +0000965 if (!cstr_array)
966 {
967 if (log)
968 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan3989fb92011-01-27 01:07:04 +0000969
970 if (m_error_stream)
971 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
972
Sean Callananafe16a72010-11-17 23:00:36 +0000973 return false;
974 }
975
976 if (!cstr_array->isCString())
977 {
978 if (log)
979 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan3989fb92011-01-27 01:07:04 +0000980
981 if (m_error_stream)
982 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
983
Sean Callananafe16a72010-11-17 23:00:36 +0000984 return false;
985 }
Sean Callanan229ce2d2011-02-10 22:17:53 +0000986 */
987
Sean Callanand2b465f2012-02-09 03:22:41 +0000988 ConstantDataArray *cstr_array = dyn_cast<ConstantDataArray>(cstr_global->getInitializer());
Sean Callananafe16a72010-11-17 23:00:36 +0000989
990 if (log)
Sean Callanan229ce2d2011-02-10 22:17:53 +0000991 {
992 if (cstr_array)
Sean Callanand2b465f2012-02-09 03:22:41 +0000993 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 +0000994 else
Sean Callanancc427fa2011-07-30 02:42:06 +0000995 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan229ce2d2011-02-10 22:17:53 +0000996 }
997
998 if (!cstr_array)
999 cstr_global = NULL;
Sean Callananafe16a72010-11-17 23:00:36 +00001000
Sean Callanan1f9db3e2013-06-28 21:44:15 +00001001 if (!RewriteObjCConstString(nsstring_global, cstr_global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001002 {
Sean Callananafe16a72010-11-17 23:00:36 +00001003 if (log)
1004 log->PutCString("Error rewriting the constant string");
Sean Callanan3989fb92011-01-27 01:07:04 +00001005
1006 // We don't print an error message here because RewriteObjCConstString has done so for us.
1007
Sean Callananafe16a72010-11-17 23:00:36 +00001008 return false;
1009 }
Sean Callananafe16a72010-11-17 23:00:36 +00001010 }
1011 }
1012
1013 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
1014 vi != ve;
1015 ++vi)
1016 {
Sean Callanancc427fa2011-07-30 02:42:06 +00001017 std::string value_name = vi->first().str();
1018 const char *value_name_cstr = value_name.c_str();
1019
1020 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callananafe16a72010-11-17 23:00:36 +00001021 {
1022 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
1023
1024 if (!gv)
1025 {
1026 if (log)
1027 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001028
1029 if (m_error_stream)
1030 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
1031
Sean Callananafe16a72010-11-17 23:00:36 +00001032 return false;
1033 }
1034
1035 gv->eraseFromParent();
1036
1037 break;
1038 }
1039 }
1040
1041 return true;
1042}
1043
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001044static bool IsObjCSelectorRef (Value *value)
Sean Callanan5300d372010-07-31 01:32:05 +00001045{
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001046 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callanan5300d372010-07-31 01:32:05 +00001047
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001048 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callanan5300d372010-07-31 01:32:05 +00001049 return false;
1050
1051 return true;
1052}
1053
Sean Callanan3989fb92011-01-27 01:07:04 +00001054// This function does not report errors; its callers are responsible.
Sean Callanan5300d372010-07-31 01:32:05 +00001055bool
Sean Callanan79763a42011-05-23 21:40:23 +00001056IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callanan5300d372010-07-31 01:32:05 +00001057{
Greg Clayton5160ce52013-03-27 23:08:40 +00001058 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001059
1060 LoadInst *load = dyn_cast<LoadInst>(selector_load);
1061
1062 if (!load)
1063 return false;
1064
1065 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
1066 //
1067 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
1068 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
1069 //
1070 // where %obj is the object pointer and %tmp is the selector.
1071 //
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001072 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
1073 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callanan5300d372010-07-31 01:32:05 +00001074
1075 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
1076
1077 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
1078
1079 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
1080 return false;
1081
1082 Constant *osr_initializer = _objc_selector_references_->getInitializer();
1083
1084 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
1085
1086 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
1087 return false;
1088
1089 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
1090
1091 if (!osr_initializer_base)
1092 return false;
1093
1094 // Find the string's initializer (a ConstantArray) and get the string from it
1095
1096 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
1097
1098 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
1099 return false;
1100
1101 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
1102
Sean Callanand2b465f2012-02-09 03:22:41 +00001103 ConstantDataArray *omvn_initializer_array = dyn_cast<ConstantDataArray>(omvn_initializer);
Sean Callanan5300d372010-07-31 01:32:05 +00001104
1105 if (!omvn_initializer_array->isString())
1106 return false;
1107
1108 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
1109
1110 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001111 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callanan5300d372010-07-31 01:32:05 +00001112
1113 // Construct a call to sel_registerName
1114
1115 if (!m_sel_registerName)
1116 {
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001117 lldb::addr_t sel_registerName_addr;
Sean Callanan5300d372010-07-31 01:32:05 +00001118
Greg Clayton7b462cc2010-10-15 22:48:33 +00001119 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001120 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callanan5300d372010-07-31 01:32:05 +00001121 return false;
1122
Sean Callananbe3a1b12010-10-26 00:31:56 +00001123 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001124 log->Printf("Found sel_registerName at 0x%" PRIx64, sel_registerName_addr);
Sean Callananbe3a1b12010-10-26 00:31:56 +00001125
Sean Callanan5300d372010-07-31 01:32:05 +00001126 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1127
1128 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callanan79763a42011-05-23 21:40:23 +00001129 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001130 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanancc427fa2011-07-30 02:42:06 +00001131 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan5300d372010-07-31 01:32:05 +00001132
Sean Callanancc427fa2011-07-30 02:42:06 +00001133 Type *type_array[1];
1134
1135 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1136
1137 ArrayRef<Type *> srN_arg_types(type_array, 1);
1138
Sean Callanan5300d372010-07-31 01:32:05 +00001139 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1140
1141 // Build the constant containing the pointer to the function
Sean Callanan5300d372010-07-31 01:32:05 +00001142 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Sean Callanan439dcae2013-12-20 19:55:02 +00001143 Constant *srN_addr_int = ConstantInt::get(m_intptr_ty, sel_registerName_addr, false);
Sean Callanan5300d372010-07-31 01:32:05 +00001144 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1145 }
1146
Sean Callanancc427fa2011-07-30 02:42:06 +00001147 Value *argument_array[1];
1148
Sean Callanan79763a42011-05-23 21:40:23 +00001149 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callanan5300d372010-07-31 01:32:05 +00001150
Sean Callanancc427fa2011-07-30 02:42:06 +00001151 argument_array[0] = omvn_pointer;
Sean Callanan5300d372010-07-31 01:32:05 +00001152
Sean Callanancc427fa2011-07-30 02:42:06 +00001153 ArrayRef<Value *> srN_arguments(argument_array, 1);
1154
Sean Callanan5300d372010-07-31 01:32:05 +00001155 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanancc427fa2011-07-30 02:42:06 +00001156 srN_arguments,
Sean Callananafe16a72010-11-17 23:00:36 +00001157 "sel_registerName",
Sean Callanan5300d372010-07-31 01:32:05 +00001158 selector_load);
1159
1160 // Replace the load with the call in all users
1161
1162 selector_load->replaceAllUsesWith(srN_call);
1163
1164 selector_load->eraseFromParent();
1165
1166 return true;
1167}
1168
1169bool
Sean Callanan79763a42011-05-23 21:40:23 +00001170IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callanan5300d372010-07-31 01:32:05 +00001171{
Greg Clayton5160ce52013-03-27 23:08:40 +00001172 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5300d372010-07-31 01:32:05 +00001173
1174 BasicBlock::iterator ii;
1175
1176 typedef SmallVector <Instruction*, 2> InstrList;
1177 typedef InstrList::iterator InstrIterator;
1178
1179 InstrList selector_loads;
1180
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001181 for (ii = basic_block.begin();
1182 ii != basic_block.end();
Sean Callanan5300d372010-07-31 01:32:05 +00001183 ++ii)
1184 {
1185 Instruction &inst = *ii;
1186
1187 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001188 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callanan5300d372010-07-31 01:32:05 +00001189 selector_loads.push_back(&inst);
1190 }
1191
1192 InstrIterator iter;
1193
1194 for (iter = selector_loads.begin();
1195 iter != selector_loads.end();
1196 ++iter)
1197 {
Sean Callanan79763a42011-05-23 21:40:23 +00001198 if (!RewriteObjCSelector(*iter))
Sean Callanan5300d372010-07-31 01:32:05 +00001199 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001200 if (m_error_stream)
1201 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1202
Enrico Granata20edcdb2011-07-19 18:03:25 +00001203 if (log)
Sean Callanan5300d372010-07-31 01:32:05 +00001204 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan3989fb92011-01-27 01:07:04 +00001205
Sean Callanan5300d372010-07-31 01:32:05 +00001206 return false;
1207 }
1208 }
1209
1210 return true;
1211}
1212
Sean Callanan3989fb92011-01-27 01:07:04 +00001213// This function does not report errors; its callers are responsible.
Sean Callanan2235f322010-08-11 03:57:18 +00001214bool
Sean Callanan79763a42011-05-23 21:40:23 +00001215IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanan2235f322010-08-11 03:57:18 +00001216{
Greg Clayton5160ce52013-03-27 23:08:40 +00001217 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanane1175b72011-01-13 21:23:32 +00001218
Sean Callanan2235f322010-08-11 03:57:18 +00001219 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1220
1221 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1222
1223 if (!alloc_md || !alloc_md->getNumOperands())
1224 return false;
1225
1226 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1227
1228 if (!constant_int)
1229 return false;
1230
1231 // We attempt to register this as a new persistent variable with the DeclMap.
1232
1233 uintptr_t ptr = constant_int->getZExtValue();
1234
Sean Callanand1e5b432010-08-12 01:56:52 +00001235 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanan2235f322010-08-11 03:57:18 +00001236
Sean Callanand1e5b432010-08-12 01:56:52 +00001237 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1238 &decl->getASTContext());
1239
Greg Clayton7b462cc2010-10-15 22:48:33 +00001240 StringRef decl_name (decl->getName());
1241 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan92adcac2011-01-13 08:53:35 +00001242 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanan2235f322010-08-11 03:57:18 +00001243 return false;
1244
Sean Callanan79763a42011-05-23 21:40:23 +00001245 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanane1175b72011-01-13 21:23:32 +00001246 alloc->getType(),
Sean Callanan2235f322010-08-11 03:57:18 +00001247 false, /* not constant */
1248 GlobalValue::ExternalLinkage,
1249 NULL, /* no initializer */
1250 alloc->getName().str().c_str());
1251
1252 // What we're going to do here is make believe this was a regular old external
1253 // variable. That means we need to make the metadata valid.
1254
Sean Callanan585c0ec82012-07-04 01:26:26 +00001255 NamedMDNode *named_metadata = m_module->getOrInsertNamedMetadata("clang.global.decl.ptrs");
Sean Callanan2235f322010-08-11 03:57:18 +00001256
1257 llvm::Value* values[2];
1258 values[0] = persistent_global;
1259 values[1] = constant_int;
Sean Callanand12cf8bb2011-05-15 22:34:38 +00001260
1261 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanan2235f322010-08-11 03:57:18 +00001262
Sean Callanan79763a42011-05-23 21:40:23 +00001263 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanan2235f322010-08-11 03:57:18 +00001264 named_metadata->addOperand(persistent_global_md);
1265
Sean Callanane1175b72011-01-13 21:23:32 +00001266 // Now, since the variable is a pointer variable, we will drop in a load of that
1267 // pointer variable.
1268
1269 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1270
1271 if (log)
1272 log->Printf("Replacing \"%s\" with \"%s\"",
1273 PrintValue(alloc).c_str(),
1274 PrintValue(persistent_load).c_str());
1275
1276 alloc->replaceAllUsesWith(persistent_load);
Sean Callanan2235f322010-08-11 03:57:18 +00001277 alloc->eraseFromParent();
1278
1279 return true;
1280}
1281
1282bool
Sean Callanan79763a42011-05-23 21:40:23 +00001283IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanan2235f322010-08-11 03:57:18 +00001284{
Sean Callanan9e6ed532010-09-13 21:34:21 +00001285 if (!m_resolve_vars)
1286 return true;
1287
Greg Clayton5160ce52013-03-27 23:08:40 +00001288 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2235f322010-08-11 03:57:18 +00001289
1290 BasicBlock::iterator ii;
1291
1292 typedef SmallVector <Instruction*, 2> InstrList;
1293 typedef InstrList::iterator InstrIterator;
1294
1295 InstrList pvar_allocs;
1296
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001297 for (ii = basic_block.begin();
1298 ii != basic_block.end();
Sean Callanan2235f322010-08-11 03:57:18 +00001299 ++ii)
1300 {
1301 Instruction &inst = *ii;
1302
1303 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callananf694a552011-01-21 22:30:25 +00001304 {
1305 llvm::StringRef alloc_name = alloc->getName();
1306
1307 if (alloc_name.startswith("$") &&
1308 !alloc_name.startswith("$__lldb"))
1309 {
1310 if (alloc_name.find_first_of("0123456789") == 1)
1311 {
1312 if (log)
1313 log->Printf("Rejecting a numeric persistent variable.");
1314
Sean Callanan3989fb92011-01-27 01:07:04 +00001315 if (m_error_stream)
1316 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1317
Sean Callananf694a552011-01-21 22:30:25 +00001318 return false;
1319 }
1320
Sean Callanan2235f322010-08-11 03:57:18 +00001321 pvar_allocs.push_back(alloc);
Sean Callananf694a552011-01-21 22:30:25 +00001322 }
1323 }
Sean Callanan2235f322010-08-11 03:57:18 +00001324 }
1325
1326 InstrIterator iter;
1327
1328 for (iter = pvar_allocs.begin();
1329 iter != pvar_allocs.end();
1330 ++iter)
1331 {
Sean Callanan79763a42011-05-23 21:40:23 +00001332 if (!RewritePersistentAlloc(*iter))
Sean Callanan2235f322010-08-11 03:57:18 +00001333 {
Sean Callanan3989fb92011-01-27 01:07:04 +00001334 if (m_error_stream)
1335 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1336
Enrico Granata20edcdb2011-07-19 18:03:25 +00001337 if (log)
Sean Callanan2235f322010-08-11 03:57:18 +00001338 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan3989fb92011-01-27 01:07:04 +00001339
Sean Callanan2235f322010-08-11 03:57:18 +00001340 return false;
1341 }
1342 }
1343
1344 return true;
1345}
1346
Sean Callananc70ed462011-10-25 18:36:40 +00001347bool
1348IRForTarget::MaterializeInitializer (uint8_t *data, Constant *initializer)
1349{
1350 if (!initializer)
1351 return true;
1352
Greg Clayton5160ce52013-03-27 23:08:40 +00001353 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc70ed462011-10-25 18:36:40 +00001354
1355 if (log && log->GetVerbose())
1356 log->Printf(" MaterializeInitializer(%p, %s)", data, PrintValue(initializer).c_str());
1357
1358 Type *initializer_type = initializer->getType();
1359
1360 if (ConstantInt *int_initializer = dyn_cast<ConstantInt>(initializer))
1361 {
1362 memcpy (data, int_initializer->getValue().getRawData(), m_target_data->getTypeStoreSize(initializer_type));
1363 return true;
1364 }
Sean Callanand2b465f2012-02-09 03:22:41 +00001365 else if (ConstantDataArray *array_initializer = dyn_cast<ConstantDataArray>(initializer))
Sean Callananc70ed462011-10-25 18:36:40 +00001366 {
1367 if (array_initializer->isString())
1368 {
1369 std::string array_initializer_string = array_initializer->getAsString();
1370 memcpy (data, array_initializer_string.c_str(), m_target_data->getTypeStoreSize(initializer_type));
1371 }
1372 else
1373 {
1374 ArrayType *array_initializer_type = array_initializer->getType();
1375 Type *array_element_type = array_initializer_type->getElementType();
1376
1377 size_t element_size = m_target_data->getTypeAllocSize(array_element_type);
1378
Andy Gibbsa297a972013-06-19 19:04:53 +00001379 for (unsigned i = 0; i < array_initializer->getNumOperands(); ++i)
Sean Callananc70ed462011-10-25 18:36:40 +00001380 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001381 Value *operand_value = array_initializer->getOperand(i);
1382 Constant *operand_constant = dyn_cast<Constant>(operand_value);
1383
1384 if (!operand_constant)
1385 return false;
1386
1387 if (!MaterializeInitializer(data + (i * element_size), operand_constant))
Sean Callananc70ed462011-10-25 18:36:40 +00001388 return false;
1389 }
1390 }
1391 return true;
1392 }
1393 else if (ConstantStruct *struct_initializer = dyn_cast<ConstantStruct>(initializer))
1394 {
1395 StructType *struct_initializer_type = struct_initializer->getType();
1396 const StructLayout *struct_layout = m_target_data->getStructLayout(struct_initializer_type);
1397
Andy Gibbsa297a972013-06-19 19:04:53 +00001398 for (unsigned i = 0;
Sean Callananc70ed462011-10-25 18:36:40 +00001399 i < struct_initializer->getNumOperands();
1400 ++i)
1401 {
1402 if (!MaterializeInitializer(data + struct_layout->getElementOffset(i), struct_initializer->getOperand(i)))
1403 return false;
1404 }
1405 return true;
1406 }
Sean Callanan76ee3e72013-04-24 19:50:12 +00001407 else if (isa<ConstantAggregateZero>(initializer))
1408 {
1409 memset(data, 0, m_target_data->getTypeStoreSize(initializer_type));
1410 return true;
1411 }
Sean Callananc70ed462011-10-25 18:36:40 +00001412 return false;
1413}
1414
1415bool
1416IRForTarget::MaterializeInternalVariable (GlobalVariable *global_variable)
1417{
1418 if (GlobalVariable::isExternalLinkage(global_variable->getLinkage()))
1419 return false;
1420
Sean Callananfe5d1392011-11-15 19:13:54 +00001421 if (global_variable == m_reloc_placeholder)
1422 return true;
1423
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001424 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callananc70ed462011-10-25 18:36:40 +00001425
1426 llvm::Type *variable_type = global_variable->getType();
1427
1428 Constant *initializer = global_variable->getInitializer();
1429
1430 llvm::Type *initializer_type = initializer->getType();
1431
1432 size_t size = m_target_data->getTypeAllocSize(initializer_type);
Sean Callanane3333d62012-06-08 22:20:41 +00001433 size_t align = m_target_data->getPrefTypeAlignment(initializer_type);
1434
1435 const size_t mask = (align - 1);
1436 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001437 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00001438 offset = aligned_offset;
Sean Callananc70ed462011-10-25 18:36:40 +00001439
1440 lldb_private::DataBufferHeap data(size, '\0');
1441
1442 if (initializer)
1443 if (!MaterializeInitializer(data.GetBytes(), initializer))
1444 return false;
1445
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001446 m_data_allocator.GetStream().Write(data.GetBytes(), data.GetByteSize());
Sean Callananc70ed462011-10-25 18:36:40 +00001447
1448 Constant *new_pointer = BuildRelocation(variable_type, offset);
1449
1450 global_variable->replaceAllUsesWith(new_pointer);
1451
1452 global_variable->eraseFromParent();
1453
1454 return true;
1455}
1456
Sean Callanan3989fb92011-01-27 01:07:04 +00001457// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001458bool
Sean Callanan79763a42011-05-23 21:40:23 +00001459IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001460{
Greg Clayton5160ce52013-03-27 23:08:40 +00001461 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001462
1463 if (log)
Sean Callanan88339f02010-12-06 22:16:55 +00001464 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callananaf8e96c2011-08-01 17:41:38 +00001465
Greg Clayton7b462cc2010-10-15 22:48:33 +00001466 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callanan4cf04d22010-08-03 00:23:29 +00001467 {
Sean Callanan5666b672010-08-04 01:02:13 +00001468 switch (constant_expr->getOpcode())
Sean Callanan4cf04d22010-08-03 00:23:29 +00001469 {
Sean Callanan5666b672010-08-04 01:02:13 +00001470 default:
1471 break;
1472 case Instruction::GetElementPtr:
1473 case Instruction::BitCast:
Sean Callanan4cf04d22010-08-03 00:23:29 +00001474 Value *s = constant_expr->getOperand(0);
Sean Callanan79763a42011-05-23 21:40:23 +00001475 if (!MaybeHandleVariable(s))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001476 return false;
Sean Callanan4cf04d22010-08-03 00:23:29 +00001477 }
1478 }
Sean Callanand6e04ae2010-12-03 19:51:05 +00001479 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001480 {
Sean Callananc70ed462011-10-25 18:36:40 +00001481 if (!GlobalValue::isExternalLinkage(global_variable->getLinkage()))
1482 return MaterializeInternalVariable(global_variable);
1483
Sean Callanan79763a42011-05-23 21:40:23 +00001484 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan2ab712f22010-07-03 01:35:46 +00001485
Sean Callanan5300d372010-07-31 01:32:05 +00001486 if (!named_decl)
1487 {
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001488 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callanan5300d372010-07-31 01:32:05 +00001489 return true;
1490
Sean Callanan14f0b0e2010-12-06 00:56:39 +00001491 if (!global_variable->hasExternalLinkage())
1492 return true;
1493
Sean Callanan5300d372010-07-31 01:32:05 +00001494 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00001495 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan3989fb92011-01-27 01:07:04 +00001496
Sean Callanan5300d372010-07-31 01:32:05 +00001497 return false;
1498 }
1499
Greg Clayton7b462cc2010-10-15 22:48:33 +00001500 std::string name (named_decl->getName().str());
Sean Callananea22d422010-07-16 00:09:46 +00001501
Greg Clayton57ee3062013-07-11 22:46:58 +00001502 clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl);
1503 if (value_decl == NULL)
Sean Callananea22d422010-07-16 00:09:46 +00001504 return false;
Greg Clayton57ee3062013-07-11 22:46:58 +00001505
1506 lldb_private::ClangASTType clang_type(&value_decl->getASTContext(), value_decl->getType());
Sean Callanan038df5032010-09-30 21:18:25 +00001507
Sean Callanan77eaf442011-07-08 00:39:14 +00001508 const Type *value_type = NULL;
Greg Clayton57ee3062013-07-11 22:46:58 +00001509
Sean Callanane1175b72011-01-13 21:23:32 +00001510 if (name[0] == '$')
Sean Callanan92adcac2011-01-13 08:53:35 +00001511 {
1512 // The $__lldb_expr_result name indicates the the return value has allocated as
1513 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1514 // accesses to this static variable need to be redirected to the result of dereferencing
1515 // a pointer that is passed in as one of the arguments.
1516 //
1517 // Consequently, when reporting the size of the type, we report a pointer type pointing
1518 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanane1175b72011-01-13 21:23:32 +00001519 //
1520 // We also do this for any user-declared persistent variables.
Greg Clayton57ee3062013-07-11 22:46:58 +00001521 clang_type = clang_type.GetPointerType();
Sean Callanan92adcac2011-01-13 08:53:35 +00001522 value_type = PointerType::get(global_variable->getType(), 0);
1523 }
1524 else
1525 {
Sean Callanan92adcac2011-01-13 08:53:35 +00001526 value_type = global_variable->getType();
1527 }
Greg Clayton57ee3062013-07-11 22:46:58 +00001528
1529 const uint64_t value_size = clang_type.GetByteSize();
1530 off_t value_alignment = (clang_type.GetTypeBitAlign() + 7ull) / 8ull;
Sean Callanan17827832010-12-13 22:46:15 +00001531
Sean Callanan038df5032010-09-30 21:18:25 +00001532 if (log)
Greg Clayton57ee3062013-07-11 22:46:58 +00001533 {
Greg Claytonfaac1112013-03-14 18:31:44 +00001534 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %" PRIu64 ", align %" PRId64 "]",
Sean Callanan038df5032010-09-30 21:18:25 +00001535 name.c_str(),
Greg Clayton57ee3062013-07-11 22:46:58 +00001536 clang_type.GetQualType().getAsString().c_str(),
1537 PrintType(value_type).c_str(),
Sean Callanan038df5032010-09-30 21:18:25 +00001538 value_size,
1539 value_alignment);
Greg Clayton57ee3062013-07-11 22:46:58 +00001540 }
Sean Callanan17827832010-12-13 22:46:15 +00001541
Sean Callanan549c9f72010-07-13 21:41:46 +00001542
Sean Callanan64dfc9a2010-08-23 23:09:38 +00001543 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton7b462cc2010-10-15 22:48:33 +00001544 lldb_private::ConstString (name.c_str()),
1545 llvm_value_ptr,
Sean Callanan4edba2d2010-07-27 02:07:53 +00001546 value_size,
1547 value_alignment))
Sean Callananaf8e96c2011-08-01 17:41:38 +00001548 {
1549 if (!global_variable->hasExternalLinkage())
1550 return true;
Sean Callanan0ff3bf92013-04-11 17:57:16 +00001551 else if (HandleSymbol (global_variable))
1552 return true;
Sean Callananaf8e96c2011-08-01 17:41:38 +00001553 else
1554 return false;
1555 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001556 }
Sean Callanan4a5fcbb2010-12-03 03:02:31 +00001557 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001558 {
1559 if (log)
1560 log->Printf("Function pointers aren't handled right now");
1561
1562 return false;
1563 }
Sean Callanan549c9f72010-07-13 21:41:46 +00001564
1565 return true;
1566}
1567
Sean Callanan3989fb92011-01-27 01:07:04 +00001568// This function does not report errors; its callers are responsible.
Sean Callanan549c9f72010-07-13 21:41:46 +00001569bool
Sean Callanan79763a42011-05-23 21:40:23 +00001570IRForTarget::HandleSymbol (Value *symbol)
Sean Callanand9ca42a2011-05-08 02:21:26 +00001571{
Greg Clayton5160ce52013-03-27 23:08:40 +00001572 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananc3a16002011-01-17 23:42:46 +00001573
1574 lldb_private::ConstString name(symbol->getName().str().c_str());
1575
Sean Callanan947ccc72011-12-01 02:04:16 +00001576 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name, lldb::eSymbolTypeAny);
Sean Callananc3a16002011-01-17 23:42:46 +00001577
Greg Clayton084db102011-06-23 04:25:29 +00001578 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc3a16002011-01-17 23:42:46 +00001579 {
1580 if (log)
1581 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1582
1583 return false;
1584 }
1585
1586 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001587 log->Printf("Found \"%s\" at 0x%" PRIx64, name.GetCString(), symbol_addr);
Sean Callananc3a16002011-01-17 23:42:46 +00001588
Sean Callanancc427fa2011-07-30 02:42:06 +00001589 Type *symbol_type = symbol->getType();
Sean Callananc3a16002011-01-17 23:42:46 +00001590
Sean Callanan439dcae2013-12-20 19:55:02 +00001591 Constant *symbol_addr_int = ConstantInt::get(m_intptr_ty, symbol_addr, false);
Sean Callananc3a16002011-01-17 23:42:46 +00001592
1593 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1594
1595 if (log)
1596 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1597
1598 symbol->replaceAllUsesWith(symbol_addr_ptr);
1599
1600 return true;
1601}
1602
1603bool
Sean Callanan79763a42011-05-23 21:40:23 +00001604IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanan85a0a832010-10-05 22:26:43 +00001605{
Greg Clayton5160ce52013-03-27 23:08:40 +00001606 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanand7a1ca22010-12-02 19:47:57 +00001607
1608 if (log)
1609 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanan85a0a832010-10-05 22:26:43 +00001610
Sean Callananafe16a72010-11-17 23:00:36 +00001611 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanan85a0a832010-10-05 22:26:43 +00001612 op_index < num_ops;
1613 ++op_index)
Sean Callanan79763a42011-05-23 21:40:23 +00001614 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan3989fb92011-01-27 01:07:04 +00001615 {
1616 if (m_error_stream)
1617 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1618
Sean Callanan85a0a832010-10-05 22:26:43 +00001619 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001620 }
1621
Sean Callanan85a0a832010-10-05 22:26:43 +00001622 return true;
1623}
1624
1625bool
Sean Callananfc89c142011-11-01 23:38:03 +00001626IRForTarget::HandleObjCClass(Value *classlist_reference)
1627{
Greg Clayton5160ce52013-03-27 23:08:40 +00001628 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananfc89c142011-11-01 23:38:03 +00001629
1630 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(classlist_reference);
1631
1632 if (!global_variable)
1633 return false;
1634
1635 Constant *initializer = global_variable->getInitializer();
1636
1637 if (!initializer)
1638 return false;
1639
1640 if (!initializer->hasName())
1641 return false;
1642
1643 StringRef name(initializer->getName());
1644 lldb_private::ConstString name_cstr(name.str().c_str());
Greg Clayton1075aca2011-12-03 20:02:42 +00001645 lldb::addr_t class_ptr = m_decl_map->GetSymbolAddress(name_cstr, lldb::eSymbolTypeObjCClass);
Sean Callananfc89c142011-11-01 23:38:03 +00001646
1647 if (log)
1648 log->Printf("Found reference to Objective-C class %s (0x%llx)", name_cstr.AsCString(), (unsigned long long)class_ptr);
1649
1650 if (class_ptr == LLDB_INVALID_ADDRESS)
1651 return false;
1652
Ed Mastea8553092014-03-10 17:24:16 +00001653 if (global_variable->use_empty())
Sean Callananfc89c142011-11-01 23:38:03 +00001654 return false;
1655
Sean Callanan719a4d52013-03-23 01:01:16 +00001656 SmallVector<LoadInst *, 2> load_instructions;
1657
Ed Mastea8553092014-03-10 17:24:16 +00001658 for (llvm::User *u : global_variable->users())
Sean Callananfc89c142011-11-01 23:38:03 +00001659 {
Ed Mastea8553092014-03-10 17:24:16 +00001660 if (LoadInst *load_instruction = dyn_cast<LoadInst>(u))
Sean Callanan719a4d52013-03-23 01:01:16 +00001661 load_instructions.push_back(load_instruction);
Sean Callananfc89c142011-11-01 23:38:03 +00001662 }
1663
Sean Callanan719a4d52013-03-23 01:01:16 +00001664 if (load_instructions.empty())
Sean Callananfc89c142011-11-01 23:38:03 +00001665 return false;
1666
Sean Callanan439dcae2013-12-20 19:55:02 +00001667 Constant *class_addr = ConstantInt::get(m_intptr_ty, (uint64_t)class_ptr);
Sean Callananfc89c142011-11-01 23:38:03 +00001668
Sean Callanan719a4d52013-03-23 01:01:16 +00001669 for (LoadInst *load_instruction : load_instructions)
1670 {
1671 Constant *class_bitcast = ConstantExpr::getIntToPtr(class_addr, load_instruction->getType());
Sean Callananfc89c142011-11-01 23:38:03 +00001672
Sean Callanan719a4d52013-03-23 01:01:16 +00001673 load_instruction->replaceAllUsesWith(class_bitcast);
1674
1675 load_instruction->eraseFromParent();
1676 }
Sean Callananfc89c142011-11-01 23:38:03 +00001677
1678 return true;
1679}
1680
1681bool
Sean Callanan6e6d4a62012-07-21 02:02:15 +00001682IRForTarget::RemoveCXAAtExit (BasicBlock &basic_block)
1683{
1684 BasicBlock::iterator ii;
1685
1686 std::vector<CallInst *> calls_to_remove;
1687
1688 for (ii = basic_block.begin();
1689 ii != basic_block.end();
1690 ++ii)
1691 {
1692 Instruction &inst = *ii;
1693
1694 CallInst *call = dyn_cast<CallInst>(&inst);
1695
1696 // MaybeHandleCallArguments handles error reporting; we are silent here
1697 if (!call)
1698 continue;
1699
1700 bool remove = false;
1701
1702 llvm::Function *func = call->getCalledFunction();
1703
1704 if (func && func->getName() == "__cxa_atexit")
1705 remove = true;
1706
1707 llvm::Value *val = call->getCalledValue();
1708
1709 if (val && val->getName() == "__cxa_atexit")
1710 remove = true;
1711
1712 if (remove)
1713 calls_to_remove.push_back(call);
1714 }
1715
1716 for (std::vector<CallInst *>::iterator ci = calls_to_remove.begin(), ce = calls_to_remove.end();
1717 ci != ce;
1718 ++ci)
1719 {
1720 (*ci)->eraseFromParent();
1721 }
1722
1723 return true;
1724}
1725
1726bool
Sean Callanan79763a42011-05-23 21:40:23 +00001727IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan549c9f72010-07-13 21:41:46 +00001728{
Sean Callanan2ab712f22010-07-03 01:35:46 +00001729 /////////////////////////////////////////////////////////////////////////
1730 // Prepare the current basic block for execution in the remote process
1731 //
1732
Sean Callanan7ea35012010-07-27 21:39:39 +00001733 BasicBlock::iterator ii;
Sean Callanan549c9f72010-07-13 21:41:46 +00001734
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001735 for (ii = basic_block.begin();
1736 ii != basic_block.end();
Sean Callanan549c9f72010-07-13 21:41:46 +00001737 ++ii)
Sean Callanan2ab712f22010-07-03 01:35:46 +00001738 {
Sean Callanan549c9f72010-07-13 21:41:46 +00001739 Instruction &inst = *ii;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001740
Sean Callanana4e55172010-11-08 00:31:32 +00001741 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callanan4edba2d2010-07-27 02:07:53 +00001742
Sean Callanan3989fb92011-01-27 01:07:04 +00001743 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callanan79763a42011-05-23 21:40:23 +00001744 if (call && !MaybeHandleCallArguments(call))
Sean Callanand7a1ca22010-12-02 19:47:57 +00001745 return false;
Sean Callanan2ab712f22010-07-03 01:35:46 +00001746 }
1747
1748 return true;
1749}
1750
Sean Callanana4e55172010-11-08 00:31:32 +00001751bool
Sean Callanan79763a42011-05-23 21:40:23 +00001752IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanana4e55172010-11-08 00:31:32 +00001753{
Greg Clayton5160ce52013-03-27 23:08:40 +00001754 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7a55a322010-11-18 22:21:58 +00001755
Sean Callanan79763a42011-05-23 21:40:23 +00001756 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanana4e55172010-11-08 00:31:32 +00001757 global != end;
1758 ++global)
1759 {
Sean Callanan694e2442011-12-22 21:24:49 +00001760 if (!global)
1761 {
1762 if (m_error_stream)
1763 m_error_stream->Printf("Internal error [IRForTarget]: global variable is NULL");
1764
1765 return false;
1766 }
1767
1768 std::string global_name = (*global).getName().str();
1769
Greg Clayton1b95a6f2010-11-19 01:05:25 +00001770 if (log)
1771 log->Printf("Examining %s, DeclForGlobalValue returns %p",
Sean Callanan694e2442011-12-22 21:24:49 +00001772 global_name.c_str(),
Sean Callanan79763a42011-05-23 21:40:23 +00001773 DeclForGlobal(global));
Sean Callananfc89c142011-11-01 23:38:03 +00001774
1775 if (global_name.find("OBJC_IVAR") == 0)
Sean Callananc3a16002011-01-17 23:42:46 +00001776 {
Sean Callanan79763a42011-05-23 21:40:23 +00001777 if (!HandleSymbol(global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001778 {
1779 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001780 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 +00001781
Sean Callananc3a16002011-01-17 23:42:46 +00001782 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001783 }
Sean Callananc3a16002011-01-17 23:42:46 +00001784 }
Sean Callananfc89c142011-11-01 23:38:03 +00001785 else if (global_name.find("OBJC_CLASSLIST_REFERENCES_$") != global_name.npos)
1786 {
1787 if (!HandleObjCClass(global))
1788 {
1789 if (m_error_stream)
1790 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1791
1792 return false;
1793 }
1794 }
Sean Callanan2ad66912013-04-24 21:25:20 +00001795 else if (global_name.find("OBJC_CLASSLIST_SUP_REFS_$") != global_name.npos)
1796 {
1797 if (!HandleObjCClass(global))
1798 {
1799 if (m_error_stream)
1800 m_error_stream->Printf("Error [IRForTarget]: Couldn't resolve the class for an Objective-C static method call\n");
1801
1802 return false;
1803 }
1804 }
Sean Callanan79763a42011-05-23 21:40:23 +00001805 else if (DeclForGlobal(global))
Sean Callananc3a16002011-01-17 23:42:46 +00001806 {
Sean Callanan79763a42011-05-23 21:40:23 +00001807 if (!MaybeHandleVariable (global))
Sean Callanan3989fb92011-01-27 01:07:04 +00001808 {
1809 if (m_error_stream)
Sean Callanan694e2442011-12-22 21:24:49 +00001810 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 +00001811
Sean Callananc3a16002011-01-17 23:42:46 +00001812 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00001813 }
Sean Callananc3a16002011-01-17 23:42:46 +00001814 }
Sean Callanana4e55172010-11-08 00:31:32 +00001815 }
1816
1817 return true;
1818}
1819
Sean Callanan79763a42011-05-23 21:40:23 +00001820bool
1821IRForTarget::ReplaceStrings ()
1822{
Greg Clayton5160ce52013-03-27 23:08:40 +00001823 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001824
Sean Callanan79763a42011-05-23 21:40:23 +00001825 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1826
1827 OffsetsTy offsets;
1828
1829 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1830 gi != ge;
1831 ++gi)
1832 {
1833 GlobalVariable *gv = gi;
1834
1835 if (!gv->hasInitializer())
1836 continue;
1837
1838 Constant *gc = gv->getInitializer();
1839
Sean Callanan5207a342011-08-10 21:05:52 +00001840 std::string str;
Sean Callanan79763a42011-05-23 21:40:23 +00001841
Sean Callanan5207a342011-08-10 21:05:52 +00001842 if (gc->isNullValue())
1843 {
1844 Type *gc_type = gc->getType();
1845
1846 ArrayType *gc_array_type = dyn_cast<ArrayType>(gc_type);
1847
1848 if (!gc_array_type)
1849 continue;
1850
1851 Type *gc_element_type = gc_array_type->getElementType();
1852
1853 IntegerType *gc_integer_type = dyn_cast<IntegerType>(gc_element_type);
1854
1855 if (gc_integer_type->getBitWidth() != 8)
1856 continue;
1857
1858 str = "";
1859 }
1860 else
1861 {
Sean Callanand2b465f2012-02-09 03:22:41 +00001862 ConstantDataArray *gc_array = dyn_cast<ConstantDataArray>(gc);
Sean Callanan5207a342011-08-10 21:05:52 +00001863
1864 if (!gc_array)
1865 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001866
Sean Callanan5207a342011-08-10 21:05:52 +00001867 if (!gc_array->isCString())
1868 continue;
Sean Callanan79763a42011-05-23 21:40:23 +00001869
Sean Callanan5207a342011-08-10 21:05:52 +00001870 if (log)
1871 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00001872
Sean Callanan5207a342011-08-10 21:05:52 +00001873 str = gc_array->getAsString();
1874 }
1875
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001876 offsets[gv] = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00001877
Sean Callanan8dfb68e2013-03-19 00:10:07 +00001878 m_data_allocator.GetStream().Write(str.c_str(), str.length() + 1);
Sean Callanan79763a42011-05-23 21:40:23 +00001879 }
1880
Sean Callanancc427fa2011-07-30 02:42:06 +00001881 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00001882
1883 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1884 oi != oe;
1885 ++oi)
1886 {
1887 GlobalVariable *gv = oi->first;
1888 size_t offset = oi->second;
1889
1890 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1891
1892 if (log)
1893 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1894
Ed Mastea8553092014-03-10 17:24:16 +00001895 for (llvm::User *u : gv->users())
Sean Callanan79763a42011-05-23 21:40:23 +00001896 {
1897 if (log)
Ed Mastea8553092014-03-10 17:24:16 +00001898 log->Printf("Found use %s", PrintValue(u).c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00001899
Ed Mastea8553092014-03-10 17:24:16 +00001900 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(u);
1901 StoreInst *store_inst = dyn_cast<StoreInst>(u);
Sean Callanan79763a42011-05-23 21:40:23 +00001902
1903 if (const_expr)
1904 {
1905 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1906 {
1907 if (log)
1908 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1909
1910 return false;
1911 }
1912
Sean Callanan5207a342011-08-10 21:05:52 +00001913 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, const_expr->getOperand(0)->getType());
1914 Constant *new_gep = const_expr->getWithOperandReplaced(0, bit_cast);
1915
1916 const_expr->replaceAllUsesWith(new_gep);
Sean Callanan79763a42011-05-23 21:40:23 +00001917 }
1918 else if (store_inst)
1919 {
1920 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1921
1922 store_inst->setOperand(0, bit_cast);
1923 }
1924 else
1925 {
1926 if (log)
1927 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1928
1929 return false;
1930 }
1931 }
1932
1933 gv->eraseFromParent();
1934 }
1935
1936 return true;
1937}
1938
1939bool
1940IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1941{
Greg Clayton5160ce52013-03-27 23:08:40 +00001942 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00001943
1944 typedef SmallVector <Value*, 2> ConstantList;
1945 typedef SmallVector <llvm::Instruction*, 2> UserList;
1946 typedef ConstantList::iterator ConstantIterator;
1947 typedef UserList::iterator UserIterator;
1948
1949 ConstantList static_constants;
1950 UserList static_users;
1951
1952 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1953 ii != ie;
1954 ++ii)
1955 {
1956 llvm::Instruction &inst = *ii;
1957
1958 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1959 oi != oe;
1960 ++oi)
1961 {
1962 Value *operand_val = oi->get();
1963
1964 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1965
Sean Callanan822944c2012-04-26 20:51:20 +00001966 if (operand_constant_fp/* && operand_constant_fp->getType()->isX86_FP80Ty()*/)
Sean Callanan79763a42011-05-23 21:40:23 +00001967 {
1968 static_constants.push_back(operand_val);
1969 static_users.push_back(ii);
1970 }
1971 }
1972 }
1973
1974 ConstantIterator constant_iter;
1975 UserIterator user_iter;
Greg Clayton9b72eb72011-05-24 23:06:02 +00001976
Sean Callanan79763a42011-05-23 21:40:23 +00001977 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1978 constant_iter != static_constants.end();
1979 ++constant_iter, ++user_iter)
1980 {
1981 Value *operand_val = *constant_iter;
1982 llvm::Instruction *inst = *user_iter;
1983
1984 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1985
1986 if (operand_constant_fp)
1987 {
Sean Callanan1582ee62013-04-18 22:06:33 +00001988 Type *operand_type = operand_constant_fp->getType();
1989
Sean Callanan79763a42011-05-23 21:40:23 +00001990 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
1991 APInt operand_apint = operand_apfloat.bitcastToAPInt();
1992
1993 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
1994 size_t operand_data_size = operand_apint.getBitWidth() / 8;
1995
1996 if (log)
1997 {
1998 std::string s;
1999 raw_string_ostream ss(s);
2000 for (size_t index = 0;
2001 index < operand_data_size;
2002 ++index)
2003 {
2004 ss << (uint32_t)operand_raw_data[index];
2005 ss << " ";
2006 }
2007 ss.flush();
2008
Greg Clayton6fea17e2014-03-03 19:15:20 +00002009 log->Printf("Found ConstantFP with size %" PRIu64 " and raw data %s", (uint64_t)operand_data_size, s.c_str());
Sean Callanan79763a42011-05-23 21:40:23 +00002010 }
2011
2012 lldb_private::DataBufferHeap data(operand_data_size, 0);
2013
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002014 if (lldb::endian::InlHostByteOrder() != m_data_allocator.GetStream().GetByteOrder())
Sean Callanan79763a42011-05-23 21:40:23 +00002015 {
2016 uint8_t *data_bytes = data.GetBytes();
2017
2018 for (size_t index = 0;
2019 index < operand_data_size;
2020 ++index)
2021 {
2022 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
2023 }
2024 }
2025 else
2026 {
2027 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
2028 }
2029
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002030 uint64_t offset = m_data_allocator.GetStream().GetSize();
Sean Callanan79763a42011-05-23 21:40:23 +00002031
Sean Callanane3333d62012-06-08 22:20:41 +00002032 size_t align = m_target_data->getPrefTypeAlignment(operand_type);
2033
2034 const size_t mask = (align - 1);
2035 uint64_t aligned_offset = (offset + mask) & ~mask;
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002036 m_data_allocator.GetStream().PutNHex8(aligned_offset - offset, 0);
Sean Callanane3333d62012-06-08 22:20:41 +00002037 offset = aligned_offset;
2038
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002039 m_data_allocator.GetStream().Write(data.GetBytes(), operand_data_size);
Sean Callanan79763a42011-05-23 21:40:23 +00002040
Sean Callanancc427fa2011-07-30 02:42:06 +00002041 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callanan79763a42011-05-23 21:40:23 +00002042
Sean Callanan1582ee62013-04-18 22:06:33 +00002043 Constant *new_pointer = BuildRelocation(fp_ptr_ty, aligned_offset);
Sean Callanan79763a42011-05-23 21:40:23 +00002044
2045 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
2046
2047 operand_constant_fp->replaceAllUsesWith(fp_load);
2048 }
2049 }
2050
2051 return true;
2052}
2053
Sean Callanan7ea35012010-07-27 21:39:39 +00002054static bool isGuardVariableRef(Value *V)
Sean Callananddb46ef2010-07-24 01:37:44 +00002055{
Sean Callanan77eaf442011-07-08 00:39:14 +00002056 Constant *Old = NULL;
Sean Callananddb46ef2010-07-24 01:37:44 +00002057
Sean Callananafe16a72010-11-17 23:00:36 +00002058 if (!(Old = dyn_cast<Constant>(V)))
Sean Callananddb46ef2010-07-24 01:37:44 +00002059 return false;
2060
Sean Callanan77eaf442011-07-08 00:39:14 +00002061 ConstantExpr *CE = NULL;
Sean Callanane2ef6e32010-09-23 03:01:22 +00002062
2063 if ((CE = dyn_cast<ConstantExpr>(V)))
2064 {
2065 if (CE->getOpcode() != Instruction::BitCast)
2066 return false;
2067
Sean Callananafe16a72010-11-17 23:00:36 +00002068 Old = CE->getOperand(0);
Sean Callanane2ef6e32010-09-23 03:01:22 +00002069 }
2070
Sean Callananafe16a72010-11-17 23:00:36 +00002071 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callananddb46ef2010-07-24 01:37:44 +00002072
2073 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
2074 return false;
2075
2076 return true;
2077}
2078
Sean Callanan79763a42011-05-23 21:40:23 +00002079void
2080IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callananddb46ef2010-07-24 01:37:44 +00002081{
Sean Callanan79763a42011-05-23 21:40:23 +00002082 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callananddb46ef2010-07-24 01:37:44 +00002083
Ed Maste80e8cc62014-03-10 14:23:10 +00002084 for (llvm::User *u : guard_load->users())
Sean Callananb27a62f2010-07-27 01:17:28 +00002085 {
Ed Maste80e8cc62014-03-10 14:23:10 +00002086 if (isa<Constant>(u))
Sean Callananb27a62f2010-07-27 01:17:28 +00002087 {
2088 // do nothing for the moment
2089 }
2090 else
2091 {
Ed Maste80e8cc62014-03-10 14:23:10 +00002092 u->replaceUsesOfWith(guard_load, zero);
Sean Callananb27a62f2010-07-27 01:17:28 +00002093 }
2094 }
Sean Callananddb46ef2010-07-24 01:37:44 +00002095
2096 guard_load->eraseFromParent();
2097}
2098
2099static void ExciseGuardStore(Instruction* guard_store)
2100{
2101 guard_store->eraseFromParent();
2102}
2103
2104bool
Sean Callanan79763a42011-05-23 21:40:23 +00002105IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callananddb46ef2010-07-24 01:37:44 +00002106{
2107 ///////////////////////////////////////////////////////
2108 // Eliminate any reference to guard variables found.
2109 //
2110
Sean Callanan7ea35012010-07-27 21:39:39 +00002111 BasicBlock::iterator ii;
Sean Callananddb46ef2010-07-24 01:37:44 +00002112
Sean Callanan7ea35012010-07-27 21:39:39 +00002113 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callananddb46ef2010-07-24 01:37:44 +00002114 typedef InstrList::iterator InstrIterator;
2115
2116 InstrList guard_loads;
2117 InstrList guard_stores;
2118
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002119 for (ii = basic_block.begin();
2120 ii != basic_block.end();
Sean Callananddb46ef2010-07-24 01:37:44 +00002121 ++ii)
2122 {
2123 Instruction &inst = *ii;
2124
2125 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
2126 if (isGuardVariableRef(load->getPointerOperand()))
2127 guard_loads.push_back(&inst);
2128
2129 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
2130 if (isGuardVariableRef(store->getPointerOperand()))
2131 guard_stores.push_back(&inst);
2132 }
2133
2134 InstrIterator iter;
2135
2136 for (iter = guard_loads.begin();
2137 iter != guard_loads.end();
2138 ++iter)
Sean Callanan79763a42011-05-23 21:40:23 +00002139 TurnGuardLoadIntoZero(*iter);
Sean Callananddb46ef2010-07-24 01:37:44 +00002140
2141 for (iter = guard_stores.begin();
2142 iter != guard_stores.end();
2143 ++iter)
2144 ExciseGuardStore(*iter);
2145
2146 return true;
2147}
2148
Sean Callanan3989fb92011-01-27 01:07:04 +00002149// This function does not report errors; its callers are responsible.
Sean Callananafe16a72010-11-17 23:00:36 +00002150bool
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002151IRForTarget::UnfoldConstant(Constant *old_constant,
2152 FunctionValueCache &value_maker,
2153 FunctionValueCache &entry_instruction_finder)
Sean Callanan7618f4e2010-07-14 23:40:29 +00002154{
Greg Clayton5160ce52013-03-27 23:08:40 +00002155 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan7618f4e2010-07-14 23:40:29 +00002156
Sean Callanan2235f322010-08-11 03:57:18 +00002157 SmallVector<User*, 16> users;
2158
2159 // We do this because the use list might change, invalidating our iterator.
2160 // Much better to keep a work list ourselves.
Ed Maste80e8cc62014-03-10 14:23:10 +00002161 for (llvm::User *u : old_constant->users())
2162 users.push_back(u);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002163
Johnny Chen44805302011-07-19 19:48:13 +00002164 for (size_t i = 0;
Sean Callanan2235f322010-08-11 03:57:18 +00002165 i < users.size();
2166 ++i)
2167 {
2168 User *user = users[i];
2169
Sean Callanan7618f4e2010-07-14 23:40:29 +00002170 if (Constant *constant = dyn_cast<Constant>(user))
2171 {
2172 // synthesize a new non-constant equivalent of the constant
2173
2174 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
2175 {
2176 switch (constant_expr->getOpcode())
2177 {
2178 default:
2179 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002180 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002181 return false;
2182 case Instruction::BitCast:
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002183 {
2184 FunctionValueCache bit_cast_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2185 // UnaryExpr
2186 // OperandList[0] is value
2187
2188 if (constant_expr->getOperand(0) != old_constant)
2189 return constant_expr;
2190
2191 return new BitCastInst(value_maker.GetValue(function),
2192 constant_expr->getType(),
2193 "",
2194 llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2195 });
Sean Callanan7618f4e2010-07-14 23:40:29 +00002196
Sean Callanan0e016fe2013-07-15 23:31:47 +00002197 if (!UnfoldConstant(constant_expr, bit_cast_maker, entry_instruction_finder))
2198 return false;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002199 }
2200 break;
2201 case Instruction::GetElementPtr:
2202 {
2203 // GetElementPtrConstantExpr
2204 // OperandList[0] is base
2205 // OperandList[1]... are indices
2206
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002207 FunctionValueCache get_element_pointer_maker ([&value_maker, &entry_instruction_finder, old_constant, constant_expr] (llvm::Function *function)->llvm::Value* {
2208 Value *ptr = constant_expr->getOperand(0);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002209
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002210 if (ptr == old_constant)
2211 ptr = value_maker.GetValue(function);
Sean Callanan7618f4e2010-07-14 23:40:29 +00002212
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002213 std::vector<Value*> index_vector;
2214
2215 unsigned operand_index;
2216 unsigned num_operands = constant_expr->getNumOperands();
2217
2218 for (operand_index = 1;
2219 operand_index < num_operands;
2220 ++operand_index)
2221 {
2222 Value *operand = constant_expr->getOperand(operand_index);
2223
2224 if (operand == old_constant)
2225 operand = value_maker.GetValue(function);
2226
2227 index_vector.push_back(operand);
2228 }
2229
2230 ArrayRef <Value*> indices(index_vector);
2231
2232 return GetElementPtrInst::Create(ptr, indices, "", llvm::cast<Instruction>(entry_instruction_finder.GetValue(function)));
2233 });
Sean Callanan7618f4e2010-07-14 23:40:29 +00002234
Sean Callanan0e016fe2013-07-15 23:31:47 +00002235 if (!UnfoldConstant(constant_expr, get_element_pointer_maker, entry_instruction_finder))
2236 return false;
Sean Callanan7618f4e2010-07-14 23:40:29 +00002237 }
2238 break;
2239 }
2240 }
2241 else
2242 {
2243 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002244 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callanan7618f4e2010-07-14 23:40:29 +00002245 return false;
2246 }
2247 }
2248 else
2249 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002250 if (Instruction *inst = llvm::dyn_cast<Instruction>(user))
2251 {
2252 inst->replaceUsesOfWith(old_constant, value_maker.GetValue(inst->getParent()->getParent()));
2253 }
2254 else
2255 {
2256 if (log)
2257 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(user).c_str());
2258 return false;
2259 }
Sean Callanan7618f4e2010-07-14 23:40:29 +00002260 }
2261 }
2262
Sean Callanan0e016fe2013-07-15 23:31:47 +00002263 if (!isa<GlobalValue>(old_constant))
2264 {
2265 old_constant->destroyConstant();
2266 }
2267
Sean Callanan7618f4e2010-07-14 23:40:29 +00002268 return true;
2269}
2270
Sean Callanan549c9f72010-07-13 21:41:46 +00002271bool
Sean Callanan79763a42011-05-23 21:40:23 +00002272IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan549c9f72010-07-13 21:41:46 +00002273{
Sean Callanan9e6ed532010-09-13 21:34:21 +00002274 if (!m_resolve_vars)
2275 return true;
2276
Greg Clayton5160ce52013-03-27 23:08:40 +00002277 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan549c9f72010-07-13 21:41:46 +00002278
2279 m_decl_map->DoStructLayout();
2280
2281 if (log)
2282 log->Printf("Element arrangement:");
2283
2284 uint32_t num_elements;
2285 uint32_t element_index;
2286
2287 size_t size;
2288 off_t alignment;
2289
2290 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2291 return false;
2292
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002293 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan549c9f72010-07-13 21:41:46 +00002294
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002295 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002296 {
2297 if (m_error_stream)
2298 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2299
Sean Callanan549c9f72010-07-13 21:41:46 +00002300 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002301 }
2302
Sean Callanan7ea35012010-07-27 21:39:39 +00002303 Argument *argument = iter;
Sean Callanan549c9f72010-07-13 21:41:46 +00002304
Sean Callananfc55f5d2010-09-21 00:44:12 +00002305 if (argument->getName().equals("this"))
2306 {
2307 ++iter;
2308
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002309 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002310 {
2311 if (m_error_stream)
2312 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2313
Sean Callananfc55f5d2010-09-21 00:44:12 +00002314 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002315 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002316
2317 argument = iter;
2318 }
Sean Callanan17827832010-12-13 22:46:15 +00002319 else if (argument->getName().equals("self"))
2320 {
2321 ++iter;
2322
2323 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002324 {
2325 if (m_error_stream)
2326 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2327
Sean Callanan17827832010-12-13 22:46:15 +00002328 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002329 }
Sean Callanan17827832010-12-13 22:46:15 +00002330
2331 if (!iter->getName().equals("_cmd"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002332 {
2333 if (m_error_stream)
2334 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2335
Sean Callanan17827832010-12-13 22:46:15 +00002336 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002337 }
Sean Callanan17827832010-12-13 22:46:15 +00002338
2339 ++iter;
2340
2341 if (iter == llvm_function.getArgumentList().end())
Sean Callanan3989fb92011-01-27 01:07:04 +00002342 {
2343 if (m_error_stream)
2344 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2345
Sean Callanan17827832010-12-13 22:46:15 +00002346 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002347 }
Sean Callanan17827832010-12-13 22:46:15 +00002348
2349 argument = iter;
2350 }
Sean Callananfc55f5d2010-09-21 00:44:12 +00002351
Greg Clayton7b462cc2010-10-15 22:48:33 +00002352 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan3989fb92011-01-27 01:07:04 +00002353 {
2354 if (m_error_stream)
2355 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2356
Sean Callanan549c9f72010-07-13 21:41:46 +00002357 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002358 }
2359
Sean Callanan549c9f72010-07-13 21:41:46 +00002360 if (log)
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002361 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan549c9f72010-07-13 21:41:46 +00002362
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002363 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callananafe16a72010-11-17 23:00:36 +00002364 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan549c9f72010-07-13 21:41:46 +00002365
Sean Callananafe16a72010-11-17 23:00:36 +00002366 if (!FirstEntryInstruction)
Sean Callanan3989fb92011-01-27 01:07:04 +00002367 {
2368 if (m_error_stream)
2369 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2370
Sean Callanan549c9f72010-07-13 21:41:46 +00002371 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002372 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002373
Sean Callanan79763a42011-05-23 21:40:23 +00002374 LLVMContext &context(m_module->getContext());
Sean Callanancc427fa2011-07-30 02:42:06 +00002375 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan549c9f72010-07-13 21:41:46 +00002376
2377 if (!offset_type)
Sean Callanan3989fb92011-01-27 01:07:04 +00002378 {
2379 if (m_error_stream)
2380 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2381
Sean Callanan549c9f72010-07-13 21:41:46 +00002382 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002383 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002384
2385 for (element_index = 0; element_index < num_elements; ++element_index)
2386 {
Sean Callanan77eaf442011-07-08 00:39:14 +00002387 const clang::NamedDecl *decl = NULL;
2388 Value *value = NULL;
Sean Callanan549c9f72010-07-13 21:41:46 +00002389 off_t offset;
Greg Clayton7b462cc2010-10-15 22:48:33 +00002390 lldb_private::ConstString name;
Sean Callanan549c9f72010-07-13 21:41:46 +00002391
Sean Callanan823bb4c2010-08-30 22:17:16 +00002392 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan3989fb92011-01-27 01:07:04 +00002393 {
2394 if (m_error_stream)
2395 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2396
Sean Callanan549c9f72010-07-13 21:41:46 +00002397 return false;
Sean Callanan3989fb92011-01-27 01:07:04 +00002398 }
2399
Sean Callanan549c9f72010-07-13 21:41:46 +00002400 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002401 log->Printf(" \"%s\" (\"%s\") placed at %" PRId64,
Greg Clayton7b462cc2010-10-15 22:48:33 +00002402 name.GetCString(),
Sean Callananc70ed462011-10-25 18:36:40 +00002403 decl->getNameAsString().c_str(),
Sean Callanan549c9f72010-07-13 21:41:46 +00002404 offset);
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002405
Sean Callananc70ed462011-10-25 18:36:40 +00002406 if (value)
Sean Callanan92adcac2011-01-13 08:53:35 +00002407 {
Sean Callananc70ed462011-10-25 18:36:40 +00002408 if (log)
2409 log->Printf(" Replacing [%s]", PrintValue(value).c_str());
Sean Callanan92adcac2011-01-13 08:53:35 +00002410
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002411 FunctionValueCache body_result_maker ([this, name, offset_type, offset, argument, value] (llvm::Function *function)->llvm::Value * {
2412 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2413 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2414 // entry in order to produce the static variable that the AST thinks it is accessing.
Sean Callananc70ed462011-10-25 18:36:40 +00002415
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002416 llvm::Instruction *entry_instruction = llvm::cast<Instruction>(m_entry_instruction_finder.GetValue(function));
Sean Callananc70ed462011-10-25 18:36:40 +00002417
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002418 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
2419 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument,
2420 offset_int,
2421 "",
2422 entry_instruction);
2423
2424 if (name == m_result_name && !m_result_is_pointer)
2425 {
2426 BitCastInst *bit_cast = new BitCastInst(get_element_ptr,
2427 value->getType()->getPointerTo(),
2428 "",
2429 entry_instruction);
2430
2431 LoadInst *load = new LoadInst(bit_cast, "", entry_instruction);
2432
2433 return load;
2434 }
2435 else
2436 {
2437 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", entry_instruction);
2438
2439 return bit_cast;
2440 }
2441 });
Sean Callananc70ed462011-10-25 18:36:40 +00002442
2443 if (Constant *constant = dyn_cast<Constant>(value))
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002444 {
2445 UnfoldConstant(constant, body_result_maker, m_entry_instruction_finder);
2446 }
2447 else if (Instruction *instruction = dyn_cast<Instruction>(value))
2448 {
2449 value->replaceAllUsesWith(body_result_maker.GetValue(instruction->getParent()->getParent()));
2450 }
Sean Callananc70ed462011-10-25 18:36:40 +00002451 else
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002452 {
2453 if (log)
2454 log->Printf("Unhandled non-constant type: \"%s\"", PrintValue(value).c_str());
2455 return false;
2456 }
Sean Callananc70ed462011-10-25 18:36:40 +00002457
2458 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2459 var->eraseFromParent();
2460 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002461 }
2462
2463 if (log)
Greg Clayton6fea17e2014-03-03 19:15:20 +00002464 log->Printf("Total structure [align %" PRId64 ", size %" PRIu64 "]", (int64_t)alignment, (uint64_t)size);
Sean Callanan549c9f72010-07-13 21:41:46 +00002465
2466 return true;
2467}
2468
Sean Callanan79763a42011-05-23 21:40:23 +00002469llvm::Constant *
Greg Clayton5160ce52013-03-27 23:08:40 +00002470IRForTarget::BuildRelocation(llvm::Type *type, uint64_t offset)
Sean Callanan79763a42011-05-23 21:40:23 +00002471{
Sean Callanan439dcae2013-12-20 19:55:02 +00002472 llvm::Constant *offset_int = ConstantInt::get(m_intptr_ty, offset);
Sean Callanancc427fa2011-07-30 02:42:06 +00002473
2474 llvm::Constant *offset_array[1];
2475
2476 offset_array[0] = offset_int;
2477
2478 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2479
2480 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callanan79763a42011-05-23 21:40:23 +00002481 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2482
2483 return reloc_getbitcast;
2484}
2485
2486bool
2487IRForTarget::CompleteDataAllocation ()
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002488{
Greg Clayton5160ce52013-03-27 23:08:40 +00002489 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan79763a42011-05-23 21:40:23 +00002490
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002491 if (!m_data_allocator.GetStream().GetSize())
Sean Callanan79763a42011-05-23 21:40:23 +00002492 return true;
2493
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002494 lldb::addr_t allocation = m_data_allocator.Allocate();
Sean Callanan79763a42011-05-23 21:40:23 +00002495
2496 if (log)
2497 {
2498 if (allocation)
2499 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2500 else
2501 log->Printf("Failed to allocate static data");
2502 }
2503
Sean Callanan8dfb68e2013-03-19 00:10:07 +00002504 if (!allocation || allocation == LLDB_INVALID_ADDRESS)
Sean Callanan79763a42011-05-23 21:40:23 +00002505 return false;
2506
Sean Callanan439dcae2013-12-20 19:55:02 +00002507 Constant *relocated_addr = ConstantInt::get(m_intptr_ty, (uint64_t)allocation);
Sean Callanan79763a42011-05-23 21:40:23 +00002508 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2509
2510 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2511
2512 m_reloc_placeholder->eraseFromParent();
2513
2514 return true;
2515}
2516
Sean Callanan2ab712f22010-07-03 01:35:46 +00002517bool
Sean Callanan3d654b32012-09-24 22:25:51 +00002518IRForTarget::StripAllGVs (Module &llvm_module)
2519{
Greg Clayton5160ce52013-03-27 23:08:40 +00002520 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3d654b32012-09-24 22:25:51 +00002521 std::vector<GlobalVariable *> global_vars;
2522 std::set<GlobalVariable *>erased_vars;
2523
2524 bool erased = true;
2525
2526 while (erased)
2527 {
2528 erased = false;
2529
2530 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2531 gi != ge;
2532 ++gi)
2533 {
2534 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2535
2536 global_var->removeDeadConstantUsers();
2537
2538 if (global_var->use_empty())
2539 {
2540 if (log)
2541 log->Printf("Did remove %s",
2542 PrintValue(global_var).c_str());
2543 global_var->eraseFromParent();
2544 erased = true;
2545 break;
2546 }
2547 }
2548 }
2549
2550 for (Module::global_iterator gi = llvm_module.global_begin(), ge = llvm_module.global_end();
2551 gi != ge;
2552 ++gi)
2553 {
2554 GlobalVariable *global_var = dyn_cast<GlobalVariable>(gi);
2555
Ed Mastea8553092014-03-10 17:24:16 +00002556 GlobalValue::user_iterator ui = global_var->user_begin();
Sean Callanan3d654b32012-09-24 22:25:51 +00002557
Jim Inghamd77557d2012-11-26 19:54:04 +00002558 if (log)
2559 log->Printf("Couldn't remove %s because of %s",
2560 PrintValue(global_var).c_str(),
2561 PrintValue(*ui).c_str());
Sean Callanan3d654b32012-09-24 22:25:51 +00002562 }
2563
2564 return true;
2565}
2566
2567bool
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002568IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002569{
Greg Clayton5160ce52013-03-27 23:08:40 +00002570 lldb_private::Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan2ab712f22010-07-03 01:35:46 +00002571
Sean Callanan79763a42011-05-23 21:40:23 +00002572 m_module = &llvm_module;
Micah Villmow8468dbe2012-10-08 16:28:57 +00002573 m_target_data.reset(new DataLayout(m_module));
Sean Callanan439dcae2013-12-20 19:55:02 +00002574 m_intptr_ty = llvm::Type::getIntNTy(m_module->getContext(), m_target_data->getPointerSizeInBits());
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002575
Sean Callananc70ed462011-10-25 18:36:40 +00002576 if (log)
2577 {
2578 std::string s;
2579 raw_string_ostream oss(s);
2580
2581 m_module->print(oss, NULL);
2582
2583 oss.flush();
2584
2585 log->Printf("Module as passed in to IRForTarget: \n\"%s\"", s.c_str());
2586 }
2587
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002588 Function* main_function = m_module->getFunction(StringRef(m_func_name.c_str()));
2589
2590 if (!main_function)
2591 {
2592 if (log)
2593 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
2594
2595 if (m_error_stream)
2596 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
2597
2598 return false;
2599 }
2600
2601 if (!FixFunctionLinkage (*main_function))
2602 {
2603 if (log)
2604 log->Printf("Couldn't fix the linkage for the function");
2605
2606 return false;
2607 }
2608
Sean Callanan439dcae2013-12-20 19:55:02 +00002609 llvm::Type *int8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan79763a42011-05-23 21:40:23 +00002610
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002611 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
Sean Callanan439dcae2013-12-20 19:55:02 +00002612 int8_ty,
Sean Callanan3d654b32012-09-24 22:25:51 +00002613 false /* IsConstant */,
Sean Callanan79763a42011-05-23 21:40:23 +00002614 GlobalVariable::InternalLinkage,
Sean Callanan439dcae2013-12-20 19:55:02 +00002615 Constant::getNullValue(int8_ty),
Sean Callanan79763a42011-05-23 21:40:23 +00002616 "reloc_placeholder",
2617 NULL /* InsertBefore */,
Sean Callanan3d654b32012-09-24 22:25:51 +00002618 GlobalVariable::NotThreadLocal /* ThreadLocal */,
Sean Callanan79763a42011-05-23 21:40:23 +00002619 0 /* AddressSpace */);
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002620
Sean Callanand1e5b432010-08-12 01:56:52 +00002621 ////////////////////////////////////////////////////////////
Greg Clayton7b462cc2010-10-15 22:48:33 +00002622 // Replace $__lldb_expr_result with a persistent variable
Sean Callanand1e5b432010-08-12 01:56:52 +00002623 //
2624
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002625 if (!CreateResultVariable(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002626 {
2627 if (log)
2628 log->Printf("CreateResultVariable() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002629
2630 // CreateResultVariable() reports its own errors, so we don't do so here
2631
Sean Callanand1e5b432010-08-12 01:56:52 +00002632 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002633 }
Sean Callanan6e6d4a62012-07-21 02:02:15 +00002634
Sean Callananea685ae2011-11-01 17:33:54 +00002635 if (log && log->GetVerbose())
Sean Callanan79763a42011-05-23 21:40:23 +00002636 {
2637 std::string s;
2638 raw_string_ostream oss(s);
2639
2640 m_module->print(oss, NULL);
2641
2642 oss.flush();
2643
2644 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2645 }
2646
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002647 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2648 fi != fe;
2649 ++fi)
2650 {
2651 llvm::Function *function = fi;
2652
2653 if (function->begin() == function->end())
2654 continue;
2655
2656 Function::iterator bbi;
2657
2658 for (bbi = function->begin();
2659 bbi != function->end();
2660 ++bbi)
2661 {
2662 if (!RemoveGuards(*bbi))
2663 {
2664 if (log)
2665 log->Printf("RemoveGuards() failed");
2666
2667 // RemoveGuards() reports its own errors, so we don't do so here
2668
2669 return false;
2670 }
2671
2672 if (!RewritePersistentAllocs(*bbi))
2673 {
2674 if (log)
2675 log->Printf("RewritePersistentAllocs() failed");
2676
2677 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2678
2679 return false;
2680 }
2681
2682 if (!RemoveCXAAtExit(*bbi))
2683 {
2684 if (log)
2685 log->Printf("RemoveCXAAtExit() failed");
2686
2687 // RemoveCXAAtExit() reports its own errors, so we don't do so here
2688
2689 return false;
2690 }
2691 }
2692 }
2693
Sean Callananafe16a72010-11-17 23:00:36 +00002694 ///////////////////////////////////////////////////////////////////////////////
2695 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2696 //
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002697
2698 if (!RewriteObjCConstStrings())
Sean Callanan17827832010-12-13 22:46:15 +00002699 {
2700 if (log)
2701 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002702
2703 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2704
Sean Callananafe16a72010-11-17 23:00:36 +00002705 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002706 }
Sean Callananafe16a72010-11-17 23:00:36 +00002707
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002708 ///////////////////////////////
2709 // Resolve function pointers
2710 //
2711
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002712 if (!ResolveFunctionPointers(llvm_module))
Sean Callanan0c4d8d22011-08-04 21:37:47 +00002713 {
2714 if (log)
2715 log->Printf("ResolveFunctionPointers() failed");
2716
2717 // ResolveFunctionPointers() reports its own errors, so we don't do so here
2718
2719 return false;
2720 }
2721
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002722 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2723 fi != fe;
2724 ++fi)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002725 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002726 llvm::Function *function = fi;
2727
2728 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2729 bbi != bbe;
2730 ++bbi)
Sean Callanan17827832010-12-13 22:46:15 +00002731 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002732 if (!RewriteObjCSelectors(*bbi))
2733 {
2734 if (log)
2735 log->Printf("RewriteObjCSelectors() failed");
2736
2737 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2738
2739 return false;
2740 }
Sean Callanan17827832010-12-13 22:46:15 +00002741 }
Sean Callananbad134f2012-07-27 19:25:24 +00002742 }
Sean Callanan2235f322010-08-11 03:57:18 +00002743
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002744 for (Module::iterator fi = m_module->begin(), fe = m_module->end();
2745 fi != fe;
2746 ++fi)
Sean Callananbad134f2012-07-27 19:25:24 +00002747 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002748 llvm::Function *function = fi;
Sean Callanan79763a42011-05-23 21:40:23 +00002749
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002750 for (llvm::Function::iterator bbi = function->begin(), bbe = function->end();
2751 bbi != bbe;
2752 ++bbi)
Sean Callanan79763a42011-05-23 21:40:23 +00002753 {
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002754 if (!ResolveCalls(*bbi))
2755 {
2756 if (log)
2757 log->Printf("ResolveCalls() failed");
2758
2759 // ResolveCalls() reports its own errors, so we don't do so here
2760
2761 return false;
2762 }
Sean Callanan79763a42011-05-23 21:40:23 +00002763
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002764 if (!ReplaceStaticLiterals(*bbi))
2765 {
2766 if (log)
2767 log->Printf("ReplaceStaticLiterals() failed");
2768
2769 return false;
2770 }
Sean Callanan79763a42011-05-23 21:40:23 +00002771 }
Sean Callanan549c9f72010-07-13 21:41:46 +00002772 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002773
2774 ////////////////////////////////////////////////////////////////////////
2775 // Run function-level passes that only make sense on the main function
Sean Callanan038df5032010-09-30 21:18:25 +00002776 //
2777
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002778 if (!ResolveExternals(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002779 {
2780 if (log)
2781 log->Printf("ResolveExternals() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002782
2783 // ResolveExternals() reports its own errors, so we don't do so here
2784
Sean Callanana4e55172010-11-08 00:31:32 +00002785 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002786 }
Sean Callanana4e55172010-11-08 00:31:32 +00002787
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002788 if (!ReplaceVariables(*main_function))
Sean Callanan17827832010-12-13 22:46:15 +00002789 {
2790 if (log)
2791 log->Printf("ReplaceVariables() failed");
Sean Callanan3989fb92011-01-27 01:07:04 +00002792
2793 // ReplaceVariables() reports its own errors, so we don't do so here
2794
Sean Callanan038df5032010-09-30 21:18:25 +00002795 return false;
Sean Callanan17827832010-12-13 22:46:15 +00002796 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002797
Sean Callanan79763a42011-05-23 21:40:23 +00002798 if (!ReplaceStrings())
2799 {
2800 if (log)
2801 log->Printf("ReplaceStrings() failed");
2802
2803 return false;
2804 }
2805
2806 if (!CompleteDataAllocation())
2807 {
2808 if (log)
2809 log->Printf("CompleteDataAllocation() failed");
2810
2811 return false;
2812 }
Sean Callanan1f9db3e2013-06-28 21:44:15 +00002813
Sean Callanan3d654b32012-09-24 22:25:51 +00002814 if (!StripAllGVs(llvm_module))
2815 {
2816 if (log)
2817 log->Printf("StripAllGVs() failed");
2818 }
2819
Sean Callananea685ae2011-11-01 17:33:54 +00002820 if (log && log->GetVerbose())
Sean Callanan549c9f72010-07-13 21:41:46 +00002821 {
Sean Callanancc54bd32010-07-28 01:00:59 +00002822 std::string s;
2823 raw_string_ostream oss(s);
Sean Callanan549c9f72010-07-13 21:41:46 +00002824
Sean Callanan79763a42011-05-23 21:40:23 +00002825 m_module->print(oss, NULL);
Sean Callanancc54bd32010-07-28 01:00:59 +00002826
2827 oss.flush();
2828
Greg Claytoncb7e3b32010-11-15 01:47:11 +00002829 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan2ab712f22010-07-03 01:35:46 +00002830 }
2831
2832 return true;
2833}
2834
2835void
Greg Clayton1b95a6f2010-11-19 01:05:25 +00002836IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan2ab712f22010-07-03 01:35:46 +00002837{
2838}
2839
2840PassManagerType
2841IRForTarget::getPotentialPassManagerType() const
2842{
2843 return PMT_ModulePassManager;
2844}