blob: dd73c519fe8e9dfee629b7a76255082d4b0dea12 [file] [log] [blame]
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001//===-- IRForTarget.cpp -------------------------------------------*- C++ -*-===//
2//
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"
Sean Callanan2a8c3382011-04-14 02:01:31 +000013#include "llvm/Constants.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000014#include "llvm/InstrTypes.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000015#include "llvm/Instructions.h"
Sean Callanan3cb1fd82010-09-28 23:55:00 +000016#include "llvm/Intrinsics.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000017#include "llvm/Module.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000018#include "llvm/Target/TargetData.h"
Sean Callanan82b74c82010-08-12 01:56:52 +000019#include "llvm/ValueSymbolTable.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000020
21#include "clang/AST/ASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000022
Greg Clayton8de27c72010-10-15 22:48:33 +000023#include "lldb/Core/ConstString.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000024#include "lldb/Core/dwarf.h"
25#include "lldb/Core/Log.h"
26#include "lldb/Core/Scalar.h"
27#include "lldb/Core/StreamString.h"
28#include "lldb/Expression/ClangExpressionDeclMap.h"
Sean Callananc0492742011-05-23 21:40:23 +000029#include "lldb/Host/Endian.h"
Sean Callanan696cf5f2011-05-07 01:06:41 +000030#include "lldb/Symbol/ClangASTContext.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000031
32#include <map>
33
34using namespace llvm;
35
Sean Callanan3351dac2010-08-18 18:50:51 +000036static char ID;
37
Sean Callananc0492742011-05-23 21:40:23 +000038IRForTarget::StaticDataAllocator::StaticDataAllocator()
39{
40}
41
42IRForTarget::StaticDataAllocator::~StaticDataAllocator()
43{
44}
45
Greg Clayton3c7feb42010-11-19 01:05:25 +000046IRForTarget::IRForTarget (lldb_private::ClangExpressionDeclMap *decl_map,
47 bool resolve_vars,
Sean Callanan696cf5f2011-05-07 01:06:41 +000048 lldb::ClangExpressionVariableSP &const_result,
Sean Callananc0492742011-05-23 21:40:23 +000049 StaticDataAllocator *data_allocator,
Sean Callanan97c924e2011-01-27 01:07:04 +000050 lldb_private::Stream *error_stream,
Greg Clayton3c7feb42010-11-19 01:05:25 +000051 const char *func_name) :
Sean Callanan47a5c4c2010-09-23 03:01:22 +000052 ModulePass(ID),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000053 m_resolve_vars(resolve_vars),
54 m_func_name(func_name),
Sean Callananc0492742011-05-23 21:40:23 +000055 m_module(NULL),
Johnny Chen2bc9eb32011-07-19 19:48:13 +000056 m_decl_map(decl_map),
57 m_data_allocator(data_allocator),
Sean Callanan6ba533e2010-11-17 23:00:36 +000058 m_CFStringCreateWithBytes(NULL),
Sean Callanan65dafa82010-08-27 01:01:44 +000059 m_sel_registerName(NULL),
Johnny Chen2bc9eb32011-07-19 19:48:13 +000060 m_const_result(const_result),
Stephen Wilsondbeb3e12011-04-11 19:41:40 +000061 m_error_stream(error_stream),
Sean Callanan6a925532011-01-13 08:53:35 +000062 m_has_side_effects(false),
Sean Callanan696cf5f2011-05-07 01:06:41 +000063 m_result_store(NULL),
64 m_result_is_pointer(false),
Sean Callananc0492742011-05-23 21:40:23 +000065 m_reloc_placeholder(NULL)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000066{
67}
68
Sean Callanan771131d2010-09-30 21:18:25 +000069/* Handy utility functions used at several places in the code */
Sean Callanana48fe162010-08-11 03:57:18 +000070
71static std::string
Greg Clayton3c7feb42010-11-19 01:05:25 +000072PrintValue(const Value *value, bool truncate = false)
Sean Callanana48fe162010-08-11 03:57:18 +000073{
74 std::string s;
75 raw_string_ostream rso(s);
Greg Clayton3c7feb42010-11-19 01:05:25 +000076 value->print(rso);
Sean Callanana48fe162010-08-11 03:57:18 +000077 rso.flush();
78 if (truncate)
79 s.resize(s.length() - 1);
80 return s;
81}
82
Sean Callanan771131d2010-09-30 21:18:25 +000083static std::string
Greg Clayton3c7feb42010-11-19 01:05:25 +000084PrintType(const Type *type, bool truncate = false)
Sean Callanan771131d2010-09-30 21:18:25 +000085{
86 std::string s;
87 raw_string_ostream rso(s);
Greg Clayton3c7feb42010-11-19 01:05:25 +000088 type->print(rso);
Sean Callanan771131d2010-09-30 21:18:25 +000089 rso.flush();
90 if (truncate)
91 s.resize(s.length() - 1);
92 return s;
93}
94
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000095IRForTarget::~IRForTarget()
96{
97}
98
Sean Callananc0492742011-05-23 21:40:23 +000099bool
100IRForTarget::FixFunctionLinkage(llvm::Function &llvm_function)
101{
102 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
103
104 llvm_function.setLinkage(GlobalValue::ExternalLinkage);
105
106 std::string name = llvm_function.getNameStr();
107
108 return true;
109}
110
Sean Callanan82b74c82010-08-12 01:56:52 +0000111bool
Sean Callananc0492742011-05-23 21:40:23 +0000112IRForTarget::HasSideEffects (llvm::Function &llvm_function)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000113{
114 llvm::Function::iterator bbi;
115 BasicBlock::iterator ii;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000116
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000117 for (bbi = llvm_function.begin();
118 bbi != llvm_function.end();
119 ++bbi)
120 {
121 BasicBlock &basic_block = *bbi;
122
123 for (ii = basic_block.begin();
124 ii != basic_block.end();
125 ++ii)
126 {
127 switch (ii->getOpcode())
128 {
129 default:
130 return true;
131 case Instruction::Store:
132 {
133 StoreInst *store_inst = dyn_cast<StoreInst>(ii);
134
135 Value *store_ptr = store_inst->getPointerOperand();
136
Sean Callanan696cf5f2011-05-07 01:06:41 +0000137 std::string ptr_name;
138
139 if (store_ptr->hasName())
140 ptr_name = store_ptr->getNameStr();
141
142 if (isa <AllocaInst> (store_ptr))
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000143 break;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000144
145 if (ptr_name.find("$__lldb_expr_result") != std::string::npos)
146 {
147 if (ptr_name.find("GV") == std::string::npos)
148 m_result_store = store_inst;
149 }
150 else
151 {
152 return true;
153 }
154
155 break;
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000156 }
157 case Instruction::Load:
158 case Instruction::Alloca:
159 case Instruction::GetElementPtr:
Sean Callanan696cf5f2011-05-07 01:06:41 +0000160 case Instruction::BitCast:
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000161 case Instruction::Ret:
Sean Callanan696cf5f2011-05-07 01:06:41 +0000162 case Instruction::ICmp:
163 case Instruction::Br:
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000164 break;
165 }
166 }
167 }
168
169 return false;
170}
171
Sean Callanan696cf5f2011-05-07 01:06:41 +0000172clang::NamedDecl *
Sean Callananc0492742011-05-23 21:40:23 +0000173IRForTarget::DeclForGlobal (GlobalValue *global_val)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000174{
175 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
176
Sean Callananc0492742011-05-23 21:40:23 +0000177 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan696cf5f2011-05-07 01:06:41 +0000178
179 if (!named_metadata)
180 return NULL;
181
182 unsigned num_nodes = named_metadata->getNumOperands();
183 unsigned node_index;
184
185 for (node_index = 0;
186 node_index < num_nodes;
187 ++node_index)
188 {
189 MDNode *metadata_node = named_metadata->getOperand(node_index);
190
191 if (!metadata_node)
192 return NULL;
193
194 if (metadata_node->getNumOperands() != 2)
195 continue;
196
197 if (metadata_node->getOperand(0) != global_val)
198 continue;
199
200 ConstantInt *constant_int = dyn_cast<ConstantInt>(metadata_node->getOperand(1));
201
202 if (!constant_int)
203 return NULL;
204
205 uintptr_t ptr = constant_int->getZExtValue();
206
207 return reinterpret_cast<clang::NamedDecl *>(ptr);
208 }
209
210 return NULL;
211}
212
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000213void
214IRForTarget::MaybeSetConstantResult (llvm::Constant *initializer,
215 const lldb_private::ConstString &name,
216 lldb_private::TypeFromParser type)
217{
Sean Callanan696cf5f2011-05-07 01:06:41 +0000218 if (llvm::ConstantExpr *init_expr = dyn_cast<llvm::ConstantExpr>(initializer))
219 {
220 switch (init_expr->getOpcode())
221 {
222 default:
223 return;
224 case Instruction::IntToPtr:
225 MaybeSetConstantResult (init_expr->getOperand(0), name, type);
226 return;
227 }
228 }
229 else if (llvm::ConstantInt *init_int = dyn_cast<llvm::ConstantInt>(initializer))
230 {
231 m_const_result = m_decl_map->BuildIntegerVariable(name, type, init_int->getValue());
232 }
233}
234
235void
Sean Callananc0492742011-05-23 21:40:23 +0000236IRForTarget::MaybeSetCastResult (lldb_private::TypeFromParser type)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000237{
238 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
239
240 if (!m_result_store)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000241 return;
242
Sean Callanan696cf5f2011-05-07 01:06:41 +0000243 LoadInst *original_load = NULL;
244
245 for (llvm::Value *current_value = m_result_store->getValueOperand(), *next_value;
246 current_value != NULL;
247 current_value = next_value)
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000248 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000249 CastInst *cast_inst = dyn_cast<CastInst>(current_value);
250 LoadInst *load_inst = dyn_cast<LoadInst>(current_value);
251
252 if (cast_inst)
253 {
254 next_value = cast_inst->getOperand(0);
255 }
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000256 else if (load_inst)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000257 {
258 if (isa<LoadInst>(load_inst->getPointerOperand()))
259 {
260 next_value = load_inst->getPointerOperand();
261 }
262 else
263 {
264 original_load = load_inst;
265 break;
266 }
267 }
268 else
269 {
270 return;
271 }
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000272 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000273
274 Value *loaded_value = original_load->getPointerOperand();
275 GlobalVariable *loaded_global = dyn_cast<GlobalVariable>(loaded_value);
276
277 if (!loaded_global)
278 return;
279
Sean Callananc0492742011-05-23 21:40:23 +0000280 clang::NamedDecl *loaded_decl = DeclForGlobal(loaded_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000281
282 if (!loaded_decl)
283 return;
284
285 clang::VarDecl *loaded_var = dyn_cast<clang::VarDecl>(loaded_decl);
286
287 if (!loaded_var)
288 return;
289
290 if (log)
291 {
292 lldb_private::StreamString type_desc_stream;
293 type.DumpTypeDescription(&type_desc_stream);
294
295 log->Printf("Type to cast variable to: \"%s\"", type_desc_stream.GetString().c_str());
296 }
297
298 m_const_result = m_decl_map->BuildCastVariable(m_result_name, loaded_var, type);
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000299}
300
301bool
Sean Callananc0492742011-05-23 21:40:23 +0000302IRForTarget::CreateResultVariable (llvm::Function &llvm_function)
Sean Callanan82b74c82010-08-12 01:56:52 +0000303{
Greg Claytone005f2c2010-11-06 01:53:30 +0000304 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan82b74c82010-08-12 01:56:52 +0000305
Sean Callanane8a59a82010-09-13 21:34:21 +0000306 if (!m_resolve_vars)
307 return true;
308
309 // Find the result variable. If it doesn't exist, we can give up right here.
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000310
Sean Callananc0492742011-05-23 21:40:23 +0000311 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000312
Sean Callanan9b6898f2011-07-30 02:42:06 +0000313 std::string result_name_str;
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000314 const char *result_name = NULL;
315
316 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
317 vi != ve;
318 ++vi)
319 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000320 result_name_str = vi->first().str();
321 const char *value_name = result_name_str.c_str();
322
323 if (strstr(value_name, "$__lldb_expr_result_ptr") &&
324 !strstr(value_name, "GV"))
Sean Callanan6a925532011-01-13 08:53:35 +0000325 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000326 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000327 m_result_is_pointer = true;
328 break;
329 }
330
Sean Callanan9b6898f2011-07-30 02:42:06 +0000331 if (strstr(value_name, "$__lldb_expr_result") &&
332 !strstr(value_name, "GV"))
Sean Callananc04743d2010-09-28 21:13:03 +0000333 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000334 result_name = value_name;
Sean Callanan6a925532011-01-13 08:53:35 +0000335 m_result_is_pointer = false;
Sean Callananc04743d2010-09-28 21:13:03 +0000336 break;
337 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000338 }
339
340 if (!result_name)
341 {
342 if (log)
343 log->PutCString("Couldn't find result variable");
344
345 return true;
346 }
347
Sean Callananc04743d2010-09-28 21:13:03 +0000348 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000349 log->Printf("Result name: \"%s\"", result_name);
Sean Callananc04743d2010-09-28 21:13:03 +0000350
Sean Callananc0492742011-05-23 21:40:23 +0000351 Value *result_value = m_module->getNamedValue(result_name);
Sean Callanan82b74c82010-08-12 01:56:52 +0000352
353 if (!result_value)
354 {
355 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000356 log->PutCString("Result variable had no data");
Sean Callanan6a925532011-01-13 08:53:35 +0000357
Sean Callanan97c924e2011-01-27 01:07:04 +0000358 if (m_error_stream)
359 m_error_stream->Printf("Internal error [IRForTarget]: Result variable's name (%s) exists, but not its definition\n", result_name);
360
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000361 return false;
Sean Callanan82b74c82010-08-12 01:56:52 +0000362 }
Sean Callanane8a59a82010-09-13 21:34:21 +0000363
Sean Callanan82b74c82010-08-12 01:56:52 +0000364 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000365 log->Printf("Found result in the IR: \"%s\"", PrintValue(result_value, false).c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000366
367 GlobalVariable *result_global = dyn_cast<GlobalVariable>(result_value);
368
369 if (!result_global)
370 {
371 if (log)
372 log->PutCString("Result variable isn't a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000373
374 if (m_error_stream)
375 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) is defined, but is not a global variable\n", result_name);
376
Sean Callanan82b74c82010-08-12 01:56:52 +0000377 return false;
378 }
379
Sean Callananc0492742011-05-23 21:40:23 +0000380 clang::NamedDecl *result_decl = DeclForGlobal (result_global);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000381 if (!result_decl)
Sean Callanan82b74c82010-08-12 01:56:52 +0000382 {
383 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000384 log->PutCString("Result variable doesn't have a corresponding Decl");
Sean Callanan82b74c82010-08-12 01:56:52 +0000385
Sean Callanan97c924e2011-01-27 01:07:04 +0000386 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000387 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) does not have a corresponding Clang entity\n", result_name);
Sean Callanan97c924e2011-01-27 01:07:04 +0000388
Sean Callanan82b74c82010-08-12 01:56:52 +0000389 return false;
390 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000391
Sean Callanan696cf5f2011-05-07 01:06:41 +0000392 if (log)
Sean Callanan82b74c82010-08-12 01:56:52 +0000393 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000394 std::string decl_desc_str;
395 raw_string_ostream decl_desc_stream(decl_desc_str);
396 result_decl->print(decl_desc_stream);
397 decl_desc_stream.flush();
Sean Callanan82b74c82010-08-12 01:56:52 +0000398
Sean Callanan696cf5f2011-05-07 01:06:41 +0000399 log->Printf("Found result decl: \"%s\"", decl_desc_str.c_str());
Sean Callanan82b74c82010-08-12 01:56:52 +0000400 }
401
Sean Callanan696cf5f2011-05-07 01:06:41 +0000402 clang::VarDecl *result_var = dyn_cast<clang::VarDecl>(result_decl);
403 if (!result_var)
Sean Callanan82b74c82010-08-12 01:56:52 +0000404 {
405 if (log)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000406 log->PutCString("Result variable Decl isn't a VarDecl");
Sean Callanan97c924e2011-01-27 01:07:04 +0000407
408 if (m_error_stream)
Sean Callanan696cf5f2011-05-07 01:06:41 +0000409 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s)'s corresponding Clang entity isn't a variable\n", result_name);
Sean Callanan97c924e2011-01-27 01:07:04 +0000410
Sean Callanan82b74c82010-08-12 01:56:52 +0000411 return false;
412 }
Sean Callanan82b74c82010-08-12 01:56:52 +0000413
Sean Callanan82b74c82010-08-12 01:56:52 +0000414 // Get the next available result name from m_decl_map and create the persistent
415 // variable for it
416
Sean Callanan6a925532011-01-13 08:53:35 +0000417 lldb_private::TypeFromParser result_decl_type;
418
Sean Callanan696cf5f2011-05-07 01:06:41 +0000419 // If the result is an Lvalue, it is emitted as a pointer; see
420 // ASTResultSynthesizer::SynthesizeBodyResult.
Sean Callanan6a925532011-01-13 08:53:35 +0000421 if (m_result_is_pointer)
422 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000423 clang::QualType pointer_qual_type = result_var->getType();
Sean Callanand5b3c352011-01-27 04:42:51 +0000424 const clang::Type *pointer_type = pointer_qual_type.getTypePtr();
425 const clang::PointerType *pointer_pointertype = dyn_cast<clang::PointerType>(pointer_type);
Sean Callanan6a925532011-01-13 08:53:35 +0000426
427 if (!pointer_pointertype)
428 {
429 if (log)
430 log->PutCString("Expected result to have pointer type, but it did not");
Sean Callanan97c924e2011-01-27 01:07:04 +0000431
432 if (m_error_stream)
433 m_error_stream->Printf("Internal error [IRForTarget]: Lvalue result (%s) is not a pointer variable\n", result_name);
434
Sean Callanan6a925532011-01-13 08:53:35 +0000435 return false;
436 }
437
438 clang::QualType element_qual_type = pointer_pointertype->getPointeeType();
439
440 result_decl_type = lldb_private::TypeFromParser(element_qual_type.getAsOpaquePtr(),
441 &result_decl->getASTContext());
442 }
443 else
444 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000445 result_decl_type = lldb_private::TypeFromParser(result_var->getType().getAsOpaquePtr(),
Sean Callanan6a925532011-01-13 08:53:35 +0000446 &result_decl->getASTContext());
447 }
448
Sean Callanan696cf5f2011-05-07 01:06:41 +0000449 if (log)
450 {
451 lldb_private::StreamString type_desc_stream;
452 result_decl_type.DumpTypeDescription(&type_desc_stream);
453
454 log->Printf("Result decl type: \"%s\"", type_desc_stream.GetString().c_str());
455 }
456
Sean Callanan6a925532011-01-13 08:53:35 +0000457 m_result_name = m_decl_map->GetPersistentResultName();
Sean Callanan82b74c82010-08-12 01:56:52 +0000458
459 if (log)
Sean Callanan6a925532011-01-13 08:53:35 +0000460 log->Printf("Creating a new result global: \"%s\"", m_result_name.GetCString());
Sean Callanan82b74c82010-08-12 01:56:52 +0000461
462 // Construct a new result global and set up its metadata
463
Sean Callananc0492742011-05-23 21:40:23 +0000464 GlobalVariable *new_result_global = new GlobalVariable((*m_module),
Sean Callanan82b74c82010-08-12 01:56:52 +0000465 result_global->getType()->getElementType(),
466 false, /* not constant */
467 GlobalValue::ExternalLinkage,
468 NULL, /* no initializer */
Sean Callanan6a925532011-01-13 08:53:35 +0000469 m_result_name.GetCString ());
Sean Callanan82b74c82010-08-12 01:56:52 +0000470
471 // It's too late in compilation to create a new VarDecl for this, but we don't
472 // need to. We point the metadata at the old VarDecl. This creates an odd
473 // anomaly: a variable with a Value whose name is something like $0 and a
Greg Clayton8de27c72010-10-15 22:48:33 +0000474 // Decl whose name is $__lldb_expr_result. This condition is handled in
Sean Callanan82b74c82010-08-12 01:56:52 +0000475 // ClangExpressionDeclMap::DoMaterialize, and the name of the variable is
476 // fixed up.
477
Sean Callananc0492742011-05-23 21:40:23 +0000478 ConstantInt *new_constant_int = ConstantInt::get(llvm::Type::getInt64Ty(m_module->getContext()),
Sean Callanan696cf5f2011-05-07 01:06:41 +0000479 reinterpret_cast<uint64_t>(result_decl),
Sean Callanan82b74c82010-08-12 01:56:52 +0000480 false);
481
482 llvm::Value* values[2];
483 values[0] = new_result_global;
484 values[1] = new_constant_int;
485
Sean Callanan0de254a2011-05-15 22:34:38 +0000486 ArrayRef<Value*> value_ref(values, 2);
487
Sean Callananc0492742011-05-23 21:40:23 +0000488 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
489 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanan82b74c82010-08-12 01:56:52 +0000490 named_metadata->addOperand(persistent_global_md);
491
492 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000493 log->Printf("Replacing \"%s\" with \"%s\"",
Sean Callanan2e2db532010-09-07 22:43:19 +0000494 PrintValue(result_global).c_str(),
Sean Callanan82b74c82010-08-12 01:56:52 +0000495 PrintValue(new_result_global).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000496
497 if (result_global->hasNUses(0))
498 {
499 // We need to synthesize a store for this variable, because otherwise
500 // there's nothing to put into its equivalent persistent variable.
Sean Callanan82b74c82010-08-12 01:56:52 +0000501
Greg Clayton8de27c72010-10-15 22:48:33 +0000502 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan2e2db532010-09-07 22:43:19 +0000503 Instruction *first_entry_instruction(entry_block.getFirstNonPHIOrDbg());
504
505 if (!first_entry_instruction)
506 return false;
507
508 if (!result_global->hasInitializer())
509 {
510 if (log)
511 log->Printf("Couldn't find initializer for unused variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000512
513 if (m_error_stream)
514 m_error_stream->Printf("Internal error [IRForTarget]: Result variable (%s) has no writes and no initializer\n", result_name);
515
Sean Callanan2e2db532010-09-07 22:43:19 +0000516 return false;
517 }
518
519 Constant *initializer = result_global->getInitializer();
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000520
521 // Here we write the initializer into a result variable assuming it
522 // can be computed statically.
523
524 if (!m_has_side_effects)
525 {
526 MaybeSetConstantResult (initializer,
Sean Callanan6a925532011-01-13 08:53:35 +0000527 m_result_name,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000528 result_decl_type);
529 }
Sean Callanan2e2db532010-09-07 22:43:19 +0000530
Greg Clayton2c344ca2011-02-05 02:28:58 +0000531 StoreInst *synthesized_store = new StoreInst(initializer,
532 new_result_global,
533 first_entry_instruction);
Sean Callanan2e2db532010-09-07 22:43:19 +0000534
535 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000536 log->Printf("Synthesized result store \"%s\"\n", PrintValue(synthesized_store).c_str());
Sean Callanan2e2db532010-09-07 22:43:19 +0000537 }
538 else
539 {
Sean Callanan696cf5f2011-05-07 01:06:41 +0000540 if (!m_has_side_effects && lldb_private::ClangASTContext::IsPointerType (result_decl_type.GetOpaqueQualType()))
541 {
Sean Callananc0492742011-05-23 21:40:23 +0000542 MaybeSetCastResult (result_decl_type);
Sean Callanan696cf5f2011-05-07 01:06:41 +0000543 }
544
Sean Callanan2e2db532010-09-07 22:43:19 +0000545 result_global->replaceAllUsesWith(new_result_global);
546 }
Sean Callanan696cf5f2011-05-07 01:06:41 +0000547
548 if (!m_const_result)
549 m_decl_map->AddPersistentVariable(result_decl,
550 m_result_name,
551 result_decl_type,
552 true,
553 m_result_is_pointer);
Sean Callanan2e2db532010-09-07 22:43:19 +0000554
Sean Callanan82b74c82010-08-12 01:56:52 +0000555 result_global->eraseFromParent();
556
557 return true;
558}
559
Greg Clayton3c7feb42010-11-19 01:05:25 +0000560static void DebugUsers(lldb::LogSP &log, Value *value, uint8_t depth)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000561{
562 if (!depth)
563 return;
564
565 depth--;
566
Greg Clayton3c7feb42010-11-19 01:05:25 +0000567 log->Printf(" <Begin %d users>", value->getNumUses());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000568
Greg Clayton3c7feb42010-11-19 01:05:25 +0000569 for (Value::use_iterator ui = value->use_begin(), ue = value->use_end();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000570 ui != ue;
571 ++ui)
572 {
573 log->Printf(" <Use %p> %s", *ui, PrintValue(*ui).c_str());
574 DebugUsers(log, *ui, depth);
575 }
576
577 log->Printf(" <End uses>");
578}
579
580bool
Sean Callananc0492742011-05-23 21:40:23 +0000581IRForTarget::RewriteObjCConstString (llvm::GlobalVariable *ns_str,
Greg Clayton3c7feb42010-11-19 01:05:25 +0000582 llvm::GlobalVariable *cstr,
583 Instruction *FirstEntryInstruction)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000584{
585 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
586
Sean Callanan9b6898f2011-07-30 02:42:06 +0000587 Type *ns_str_ty = ns_str->getType();
Sean Callananc0492742011-05-23 21:40:23 +0000588
Sean Callanan9b6898f2011-07-30 02:42:06 +0000589 Type *i8_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
590 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
Sean Callananc0492742011-05-23 21:40:23 +0000591 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callanan9b6898f2011-07-30 02:42:06 +0000592 Type *i32_ty = Type::getInt32Ty(m_module->getContext());
593 Type *i8_ty = Type::getInt8Ty(m_module->getContext());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000594
595 if (!m_CFStringCreateWithBytes)
596 {
597 lldb::addr_t CFStringCreateWithBytes_addr;
598
599 static lldb_private::ConstString g_CFStringCreateWithBytes_str ("CFStringCreateWithBytes");
600
601 if (!m_decl_map->GetFunctionAddress (g_CFStringCreateWithBytes_str, CFStringCreateWithBytes_addr))
602 {
603 if (log)
604 log->PutCString("Couldn't find CFStringCreateWithBytes in the target");
605
Sean Callanan97c924e2011-01-27 01:07:04 +0000606 if (m_error_stream)
607 m_error_stream->Printf("Error [IRForTarget]: Rewriting an Objective-C constant string requires CFStringCreateWithBytes\n");
608
Sean Callanan6ba533e2010-11-17 23:00:36 +0000609 return false;
610 }
611
612 if (log)
613 log->Printf("Found CFStringCreateWithBytes at 0x%llx", CFStringCreateWithBytes_addr);
614
615 // Build the function type:
616 //
617 // CFStringRef CFStringCreateWithBytes (
618 // CFAllocatorRef alloc,
619 // const UInt8 *bytes,
620 // CFIndex numBytes,
621 // CFStringEncoding encoding,
622 // Boolean isExternalRepresentation
623 // );
624 //
625 // We make the following substitutions:
626 //
627 // CFStringRef -> i8*
628 // CFAllocatorRef -> i8*
629 // UInt8 * -> i8*
630 // CFIndex -> long (i32 or i64, as appropriate; we ask the module for its pointer size for now)
631 // CFStringEncoding -> i32
632 // Boolean -> i8
633
Sean Callanan9b6898f2011-07-30 02:42:06 +0000634 Type *arg_type_array[5];
635
636 arg_type_array[0] = i8_ptr_ty;
637 arg_type_array[1] = i8_ptr_ty;
638 arg_type_array[2] = intptr_ty;
639 arg_type_array[3] = i32_ty;
640 arg_type_array[4] = i8_ty;
641
642 ArrayRef<Type *> CFSCWB_arg_types(arg_type_array, 5);
643
Sean Callananc0492742011-05-23 21:40:23 +0000644 llvm::Type *CFSCWB_ty = FunctionType::get(ns_str_ty, CFSCWB_arg_types, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000645
646 // Build the constant containing the pointer to the function
647 PointerType *CFSCWB_ptr_ty = PointerType::getUnqual(CFSCWB_ty);
648 Constant *CFSCWB_addr_int = ConstantInt::get(intptr_ty, CFStringCreateWithBytes_addr, false);
649 m_CFStringCreateWithBytes = ConstantExpr::getIntToPtr(CFSCWB_addr_int, CFSCWB_ptr_ty);
650 }
651
Sean Callanan58baaad2011-07-08 00:39:14 +0000652 ConstantArray *string_array = NULL;
Sean Callanan0ece5262011-02-10 22:17:53 +0000653
654 if (cstr)
655 string_array = dyn_cast<ConstantArray>(cstr->getInitializer());
Sean Callanan9b6898f2011-07-30 02:42:06 +0000656
Sean Callanan6ba533e2010-11-17 23:00:36 +0000657 Constant *alloc_arg = Constant::getNullValue(i8_ptr_ty);
Sean Callanan0ece5262011-02-10 22:17:53 +0000658 Constant *bytes_arg = cstr ? ConstantExpr::getBitCast(cstr, i8_ptr_ty) : Constant::getNullValue(i8_ptr_ty);
659 Constant *numBytes_arg = ConstantInt::get(intptr_ty, cstr ? string_array->getType()->getNumElements() - 1 : 0, false);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000660 Constant *encoding_arg = ConstantInt::get(i32_ty, 0x0600, false); /* 0x0600 is kCFStringEncodingASCII */
661 Constant *isExternal_arg = ConstantInt::get(i8_ty, 0x0, false); /* 0x0 is false */
662
Sean Callanan9b6898f2011-07-30 02:42:06 +0000663 Value *argument_array[5];
664
665 argument_array[0] = alloc_arg;
666 argument_array[1] = bytes_arg;
667 argument_array[2] = numBytes_arg;
668 argument_array[3] = encoding_arg;
669 argument_array[4] = isExternal_arg;
670
671 ArrayRef <Value *> CFSCWB_arguments(argument_array, 5);
Sean Callanan6ba533e2010-11-17 23:00:36 +0000672
673 CallInst *CFSCWB_call = CallInst::Create(m_CFStringCreateWithBytes,
Sean Callanan9b6898f2011-07-30 02:42:06 +0000674 CFSCWB_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +0000675 "CFStringCreateWithBytes",
676 FirstEntryInstruction);
Sean Callananae71e302010-11-18 22:21:58 +0000677
Greg Clayton3c7feb42010-11-19 01:05:25 +0000678 if (!UnfoldConstant(ns_str, CFSCWB_call, FirstEntryInstruction))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000679 {
680 if (log)
681 log->PutCString("Couldn't replace the NSString with the result of the call");
682
Sean Callanan97c924e2011-01-27 01:07:04 +0000683 if (m_error_stream)
684 m_error_stream->Printf("Error [IRForTarget]: Couldn't replace an Objective-C constant string with a dynamic string\n");
685
Sean Callanan6ba533e2010-11-17 23:00:36 +0000686 return false;
687 }
688
Greg Clayton3c7feb42010-11-19 01:05:25 +0000689 ns_str->eraseFromParent();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000690
691 return true;
692}
693
694bool
Sean Callananc0492742011-05-23 21:40:23 +0000695IRForTarget::RewriteObjCConstStrings(Function &llvm_function)
Sean Callanan6ba533e2010-11-17 23:00:36 +0000696{
697 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
698
Sean Callananc0492742011-05-23 21:40:23 +0000699 ValueSymbolTable& value_symbol_table = m_module->getValueSymbolTable();
Sean Callanan6ba533e2010-11-17 23:00:36 +0000700
Greg Clayton3c7feb42010-11-19 01:05:25 +0000701 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000702 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
703
704 if (!FirstEntryInstruction)
705 {
706 if (log)
707 log->PutCString("Couldn't find first instruction for rewritten Objective-C strings");
708
Sean Callanan97c924e2011-01-27 01:07:04 +0000709 if (m_error_stream)
710 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the location for calls to CFStringCreateWithBytes\n");
711
Sean Callanan6ba533e2010-11-17 23:00:36 +0000712 return false;
713 }
714
715 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
716 vi != ve;
717 ++vi)
718 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000719 std::string value_name = vi->first().str();
720 const char *value_name_cstr = value_name.c_str();
721
722 if (strstr(value_name_cstr, "_unnamed_cfstring_"))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000723 {
724 Value *nsstring_value = vi->second;
725
726 GlobalVariable *nsstring_global = dyn_cast<GlobalVariable>(nsstring_value);
727
728 if (!nsstring_global)
729 {
730 if (log)
731 log->PutCString("NSString variable is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000732
733 if (m_error_stream)
734 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a global variable\n");
735
Sean Callanan6ba533e2010-11-17 23:00:36 +0000736 return false;
737 }
738
739 if (!nsstring_global->hasInitializer())
740 {
741 if (log)
742 log->PutCString("NSString variable does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000743
744 if (m_error_stream)
745 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have an initializer\n");
746
Sean Callanan6ba533e2010-11-17 23:00:36 +0000747 return false;
748 }
749
750 ConstantStruct *nsstring_struct = dyn_cast<ConstantStruct>(nsstring_global->getInitializer());
751
752 if (!nsstring_struct)
753 {
754 if (log)
755 log->PutCString("NSString variable's initializer is not a ConstantStruct");
Sean Callanan97c924e2011-01-27 01:07:04 +0000756
757 if (m_error_stream)
758 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string is not a structure constant\n");
759
Sean Callanan6ba533e2010-11-17 23:00:36 +0000760 return false;
761 }
762
763 // We expect the following structure:
764 //
765 // struct {
766 // int *isa;
767 // int flags;
768 // char *str;
769 // long length;
770 // };
771
772 if (nsstring_struct->getNumOperands() != 4)
773 {
774 if (log)
775 log->Printf("NSString variable's initializer structure has an unexpected number of members. Should be 4, is %d", nsstring_struct->getNumOperands());
Sean Callanan97c924e2011-01-27 01:07:04 +0000776
777 if (m_error_stream)
778 m_error_stream->Printf("Internal error [IRForTarget]: The struct for an Objective-C constant string is not as expected\n");
779
Sean Callanan6ba533e2010-11-17 23:00:36 +0000780 return false;
781 }
782
783 Constant *nsstring_member = nsstring_struct->getOperand(2);
784
785 if (!nsstring_member)
786 {
787 if (log)
788 log->PutCString("NSString initializer's str element was empty");
Sean Callanan97c924e2011-01-27 01:07:04 +0000789
790 if (m_error_stream)
791 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string does not have a string initializer\n");
792
Sean Callanan6ba533e2010-11-17 23:00:36 +0000793 return false;
794 }
795
796 ConstantExpr *nsstring_expr = dyn_cast<ConstantExpr>(nsstring_member);
797
798 if (!nsstring_expr)
799 {
800 if (log)
801 log->PutCString("NSString initializer's str element is not a ConstantExpr");
Sean Callanan97c924e2011-01-27 01:07:04 +0000802
803 if (m_error_stream)
804 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not constant\n");
805
Sean Callanan6ba533e2010-11-17 23:00:36 +0000806 return false;
807 }
808
809 if (nsstring_expr->getOpcode() != Instruction::GetElementPtr)
810 {
811 if (log)
812 log->Printf("NSString initializer's str element is not a GetElementPtr expression, it's a %s", nsstring_expr->getOpcodeName());
Sean Callanan97c924e2011-01-27 01:07:04 +0000813
814 if (m_error_stream)
815 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer is not an array\n");
816
Sean Callanan6ba533e2010-11-17 23:00:36 +0000817 return false;
818 }
819
820 Constant *nsstring_cstr = nsstring_expr->getOperand(0);
821
822 GlobalVariable *cstr_global = dyn_cast<GlobalVariable>(nsstring_cstr);
823
824 if (!cstr_global)
825 {
826 if (log)
827 log->PutCString("NSString initializer's str element is not a GlobalVariable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000828
829 if (m_error_stream)
830 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a global\n");
Sean Callanan65e2aee2010-11-20 02:06:01 +0000831
Sean Callanan6ba533e2010-11-17 23:00:36 +0000832 return false;
833 }
834
835 if (!cstr_global->hasInitializer())
836 {
837 if (log)
838 log->PutCString("NSString initializer's str element does not have an initializer");
Sean Callanan97c924e2011-01-27 01:07:04 +0000839
840 if (m_error_stream)
841 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to initialized data\n");
842
Sean Callanan6ba533e2010-11-17 23:00:36 +0000843 return false;
844 }
Sean Callanan0ece5262011-02-10 22:17:53 +0000845
846 /*
Sean Callanan6ba533e2010-11-17 23:00:36 +0000847 if (!cstr_array)
848 {
849 if (log)
850 log->PutCString("NSString initializer's str element is not a ConstantArray");
Sean Callanan97c924e2011-01-27 01:07:04 +0000851
852 if (m_error_stream)
853 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to an array\n");
854
Sean Callanan6ba533e2010-11-17 23:00:36 +0000855 return false;
856 }
857
858 if (!cstr_array->isCString())
859 {
860 if (log)
861 log->PutCString("NSString initializer's str element is not a C string array");
Sean Callanan97c924e2011-01-27 01:07:04 +0000862
863 if (m_error_stream)
864 m_error_stream->Printf("Internal error [IRForTarget]: An Objective-C constant string's string initializer doesn't point to a C string\n");
865
Sean Callanan6ba533e2010-11-17 23:00:36 +0000866 return false;
867 }
Sean Callanan0ece5262011-02-10 22:17:53 +0000868 */
869
870 ConstantArray *cstr_array = dyn_cast<ConstantArray>(cstr_global->getInitializer());
Sean Callanan6ba533e2010-11-17 23:00:36 +0000871
872 if (log)
Sean Callanan0ece5262011-02-10 22:17:53 +0000873 {
874 if (cstr_array)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000875 log->Printf("Found NSString constant %s, which contains \"%s\"", value_name_cstr, cstr_array->getAsString().c_str());
Sean Callanan0ece5262011-02-10 22:17:53 +0000876 else
Sean Callanan9b6898f2011-07-30 02:42:06 +0000877 log->Printf("Found NSString constant %s, which contains \"\"", value_name_cstr);
Sean Callanan0ece5262011-02-10 22:17:53 +0000878 }
879
880 if (!cstr_array)
881 cstr_global = NULL;
Sean Callanan6ba533e2010-11-17 23:00:36 +0000882
Sean Callananc0492742011-05-23 21:40:23 +0000883 if (!RewriteObjCConstString(nsstring_global, cstr_global, FirstEntryInstruction))
Sean Callanan97c924e2011-01-27 01:07:04 +0000884 {
Sean Callanan6ba533e2010-11-17 23:00:36 +0000885 if (log)
886 log->PutCString("Error rewriting the constant string");
Sean Callanan97c924e2011-01-27 01:07:04 +0000887
888 // We don't print an error message here because RewriteObjCConstString has done so for us.
889
Sean Callanan6ba533e2010-11-17 23:00:36 +0000890 return false;
891 }
Sean Callanan6ba533e2010-11-17 23:00:36 +0000892 }
893 }
894
895 for (ValueSymbolTable::iterator vi = value_symbol_table.begin(), ve = value_symbol_table.end();
896 vi != ve;
897 ++vi)
898 {
Sean Callanan9b6898f2011-07-30 02:42:06 +0000899 std::string value_name = vi->first().str();
900 const char *value_name_cstr = value_name.c_str();
901
902 if (!strcmp(value_name_cstr, "__CFConstantStringClassReference"))
Sean Callanan6ba533e2010-11-17 23:00:36 +0000903 {
904 GlobalVariable *gv = dyn_cast<GlobalVariable>(vi->second);
905
906 if (!gv)
907 {
908 if (log)
909 log->PutCString("__CFConstantStringClassReference is not a global variable");
Sean Callanan97c924e2011-01-27 01:07:04 +0000910
911 if (m_error_stream)
912 m_error_stream->Printf("Internal error [IRForTarget]: Found a CFConstantStringClassReference, but it is not a global object\n");
913
Sean Callanan6ba533e2010-11-17 23:00:36 +0000914 return false;
915 }
916
917 gv->eraseFromParent();
918
919 break;
920 }
921 }
922
923 return true;
924}
925
Greg Clayton3c7feb42010-11-19 01:05:25 +0000926static bool IsObjCSelectorRef (Value *value)
Sean Callananf5857a02010-07-31 01:32:05 +0000927{
Greg Clayton3c7feb42010-11-19 01:05:25 +0000928 GlobalVariable *global_variable = dyn_cast<GlobalVariable>(value);
Sean Callananf5857a02010-07-31 01:32:05 +0000929
Greg Clayton3c7feb42010-11-19 01:05:25 +0000930 if (!global_variable || !global_variable->hasName() || !global_variable->getName().startswith("\01L_OBJC_SELECTOR_REFERENCES_"))
Sean Callananf5857a02010-07-31 01:32:05 +0000931 return false;
932
933 return true;
934}
935
Sean Callanan97c924e2011-01-27 01:07:04 +0000936// This function does not report errors; its callers are responsible.
Sean Callananf5857a02010-07-31 01:32:05 +0000937bool
Sean Callananc0492742011-05-23 21:40:23 +0000938IRForTarget::RewriteObjCSelector (Instruction* selector_load)
Sean Callananf5857a02010-07-31 01:32:05 +0000939{
Greg Claytone005f2c2010-11-06 01:53:30 +0000940 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +0000941
942 LoadInst *load = dyn_cast<LoadInst>(selector_load);
943
944 if (!load)
945 return false;
946
947 // Unpack the message name from the selector. In LLVM IR, an objc_msgSend gets represented as
948 //
949 // %tmp = load i8** @"\01L_OBJC_SELECTOR_REFERENCES_" ; <i8*>
950 // %call = call i8* (i8*, i8*, ...)* @objc_msgSend(i8* %obj, i8* %tmp, ...) ; <i8*>
951 //
952 // where %obj is the object pointer and %tmp is the selector.
953 //
Greg Clayton3c7feb42010-11-19 01:05:25 +0000954 // @"\01L_OBJC_SELECTOR_REFERENCES_" is a pointer to a character array called @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_".
955 // @"\01L_OBJC_llvm_moduleETH_VAR_NAllvm_moduleE_" contains the string.
Sean Callananf5857a02010-07-31 01:32:05 +0000956
957 // Find the pointer's initializer (a ConstantExpr with opcode GetElementPtr) and get the string from its target
958
959 GlobalVariable *_objc_selector_references_ = dyn_cast<GlobalVariable>(load->getPointerOperand());
960
961 if (!_objc_selector_references_ || !_objc_selector_references_->hasInitializer())
962 return false;
963
964 Constant *osr_initializer = _objc_selector_references_->getInitializer();
965
966 ConstantExpr *osr_initializer_expr = dyn_cast<ConstantExpr>(osr_initializer);
967
968 if (!osr_initializer_expr || osr_initializer_expr->getOpcode() != Instruction::GetElementPtr)
969 return false;
970
971 Value *osr_initializer_base = osr_initializer_expr->getOperand(0);
972
973 if (!osr_initializer_base)
974 return false;
975
976 // Find the string's initializer (a ConstantArray) and get the string from it
977
978 GlobalVariable *_objc_meth_var_name_ = dyn_cast<GlobalVariable>(osr_initializer_base);
979
980 if (!_objc_meth_var_name_ || !_objc_meth_var_name_->hasInitializer())
981 return false;
982
983 Constant *omvn_initializer = _objc_meth_var_name_->getInitializer();
984
985 ConstantArray *omvn_initializer_array = dyn_cast<ConstantArray>(omvn_initializer);
986
987 if (!omvn_initializer_array->isString())
988 return false;
989
990 std::string omvn_initializer_string = omvn_initializer_array->getAsString();
991
992 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +0000993 log->Printf("Found Objective-C selector reference \"%s\"", omvn_initializer_string.c_str());
Sean Callananf5857a02010-07-31 01:32:05 +0000994
995 // Construct a call to sel_registerName
996
997 if (!m_sel_registerName)
998 {
Greg Claytonb5037af2010-11-15 01:47:11 +0000999 lldb::addr_t sel_registerName_addr;
Sean Callananf5857a02010-07-31 01:32:05 +00001000
Greg Clayton8de27c72010-10-15 22:48:33 +00001001 static lldb_private::ConstString g_sel_registerName_str ("sel_registerName");
Greg Claytonb5037af2010-11-15 01:47:11 +00001002 if (!m_decl_map->GetFunctionAddress (g_sel_registerName_str, sel_registerName_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001003 return false;
1004
Sean Callananc2c6f772010-10-26 00:31:56 +00001005 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001006 log->Printf("Found sel_registerName at 0x%llx", sel_registerName_addr);
Sean Callananc2c6f772010-10-26 00:31:56 +00001007
Sean Callananf5857a02010-07-31 01:32:05 +00001008 // Build the function type: struct objc_selector *sel_registerName(uint8_t*)
1009
1010 // The below code would be "more correct," but in actuality what's required is uint8_t*
Sean Callananc0492742011-05-23 21:40:23 +00001011 //Type *sel_type = StructType::get(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001012 //Type *sel_ptr_type = PointerType::getUnqual(sel_type);
Sean Callanan9b6898f2011-07-30 02:42:06 +00001013 Type *sel_ptr_type = Type::getInt8PtrTy(m_module->getContext());
Sean Callananf5857a02010-07-31 01:32:05 +00001014
Sean Callanan9b6898f2011-07-30 02:42:06 +00001015 Type *type_array[1];
1016
1017 type_array[0] = llvm::Type::getInt8PtrTy(m_module->getContext());
1018
1019 ArrayRef<Type *> srN_arg_types(type_array, 1);
1020
Sean Callananf5857a02010-07-31 01:32:05 +00001021 llvm::Type *srN_type = FunctionType::get(sel_ptr_type, srN_arg_types, false);
1022
1023 // Build the constant containing the pointer to the function
Sean Callanan9b6898f2011-07-30 02:42:06 +00001024 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1025 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananf5857a02010-07-31 01:32:05 +00001026 PointerType *srN_ptr_ty = PointerType::getUnqual(srN_type);
Greg Claytonb5037af2010-11-15 01:47:11 +00001027 Constant *srN_addr_int = ConstantInt::get(intptr_ty, sel_registerName_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001028 m_sel_registerName = ConstantExpr::getIntToPtr(srN_addr_int, srN_ptr_ty);
1029 }
1030
Sean Callanan9b6898f2011-07-30 02:42:06 +00001031 Value *argument_array[1];
1032
Sean Callananc0492742011-05-23 21:40:23 +00001033 Constant *omvn_pointer = ConstantExpr::getBitCast(_objc_meth_var_name_, Type::getInt8PtrTy(m_module->getContext()));
Sean Callananf5857a02010-07-31 01:32:05 +00001034
Sean Callanan9b6898f2011-07-30 02:42:06 +00001035 argument_array[0] = omvn_pointer;
Sean Callananf5857a02010-07-31 01:32:05 +00001036
Sean Callanan9b6898f2011-07-30 02:42:06 +00001037 ArrayRef<Value *> srN_arguments(argument_array, 1);
1038
Sean Callananf5857a02010-07-31 01:32:05 +00001039 CallInst *srN_call = CallInst::Create(m_sel_registerName,
Sean Callanan9b6898f2011-07-30 02:42:06 +00001040 srN_arguments,
Sean Callanan6ba533e2010-11-17 23:00:36 +00001041 "sel_registerName",
Sean Callananf5857a02010-07-31 01:32:05 +00001042 selector_load);
1043
1044 // Replace the load with the call in all users
1045
1046 selector_load->replaceAllUsesWith(srN_call);
1047
1048 selector_load->eraseFromParent();
1049
1050 return true;
1051}
1052
1053bool
Sean Callananc0492742011-05-23 21:40:23 +00001054IRForTarget::RewriteObjCSelectors (BasicBlock &basic_block)
Sean Callananf5857a02010-07-31 01:32:05 +00001055{
Greg Claytone005f2c2010-11-06 01:53:30 +00001056 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananf5857a02010-07-31 01:32:05 +00001057
1058 BasicBlock::iterator ii;
1059
1060 typedef SmallVector <Instruction*, 2> InstrList;
1061 typedef InstrList::iterator InstrIterator;
1062
1063 InstrList selector_loads;
1064
Greg Clayton3c7feb42010-11-19 01:05:25 +00001065 for (ii = basic_block.begin();
1066 ii != basic_block.end();
Sean Callananf5857a02010-07-31 01:32:05 +00001067 ++ii)
1068 {
1069 Instruction &inst = *ii;
1070
1071 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
Greg Clayton3c7feb42010-11-19 01:05:25 +00001072 if (IsObjCSelectorRef(load->getPointerOperand()))
Sean Callananf5857a02010-07-31 01:32:05 +00001073 selector_loads.push_back(&inst);
1074 }
1075
1076 InstrIterator iter;
1077
1078 for (iter = selector_loads.begin();
1079 iter != selector_loads.end();
1080 ++iter)
1081 {
Sean Callananc0492742011-05-23 21:40:23 +00001082 if (!RewriteObjCSelector(*iter))
Sean Callananf5857a02010-07-31 01:32:05 +00001083 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001084 if (m_error_stream)
1085 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't change a static reference to an Objective-C selector to a dynamic reference\n");
1086
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001087 if (log)
Sean Callananf5857a02010-07-31 01:32:05 +00001088 log->PutCString("Couldn't rewrite a reference to an Objective-C selector");
Sean Callanan97c924e2011-01-27 01:07:04 +00001089
Sean Callananf5857a02010-07-31 01:32:05 +00001090 return false;
1091 }
1092 }
1093
1094 return true;
1095}
1096
Sean Callanan97c924e2011-01-27 01:07:04 +00001097// This function does not report errors; its callers are responsible.
Sean Callanana48fe162010-08-11 03:57:18 +00001098bool
Sean Callananc0492742011-05-23 21:40:23 +00001099IRForTarget::RewritePersistentAlloc (llvm::Instruction *persistent_alloc)
Sean Callanana48fe162010-08-11 03:57:18 +00001100{
Sean Callanan97678d12011-01-13 21:23:32 +00001101 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1102
Sean Callanana48fe162010-08-11 03:57:18 +00001103 AllocaInst *alloc = dyn_cast<AllocaInst>(persistent_alloc);
1104
1105 MDNode *alloc_md = alloc->getMetadata("clang.decl.ptr");
1106
1107 if (!alloc_md || !alloc_md->getNumOperands())
1108 return false;
1109
1110 ConstantInt *constant_int = dyn_cast<ConstantInt>(alloc_md->getOperand(0));
1111
1112 if (!constant_int)
1113 return false;
1114
1115 // We attempt to register this as a new persistent variable with the DeclMap.
1116
1117 uintptr_t ptr = constant_int->getZExtValue();
1118
Sean Callanan82b74c82010-08-12 01:56:52 +00001119 clang::VarDecl *decl = reinterpret_cast<clang::VarDecl *>(ptr);
Sean Callanana48fe162010-08-11 03:57:18 +00001120
Sean Callanan82b74c82010-08-12 01:56:52 +00001121 lldb_private::TypeFromParser result_decl_type (decl->getType().getAsOpaquePtr(),
1122 &decl->getASTContext());
1123
Greg Clayton8de27c72010-10-15 22:48:33 +00001124 StringRef decl_name (decl->getName());
1125 lldb_private::ConstString persistent_variable_name (decl_name.data(), decl_name.size());
Sean Callanan6a925532011-01-13 08:53:35 +00001126 if (!m_decl_map->AddPersistentVariable(decl, persistent_variable_name, result_decl_type, false, false))
Sean Callanana48fe162010-08-11 03:57:18 +00001127 return false;
1128
Sean Callananc0492742011-05-23 21:40:23 +00001129 GlobalVariable *persistent_global = new GlobalVariable((*m_module),
Sean Callanan97678d12011-01-13 21:23:32 +00001130 alloc->getType(),
Sean Callanana48fe162010-08-11 03:57:18 +00001131 false, /* not constant */
1132 GlobalValue::ExternalLinkage,
1133 NULL, /* no initializer */
1134 alloc->getName().str().c_str());
1135
1136 // What we're going to do here is make believe this was a regular old external
1137 // variable. That means we need to make the metadata valid.
1138
Sean Callananc0492742011-05-23 21:40:23 +00001139 NamedMDNode *named_metadata = m_module->getNamedMetadata("clang.global.decl.ptrs");
Sean Callanana48fe162010-08-11 03:57:18 +00001140
1141 llvm::Value* values[2];
1142 values[0] = persistent_global;
1143 values[1] = constant_int;
Sean Callanan0de254a2011-05-15 22:34:38 +00001144
1145 ArrayRef<llvm::Value*> value_ref(values, 2);
Sean Callanana48fe162010-08-11 03:57:18 +00001146
Sean Callananc0492742011-05-23 21:40:23 +00001147 MDNode *persistent_global_md = MDNode::get(m_module->getContext(), value_ref);
Sean Callanana48fe162010-08-11 03:57:18 +00001148 named_metadata->addOperand(persistent_global_md);
1149
Sean Callanan97678d12011-01-13 21:23:32 +00001150 // Now, since the variable is a pointer variable, we will drop in a load of that
1151 // pointer variable.
1152
1153 LoadInst *persistent_load = new LoadInst (persistent_global, "", alloc);
1154
1155 if (log)
1156 log->Printf("Replacing \"%s\" with \"%s\"",
1157 PrintValue(alloc).c_str(),
1158 PrintValue(persistent_load).c_str());
1159
1160 alloc->replaceAllUsesWith(persistent_load);
Sean Callanana48fe162010-08-11 03:57:18 +00001161 alloc->eraseFromParent();
1162
1163 return true;
1164}
1165
1166bool
Sean Callananc0492742011-05-23 21:40:23 +00001167IRForTarget::RewritePersistentAllocs(llvm::BasicBlock &basic_block)
Sean Callanana48fe162010-08-11 03:57:18 +00001168{
Sean Callanane8a59a82010-09-13 21:34:21 +00001169 if (!m_resolve_vars)
1170 return true;
1171
Greg Claytone005f2c2010-11-06 01:53:30 +00001172 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanana48fe162010-08-11 03:57:18 +00001173
1174 BasicBlock::iterator ii;
1175
1176 typedef SmallVector <Instruction*, 2> InstrList;
1177 typedef InstrList::iterator InstrIterator;
1178
1179 InstrList pvar_allocs;
1180
Greg Clayton3c7feb42010-11-19 01:05:25 +00001181 for (ii = basic_block.begin();
1182 ii != basic_block.end();
Sean Callanana48fe162010-08-11 03:57:18 +00001183 ++ii)
1184 {
1185 Instruction &inst = *ii;
1186
1187 if (AllocaInst *alloc = dyn_cast<AllocaInst>(&inst))
Sean Callanan237e4742011-01-21 22:30:25 +00001188 {
1189 llvm::StringRef alloc_name = alloc->getName();
1190
1191 if (alloc_name.startswith("$") &&
1192 !alloc_name.startswith("$__lldb"))
1193 {
1194 if (alloc_name.find_first_of("0123456789") == 1)
1195 {
1196 if (log)
1197 log->Printf("Rejecting a numeric persistent variable.");
1198
Sean Callanan97c924e2011-01-27 01:07:04 +00001199 if (m_error_stream)
1200 m_error_stream->Printf("Error [IRForTarget]: Names starting with $0, $1, ... are reserved for use as result names\n");
1201
Sean Callanan237e4742011-01-21 22:30:25 +00001202 return false;
1203 }
1204
Sean Callanana48fe162010-08-11 03:57:18 +00001205 pvar_allocs.push_back(alloc);
Sean Callanan237e4742011-01-21 22:30:25 +00001206 }
1207 }
Sean Callanana48fe162010-08-11 03:57:18 +00001208 }
1209
1210 InstrIterator iter;
1211
1212 for (iter = pvar_allocs.begin();
1213 iter != pvar_allocs.end();
1214 ++iter)
1215 {
Sean Callananc0492742011-05-23 21:40:23 +00001216 if (!RewritePersistentAlloc(*iter))
Sean Callanana48fe162010-08-11 03:57:18 +00001217 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001218 if (m_error_stream)
1219 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite the creation of a persistent variable\n");
1220
Enrico Granata4c3fb4b2011-07-19 18:03:25 +00001221 if (log)
Sean Callanana48fe162010-08-11 03:57:18 +00001222 log->PutCString("Couldn't rewrite the creation of a persistent variable");
Sean Callanan97c924e2011-01-27 01:07:04 +00001223
Sean Callanana48fe162010-08-11 03:57:18 +00001224 return false;
1225 }
1226 }
1227
1228 return true;
1229}
1230
Sean Callanan97c924e2011-01-27 01:07:04 +00001231// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001232bool
Sean Callananc0492742011-05-23 21:40:23 +00001233IRForTarget::MaybeHandleVariable (Value *llvm_value_ptr)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001234{
Greg Claytone005f2c2010-11-06 01:53:30 +00001235 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan48443652010-12-02 19:47:57 +00001236
1237 if (log)
Sean Callananb9f09a62010-12-06 22:16:55 +00001238 log->Printf("MaybeHandleVariable (%s)", PrintValue(llvm_value_ptr).c_str());
Sean Callananf5857a02010-07-31 01:32:05 +00001239
Greg Clayton8de27c72010-10-15 22:48:33 +00001240 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(llvm_value_ptr))
Sean Callananbc2928a2010-08-03 00:23:29 +00001241 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001242 switch (constant_expr->getOpcode())
Sean Callananbc2928a2010-08-03 00:23:29 +00001243 {
Sean Callanan93a4b1a2010-08-04 01:02:13 +00001244 default:
1245 break;
1246 case Instruction::GetElementPtr:
1247 case Instruction::BitCast:
Sean Callananbc2928a2010-08-03 00:23:29 +00001248 Value *s = constant_expr->getOperand(0);
Sean Callananc0492742011-05-23 21:40:23 +00001249 if (!MaybeHandleVariable(s))
Sean Callanan48443652010-12-02 19:47:57 +00001250 return false;
Sean Callananbc2928a2010-08-03 00:23:29 +00001251 }
1252 }
Sean Callananf921cf52010-12-03 19:51:05 +00001253 else if (GlobalVariable *global_variable = dyn_cast<GlobalVariable>(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001254 {
Sean Callananc0492742011-05-23 21:40:23 +00001255 clang::NamedDecl *named_decl = DeclForGlobal(global_variable);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001256
Sean Callananf5857a02010-07-31 01:32:05 +00001257 if (!named_decl)
1258 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001259 if (IsObjCSelectorRef(llvm_value_ptr))
Sean Callananf5857a02010-07-31 01:32:05 +00001260 return true;
1261
Sean Callanan7cd46742010-12-06 00:56:39 +00001262 if (!global_variable->hasExternalLinkage())
1263 return true;
1264
Sean Callananf5857a02010-07-31 01:32:05 +00001265 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001266 log->Printf("Found global variable \"%s\" without metadata", global_variable->getName().str().c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001267
Sean Callananf5857a02010-07-31 01:32:05 +00001268 return false;
1269 }
1270
Greg Clayton8de27c72010-10-15 22:48:33 +00001271 std::string name (named_decl->getName().str());
Sean Callanan810f22d2010-07-16 00:09:46 +00001272
Sean Callanan771131d2010-09-30 21:18:25 +00001273 void *opaque_type = NULL;
Sean Callananf328c9f2010-07-20 23:31:16 +00001274 clang::ASTContext *ast_context = NULL;
Sean Callanan810f22d2010-07-16 00:09:46 +00001275
1276 if (clang::ValueDecl *value_decl = dyn_cast<clang::ValueDecl>(named_decl))
Sean Callananf328c9f2010-07-20 23:31:16 +00001277 {
Sean Callanan771131d2010-09-30 21:18:25 +00001278 opaque_type = value_decl->getType().getAsOpaquePtr();
Sean Callananf328c9f2010-07-20 23:31:16 +00001279 ast_context = &value_decl->getASTContext();
1280 }
Sean Callanan810f22d2010-07-16 00:09:46 +00001281 else
Sean Callananf328c9f2010-07-20 23:31:16 +00001282 {
Sean Callanan810f22d2010-07-16 00:09:46 +00001283 return false;
Sean Callananf328c9f2010-07-20 23:31:16 +00001284 }
Sean Callanan771131d2010-09-30 21:18:25 +00001285
Sean Callanan6a925532011-01-13 08:53:35 +00001286 clang::QualType qual_type;
Sean Callanan58baaad2011-07-08 00:39:14 +00001287 const Type *value_type = NULL;
Sean Callanan6a925532011-01-13 08:53:35 +00001288
Sean Callanan97678d12011-01-13 21:23:32 +00001289 if (name[0] == '$')
Sean Callanan6a925532011-01-13 08:53:35 +00001290 {
1291 // The $__lldb_expr_result name indicates the the return value has allocated as
1292 // a static variable. Per the comment at ASTResultSynthesizer::SynthesizeBodyResult,
1293 // accesses to this static variable need to be redirected to the result of dereferencing
1294 // a pointer that is passed in as one of the arguments.
1295 //
1296 // Consequently, when reporting the size of the type, we report a pointer type pointing
1297 // to the type of $__lldb_expr_result, not the type itself.
Sean Callanan97678d12011-01-13 21:23:32 +00001298 //
1299 // We also do this for any user-declared persistent variables.
Sean Callananf328c9f2010-07-20 23:31:16 +00001300
Sean Callanan6a925532011-01-13 08:53:35 +00001301 qual_type = ast_context->getPointerType(clang::QualType::getFromOpaquePtr(opaque_type));
1302 value_type = PointerType::get(global_variable->getType(), 0);
1303 }
1304 else
1305 {
1306 qual_type = clang::QualType::getFromOpaquePtr(opaque_type);
1307 value_type = global_variable->getType();
1308 }
Sean Callanan771131d2010-09-30 21:18:25 +00001309
1310 size_t value_size = (ast_context->getTypeSize(qual_type) + 7) / 8;
1311 off_t value_alignment = (ast_context->getTypeAlign(qual_type) + 7) / 8;
Sean Callanan3aa7da52010-12-13 22:46:15 +00001312
Sean Callanan771131d2010-09-30 21:18:25 +00001313 if (log)
Sean Callanan97678d12011-01-13 21:23:32 +00001314 log->Printf("Type of \"%s\" is [clang \"%s\", llvm \"%s\"] [size %d, align %d]",
Sean Callanan771131d2010-09-30 21:18:25 +00001315 name.c_str(),
1316 qual_type.getAsString().c_str(),
1317 PrintType(value_type).c_str(),
1318 value_size,
1319 value_alignment);
Sean Callanan3aa7da52010-12-13 22:46:15 +00001320
Sean Callanan8bce6652010-07-13 21:41:46 +00001321
Sean Callanan8c127202010-08-23 23:09:38 +00001322 if (named_decl && !m_decl_map->AddValueToStruct(named_decl,
Greg Clayton8de27c72010-10-15 22:48:33 +00001323 lldb_private::ConstString (name.c_str()),
1324 llvm_value_ptr,
Sean Callananba992c52010-07-27 02:07:53 +00001325 value_size,
1326 value_alignment))
Sean Callanan8bce6652010-07-13 21:41:46 +00001327 return false;
1328 }
Sean Callananf3143b72010-12-03 03:02:31 +00001329 else if (dyn_cast<llvm::Function>(llvm_value_ptr))
Sean Callanan48443652010-12-02 19:47:57 +00001330 {
1331 if (log)
1332 log->Printf("Function pointers aren't handled right now");
1333
1334 return false;
1335 }
Sean Callanan8bce6652010-07-13 21:41:46 +00001336
1337 return true;
1338}
1339
Sean Callanan97c924e2011-01-27 01:07:04 +00001340// This function does not report errors; its callers are responsible.
Sean Callanan8bce6652010-07-13 21:41:46 +00001341bool
Sean Callananc0492742011-05-23 21:40:23 +00001342IRForTarget::HandleSymbol (Value *symbol)
Sean Callanan81974962011-05-08 02:21:26 +00001343{
Sean Callananc7674af2011-01-17 23:42:46 +00001344 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1345
1346 lldb_private::ConstString name(symbol->getName().str().c_str());
1347
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001348 lldb::addr_t symbol_addr = m_decl_map->GetSymbolAddress (name);
Sean Callananc7674af2011-01-17 23:42:46 +00001349
Greg Claytoncbc07cf2011-06-23 04:25:29 +00001350 if (symbol_addr == LLDB_INVALID_ADDRESS)
Sean Callananc7674af2011-01-17 23:42:46 +00001351 {
1352 if (log)
1353 log->Printf ("Symbol \"%s\" had no address", name.GetCString());
1354
1355 return false;
1356 }
1357
1358 if (log)
1359 log->Printf("Found \"%s\" at 0x%llx", name.GetCString(), symbol_addr);
1360
Sean Callanan9b6898f2011-07-30 02:42:06 +00001361 Type *symbol_type = symbol->getType();
Sean Callananc7674af2011-01-17 23:42:46 +00001362
Sean Callanan9b6898f2011-07-30 02:42:06 +00001363 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1364 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc7674af2011-01-17 23:42:46 +00001365
1366 Constant *symbol_addr_int = ConstantInt::get(intptr_ty, symbol_addr, false);
1367
1368 Value *symbol_addr_ptr = ConstantExpr::getIntToPtr(symbol_addr_int, symbol_type);
1369
1370 if (log)
1371 log->Printf("Replacing %s with %s", PrintValue(symbol).c_str(), PrintValue(symbol_addr_ptr).c_str());
1372
1373 symbol->replaceAllUsesWith(symbol_addr_ptr);
1374
1375 return true;
1376}
1377
1378bool
Sean Callananc0492742011-05-23 21:40:23 +00001379IRForTarget::MaybeHandleCallArguments (CallInst *Old)
Sean Callanandc27aba2010-10-05 22:26:43 +00001380{
Sean Callanan48443652010-12-02 19:47:57 +00001381 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1382
1383 if (log)
1384 log->Printf("MaybeHandleCallArguments(%s)", PrintValue(Old).c_str());
Sean Callanandc27aba2010-10-05 22:26:43 +00001385
Sean Callanan6ba533e2010-11-17 23:00:36 +00001386 for (unsigned op_index = 0, num_ops = Old->getNumArgOperands();
Sean Callanandc27aba2010-10-05 22:26:43 +00001387 op_index < num_ops;
1388 ++op_index)
Sean Callananc0492742011-05-23 21:40:23 +00001389 if (!MaybeHandleVariable(Old->getArgOperand(op_index))) // conservatively believe that this is a store
Sean Callanan97c924e2011-01-27 01:07:04 +00001390 {
1391 if (m_error_stream)
1392 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite one of the arguments of a function call.\n");
1393
Sean Callanandc27aba2010-10-05 22:26:43 +00001394 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001395 }
1396
Sean Callanandc27aba2010-10-05 22:26:43 +00001397 return true;
1398}
1399
1400bool
Sean Callananc0492742011-05-23 21:40:23 +00001401IRForTarget::MaybeHandleCall (CallInst *llvm_call_inst)
Sean Callananba992c52010-07-27 02:07:53 +00001402{
Greg Claytone005f2c2010-11-06 01:53:30 +00001403 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananba992c52010-07-27 02:07:53 +00001404
Greg Clayton8de27c72010-10-15 22:48:33 +00001405 Function *fun = llvm_call_inst->getCalledFunction();
Sean Callananba992c52010-07-27 02:07:53 +00001406
1407 if (fun == NULL)
Sean Callanan65af7342010-09-08 20:04:08 +00001408 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001409 Value *val = llvm_call_inst->getCalledValue();
Sean Callanan65af7342010-09-08 20:04:08 +00001410
1411 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(val);
Sean Callanand5b3c352011-01-27 04:42:51 +00001412 LoadInst *load_inst = dyn_cast<LoadInst>(val);
Sean Callanan65af7342010-09-08 20:04:08 +00001413
1414 if (const_expr && const_expr->getOpcode() == Instruction::BitCast)
1415 {
1416 fun = dyn_cast<Function>(const_expr->getOperand(0));
1417
1418 if (!fun)
Sean Callanan97c924e2011-01-27 01:07:04 +00001419 {
1420 if (m_error_stream)
Sean Callanan9b6898f2011-07-30 02:42:06 +00001421 m_error_stream->Printf("Internal error [IRForTaget]: Called entity is a cast of something not a function\n");
Sean Callanan97c924e2011-01-27 01:07:04 +00001422
Sean Callanan48443652010-12-02 19:47:57 +00001423 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001424 }
Sean Callanan65af7342010-09-08 20:04:08 +00001425 }
Sean Callananc4217a62010-12-06 23:53:20 +00001426 else if (const_expr && const_expr->getOpcode() == Instruction::IntToPtr)
1427 {
1428 return true; // already resolved
1429 }
Sean Callanand5b3c352011-01-27 04:42:51 +00001430 else if (load_inst)
1431 {
1432 return true; // virtual method call
1433 }
Sean Callanan65af7342010-09-08 20:04:08 +00001434 else
1435 {
Sean Callanan97c924e2011-01-27 01:07:04 +00001436 if (m_error_stream)
1437 m_error_stream->Printf("Internal error [IRForTarget]: Called entity is not a function\n");
1438
Sean Callanan48443652010-12-02 19:47:57 +00001439 return false;
Sean Callanan65af7342010-09-08 20:04:08 +00001440 }
1441 }
Sean Callananba992c52010-07-27 02:07:53 +00001442
Greg Clayton8de27c72010-10-15 22:48:33 +00001443 lldb_private::ConstString str;
Sean Callananc04743d2010-09-28 21:13:03 +00001444
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001445 if (fun->isIntrinsic())
Sean Callananc04743d2010-09-28 21:13:03 +00001446 {
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001447 Intrinsic::ID intrinsic_id = (Intrinsic::ID)fun->getIntrinsicID();
Sean Callananc04743d2010-09-28 21:13:03 +00001448
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001449 switch (intrinsic_id)
1450 {
1451 default:
1452 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001453 log->Printf("Unresolved intrinsic \"%s\"", Intrinsic::getName(intrinsic_id).c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00001454
1455 if (m_error_stream)
1456 m_error_stream->Printf("Internal error [IRForTarget]: Call to unhandled compiler intrinsic '%s'\n", Intrinsic::getName(intrinsic_id).c_str());
1457
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001458 return false;
1459 case Intrinsic::memcpy:
Greg Clayton8de27c72010-10-15 22:48:33 +00001460 {
1461 static lldb_private::ConstString g_memcpy_str ("memcpy");
1462 str = g_memcpy_str;
1463 }
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001464 break;
1465 }
Sean Callananc04743d2010-09-28 21:13:03 +00001466
Greg Clayton8de27c72010-10-15 22:48:33 +00001467 if (log && str)
Greg Claytonb5037af2010-11-15 01:47:11 +00001468 log->Printf("Resolved intrinsic name \"%s\"", str.GetCString());
Sean Callanan3cb1fd82010-09-28 23:55:00 +00001469 }
1470 else
1471 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001472 str.SetCStringWithLength (fun->getName().data(), fun->getName().size());
Sean Callananc04743d2010-09-28 21:13:03 +00001473 }
1474
Sean Callananc0492742011-05-23 21:40:23 +00001475 clang::NamedDecl *fun_decl = DeclForGlobal (fun);
Greg Claytonb5037af2010-11-15 01:47:11 +00001476 lldb::addr_t fun_addr = LLDB_INVALID_ADDRESS;
Sean Callananf5857a02010-07-31 01:32:05 +00001477 Value **fun_value_ptr = NULL;
Sean Callananba992c52010-07-27 02:07:53 +00001478
Sean Callananf5857a02010-07-31 01:32:05 +00001479 if (fun_decl)
Sean Callananba992c52010-07-27 02:07:53 +00001480 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001481 if (!m_decl_map->GetFunctionInfo (fun_decl, fun_value_ptr, fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001482 {
Sean Callanan92aa6662010-09-07 21:49:41 +00001483 fun_value_ptr = NULL;
1484
Greg Clayton8de27c72010-10-15 22:48:33 +00001485 if (!m_decl_map->GetFunctionAddress (str, fun_addr))
Sean Callanan92aa6662010-09-07 21:49:41 +00001486 {
1487 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001488 log->Printf("Function \"%s\" had no address", str.GetCString());
Sean Callanan92aa6662010-09-07 21:49:41 +00001489
Sean Callanan97c924e2011-01-27 01:07:04 +00001490 if (m_error_stream)
1491 m_error_stream->Printf("Error [IRForTarget]: Call to a function '%s' that is not present in the target\n", str.GetCString());
1492
Sean Callanan92aa6662010-09-07 21:49:41 +00001493 return false;
1494 }
Sean Callananf5857a02010-07-31 01:32:05 +00001495 }
1496 }
1497 else
1498 {
Greg Clayton8de27c72010-10-15 22:48:33 +00001499 if (!m_decl_map->GetFunctionAddress (str, fun_addr))
Sean Callananf5857a02010-07-31 01:32:05 +00001500 {
1501 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001502 log->Printf ("Metadataless function \"%s\" had no address", str.GetCString());
Sean Callanan97c924e2011-01-27 01:07:04 +00001503
1504 if (m_error_stream)
1505 m_error_stream->Printf("Error [IRForTarget]: Call to a symbol-only function '%s' that is not present in the target\n", str.GetCString());
1506
1507 return false;
Sean Callananf5857a02010-07-31 01:32:05 +00001508 }
Sean Callananba992c52010-07-27 02:07:53 +00001509 }
1510
1511 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001512 log->Printf("Found \"%s\" at 0x%llx", str.GetCString(), fun_addr);
Sean Callananba992c52010-07-27 02:07:53 +00001513
Sean Callanan58baaad2011-07-08 00:39:14 +00001514 Value *fun_addr_ptr = NULL;
Sean Callananf5857a02010-07-31 01:32:05 +00001515
1516 if (!fun_value_ptr || !*fun_value_ptr)
Sean Callanan02fbafa2010-07-27 21:39:39 +00001517 {
Sean Callanan9b6898f2011-07-30 02:42:06 +00001518 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
1519 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
1520 FunctionType *fun_ty = fun->getFunctionType();
Sean Callanan02fbafa2010-07-27 21:39:39 +00001521 PointerType *fun_ptr_ty = PointerType::getUnqual(fun_ty);
1522 Constant *fun_addr_int = ConstantInt::get(intptr_ty, fun_addr, false);
Sean Callananf5857a02010-07-31 01:32:05 +00001523 fun_addr_ptr = ConstantExpr::getIntToPtr(fun_addr_int, fun_ptr_ty);
1524
1525 if (fun_value_ptr)
1526 *fun_value_ptr = fun_addr_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001527 }
Sean Callananf5857a02010-07-31 01:32:05 +00001528
1529 if (fun_value_ptr)
1530 fun_addr_ptr = *fun_value_ptr;
Sean Callanan02fbafa2010-07-27 21:39:39 +00001531
Greg Clayton8de27c72010-10-15 22:48:33 +00001532 llvm_call_inst->setCalledFunction(fun_addr_ptr);
Sean Callanan02fbafa2010-07-27 21:39:39 +00001533
Sean Callananc0492742011-05-23 21:40:23 +00001534 ConstantArray *func_name = (ConstantArray*)ConstantArray::get(m_module->getContext(), str.GetCString());
Sean Callanane8a59a82010-09-13 21:34:21 +00001535
1536 Value *values[1];
1537 values[0] = func_name;
Sean Callanan0de254a2011-05-15 22:34:38 +00001538 ArrayRef<Value*> value_ref(values, 1);
1539
Sean Callananc0492742011-05-23 21:40:23 +00001540 MDNode *func_metadata = MDNode::get(m_module->getContext(), value_ref);
Sean Callanane8a59a82010-09-13 21:34:21 +00001541
Greg Clayton8de27c72010-10-15 22:48:33 +00001542 llvm_call_inst->setMetadata("lldb.call.realName", func_metadata);
Sean Callanane8a59a82010-09-13 21:34:21 +00001543
1544 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001545 log->Printf("Set metadata for %p [%d, \"%s\"]", llvm_call_inst, func_name->isString(), func_name->getAsString().c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +00001546
Sean Callananba992c52010-07-27 02:07:53 +00001547 return true;
1548}
1549
1550bool
Sean Callananc0492742011-05-23 21:40:23 +00001551IRForTarget::ResolveCalls(BasicBlock &basic_block)
Sean Callanan8bce6652010-07-13 21:41:46 +00001552{
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001553 /////////////////////////////////////////////////////////////////////////
1554 // Prepare the current basic block for execution in the remote process
1555 //
1556
Sean Callanan02fbafa2010-07-27 21:39:39 +00001557 BasicBlock::iterator ii;
Sean Callanan8bce6652010-07-13 21:41:46 +00001558
Greg Clayton3c7feb42010-11-19 01:05:25 +00001559 for (ii = basic_block.begin();
1560 ii != basic_block.end();
Sean Callanan8bce6652010-07-13 21:41:46 +00001561 ++ii)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001562 {
Sean Callanan8bce6652010-07-13 21:41:46 +00001563 Instruction &inst = *ii;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001564
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001565 CallInst *call = dyn_cast<CallInst>(&inst);
Sean Callananba992c52010-07-27 02:07:53 +00001566
Sean Callanan97c924e2011-01-27 01:07:04 +00001567 // MaybeHandleCall handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001568 if (call && !MaybeHandleCall(call))
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001569 return false;
Sean Callanan48443652010-12-02 19:47:57 +00001570
Sean Callanan97c924e2011-01-27 01:07:04 +00001571 // MaybeHandleCallArguments handles error reporting; we are silent here
Sean Callananc0492742011-05-23 21:40:23 +00001572 if (call && !MaybeHandleCallArguments(call))
Sean Callanan48443652010-12-02 19:47:57 +00001573 return false;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00001574 }
1575
1576 return true;
1577}
1578
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001579bool
Sean Callananc0492742011-05-23 21:40:23 +00001580IRForTarget::ResolveExternals (Function &llvm_function)
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001581{
Sean Callananae71e302010-11-18 22:21:58 +00001582 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1583
Sean Callananc0492742011-05-23 21:40:23 +00001584 for (Module::global_iterator global = m_module->global_begin(), end = m_module->global_end();
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001585 global != end;
1586 ++global)
1587 {
Greg Clayton3c7feb42010-11-19 01:05:25 +00001588 if (log)
1589 log->Printf("Examining %s, DeclForGlobalValue returns %p",
1590 (*global).getName().str().c_str(),
Sean Callananc0492742011-05-23 21:40:23 +00001591 DeclForGlobal(global));
Greg Clayton3c7feb42010-11-19 01:05:25 +00001592
Sean Callananc7674af2011-01-17 23:42:46 +00001593 if ((*global).getName().str().find("OBJC_IVAR") == 0)
1594 {
Sean Callananc0492742011-05-23 21:40:23 +00001595 if (!HandleSymbol(global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001596 {
1597 if (m_error_stream)
1598 m_error_stream->Printf("Error [IRForTarget]: Couldn't find Objective-C indirect ivar symbol %s\n", (*global).getName().str().c_str());
1599
Sean Callananc7674af2011-01-17 23:42:46 +00001600 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001601 }
Sean Callananc7674af2011-01-17 23:42:46 +00001602 }
Sean Callananc0492742011-05-23 21:40:23 +00001603 else if (DeclForGlobal(global))
Sean Callananc7674af2011-01-17 23:42:46 +00001604 {
Sean Callananc0492742011-05-23 21:40:23 +00001605 if (!MaybeHandleVariable (global))
Sean Callanan97c924e2011-01-27 01:07:04 +00001606 {
1607 if (m_error_stream)
1608 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't rewrite external variable %s\n", (*global).getName().str().c_str());
1609
Sean Callananc7674af2011-01-17 23:42:46 +00001610 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00001611 }
Sean Callananc7674af2011-01-17 23:42:46 +00001612 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00001613 }
1614
1615 return true;
1616}
1617
Sean Callananc0492742011-05-23 21:40:23 +00001618bool
1619IRForTarget::ReplaceStrings ()
1620{
1621 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1622
1623 if (!m_data_allocator)
1624 return true; // hope for the best; some clients may not want static allocation!
1625
1626 typedef std::map <GlobalVariable *, size_t> OffsetsTy;
1627
1628 OffsetsTy offsets;
1629
1630 for (Module::global_iterator gi = m_module->global_begin(), ge = m_module->global_end();
1631 gi != ge;
1632 ++gi)
1633 {
1634 GlobalVariable *gv = gi;
1635
1636 if (!gv->hasInitializer())
1637 continue;
1638
1639 Constant *gc = gv->getInitializer();
1640
1641 ConstantArray *gc_array = dyn_cast<ConstantArray>(gc);
1642
1643 if (!gc_array)
1644 continue;
1645
1646 if (!gc_array->isCString())
1647 continue;
1648
1649 if (log)
1650 log->Printf("Found a GlobalVariable with string initializer %s", PrintValue(gc).c_str());
1651
1652 std::string str = gc_array->getAsString();
1653
1654 offsets[gv] = m_data_allocator->GetStream().GetSize();
1655
1656 m_data_allocator->GetStream().Write(str.c_str(), str.length() + 1);
1657 }
1658
Sean Callanan9b6898f2011-07-30 02:42:06 +00001659 Type *char_ptr_ty = Type::getInt8PtrTy(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00001660
1661 for (OffsetsTy::iterator oi = offsets.begin(), oe = offsets.end();
1662 oi != oe;
1663 ++oi)
1664 {
1665 GlobalVariable *gv = oi->first;
1666 size_t offset = oi->second;
1667
1668 Constant *new_initializer = BuildRelocation(char_ptr_ty, offset);
1669
1670 if (log)
1671 log->Printf("Replacing GV %s with %s", PrintValue(gv).c_str(), PrintValue(new_initializer).c_str());
1672
1673 for (GlobalVariable::use_iterator ui = gv->use_begin(), ue = gv->use_end();
1674 ui != ue;
1675 ++ui)
1676 {
1677 if (log)
1678 log->Printf("Found use %s", PrintValue(*ui).c_str());
1679
1680 ConstantExpr *const_expr = dyn_cast<ConstantExpr>(*ui);
1681 StoreInst *store_inst = dyn_cast<StoreInst>(*ui);
1682
1683 if (const_expr)
1684 {
1685 if (const_expr->getOpcode() != Instruction::GetElementPtr)
1686 {
1687 if (log)
1688 log->Printf("Use (%s) of string variable is not a GetElementPtr constant", PrintValue(const_expr).c_str());
1689
1690 return false;
1691 }
1692
1693 const_expr->replaceAllUsesWith(new_initializer);
1694 }
1695 else if (store_inst)
1696 {
1697 Constant *bit_cast = ConstantExpr::getBitCast(new_initializer, store_inst->getValueOperand()->getType());
1698
1699 store_inst->setOperand(0, bit_cast);
1700 }
1701 else
1702 {
1703 if (log)
1704 log->Printf("Use (%s) of string variable is neither a constant nor a store", PrintValue(const_expr).c_str());
1705
1706 return false;
1707 }
1708 }
1709
1710 gv->eraseFromParent();
1711 }
1712
1713 return true;
1714}
1715
1716bool
1717IRForTarget::ReplaceStaticLiterals (llvm::BasicBlock &basic_block)
1718{
1719 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
1720
1721 if (!m_data_allocator)
1722 return true;
1723
1724 typedef SmallVector <Value*, 2> ConstantList;
1725 typedef SmallVector <llvm::Instruction*, 2> UserList;
1726 typedef ConstantList::iterator ConstantIterator;
1727 typedef UserList::iterator UserIterator;
1728
1729 ConstantList static_constants;
1730 UserList static_users;
1731
1732 for (BasicBlock::iterator ii = basic_block.begin(), ie = basic_block.end();
1733 ii != ie;
1734 ++ii)
1735 {
1736 llvm::Instruction &inst = *ii;
1737
1738 for (Instruction::op_iterator oi = inst.op_begin(), oe = inst.op_end();
1739 oi != oe;
1740 ++oi)
1741 {
1742 Value *operand_val = oi->get();
1743
1744 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1745
1746 if (operand_constant_fp && operand_constant_fp->getType()->isX86_FP80Ty())
1747 {
1748 static_constants.push_back(operand_val);
1749 static_users.push_back(ii);
1750 }
1751 }
1752 }
1753
1754 ConstantIterator constant_iter;
1755 UserIterator user_iter;
Greg Clayton54b38412011-05-24 23:06:02 +00001756
Sean Callananc0492742011-05-23 21:40:23 +00001757 for (constant_iter = static_constants.begin(), user_iter = static_users.begin();
1758 constant_iter != static_constants.end();
1759 ++constant_iter, ++user_iter)
1760 {
1761 Value *operand_val = *constant_iter;
1762 llvm::Instruction *inst = *user_iter;
1763
1764 ConstantFP *operand_constant_fp = dyn_cast<ConstantFP>(operand_val);
1765
1766 if (operand_constant_fp)
1767 {
1768 APFloat operand_apfloat = operand_constant_fp->getValueAPF();
1769 APInt operand_apint = operand_apfloat.bitcastToAPInt();
1770
1771 const uint8_t* operand_raw_data = (const uint8_t*)operand_apint.getRawData();
1772 size_t operand_data_size = operand_apint.getBitWidth() / 8;
1773
1774 if (log)
1775 {
1776 std::string s;
1777 raw_string_ostream ss(s);
1778 for (size_t index = 0;
1779 index < operand_data_size;
1780 ++index)
1781 {
1782 ss << (uint32_t)operand_raw_data[index];
1783 ss << " ";
1784 }
1785 ss.flush();
1786
1787 log->Printf("Found ConstantFP with size %d and raw data %s", operand_data_size, s.c_str());
1788 }
1789
1790 lldb_private::DataBufferHeap data(operand_data_size, 0);
1791
1792 if (lldb::endian::InlHostByteOrder() != m_data_allocator->GetStream().GetByteOrder())
1793 {
1794 uint8_t *data_bytes = data.GetBytes();
1795
1796 for (size_t index = 0;
1797 index < operand_data_size;
1798 ++index)
1799 {
1800 data_bytes[index] = operand_raw_data[operand_data_size - (1 + index)];
1801 }
1802 }
1803 else
1804 {
1805 memcpy(data.GetBytes(), operand_raw_data, operand_data_size);
1806 }
1807
1808 uint64_t offset = m_data_allocator->GetStream().GetSize();
1809
1810 m_data_allocator->GetStream().Write(data.GetBytes(), operand_data_size);
1811
Sean Callanan9b6898f2011-07-30 02:42:06 +00001812 llvm::Type *fp_ptr_ty = operand_constant_fp->getType()->getPointerTo();
Sean Callananc0492742011-05-23 21:40:23 +00001813
1814 Constant *new_pointer = BuildRelocation(fp_ptr_ty, offset);
1815
1816 llvm::LoadInst *fp_load = new llvm::LoadInst(new_pointer, "fp_load", inst);
1817
1818 operand_constant_fp->replaceAllUsesWith(fp_load);
1819 }
1820 }
1821
1822 return true;
1823}
1824
Sean Callanan02fbafa2010-07-27 21:39:39 +00001825static bool isGuardVariableRef(Value *V)
Sean Callanan45839272010-07-24 01:37:44 +00001826{
Sean Callanan58baaad2011-07-08 00:39:14 +00001827 Constant *Old = NULL;
Sean Callanan45839272010-07-24 01:37:44 +00001828
Sean Callanan6ba533e2010-11-17 23:00:36 +00001829 if (!(Old = dyn_cast<Constant>(V)))
Sean Callanan45839272010-07-24 01:37:44 +00001830 return false;
1831
Sean Callanan58baaad2011-07-08 00:39:14 +00001832 ConstantExpr *CE = NULL;
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001833
1834 if ((CE = dyn_cast<ConstantExpr>(V)))
1835 {
1836 if (CE->getOpcode() != Instruction::BitCast)
1837 return false;
1838
Sean Callanan6ba533e2010-11-17 23:00:36 +00001839 Old = CE->getOperand(0);
Sean Callanan47a5c4c2010-09-23 03:01:22 +00001840 }
1841
Sean Callanan6ba533e2010-11-17 23:00:36 +00001842 GlobalVariable *GV = dyn_cast<GlobalVariable>(Old);
Sean Callanan45839272010-07-24 01:37:44 +00001843
1844 if (!GV || !GV->hasName() || !GV->getName().startswith("_ZGV"))
1845 return false;
1846
1847 return true;
1848}
1849
Sean Callananc0492742011-05-23 21:40:23 +00001850void
1851IRForTarget::TurnGuardLoadIntoZero(llvm::Instruction* guard_load)
Sean Callanan45839272010-07-24 01:37:44 +00001852{
Sean Callananc0492742011-05-23 21:40:23 +00001853 Constant* zero(ConstantInt::get(Type::getInt8Ty(m_module->getContext()), 0, true));
Sean Callanan45839272010-07-24 01:37:44 +00001854
1855 Value::use_iterator ui;
1856
1857 for (ui = guard_load->use_begin();
1858 ui != guard_load->use_end();
1859 ++ui)
Sean Callananb5b749c2010-07-27 01:17:28 +00001860 {
Greg Clayton6e713402010-07-30 20:30:44 +00001861 if (isa<Constant>(*ui))
Sean Callananb5b749c2010-07-27 01:17:28 +00001862 {
1863 // do nothing for the moment
1864 }
1865 else
1866 {
1867 ui->replaceUsesOfWith(guard_load, zero);
1868 }
1869 }
Sean Callanan45839272010-07-24 01:37:44 +00001870
1871 guard_load->eraseFromParent();
1872}
1873
1874static void ExciseGuardStore(Instruction* guard_store)
1875{
1876 guard_store->eraseFromParent();
1877}
1878
1879bool
Sean Callananc0492742011-05-23 21:40:23 +00001880IRForTarget::RemoveGuards(BasicBlock &basic_block)
Sean Callanan45839272010-07-24 01:37:44 +00001881{
1882 ///////////////////////////////////////////////////////
1883 // Eliminate any reference to guard variables found.
1884 //
1885
Sean Callanan02fbafa2010-07-27 21:39:39 +00001886 BasicBlock::iterator ii;
Sean Callanan45839272010-07-24 01:37:44 +00001887
Sean Callanan02fbafa2010-07-27 21:39:39 +00001888 typedef SmallVector <Instruction*, 2> InstrList;
Sean Callanan45839272010-07-24 01:37:44 +00001889 typedef InstrList::iterator InstrIterator;
1890
1891 InstrList guard_loads;
1892 InstrList guard_stores;
1893
Greg Clayton3c7feb42010-11-19 01:05:25 +00001894 for (ii = basic_block.begin();
1895 ii != basic_block.end();
Sean Callanan45839272010-07-24 01:37:44 +00001896 ++ii)
1897 {
1898 Instruction &inst = *ii;
1899
1900 if (LoadInst *load = dyn_cast<LoadInst>(&inst))
1901 if (isGuardVariableRef(load->getPointerOperand()))
1902 guard_loads.push_back(&inst);
1903
1904 if (StoreInst *store = dyn_cast<StoreInst>(&inst))
1905 if (isGuardVariableRef(store->getPointerOperand()))
1906 guard_stores.push_back(&inst);
1907 }
1908
1909 InstrIterator iter;
1910
1911 for (iter = guard_loads.begin();
1912 iter != guard_loads.end();
1913 ++iter)
Sean Callananc0492742011-05-23 21:40:23 +00001914 TurnGuardLoadIntoZero(*iter);
Sean Callanan45839272010-07-24 01:37:44 +00001915
1916 for (iter = guard_stores.begin();
1917 iter != guard_stores.end();
1918 ++iter)
1919 ExciseGuardStore(*iter);
1920
1921 return true;
1922}
1923
Sean Callanan97c924e2011-01-27 01:07:04 +00001924// This function does not report errors; its callers are responsible.
Sean Callanan6ba533e2010-11-17 23:00:36 +00001925bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00001926IRForTarget::UnfoldConstant(Constant *old_constant, Value *new_constant, Instruction *first_entry_inst)
Sean Callananbafd6852010-07-14 23:40:29 +00001927{
Greg Claytone005f2c2010-11-06 01:53:30 +00001928 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananbafd6852010-07-14 23:40:29 +00001929
1930 Value::use_iterator ui;
1931
Sean Callanana48fe162010-08-11 03:57:18 +00001932 SmallVector<User*, 16> users;
1933
1934 // We do this because the use list might change, invalidating our iterator.
1935 // Much better to keep a work list ourselves.
Greg Clayton3c7feb42010-11-19 01:05:25 +00001936 for (ui = old_constant->use_begin();
1937 ui != old_constant->use_end();
Sean Callananbafd6852010-07-14 23:40:29 +00001938 ++ui)
Sean Callanana48fe162010-08-11 03:57:18 +00001939 users.push_back(*ui);
Sean Callananbafd6852010-07-14 23:40:29 +00001940
Johnny Chen2bc9eb32011-07-19 19:48:13 +00001941 for (size_t i = 0;
Sean Callanana48fe162010-08-11 03:57:18 +00001942 i < users.size();
1943 ++i)
1944 {
1945 User *user = users[i];
1946
Sean Callananbafd6852010-07-14 23:40:29 +00001947 if (Constant *constant = dyn_cast<Constant>(user))
1948 {
1949 // synthesize a new non-constant equivalent of the constant
1950
1951 if (ConstantExpr *constant_expr = dyn_cast<ConstantExpr>(constant))
1952 {
1953 switch (constant_expr->getOpcode())
1954 {
1955 default:
1956 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00001957 log->Printf("Unhandled constant expression type: \"%s\"", PrintValue(constant_expr).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00001958 return false;
1959 case Instruction::BitCast:
1960 {
1961 // UnaryExpr
1962 // OperandList[0] is value
1963
1964 Value *s = constant_expr->getOperand(0);
1965
Greg Clayton3c7feb42010-11-19 01:05:25 +00001966 if (s == old_constant)
1967 s = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00001968
Sean Callananc0492742011-05-23 21:40:23 +00001969 BitCastInst *bit_cast(new BitCastInst(s, constant_expr->getType(), "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00001970
Greg Clayton3c7feb42010-11-19 01:05:25 +00001971 UnfoldConstant(constant_expr, bit_cast, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00001972 }
1973 break;
1974 case Instruction::GetElementPtr:
1975 {
1976 // GetElementPtrConstantExpr
1977 // OperandList[0] is base
1978 // OperandList[1]... are indices
1979
1980 Value *ptr = constant_expr->getOperand(0);
1981
Greg Clayton3c7feb42010-11-19 01:05:25 +00001982 if (ptr == old_constant)
1983 ptr = new_constant;
Sean Callanan9b6898f2011-07-30 02:42:06 +00001984
1985 std::vector<Value*> index_vector;
Sean Callananbafd6852010-07-14 23:40:29 +00001986
1987 unsigned operand_index;
1988 unsigned num_operands = constant_expr->getNumOperands();
1989
1990 for (operand_index = 1;
1991 operand_index < num_operands;
1992 ++operand_index)
1993 {
1994 Value *operand = constant_expr->getOperand(operand_index);
1995
Greg Clayton3c7feb42010-11-19 01:05:25 +00001996 if (operand == old_constant)
1997 operand = new_constant;
Sean Callananbafd6852010-07-14 23:40:29 +00001998
Sean Callanan9b6898f2011-07-30 02:42:06 +00001999 index_vector.push_back(operand);
Sean Callananbafd6852010-07-14 23:40:29 +00002000 }
2001
Sean Callanan9b6898f2011-07-30 02:42:06 +00002002 ArrayRef <Value*> indices(index_vector);
2003
2004 GetElementPtrInst *get_element_ptr(GetElementPtrInst::Create(ptr, indices, "", first_entry_inst));
Sean Callananbafd6852010-07-14 23:40:29 +00002005
Greg Clayton3c7feb42010-11-19 01:05:25 +00002006 UnfoldConstant(constant_expr, get_element_ptr, first_entry_inst);
Sean Callananbafd6852010-07-14 23:40:29 +00002007 }
2008 break;
2009 }
2010 }
2011 else
2012 {
2013 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002014 log->Printf("Unhandled constant type: \"%s\"", PrintValue(constant).c_str());
Sean Callananbafd6852010-07-14 23:40:29 +00002015 return false;
2016 }
2017 }
2018 else
2019 {
2020 // simple fall-through case for non-constants
Greg Clayton3c7feb42010-11-19 01:05:25 +00002021 user->replaceUsesOfWith(old_constant, new_constant);
Sean Callananbafd6852010-07-14 23:40:29 +00002022 }
2023 }
2024
2025 return true;
2026}
2027
Sean Callanan8bce6652010-07-13 21:41:46 +00002028bool
Sean Callananc0492742011-05-23 21:40:23 +00002029IRForTarget::ReplaceVariables (Function &llvm_function)
Sean Callanan8bce6652010-07-13 21:41:46 +00002030{
Sean Callanane8a59a82010-09-13 21:34:21 +00002031 if (!m_resolve_vars)
2032 return true;
2033
Greg Claytone005f2c2010-11-06 01:53:30 +00002034 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan8bce6652010-07-13 21:41:46 +00002035
2036 m_decl_map->DoStructLayout();
2037
2038 if (log)
2039 log->Printf("Element arrangement:");
2040
2041 uint32_t num_elements;
2042 uint32_t element_index;
2043
2044 size_t size;
2045 off_t alignment;
2046
2047 if (!m_decl_map->GetStructInfo (num_elements, size, alignment))
2048 return false;
2049
Greg Clayton3c7feb42010-11-19 01:05:25 +00002050 Function::arg_iterator iter(llvm_function.getArgumentList().begin());
Sean Callanan8bce6652010-07-13 21:41:46 +00002051
Greg Clayton3c7feb42010-11-19 01:05:25 +00002052 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002053 {
2054 if (m_error_stream)
2055 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes no arguments (should take at least a struct pointer)");
2056
Sean Callanan8bce6652010-07-13 21:41:46 +00002057 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002058 }
2059
Sean Callanan02fbafa2010-07-27 21:39:39 +00002060 Argument *argument = iter;
Sean Callanan8bce6652010-07-13 21:41:46 +00002061
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002062 if (argument->getName().equals("this"))
2063 {
2064 ++iter;
2065
Greg Clayton3c7feb42010-11-19 01:05:25 +00002066 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002067 {
2068 if (m_error_stream)
2069 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'this' argument (should take a struct pointer too)");
2070
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002071 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002072 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002073
2074 argument = iter;
2075 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002076 else if (argument->getName().equals("self"))
2077 {
2078 ++iter;
2079
2080 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002081 {
2082 if (m_error_stream)
2083 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' argument (should take '_cmd' and a struct pointer too)");
2084
Sean Callanan3aa7da52010-12-13 22:46:15 +00002085 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002086 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002087
2088 if (!iter->getName().equals("_cmd"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002089 {
2090 if (m_error_stream)
2091 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes '%s' after 'self' argument (should take '_cmd')", iter->getName().str().c_str());
2092
Sean Callanan3aa7da52010-12-13 22:46:15 +00002093 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002094 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002095
2096 ++iter;
2097
2098 if (iter == llvm_function.getArgumentList().end())
Sean Callanan97c924e2011-01-27 01:07:04 +00002099 {
2100 if (m_error_stream)
2101 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes only 'self' and '_cmd' arguments (should take a struct pointer too)");
2102
Sean Callanan3aa7da52010-12-13 22:46:15 +00002103 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002104 }
Sean Callanan3aa7da52010-12-13 22:46:15 +00002105
2106 argument = iter;
2107 }
Sean Callanan3c9c5eb2010-09-21 00:44:12 +00002108
Greg Clayton8de27c72010-10-15 22:48:33 +00002109 if (!argument->getName().equals("$__lldb_arg"))
Sean Callanan97c924e2011-01-27 01:07:04 +00002110 {
2111 if (m_error_stream)
2112 m_error_stream->Printf("Internal error [IRForTarget]: Wrapper takes an argument named '%s' instead of the struct pointer", argument->getName().str().c_str());
2113
Sean Callanan8bce6652010-07-13 21:41:46 +00002114 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002115 }
2116
Sean Callanan8bce6652010-07-13 21:41:46 +00002117 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002118 log->Printf("Arg: \"%s\"", PrintValue(argument).c_str());
Sean Callanan8bce6652010-07-13 21:41:46 +00002119
Greg Clayton3c7feb42010-11-19 01:05:25 +00002120 BasicBlock &entry_block(llvm_function.getEntryBlock());
Sean Callanan6ba533e2010-11-17 23:00:36 +00002121 Instruction *FirstEntryInstruction(entry_block.getFirstNonPHIOrDbg());
Sean Callanan8bce6652010-07-13 21:41:46 +00002122
Sean Callanan6ba533e2010-11-17 23:00:36 +00002123 if (!FirstEntryInstruction)
Sean Callanan97c924e2011-01-27 01:07:04 +00002124 {
2125 if (m_error_stream)
2126 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find the first instruction in the wrapper for use in rewriting");
2127
Sean Callanan8bce6652010-07-13 21:41:46 +00002128 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002129 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002130
Sean Callananc0492742011-05-23 21:40:23 +00002131 LLVMContext &context(m_module->getContext());
Sean Callanan9b6898f2011-07-30 02:42:06 +00002132 IntegerType *offset_type(Type::getInt32Ty(context));
Sean Callanan8bce6652010-07-13 21:41:46 +00002133
2134 if (!offset_type)
Sean Callanan97c924e2011-01-27 01:07:04 +00002135 {
2136 if (m_error_stream)
2137 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't produce an offset type");
2138
Sean Callanan8bce6652010-07-13 21:41:46 +00002139 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002140 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002141
2142 for (element_index = 0; element_index < num_elements; ++element_index)
2143 {
Sean Callanan58baaad2011-07-08 00:39:14 +00002144 const clang::NamedDecl *decl = NULL;
2145 Value *value = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002146 off_t offset;
Greg Clayton8de27c72010-10-15 22:48:33 +00002147 lldb_private::ConstString name;
Sean Callanan8bce6652010-07-13 21:41:46 +00002148
Sean Callanan45690fe2010-08-30 22:17:16 +00002149 if (!m_decl_map->GetStructElement (decl, value, offset, name, element_index))
Sean Callanan97c924e2011-01-27 01:07:04 +00002150 {
2151 if (m_error_stream)
2152 m_error_stream->Printf("Internal error [IRForTarget]: Structure information is incomplete");
2153
Sean Callanan8bce6652010-07-13 21:41:46 +00002154 return false;
Sean Callanan97c924e2011-01-27 01:07:04 +00002155 }
2156
Sean Callanan8bce6652010-07-13 21:41:46 +00002157 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002158 log->Printf(" \"%s\" [\"%s\"] (\"%s\") placed at %d",
Sean Callanan82b74c82010-08-12 01:56:52 +00002159 value->getName().str().c_str(),
Greg Clayton8de27c72010-10-15 22:48:33 +00002160 name.GetCString(),
Sean Callanan8bce6652010-07-13 21:41:46 +00002161 PrintValue(value, true).c_str(),
2162 offset);
2163
Sean Callanan9b6898f2011-07-30 02:42:06 +00002164 ConstantInt *offset_int(ConstantInt::get(offset_type, offset, true));
Sean Callanan6ba533e2010-11-17 23:00:36 +00002165 GetElementPtrInst *get_element_ptr = GetElementPtrInst::Create(argument, offset_int, "", FirstEntryInstruction);
Sean Callanan6a925532011-01-13 08:53:35 +00002166
Sean Callanan58baaad2011-07-08 00:39:14 +00002167 Value *replacement = NULL;
Sean Callanan8bce6652010-07-13 21:41:46 +00002168
Sean Callanan6a925532011-01-13 08:53:35 +00002169 // Per the comment at ASTResultSynthesizer::SynthesizeBodyResult, in cases where the result
2170 // variable is an rvalue, we have to synthesize a dereference of the appropriate structure
2171 // entry in order to produce the static variable that the AST thinks it is accessing.
2172 if (name == m_result_name && !m_result_is_pointer)
2173 {
2174 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType()->getPointerTo(), "", FirstEntryInstruction);
2175
2176 LoadInst *load = new LoadInst(bit_cast, "", FirstEntryInstruction);
2177
2178 replacement = load;
2179 }
Sean Callananbafd6852010-07-14 23:40:29 +00002180 else
Sean Callanan6a925532011-01-13 08:53:35 +00002181 {
2182 BitCastInst *bit_cast = new BitCastInst(get_element_ptr, value->getType(), "", FirstEntryInstruction);
2183
2184 replacement = bit_cast;
2185 }
2186
2187 if (Constant *constant = dyn_cast<Constant>(value))
2188 UnfoldConstant(constant, replacement, FirstEntryInstruction);
2189 else
2190 value->replaceAllUsesWith(replacement);
Sean Callananb51ee982010-11-02 23:51:17 +00002191
2192 if (GlobalVariable *var = dyn_cast<GlobalVariable>(value))
2193 var->eraseFromParent();
Sean Callanan8bce6652010-07-13 21:41:46 +00002194 }
2195
2196 if (log)
2197 log->Printf("Total structure [align %d, size %d]", alignment, size);
2198
2199 return true;
2200}
2201
Sean Callananc0492742011-05-23 21:40:23 +00002202llvm::Constant *
Sean Callanan9b6898f2011-07-30 02:42:06 +00002203IRForTarget::BuildRelocation(llvm::Type *type,
Sean Callananc0492742011-05-23 21:40:23 +00002204 uint64_t offset)
2205{
2206 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2207
Sean Callanan9b6898f2011-07-30 02:42:06 +00002208 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2209 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002210
2211 llvm::Constant *offset_int = ConstantInt::get(intptr_ty, offset);
Sean Callanan9b6898f2011-07-30 02:42:06 +00002212
2213 llvm::Constant *offset_array[1];
2214
2215 offset_array[0] = offset_int;
2216
2217 llvm::ArrayRef<llvm::Constant *> offsets(offset_array, 1);
2218
2219 llvm::Constant *reloc_getelementptr = ConstantExpr::getGetElementPtr(m_reloc_placeholder, offsets);
Sean Callananc0492742011-05-23 21:40:23 +00002220 llvm::Constant *reloc_getbitcast = ConstantExpr::getBitCast(reloc_getelementptr, type);
2221
2222 return reloc_getbitcast;
2223}
2224
2225bool
2226IRForTarget::CompleteDataAllocation ()
2227{
2228 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
2229
2230 if (!m_data_allocator->GetStream().GetSize())
2231 return true;
2232
2233 lldb::addr_t allocation = m_data_allocator->Allocate();
2234
2235 if (log)
2236 {
2237 if (allocation)
2238 log->Printf("Allocated static data at 0x%llx", (unsigned long long)allocation);
2239 else
2240 log->Printf("Failed to allocate static data");
2241 }
2242
2243 if (!allocation)
2244 return false;
2245
Sean Callanan9b6898f2011-07-30 02:42:06 +00002246 IntegerType *intptr_ty = Type::getIntNTy(m_module->getContext(),
2247 (m_module->getPointerSize() == Module::Pointer64) ? 64 : 32);
Sean Callananc0492742011-05-23 21:40:23 +00002248
2249 Constant *relocated_addr = ConstantInt::get(intptr_ty, (uint64_t)allocation);
2250 Constant *relocated_bitcast = ConstantExpr::getIntToPtr(relocated_addr, llvm::Type::getInt8PtrTy(m_module->getContext()));
2251
2252 m_reloc_placeholder->replaceAllUsesWith(relocated_bitcast);
2253
2254 m_reloc_placeholder->eraseFromParent();
2255
2256 return true;
2257}
2258
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002259bool
Greg Clayton3c7feb42010-11-19 01:05:25 +00002260IRForTarget::runOnModule (Module &llvm_module)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002261{
Greg Claytone005f2c2010-11-06 01:53:30 +00002262 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002263
Sean Callananc0492742011-05-23 21:40:23 +00002264 m_module = &llvm_module;
2265
2266 Function* function = m_module->getFunction(StringRef(m_func_name.c_str()));
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002267
2268 if (!function)
2269 {
2270 if (log)
Greg Claytonb5037af2010-11-15 01:47:11 +00002271 log->Printf("Couldn't find \"%s()\" in the module", m_func_name.c_str());
Sean Callanan97c924e2011-01-27 01:07:04 +00002272
2273 if (m_error_stream)
Sean Callananc0492742011-05-23 21:40:23 +00002274 m_error_stream->Printf("Internal error [IRForTarget]: Couldn't find wrapper '%s' in the module", m_func_name.c_str());
Sean Callanan6a925532011-01-13 08:53:35 +00002275
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002276 return false;
2277 }
Sean Callananc0492742011-05-23 21:40:23 +00002278
2279 if (!FixFunctionLinkage (*function))
2280 {
2281 if (log)
2282 log->Printf("Couldn't fix the linkage for the function");
2283
2284 return false;
2285 }
2286
Sean Callanan9b6898f2011-07-30 02:42:06 +00002287 llvm::Type *intptr_ty = Type::getInt8Ty(m_module->getContext());
Sean Callananc0492742011-05-23 21:40:23 +00002288
2289 m_reloc_placeholder = new llvm::GlobalVariable((*m_module),
2290 intptr_ty,
2291 false /* isConstant */,
2292 GlobalVariable::InternalLinkage,
2293 Constant::getNullValue(intptr_ty),
2294 "reloc_placeholder",
2295 NULL /* InsertBefore */,
2296 false /* ThreadLocal */,
2297 0 /* AddressSpace */);
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002298
Sean Callanan02fbafa2010-07-27 21:39:39 +00002299 Function::iterator bbi;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002300
Sean Callananc0492742011-05-23 21:40:23 +00002301 m_has_side_effects = HasSideEffects(*function);
Sean Callanan05a5a1b2010-12-16 03:17:46 +00002302
Sean Callanan82b74c82010-08-12 01:56:52 +00002303 ////////////////////////////////////////////////////////////
Greg Clayton8de27c72010-10-15 22:48:33 +00002304 // Replace $__lldb_expr_result with a persistent variable
Sean Callanan82b74c82010-08-12 01:56:52 +00002305 //
2306
Sean Callananc0492742011-05-23 21:40:23 +00002307 if (!CreateResultVariable(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002308 {
2309 if (log)
2310 log->Printf("CreateResultVariable() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002311
2312 // CreateResultVariable() reports its own errors, so we don't do so here
2313
Sean Callanan82b74c82010-08-12 01:56:52 +00002314 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002315 }
Sean Callanan82b74c82010-08-12 01:56:52 +00002316
Sean Callanan696cf5f2011-05-07 01:06:41 +00002317 if (m_const_result)
2318 return true;
2319
Sean Callananc0492742011-05-23 21:40:23 +00002320 if (log)
2321 {
2322 std::string s;
2323 raw_string_ostream oss(s);
2324
2325 m_module->print(oss, NULL);
2326
2327 oss.flush();
2328
2329 log->Printf("Module after creating the result variable: \n\"%s\"", s.c_str());
2330 }
2331
Sean Callanan6ba533e2010-11-17 23:00:36 +00002332 ///////////////////////////////////////////////////////////////////////////////
2333 // Fix all Objective-C constant strings to use NSStringWithCString:encoding:
2334 //
Sean Callanan6ba533e2010-11-17 23:00:36 +00002335
Sean Callananc0492742011-05-23 21:40:23 +00002336 if (!RewriteObjCConstStrings(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002337 {
2338 if (log)
2339 log->Printf("RewriteObjCConstStrings() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002340
2341 // RewriteObjCConstStrings() reports its own errors, so we don't do so here
2342
Sean Callanan6ba533e2010-11-17 23:00:36 +00002343 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002344 }
Sean Callanan6ba533e2010-11-17 23:00:36 +00002345
Sean Callananf5857a02010-07-31 01:32:05 +00002346 //////////////////////////////////
2347 // Run basic-block level passes
2348 //
2349
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002350 for (bbi = function->begin();
2351 bbi != function->end();
2352 ++bbi)
2353 {
Sean Callananc0492742011-05-23 21:40:23 +00002354 if (!RemoveGuards(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002355 {
2356 if (log)
2357 log->Printf("RemoveGuards() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002358
2359 // RemoveGuards() reports its own errors, so we don't do so here
2360
Sean Callanan8c127202010-08-23 23:09:38 +00002361 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002362 }
Sean Callanan8c127202010-08-23 23:09:38 +00002363
Sean Callananc0492742011-05-23 21:40:23 +00002364 if (!RewritePersistentAllocs(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002365 {
2366 if (log)
2367 log->Printf("RewritePersistentAllocs() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002368
2369 // RewritePersistentAllocs() reports its own errors, so we don't do so here
2370
Sean Callananf5857a02010-07-31 01:32:05 +00002371 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002372 }
Sean Callananf5857a02010-07-31 01:32:05 +00002373
Sean Callananc0492742011-05-23 21:40:23 +00002374 if (!RewriteObjCSelectors(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002375 {
2376 if (log)
2377 log->Printf("RewriteObjCSelectors() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002378
2379 // RewriteObjCSelectors() reports its own errors, so we don't do so here
2380
Sean Callanana48fe162010-08-11 03:57:18 +00002381 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002382 }
Sean Callanana48fe162010-08-11 03:57:18 +00002383
Sean Callananc0492742011-05-23 21:40:23 +00002384 if (!ResolveCalls(*bbi))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002385 {
2386 if (log)
2387 log->Printf("ResolveCalls() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002388
2389 // ResolveCalls() reports its own errors, so we don't do so here
2390
Sean Callanan8bce6652010-07-13 21:41:46 +00002391 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002392 }
Sean Callananc0492742011-05-23 21:40:23 +00002393
2394 if (!ReplaceStaticLiterals(*bbi))
2395 {
2396 if (log)
2397 log->Printf("ReplaceStaticLiterals() failed");
2398
2399 return false;
2400 }
Sean Callanan8bce6652010-07-13 21:41:46 +00002401 }
2402
Sean Callanan771131d2010-09-30 21:18:25 +00002403 ///////////////////////////////
2404 // Run function-level passes
2405 //
2406
Sean Callananc0492742011-05-23 21:40:23 +00002407 if (!ResolveExternals(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002408 {
2409 if (log)
2410 log->Printf("ResolveExternals() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002411
2412 // ResolveExternals() reports its own errors, so we don't do so here
2413
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002414 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002415 }
Sean Callanan1d1b39c2010-11-08 00:31:32 +00002416
Sean Callananc0492742011-05-23 21:40:23 +00002417 if (!ReplaceVariables(*function))
Sean Callanan3aa7da52010-12-13 22:46:15 +00002418 {
2419 if (log)
2420 log->Printf("ReplaceVariables() failed");
Sean Callanan97c924e2011-01-27 01:07:04 +00002421
2422 // ReplaceVariables() reports its own errors, so we don't do so here
2423
Sean Callanan771131d2010-09-30 21:18:25 +00002424 return false;
Sean Callanan3aa7da52010-12-13 22:46:15 +00002425 }
Sean Callanan771131d2010-09-30 21:18:25 +00002426
Sean Callananc0492742011-05-23 21:40:23 +00002427 if (!ReplaceStrings())
2428 {
2429 if (log)
2430 log->Printf("ReplaceStrings() failed");
2431
2432 return false;
2433 }
2434
2435 if (!CompleteDataAllocation())
2436 {
2437 if (log)
2438 log->Printf("CompleteDataAllocation() failed");
2439
2440 return false;
2441 }
2442
Sean Callanan8bce6652010-07-13 21:41:46 +00002443 if (log)
2444 {
Sean Callanan321fe9e2010-07-28 01:00:59 +00002445 std::string s;
2446 raw_string_ostream oss(s);
Sean Callanan8bce6652010-07-13 21:41:46 +00002447
Sean Callananc0492742011-05-23 21:40:23 +00002448 m_module->print(oss, NULL);
Sean Callanan321fe9e2010-07-28 01:00:59 +00002449
2450 oss.flush();
2451
Greg Claytonb5037af2010-11-15 01:47:11 +00002452 log->Printf("Module after preparing for execution: \n\"%s\"", s.c_str());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002453 }
2454
2455 return true;
2456}
2457
2458void
Greg Clayton3c7feb42010-11-19 01:05:25 +00002459IRForTarget::assignPassManager (PMStack &pass_mgr_stack, PassManagerType pass_mgr_type)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +00002460{
2461}
2462
2463PassManagerType
2464IRForTarget::getPotentialPassManagerType() const
2465{
2466 return PMT_ModulePassManager;
2467}