blob: d7038fd2c9a8dbec6c895c87626180c37755fe1c [file] [log] [blame]
Misha Brukman857c21b2003-10-10 17:45:12 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukman835702a2005-04-21 22:36:52 +00009//
Chris Lattner996fe012002-12-24 00:01:05 +000010// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +000015#include "llvm/ExecutionEngine/ExecutionEngine.h"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000016#include "llvm/ADT/STLExtras.h"
Daniel Dunbar868e3f02010-11-13 02:48:57 +000017#include "llvm/ADT/SmallString.h"
Chris Lattner390d78b2009-08-23 22:49:13 +000018#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ExecutionEngine/GenericValue.h"
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000020#include "llvm/ExecutionEngine/JITEventListener.h"
Lang Hames633fe142015-03-30 03:37:06 +000021#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DerivedTypes.h"
Lang Hames3dac3f72015-03-31 20:31:14 +000025#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Module.h"
27#include "llvm/IR/Operator.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000028#include "llvm/IR/ValueHandle.h"
Rafael Espindoladd396572014-08-01 19:28:15 +000029#include "llvm/Object/Archive.h"
David Blaikie35907d82014-04-29 22:04:55 +000030#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000031#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Support/DynamicLibrary.h"
Torok Edwin6c2d2332009-07-07 17:32:34 +000033#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/Host.h"
Chris Lattner6d8dd182006-05-08 22:00:52 +000035#include "llvm/Support/MutexGuard.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Support/TargetRegistry.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000037#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +000038#include "llvm/Target/TargetMachine.h"
Anton Korobeynikov579f0712008-02-20 11:08:44 +000039#include <cmath>
40#include <cstring>
Chris Lattner29681de2003-11-19 21:08:57 +000041using namespace llvm;
Chris Lattner996fe012002-12-24 00:01:05 +000042
Chandler Carruthf58e3762014-04-22 03:04:17 +000043#define DEBUG_TYPE "jit"
44
Chris Lattnerc346ecd2006-12-19 22:43:32 +000045STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
46STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattner996fe012002-12-24 00:01:05 +000047
Daniel Dunbar70ff8b02010-11-17 16:06:37 +000048ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
David Blaikie196e3232014-09-02 22:41:07 +000049 std::unique_ptr<Module> M, std::string *ErrorStr,
Lang Hames633fe142015-03-30 03:37:06 +000050 std::shared_ptr<MCJITMemoryManager> MemMgr,
51 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
Lang Hames4a5697e2014-12-03 00:51:19 +000052 std::unique_ptr<TargetMachine> TM) = nullptr;
Lang Hames93de2a12015-01-23 21:25:00 +000053
54ExecutionEngine *(*ExecutionEngine::OrcMCJITReplacementCtor)(
Lang Hames633fe142015-03-30 03:37:06 +000055 std::string *ErrorStr, std::shared_ptr<MCJITMemoryManager> MemMgr,
56 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
Lang Hames93de2a12015-01-23 21:25:00 +000057 std::unique_ptr<TargetMachine> TM) = nullptr;
58
Rafael Espindola2a8a2792014-08-19 04:04:25 +000059ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
Craig Topper2617dcc2014-04-15 06:32:26 +000060 std::string *ErrorStr) =nullptr;
Chris Lattner2d52c1b2006-03-22 06:07:50 +000061
Lang Hames7ea98e12014-11-27 01:41:16 +000062void JITEventListener::anchor() {}
63
Rafael Espindola2a8a2792014-08-19 04:04:25 +000064ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
Lang Hames3dac3f72015-03-31 20:31:14 +000065 : LazyFunctionCreator(nullptr) {
Jeffrey Yasskin4567db42009-10-27 20:30:28 +000066 CompilingLazily = false;
Evan Chengcdc00602008-09-24 16:25:55 +000067 GVCompilationDisabled = false;
Evan Cheng84a90552008-06-17 16:49:02 +000068 SymbolSearchingDisabled = false;
Lang Hamesbc876012014-04-18 06:48:23 +000069
70 // IR module verification is enabled by default in debug builds, and disabled
71 // by default in release builds.
72#ifndef NDEBUG
73 VerifyModules = true;
74#else
75 VerifyModules = false;
76#endif
77
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000078 assert(M && "Module is null?");
Rafael Espindola2a8a2792014-08-19 04:04:25 +000079 Modules.push_back(std::move(M));
Misha Brukman260b0c82003-10-16 21:18:05 +000080}
81
Brian Gaeke92f8b302003-09-04 22:57:27 +000082ExecutionEngine::~ExecutionEngine() {
Reid Spencer603682a2007-03-03 18:19:18 +000083 clearAllGlobalMappings();
Brian Gaeke92f8b302003-09-04 22:57:27 +000084}
85
Jeffrey Yasskina4044332010-03-27 04:53:56 +000086namespace {
Daniel Dunbar868e3f02010-11-13 02:48:57 +000087/// \brief Helper class which uses a value handler to automatically deletes the
88/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskina4044332010-03-27 04:53:56 +000089class GVMemoryBlock : public CallbackVH {
90 GVMemoryBlock(const GlobalVariable *GV)
91 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
92
93public:
Daniel Dunbar868e3f02010-11-13 02:48:57 +000094 /// \brief Returns the address the GlobalVariable should be written into. The
95 /// GVMemoryBlock object prefixes that.
Micah Villmowcdfe20b2012-10-08 16:38:25 +000096 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
Chris Lattner229907c2011-07-18 04:54:35 +000097 Type *ElTy = GV->getType()->getElementType();
Jeffrey Yasskina4044332010-03-27 04:53:56 +000098 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
99 void *RawMemory = ::operator new(
David Majnemerf3cadce2014-10-20 06:13:33 +0000100 RoundUpToAlignment(sizeof(GVMemoryBlock),
101 TD.getPreferredAlignment(GV))
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000102 + GVSize);
103 new(RawMemory) GVMemoryBlock(GV);
104 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
105 }
106
Craig Topperb51ff602014-03-08 07:51:20 +0000107 void deleted() override {
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000108 // We allocated with operator new and with some extra memory hanging off the
109 // end, so don't just delete this. I'm not sure if this is actually
110 // required.
111 this->~GVMemoryBlock();
112 ::operator delete(this);
113 }
114};
115} // anonymous namespace
116
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000117char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000118 return GVMemoryBlock::Create(GV, *getDataLayout());
Nicolas Geoffray5457ce92008-10-25 15:41:43 +0000119}
120
David Blaikie35907d82014-04-29 22:04:55 +0000121void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
122 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
123}
124
Rafael Espindola7271c192014-08-26 21:04:04 +0000125void
126ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
127 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
128}
129
Rafael Espindola48af1c22014-08-19 18:44:46 +0000130void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolaacfd6282014-08-01 18:49:24 +0000131 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
132}
133
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000134bool ExecutionEngine::removeModule(Module *M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000135 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
136 Module *Found = I->get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000137 if (Found == M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000138 I->release();
Devang Patel324fe892007-10-15 19:56:32 +0000139 Modules.erase(I);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000140 clearGlobalMappingsFromModule(M);
141 return true;
Devang Patel324fe892007-10-15 19:56:32 +0000142 }
143 }
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000144 return false;
Nate Begeman617001d2009-01-23 19:27:28 +0000145}
146
Chris Lattner0621cae2006-08-16 01:24:12 +0000147Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
148 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Keno Fischer5f92a082015-01-27 19:29:00 +0000149 Function *F = Modules[i]->getFunction(FnName);
150 if (F && !F->isDeclaration())
Chris Lattner0621cae2006-08-16 01:24:12 +0000151 return F;
152 }
Craig Topper2617dcc2014-04-15 06:32:26 +0000153 return nullptr;
Chris Lattner0621cae2006-08-16 01:24:12 +0000154}
155
156
Lang Hames3dac3f72015-03-31 20:31:14 +0000157uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
158 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
159 uint64_t OldVal;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000160
161 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
162 // GlobalAddressMap.
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000163 if (I == GlobalAddressMap.end())
Lang Hames3dac3f72015-03-31 20:31:14 +0000164 OldVal = 0;
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000165 else {
Lang Hames3dac3f72015-03-31 20:31:14 +0000166 GlobalAddressReverseMap.erase(I->second);
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000167 OldVal = I->second;
168 GlobalAddressMap.erase(I);
169 }
170
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000171 return OldVal;
172}
173
Lang Hames3dac3f72015-03-31 20:31:14 +0000174std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
175 MutexGuard locked(lock);
176 Mangler Mang(DL);
177 SmallString<128> FullName;
178 Mang.getNameWithPrefix(FullName, GV->getName());
179 return FullName.str();
180}
181
Chris Lattner6d8dd182006-05-08 22:00:52 +0000182void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000183 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000184 addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
185}
Evan Cheng5cc53c32008-09-18 07:54:21 +0000186
Lang Hames3dac3f72015-03-31 20:31:14 +0000187void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
188 MutexGuard locked(lock);
189
190 assert(!Name.empty() && "Empty GlobalMapping symbol name!");
191
192 DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
193 uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
Craig Topper2617dcc2014-04-15 06:32:26 +0000194 assert((!CurVal || !Addr) && "GlobalMapping already established!");
Chris Lattner6d8dd182006-05-08 22:00:52 +0000195 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000196
197 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000198 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames3dac3f72015-03-31 20:31:14 +0000199 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
200 assert((!V.empty() || !Name.empty()) &&
201 "GlobalMapping already established!");
202 V = Name;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000203 }
204}
205
Chris Lattner6d8dd182006-05-08 22:00:52 +0000206void ExecutionEngine::clearAllGlobalMappings() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000207 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000208
Zachary Turner2f825df2014-06-16 20:54:28 +0000209 EEState.getGlobalAddressMap().clear();
210 EEState.getGlobalAddressReverseMap().clear();
Chris Lattner6d8dd182006-05-08 22:00:52 +0000211}
212
Nate Begeman8f83fc42008-05-21 16:34:48 +0000213void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000214 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000215
216 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Lang Hames3dac3f72015-03-31 20:31:14 +0000217 EEState.RemoveMapping(getMangledName(FI));
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000218 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
219 GI != GE; ++GI)
Lang Hames3dac3f72015-03-31 20:31:14 +0000220 EEState.RemoveMapping(getMangledName(GI));
Nate Begeman8f83fc42008-05-21 16:34:48 +0000221}
222
Lang Hames3dac3f72015-03-31 20:31:14 +0000223uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
224 void *Addr) {
225 MutexGuard locked(lock);
226 return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
227}
228
229uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000230 MutexGuard locked(lock);
Chris Lattneree181732008-04-04 04:47:41 +0000231
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000232 ExecutionEngineState::GlobalAddressMapTy &Map =
Zachary Turner2f825df2014-06-16 20:54:28 +0000233 EEState.getGlobalAddressMap();
Chris Lattneree181732008-04-04 04:47:41 +0000234
Chris Lattner6d8dd182006-05-08 22:00:52 +0000235 // Deleting from the mapping?
Craig Topper2617dcc2014-04-15 06:32:26 +0000236 if (!Addr)
Lang Hames3dac3f72015-03-31 20:31:14 +0000237 return EEState.RemoveMapping(Name);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000238
Lang Hames3dac3f72015-03-31 20:31:14 +0000239 uint64_t &CurVal = Map[Name];
240 uint64_t OldVal = CurVal;
Chris Lattneree181732008-04-04 04:47:41 +0000241
Zachary Turner2f825df2014-06-16 20:54:28 +0000242 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
243 EEState.getGlobalAddressReverseMap().erase(CurVal);
Chris Lattner6d8dd182006-05-08 22:00:52 +0000244 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000245
246 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000247 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames3dac3f72015-03-31 20:31:14 +0000248 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
249 assert((!V.empty() || !Name.empty()) &&
250 "GlobalMapping already established!");
251 V = Name;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000252 }
Chris Lattneree181732008-04-04 04:47:41 +0000253 return OldVal;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000254}
255
Lang Hames3dac3f72015-03-31 20:31:14 +0000256uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
257 MutexGuard locked(lock);
258 uint64_t Address = 0;
259 ExecutionEngineState::GlobalAddressMapTy::iterator I =
260 EEState.getGlobalAddressMap().find(S);
261 if (I != EEState.getGlobalAddressMap().end())
262 Address = I->second;
263 return Address;
264}
265
266
267void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
268 MutexGuard locked(lock);
269 if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
270 return Address;
271 return nullptr;
272}
273
Chris Lattner6d8dd182006-05-08 22:00:52 +0000274void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000275 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000276 return getPointerToGlobalIfAvailable(getMangledName(GV));
Chris Lattner6d8dd182006-05-08 22:00:52 +0000277}
278
Chris Lattner748e8572003-12-31 20:21:04 +0000279const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000280 MutexGuard locked(lock);
Reid Spencer79876f52005-07-12 15:51:55 +0000281
Chris Lattner748e8572003-12-31 20:21:04 +0000282 // If we haven't computed the reverse mapping yet, do so first.
Zachary Turner2f825df2014-06-16 20:54:28 +0000283 if (EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000284 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Lang Hames3dac3f72015-03-31 20:31:14 +0000285 I = EEState.getGlobalAddressMap().begin(),
286 E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
287 StringRef Name = I->first();
288 uint64_t Addr = I->second;
Zachary Turner2f825df2014-06-16 20:54:28 +0000289 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
Lang Hames3dac3f72015-03-31 20:31:14 +0000290 Addr, Name));
291 }
Chris Lattner748e8572003-12-31 20:21:04 +0000292 }
293
Lang Hames3dac3f72015-03-31 20:31:14 +0000294 std::map<uint64_t, std::string>::iterator I =
295 EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);
296
297 if (I != EEState.getGlobalAddressReverseMap().end()) {
298 StringRef Name = I->second;
299 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
300 if (GlobalValue *GV = Modules[i]->getNamedValue(Name))
301 return GV;
302 }
303 return nullptr;
Chris Lattner748e8572003-12-31 20:21:04 +0000304}
Chris Lattner5a0d4822003-12-26 06:50:30 +0000305
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000306namespace {
307class ArgvArray {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000308 std::unique_ptr<char[]> Array;
309 std::vector<std::unique_ptr<char[]>> Values;
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000310public:
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000311 /// Turn a vector of strings into a nice argv style array of pointers to null
312 /// terminated strings.
313 void *reset(LLVMContext &C, ExecutionEngine *EE,
314 const std::vector<std::string> &InputArgv);
315};
316} // anonymous namespace
317void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
318 const std::vector<std::string> &InputArgv) {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000319 Values.clear(); // Free the old contents.
320 Values.reserve(InputArgv.size());
Chandler Carruth5da3f052012-11-01 09:14:31 +0000321 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000322 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000323
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000324 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
Chris Lattner229907c2011-07-18 04:54:35 +0000325 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000326
327 for (unsigned i = 0; i != InputArgv.size(); ++i) {
328 unsigned Size = InputArgv[i].size()+1;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000329 auto Dest = make_unique<char[]>(Size);
330 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
Misha Brukman835702a2005-04-21 22:36:52 +0000331
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000332 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
Chris Lattner5a0d4822003-12-26 06:50:30 +0000333 Dest[Size-1] = 0;
Misha Brukman835702a2005-04-21 22:36:52 +0000334
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000335 // Endian safe: Array[i] = (PointerTy)Dest;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000336 EE->StoreValueToMemory(PTOGV(Dest.get()),
337 (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
338 Values.push_back(std::move(Dest));
Chris Lattner5a0d4822003-12-26 06:50:30 +0000339 }
340
341 // Null terminate it
Craig Topper2617dcc2014-04-15 06:32:26 +0000342 EE->StoreValueToMemory(PTOGV(nullptr),
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000343 (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
Chris Lattner5a0d4822003-12-26 06:50:30 +0000344 SBytePtr);
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000345 return Array.get();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000346}
347
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000348void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000349 bool isDtors) {
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000350 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000351 GlobalVariable *GV = module.getNamedGlobal(Name);
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000352
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000353 // If this global has internal linkage, or if it has a use, then it must be
354 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
355 // this is the case, don't execute any of the global ctors, __main will do
356 // it.
357 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
358
Nick Lewycky0cbfcb22011-04-06 20:38:44 +0000359 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000360 // the init priority, which we ignore.
Chris Lattner00245f42012-01-24 13:41:11 +0000361 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
Craig Topper2617dcc2014-04-15 06:32:26 +0000362 if (!InitList)
Nick Lewycky0f857892011-04-11 22:11:20 +0000363 return;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000364 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner00245f42012-01-24 13:41:11 +0000365 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
Craig Topper2617dcc2014-04-15 06:32:26 +0000366 if (!CS) continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000367
368 Constant *FP = CS->getOperand(1);
369 if (FP->isNullValue())
Nick Lewycky0f857892011-04-11 22:11:20 +0000370 continue; // Found a sentinal value, ignore.
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000371
372 // Strip off constant expression casts.
373 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
374 if (CE->isCast())
375 FP = CE->getOperand(0);
376
377 // Execute the ctor/dtor function!
378 if (Function *F = dyn_cast<Function>(FP))
379 runFunction(F, std::vector<GenericValue>());
380
381 // FIXME: It is marginally lame that we just do nothing here if we see an
382 // entry we don't recognize. It might not be unreasonable for the verifier
383 // to not even allow this and just assert here.
384 }
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000385}
386
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000387void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
388 // Execute global ctors/dtors for each module in the program.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000389 for (std::unique_ptr<Module> &M : Modules)
390 runStaticConstructorsDestructors(*M, isDtors);
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000391}
392
Dan Gohmancf3e3012008-08-26 01:38:29 +0000393#ifndef NDEBUG
Duncan Sands1202d1b2007-12-14 19:38:31 +0000394/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
395static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
Chandler Carruth5da3f052012-11-01 09:14:31 +0000396 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Duncan Sands1202d1b2007-12-14 19:38:31 +0000397 for (unsigned i = 0; i < PtrSize; ++i)
398 if (*(i + (uint8_t*)Loc))
399 return false;
400 return true;
401}
Dan Gohmancf3e3012008-08-26 01:38:29 +0000402#endif
Duncan Sands1202d1b2007-12-14 19:38:31 +0000403
Chris Lattner5a0d4822003-12-26 06:50:30 +0000404int ExecutionEngine::runFunctionAsMain(Function *Fn,
405 const std::vector<std::string> &argv,
406 const char * const * envp) {
407 std::vector<GenericValue> GVArgs;
408 GenericValue GVArgc;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000409 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000410
411 // Check main() type
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000412 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattner229907c2011-07-18 04:54:35 +0000413 FunctionType *FTy = Fn->getFunctionType();
414 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000415
416 // Check the argument types.
417 if (NumArgs > 3)
418 report_fatal_error("Invalid number of arguments of main() supplied");
419 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
420 report_fatal_error("Invalid type for third argument of main() supplied");
421 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
422 report_fatal_error("Invalid type for second argument of main() supplied");
423 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
424 report_fatal_error("Invalid type for first argument of main() supplied");
425 if (!FTy->getReturnType()->isIntegerTy() &&
426 !FTy->getReturnType()->isVoidTy())
427 report_fatal_error("Invalid return type of main() supplied");
428
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000429 ArgvArray CArgv;
430 ArgvArray CEnv;
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000431 if (NumArgs) {
432 GVArgs.push_back(GVArgc); // Arg #0 = argc.
433 if (NumArgs > 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000434 // Arg #1 = argv.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000435 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands1202d1b2007-12-14 19:38:31 +0000436 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000437 "argv[0] was null after CreateArgv");
438 if (NumArgs > 2) {
439 std::vector<std::string> EnvVars;
440 for (unsigned i = 0; envp[i]; ++i)
441 EnvVars.push_back(envp[i]);
Owen Anderson55f1c092009-08-13 21:58:54 +0000442 // Arg #2 = envp.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000443 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000444 }
445 }
446 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000447
Reid Spencer87aa65f2007-03-06 03:04:04 +0000448 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000449}
450
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000451EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
Lang Hames93de2a12015-01-23 21:25:00 +0000452
Lang Hames4a5697e2014-12-03 00:51:19 +0000453EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000454 : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
Lang Hames633fe142015-03-30 03:37:06 +0000455 OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr),
456 RelocModel(Reloc::Default), CMModel(CodeModel::JITDefault),
457 UseOrcMCJITReplacement(false) {
Alp Toker322db9e2014-05-31 21:26:17 +0000458// IR module verification is enabled by default in debug builds, and disabled
459// by default in release builds.
460#ifndef NDEBUG
461 VerifyModules = true;
462#else
463 VerifyModules = false;
464#endif
465}
466
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000467EngineBuilder::~EngineBuilder() = default;
468
469EngineBuilder &EngineBuilder::setMCJITMemoryManager(
470 std::unique_ptr<RTDyldMemoryManager> mcjmm) {
Lang Hames633fe142015-03-30 03:37:06 +0000471 auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
472 MemMgr = SharedMM;
473 Resolver = SharedMM;
474 return *this;
475}
476
477EngineBuilder&
478EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
479 MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
480 return *this;
481}
482
483EngineBuilder&
484EngineBuilder::setSymbolResolver(std::unique_ptr<RuntimeDyld::SymbolResolver> SR) {
485 Resolver = std::shared_ptr<RuntimeDyld::SymbolResolver>(std::move(SR));
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000486 return *this;
487}
488
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000489ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000490 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000491
Nick Lewyckya53414f2008-03-08 02:49:45 +0000492 // Make sure we can resolve symbols in the program as well. The zero arg
493 // to the function tells DynamicLibrary to load the program, not a library.
Craig Topper2617dcc2014-04-15 06:32:26 +0000494 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
495 return nullptr;
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000496
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000497 // If the user specified a memory manager but didn't specify which engine to
498 // create, we assume they only want the JIT, and we fail if they only want
499 // the interpreter.
Lang Hames633fe142015-03-30 03:37:06 +0000500 if (MemMgr) {
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000501 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000502 WhichEngine = EngineKind::JIT;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000503 else {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000504 if (ErrorStr)
505 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000506 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000507 }
508 }
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000509
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000510 // Unless the interpreter was explicitly selected or the JIT is not linked,
511 // try making a JIT.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000512 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000513 Triple TT(M->getTargetTriple());
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000514 if (!TM->getTarget().hasJIT()) {
515 errs() << "WARNING: This target JIT is not designed for the host"
516 << " you are running. If bad things happen, please choose"
517 << " a different -march switch.\n";
518 }
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000519
Lang Hamesbc876012014-04-18 06:48:23 +0000520 ExecutionEngine *EE = nullptr;
Lang Hames93de2a12015-01-23 21:25:00 +0000521 if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
Lang Hames633fe142015-03-30 03:37:06 +0000522 EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
523 std::move(Resolver),
Lang Hames93de2a12015-01-23 21:25:00 +0000524 std::move(TheTM));
525 EE->addModule(std::move(M));
526 } else if (ExecutionEngine::MCJITCtor)
Lang Hames633fe142015-03-30 03:37:06 +0000527 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
528 std::move(Resolver), std::move(TheTM));
Lang Hames93de2a12015-01-23 21:25:00 +0000529
Lang Hamesbc876012014-04-18 06:48:23 +0000530 if (EE) {
531 EE->setVerifyModules(VerifyModules);
532 return EE;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000533 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000534 }
535
536 // If we can't make a JIT and we didn't request one specifically, try making
537 // an interpreter instead.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000538 if (WhichEngine & EngineKind::Interpreter) {
539 if (ExecutionEngine::InterpCtor)
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000540 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
Chris Lattner8bcc6442009-09-23 02:03:49 +0000541 if (ErrorStr)
542 *ErrorStr = "Interpreter has not been linked in.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000543 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000544 }
Chris Lattner8bcc6442009-09-23 02:03:49 +0000545
Eric Christopher79cc1e32014-09-02 22:28:02 +0000546 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000547 if (ErrorStr)
548 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000549 }
550
Craig Topper2617dcc2014-04-15 06:32:26 +0000551 return nullptr;
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000552}
553
Chris Lattner996fe012002-12-24 00:01:05 +0000554void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke1678e852003-08-13 18:16:14 +0000555 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattner996fe012002-12-24 00:01:05 +0000556 return getPointerToFunction(F);
557
Zachary Turnerc04b8922014-06-20 21:07:14 +0000558 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000559 if (void* P = getPointerToGlobalIfAvailable(GV))
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000560 return P;
Jeff Cohen69e849012006-02-07 05:11:57 +0000561
562 // Global variable might have been added since interpreter started.
563 if (GlobalVariable *GVar =
564 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
565 EmitGlobalVariable(GVar);
566 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000567 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000568
Lang Hames3dac3f72015-03-31 20:31:14 +0000569 return getPointerToGlobalIfAvailable(GV);
Chris Lattner996fe012002-12-24 00:01:05 +0000570}
571
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000572/// \brief Converts a Constant* into a GenericValue, including handling of
573/// ConstantExpr values.
Chris Lattner996fe012002-12-24 00:01:05 +0000574GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000575 // If its undefined, return the garbage.
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000576 if (isa<UndefValue>(C)) {
577 GenericValue Result;
578 switch (C->getType()->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000579 default:
580 break;
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000581 case Type::IntegerTyID:
582 case Type::X86_FP80TyID:
583 case Type::FP128TyID:
584 case Type::PPC_FP128TyID:
585 // Although the value is undefined, we still have to construct an APInt
586 // with the correct bit width.
587 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
588 break;
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000589 case Type::StructTyID: {
590 // if the whole struct is 'undef' just reserve memory for the value.
591 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
592 unsigned int elemNum = STy->getNumElements();
593 Result.AggregateVal.resize(elemNum);
594 for (unsigned int i = 0; i < elemNum; ++i) {
595 Type *ElemTy = STy->getElementType(i);
596 if (ElemTy->isIntegerTy())
597 Result.AggregateVal[i].IntVal =
598 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
599 else if (ElemTy->isAggregateType()) {
600 const Constant *ElemUndef = UndefValue::get(ElemTy);
601 Result.AggregateVal[i] = getConstantValue(ElemUndef);
602 }
603 }
604 }
605 }
606 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000607 case Type::VectorTyID:
608 // if the whole vector is 'undef' just reserve memory for the value.
609 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
610 const Type *ElemTy = VTy->getElementType();
611 unsigned int elemNum = VTy->getNumElements();
612 Result.AggregateVal.resize(elemNum);
613 if (ElemTy->isIntegerTy())
614 for (unsigned int i = 0; i < elemNum; ++i)
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000615 Result.AggregateVal[i].IntVal =
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000616 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000617 break;
618 }
619 return Result;
620 }
Chris Lattner9de0d142003-04-23 19:01:49 +0000621
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000622 // Otherwise, if the value is a ConstantExpr...
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000623 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000624 Constant *Op0 = CE->getOperand(0);
Chris Lattner9de0d142003-04-23 19:01:49 +0000625 switch (CE->getOpcode()) {
626 case Instruction::GetElementPtr: {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000627 // Compute the index
Reid Spencer4fd528f2007-03-06 22:23:15 +0000628 GenericValue Result = getConstantValue(Op0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000629 APInt Offset(DL->getPointerSizeInBits(), 0);
630 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
Misha Brukman835702a2005-04-21 22:36:52 +0000631
Reid Spencer87aa65f2007-03-06 03:04:04 +0000632 char* tmp = (char*) Result.PointerVal;
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000633 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattner9de0d142003-04-23 19:01:49 +0000634 return Result;
635 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000636 case Instruction::Trunc: {
637 GenericValue GV = getConstantValue(Op0);
638 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
639 GV.IntVal = GV.IntVal.trunc(BitWidth);
640 return GV;
641 }
642 case Instruction::ZExt: {
643 GenericValue GV = getConstantValue(Op0);
644 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
645 GV.IntVal = GV.IntVal.zext(BitWidth);
646 return GV;
647 }
648 case Instruction::SExt: {
649 GenericValue GV = getConstantValue(Op0);
650 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
651 GV.IntVal = GV.IntVal.sext(BitWidth);
652 return GV;
653 }
654 case Instruction::FPTrunc: {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000655 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000656 GenericValue GV = getConstantValue(Op0);
657 GV.FloatVal = float(GV.DoubleVal);
658 return GV;
659 }
660 case Instruction::FPExt:{
Dale Johannesena1336cf2007-09-17 18:44:13 +0000661 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000662 GenericValue GV = getConstantValue(Op0);
663 GV.DoubleVal = double(GV.FloatVal);
664 return GV;
665 }
666 case Instruction::UIToFP: {
667 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000668 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000669 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000670 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000671 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000672 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000673 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000674 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000675 false,
676 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000677 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000678 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000679 return GV;
680 }
681 case Instruction::SIToFP: {
682 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000683 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000684 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000685 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000686 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000687 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000688 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000689 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000690 true,
691 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000692 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000693 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000694 return GV;
695 }
696 case Instruction::FPToUI: // double->APInt conversion handles sign
697 case Instruction::FPToSI: {
698 GenericValue GV = getConstantValue(Op0);
699 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000700 if (Op0->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000701 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000702 else if (Op0->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000703 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000704 else if (Op0->getType()->isX86_FP80Ty()) {
Tim Northover29178a32013-01-22 09:46:31 +0000705 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000706 uint64_t v;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000707 bool ignored;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000708 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000709 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000710 APFloat::rmTowardZero, &ignored);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000711 GV.IntVal = v; // endian?
712 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000713 return GV;
714 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000715 case Instruction::PtrToInt: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000716 GenericValue GV = getConstantValue(Op0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000717 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000718 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000719 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000720 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000721 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000722 return GV;
723 }
724 case Instruction::IntToPtr: {
725 GenericValue GV = getConstantValue(Op0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000726 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000727 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000728 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
729 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000730 return GV;
731 }
732 case Instruction::BitCast: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000733 GenericValue GV = getConstantValue(Op0);
Chris Lattner229907c2011-07-18 04:54:35 +0000734 Type* DestTy = CE->getType();
Reid Spencer4fd528f2007-03-06 22:23:15 +0000735 switch (Op0->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000736 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000737 case Type::IntegerTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000738 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnerfdd87902009-10-05 05:54:46 +0000739 if (DestTy->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000740 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000741 else if (DestTy->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000742 GV.DoubleVal = GV.IntVal.bitsToDouble();
743 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000744 case Type::FloatTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000745 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000746 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000747 break;
748 case Type::DoubleTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000749 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000750 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000751 break;
752 case Type::PointerTyID:
Duncan Sands19d0b472010-02-16 11:11:14 +0000753 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000754 break; // getConstantValue(Op0) above already converted it
755 }
756 return GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000757 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000758 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +0000759 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000760 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +0000761 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000762 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +0000763 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000764 case Instruction::UDiv:
765 case Instruction::SDiv:
766 case Instruction::URem:
767 case Instruction::SRem:
768 case Instruction::And:
769 case Instruction::Or:
770 case Instruction::Xor: {
771 GenericValue LHS = getConstantValue(Op0);
772 GenericValue RHS = getConstantValue(CE->getOperand(1));
773 GenericValue GV;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000774 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000775 default: llvm_unreachable("Bad add type!");
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000776 case Type::IntegerTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000777 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000778 default: llvm_unreachable("Invalid integer opcode");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000779 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
780 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
781 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
782 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
783 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
784 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
785 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
786 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
787 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
788 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
789 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000790 break;
791 case Type::FloatTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000792 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000793 default: llvm_unreachable("Invalid float opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000794 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000795 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000796 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000797 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000798 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000799 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000800 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000801 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000802 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000803 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000804 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000805 break;
806 case Type::DoubleTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000807 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000808 default: llvm_unreachable("Invalid double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000809 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000810 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000811 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000812 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000813 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000814 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000815 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000816 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000817 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000818 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000819 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000820 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000821 case Type::X86_FP80TyID:
822 case Type::PPC_FP128TyID:
823 case Type::FP128TyID: {
Tim Northover29178a32013-01-22 09:46:31 +0000824 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
825 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000826 switch (CE->getOpcode()) {
Daniel Dunbare4f47432010-11-13 00:55:42 +0000827 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000828 case Instruction::FAdd:
Tim Northover29178a32013-01-22 09:46:31 +0000829 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000830 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000831 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000832 case Instruction::FSub:
Tim Northover29178a32013-01-22 09:46:31 +0000833 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
834 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000835 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000836 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000837 case Instruction::FMul:
Tim Northover29178a32013-01-22 09:46:31 +0000838 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
839 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000840 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000841 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000842 case Instruction::FDiv:
Tim Northover29178a32013-01-22 09:46:31 +0000843 apfLHS.divide(APFloat(Sem, RHS.IntVal),
844 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000845 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000846 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000847 case Instruction::FRem:
Tim Northover29178a32013-01-22 09:46:31 +0000848 apfLHS.mod(APFloat(Sem, RHS.IntVal),
849 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000850 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000851 break;
852 }
853 }
854 break;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000855 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000856 return GV;
857 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000858 default:
859 break;
860 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000861
862 SmallString<256> Msg;
863 raw_svector_ostream OS(Msg);
864 OS << "ConstantExpr not handled: " << *CE;
865 report_fatal_error(OS.str());
Chris Lattner68cbcc32003-05-14 17:51:49 +0000866 }
Misha Brukman835702a2005-04-21 22:36:52 +0000867
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000868 // Otherwise, we have a simple constant.
Reid Spencer4fd528f2007-03-06 22:23:15 +0000869 GenericValue Result;
Chris Lattner6b727592004-06-17 18:19:28 +0000870 switch (C->getType()->getTypeID()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000871 case Type::FloatTyID:
872 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000873 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000874 case Type::DoubleTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000875 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer87aa65f2007-03-06 03:04:04 +0000876 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000877 case Type::X86_FP80TyID:
878 case Type::FP128TyID:
879 case Type::PPC_FP128TyID:
Dale Johannesen54306fe2008-10-09 18:53:47 +0000880 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000881 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000882 case Type::IntegerTyID:
883 Result.IntVal = cast<ConstantInt>(C)->getValue();
884 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000885 case Type::PointerTyID:
Reid Spencer6a0fd732004-07-18 00:41:27 +0000886 if (isa<ConstantPointerNull>(C))
Craig Topper2617dcc2014-04-15 06:32:26 +0000887 Result.PointerVal = nullptr;
Reid Spencer6a0fd732004-07-18 00:41:27 +0000888 else if (const Function *F = dyn_cast<Function>(C))
889 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000890 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer6a0fd732004-07-18 00:41:27 +0000891 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
892 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000893 llvm_unreachable("Unknown constant pointer type!");
Chris Lattner996fe012002-12-24 00:01:05 +0000894 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000895 case Type::VectorTyID: {
896 unsigned elemNum;
897 Type* ElemTy;
898 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
899 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
900 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
901
902 if (CDV) {
903 elemNum = CDV->getNumElements();
904 ElemTy = CDV->getElementType();
905 } else if (CV || CAZ) {
906 VectorType* VTy = dyn_cast<VectorType>(C->getType());
907 elemNum = VTy->getNumElements();
908 ElemTy = VTy->getElementType();
909 } else {
910 llvm_unreachable("Unknown constant vector type!");
911 }
912
913 Result.AggregateVal.resize(elemNum);
914 // Check if vector holds floats.
915 if(ElemTy->isFloatTy()) {
916 if (CAZ) {
917 GenericValue floatZero;
918 floatZero.FloatVal = 0.f;
919 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
920 floatZero);
921 break;
922 }
923 if(CV) {
924 for (unsigned i = 0; i < elemNum; ++i)
925 if (!isa<UndefValue>(CV->getOperand(i)))
926 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
927 CV->getOperand(i))->getValueAPF().convertToFloat();
928 break;
929 }
930 if(CDV)
931 for (unsigned i = 0; i < elemNum; ++i)
932 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
933
934 break;
935 }
936 // Check if vector holds doubles.
937 if (ElemTy->isDoubleTy()) {
938 if (CAZ) {
939 GenericValue doubleZero;
940 doubleZero.DoubleVal = 0.0;
941 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
942 doubleZero);
943 break;
944 }
945 if(CV) {
946 for (unsigned i = 0; i < elemNum; ++i)
947 if (!isa<UndefValue>(CV->getOperand(i)))
948 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
949 CV->getOperand(i))->getValueAPF().convertToDouble();
950 break;
951 }
952 if(CDV)
953 for (unsigned i = 0; i < elemNum; ++i)
954 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
955
956 break;
957 }
958 // Check if vector holds integers.
959 if (ElemTy->isIntegerTy()) {
960 if (CAZ) {
961 GenericValue intZero;
962 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
963 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
964 intZero);
965 break;
966 }
967 if(CV) {
968 for (unsigned i = 0; i < elemNum; ++i)
969 if (!isa<UndefValue>(CV->getOperand(i)))
970 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
971 CV->getOperand(i))->getValue();
972 else {
973 Result.AggregateVal[i].IntVal =
974 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
975 }
976 break;
977 }
978 if(CDV)
979 for (unsigned i = 0; i < elemNum; ++i)
980 Result.AggregateVal[i].IntVal = APInt(
981 CDV->getElementType()->getPrimitiveSizeInBits(),
982 CDV->getElementAsInteger(i));
983
984 break;
985 }
986 llvm_unreachable("Unknown constant pointer type!");
987 }
988 break;
989
Chris Lattner996fe012002-12-24 00:01:05 +0000990 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000991 SmallString<256> Msg;
992 raw_svector_ostream OS(Msg);
993 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
994 report_fatal_error(OS.str());
Chris Lattner996fe012002-12-24 00:01:05 +0000995 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000996
Chris Lattner996fe012002-12-24 00:01:05 +0000997 return Result;
998}
999
Duncan Sands1202d1b2007-12-14 19:38:31 +00001000/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1001/// with the integer held in IntVal.
1002static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1003 unsigned StoreBytes) {
1004 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divackyad06cee2012-09-05 22:26:57 +00001005 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands1202d1b2007-12-14 19:38:31 +00001006
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001007 if (sys::IsLittleEndianHost) {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001008 // Little-endian host - the source is ordered from LSB to MSB. Order the
1009 // destination from LSB to MSB: Do a straight copy.
1010 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001011 } else {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001012 // Big-endian host - the source is an array of 64 bit words ordered from
1013 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1014 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1015 while (StoreBytes > sizeof(uint64_t)) {
1016 StoreBytes -= sizeof(uint64_t);
1017 // May not be aligned so use memcpy.
1018 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1019 Src += sizeof(uint64_t);
1020 }
1021
1022 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1023 }
1024}
1025
Evan Cheng09053e62008-11-04 06:10:31 +00001026void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattner229907c2011-07-18 04:54:35 +00001027 GenericValue *Ptr, Type *Ty) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001028 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001029
Reid Spencer87aa65f2007-03-06 03:04:04 +00001030 switch (Ty->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001031 default:
1032 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1033 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001034 case Type::IntegerTyID:
1035 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001036 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001037 case Type::FloatTyID:
1038 *((float*)Ptr) = Val.FloatVal;
1039 break;
1040 case Type::DoubleTyID:
1041 *((double*)Ptr) = Val.DoubleVal;
1042 break;
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001043 case Type::X86_FP80TyID:
1044 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1045 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001046 case Type::PointerTyID:
1047 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1048 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth93da3c82011-04-28 08:37:18 +00001049 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001050
Reid Spencer87aa65f2007-03-06 03:04:04 +00001051 *((PointerTy*)Ptr) = Val.PointerVal;
1052 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001053 case Type::VectorTyID:
1054 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1055 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1056 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1057 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1058 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1059 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1060 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1061 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1062 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1063 }
1064 }
1065 break;
Chris Lattner996fe012002-12-24 00:01:05 +00001066 }
Duncan Sands1202d1b2007-12-14 19:38:31 +00001067
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001068 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
Duncan Sands1202d1b2007-12-14 19:38:31 +00001069 // Host and target are different endian - reverse the stored bytes.
1070 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1071}
1072
1073/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1074/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1075static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1076 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greene82b63572013-01-14 21:04:45 +00001077 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1078 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands1202d1b2007-12-14 19:38:31 +00001079
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001080 if (sys::IsLittleEndianHost)
Duncan Sands1202d1b2007-12-14 19:38:31 +00001081 // Little-endian host - the destination must be ordered from LSB to MSB.
1082 // The source is ordered from LSB to MSB: Do a straight copy.
1083 memcpy(Dst, Src, LoadBytes);
1084 else {
1085 // Big-endian - the destination is an array of 64 bit words ordered from
1086 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1087 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1088 // a word.
1089 while (LoadBytes > sizeof(uint64_t)) {
1090 LoadBytes -= sizeof(uint64_t);
1091 // May not be aligned so use memcpy.
1092 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1093 Dst += sizeof(uint64_t);
1094 }
1095
1096 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1097 }
Chris Lattner996fe012002-12-24 00:01:05 +00001098}
1099
Misha Brukman857c21b2003-10-10 17:45:12 +00001100/// FIXME: document
1101///
Duncan Sands1202d1b2007-12-14 19:38:31 +00001102void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandscd4a6be2008-03-10 16:38:37 +00001103 GenericValue *Ptr,
Chris Lattner229907c2011-07-18 04:54:35 +00001104 Type *Ty) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001105 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands5c65cb42007-12-10 17:43:13 +00001106
Duncan Sands1202d1b2007-12-14 19:38:31 +00001107 switch (Ty->getTypeID()) {
1108 case Type::IntegerTyID:
1109 // An APInt with all words initially zero.
1110 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1111 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1112 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001113 case Type::FloatTyID:
1114 Result.FloatVal = *((float*)Ptr);
1115 break;
1116 case Type::DoubleTyID:
Duncan Sands1202d1b2007-12-14 19:38:31 +00001117 Result.DoubleVal = *((double*)Ptr);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001118 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001119 case Type::PointerTyID:
Reid Spencer87aa65f2007-03-06 03:04:04 +00001120 Result.PointerVal = *((PointerTy*)Ptr);
1121 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +00001122 case Type::X86_FP80TyID: {
1123 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands26d65392007-12-15 17:37:40 +00001124 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001125 uint64_t y[2];
1126 memcpy(y, Ptr, 10);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00001127 Result.IntVal = APInt(80, y);
Dale Johannesena1336cf2007-09-17 18:44:13 +00001128 break;
1129 }
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001130 case Type::VectorTyID: {
1131 const VectorType *VT = cast<VectorType>(Ty);
1132 const Type *ElemT = VT->getElementType();
1133 const unsigned numElems = VT->getNumElements();
1134 if (ElemT->isFloatTy()) {
1135 Result.AggregateVal.resize(numElems);
1136 for (unsigned i = 0; i < numElems; ++i)
1137 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1138 }
1139 if (ElemT->isDoubleTy()) {
1140 Result.AggregateVal.resize(numElems);
1141 for (unsigned i = 0; i < numElems; ++i)
1142 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1143 }
1144 if (ElemT->isIntegerTy()) {
1145 GenericValue intZero;
1146 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1147 intZero.IntVal = APInt(elemBitWidth, 0);
1148 Result.AggregateVal.resize(numElems, intZero);
1149 for (unsigned i = 0; i < numElems; ++i)
1150 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1151 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1152 }
1153 break;
1154 }
Reid Spencer87aa65f2007-03-06 03:04:04 +00001155 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001156 SmallString<256> Msg;
1157 raw_svector_ostream OS(Msg);
1158 OS << "Cannot load value of type " << *Ty << "!";
1159 report_fatal_error(OS.str());
Chris Lattner7f389e82003-05-08 16:52:16 +00001160 }
Chris Lattner7f389e82003-05-08 16:52:16 +00001161}
1162
Chris Lattner996fe012002-12-24 00:01:05 +00001163void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene0967d2d2010-01-05 01:27:39 +00001164 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesenb086d382008-08-07 01:30:15 +00001165 DEBUG(Init->dump());
Chris Lattner00245f42012-01-24 13:41:11 +00001166 if (isa<UndefValue>(Init))
Chris Lattner61753bf2004-10-16 18:19:26 +00001167 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001168
1169 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino69d62132006-01-20 18:18:40 +00001170 unsigned ElementSize =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001171 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino69d62132006-01-20 18:18:40 +00001172 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1173 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1174 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001175 }
1176
1177 if (isa<ConstantAggregateZero>(Init)) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001178 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
Chris Lattner1dd86b12008-02-15 00:57:28 +00001179 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001180 }
1181
1182 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001183 unsigned ElementSize =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001184 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001185 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1186 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1187 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001188 }
1189
1190 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001191 const StructLayout *SL =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001192 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001193 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1194 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1195 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001196 }
1197
1198 if (const ConstantDataSequential *CDS =
1199 dyn_cast<ConstantDataSequential>(Init)) {
1200 // CDS is already laid out in host memory order.
1201 StringRef Data = CDS->getRawDataValues();
1202 memcpy(Addr, Data.data(), Data.size());
1203 return;
1204 }
1205
1206 if (Init->getType()->isFirstClassType()) {
Chris Lattner996fe012002-12-24 00:01:05 +00001207 GenericValue Val = getConstantValue(Init);
1208 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1209 return;
1210 }
1211
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001212 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinfbcc6632009-07-14 16:55:14 +00001213 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattner996fe012002-12-24 00:01:05 +00001214}
1215
Chris Lattner996fe012002-12-24 00:01:05 +00001216/// EmitGlobals - Emit all of the global variables to memory, storing their
1217/// addresses into GlobalAddress. This must make sure to copy the contents of
1218/// their initializers into the memory.
Chris Lattner996fe012002-12-24 00:01:05 +00001219void ExecutionEngine::emitGlobals() {
Chris Lattner996fe012002-12-24 00:01:05 +00001220 // Loop over all of the global variables in the program, allocating the memory
Chris Lattner0621cae2006-08-16 01:24:12 +00001221 // to hold them. If there is more than one module, do a prepass over globals
1222 // to figure out how the different modules should link together.
Chris Lattner229907c2011-07-18 04:54:35 +00001223 std::map<std::pair<std::string, Type*>,
Chris Lattner0621cae2006-08-16 01:24:12 +00001224 const GlobalValue*> LinkedGlobalsMap;
Misha Brukman835702a2005-04-21 22:36:52 +00001225
Chris Lattner0621cae2006-08-16 01:24:12 +00001226 if (Modules.size() != 1) {
1227 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001228 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001229 for (const auto &GV : M.globals()) {
1230 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1231 GV.hasAppendingLinkage() || !GV.hasName())
Chris Lattner0621cae2006-08-16 01:24:12 +00001232 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001233
1234 const GlobalValue *&GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001235 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
Chris Lattner0621cae2006-08-16 01:24:12 +00001236
1237 // If this is the first time we've seen this global, it is the canonical
1238 // version.
1239 if (!GVEntry) {
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001240 GVEntry = &GV;
Chris Lattner0621cae2006-08-16 01:24:12 +00001241 continue;
1242 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001243
Chris Lattner0621cae2006-08-16 01:24:12 +00001244 // If the existing global is strong, never replace it.
Nico Rieck7157bb72014-01-14 15:22:47 +00001245 if (GVEntry->hasExternalLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +00001246 continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001247
Chris Lattner0621cae2006-08-16 01:24:12 +00001248 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesence4396b2008-05-14 20:12:51 +00001249 // symbol. FIXME is this right for common?
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001250 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1251 GVEntry = &GV;
Chris Lattner9de0d142003-04-23 19:01:49 +00001252 }
Chris Lattner996fe012002-12-24 00:01:05 +00001253 }
Chris Lattner0621cae2006-08-16 01:24:12 +00001254 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001255
Chris Lattner0621cae2006-08-16 01:24:12 +00001256 std::vector<const GlobalValue*> NonCanonicalGlobals;
1257 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001258 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001259 for (const auto &GV : M.globals()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001260 // In the multi-module case, see what this global maps to.
1261 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001262 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001263 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001264 // If something else is the canonical global, ignore this one.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001265 if (GVEntry != &GV) {
1266 NonCanonicalGlobals.push_back(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001267 continue;
1268 }
1269 }
1270 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001271
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001272 if (!GV.isDeclaration()) {
1273 addGlobalMapping(&GV, getMemoryForGV(&GV));
Chris Lattner0621cae2006-08-16 01:24:12 +00001274 } else {
1275 // External variable reference. Try to use the dynamic loader to
1276 // get a pointer to it.
1277 if (void *SymAddr =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001278 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1279 addGlobalMapping(&GV, SymAddr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001280 else {
Chris Lattner2104b8d2010-04-07 22:58:41 +00001281 report_fatal_error("Could not resolve external global address: "
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001282 +GV.getName());
Chris Lattner0621cae2006-08-16 01:24:12 +00001283 }
1284 }
1285 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001286
Chris Lattner0621cae2006-08-16 01:24:12 +00001287 // If there are multiple modules, map the non-canonical globals to their
1288 // canonical location.
1289 if (!NonCanonicalGlobals.empty()) {
1290 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1291 const GlobalValue *GV = NonCanonicalGlobals[i];
1292 const GlobalValue *CGV =
1293 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1294 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1295 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesa67f06b2008-10-14 10:04:52 +00001296 addGlobalMapping(GV, Ptr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001297 }
1298 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001299
1300 // Now that all of the globals are set up in memory, loop through them all
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001301 // and initialize their contents.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001302 for (const auto &GV : M.globals()) {
1303 if (!GV.isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001304 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001305 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001306 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1307 if (GVEntry != &GV) // Not the canonical variable.
Chris Lattner0621cae2006-08-16 01:24:12 +00001308 continue;
1309 }
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001310 EmitGlobalVariable(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001311 }
1312 }
1313 }
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001314}
1315
1316// EmitGlobalVariable - This method emits the specified global variable to the
1317// address specified in GlobalAddresses, or allocates new memory if it's not
1318// already in the map.
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +00001319void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner748e8572003-12-31 20:21:04 +00001320 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattnerdc631732004-02-08 19:33:23 +00001321
Craig Topper2617dcc2014-04-15 06:32:26 +00001322 if (!GA) {
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001323 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001324 GA = getMemoryForGV(GV);
Andrew Kaylor3b442372013-11-15 17:52:54 +00001325
1326 // If we failed to allocate memory for this global, return.
Craig Topper2617dcc2014-04-15 06:32:26 +00001327 if (!GA) return;
Andrew Kaylor3b442372013-11-15 17:52:54 +00001328
Chris Lattner748e8572003-12-31 20:21:04 +00001329 addGlobalMapping(GV, GA);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001330 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001331
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001332 // Don't initialize if it's thread local, let the client do it.
1333 if (!GV->isThreadLocal())
1334 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001335
Chris Lattner229907c2011-07-18 04:54:35 +00001336 Type *ElTy = GV->getType()->getElementType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001337 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
Chris Lattnerdf1f1522005-01-08 20:13:19 +00001338 NumInitBytes += (unsigned)GVSize;
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001339 ++NumGlobals;
Chris Lattner996fe012002-12-24 00:01:05 +00001340}