blob: b0e985d6dd54252a82c55ed38eb1293222ac5253 [file] [log] [blame]
Misha Brukman4afac182003-10-10 17:45:12 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanedf128a2005-04-21 22:36:52 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00009//
Chris Lattnerbd199fb2002-12-24 00:01:05 +000010// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000015#include "llvm/ExecutionEngine/ExecutionEngine.h"
Daniel Dunbar48dd8752010-11-13 02:48:57 +000016#include "llvm/ADT/SmallString.h"
Chris Lattner9f3ff922009-08-23 22:49:13 +000017#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ExecutionEngine/GenericValue.h"
Stephen Hines36b56882014-04-23 16:57:46 -070019#include "llvm/ExecutionEngine/JITMemoryManager.h"
20#include "llvm/ExecutionEngine/ObjectCache.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/Operator.h"
Stephen Hines36b56882014-04-23 16:57:46 -070026#include "llvm/IR/ValueHandle.h"
Stephen Hinesdce4a402014-05-29 02:49:00 -070027#include "llvm/Object/ObjectFile.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000029#include "llvm/Support/DynamicLibrary.h"
Torok Edwin31e24662009-07-07 17:32:34 +000030#include "llvm/Support/ErrorHandling.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000031#include "llvm/Support/Host.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000032#include "llvm/Support/MutexGuard.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000033#include "llvm/Support/TargetRegistry.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000034#include "llvm/Support/raw_ostream.h"
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000035#include "llvm/Target/TargetMachine.h"
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000036#include <cmath>
37#include <cstring>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000038using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000039
Stephen Hinesdce4a402014-05-29 02:49:00 -070040#define DEBUG_TYPE "jit"
41
Chris Lattner36343732006-12-19 22:43:32 +000042STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
43STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000044
Juergen Ributzka35436252013-11-19 00:57:56 +000045// Pin the vtable to this file.
46void ObjectCache::anchor() {}
47void ObjectBuffer::anchor() {}
48void ObjectBufferStream::anchor() {}
49
Jeffrey Yasskin46882612010-02-05 16:19:36 +000050ExecutionEngine *(*ExecutionEngine::JITCtor)(
51 Module *M,
52 std::string *ErrorStr,
53 JITMemoryManager *JMM,
Jeffrey Yasskin46882612010-02-05 16:19:36 +000054 bool GVsWithCode,
Stephen Hinesdce4a402014-05-29 02:49:00 -070055 TargetMachine *TM) = nullptr;
Daniel Dunbar6d135972010-11-17 16:06:37 +000056ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
57 Module *M,
58 std::string *ErrorStr,
Filip Pizlo13a3cf12013-05-14 19:29:00 +000059 RTDyldMemoryManager *MCJMM,
Daniel Dunbar6d135972010-11-17 16:06:37 +000060 bool GVsWithCode,
Stephen Hinesdce4a402014-05-29 02:49:00 -070061 TargetMachine *TM) = nullptr;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000062ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Stephen Hinesdce4a402014-05-29 02:49:00 -070063 std::string *ErrorStr) =nullptr;
Chris Lattner2fe4bb02006-03-22 06:07:50 +000064
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000065ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +000066 : EEState(*this),
Stephen Hinesdce4a402014-05-29 02:49:00 -070067 LazyFunctionCreator(nullptr) {
Jeffrey Yasskindc857242009-10-27 20:30:28 +000068 CompilingLazily = false;
Evan Cheng446531e2008-09-24 16:25:55 +000069 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000070 SymbolSearchingDisabled = false;
Stephen Hinesdce4a402014-05-29 02:49:00 -070071
72 // IR module verification is enabled by default in debug builds, and disabled
73 // by default in release builds.
74#ifndef NDEBUG
75 VerifyModules = true;
76#else
77 VerifyModules = false;
78#endif
79
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000080 Modules.push_back(M);
81 assert(M && "Module is null?");
Misha Brukman19684162003-10-16 21:18:05 +000082}
83
Brian Gaeke8e539482003-09-04 22:57:27 +000084ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000085 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000086 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
87 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000088}
89
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000090namespace {
Daniel Dunbar48dd8752010-11-13 02:48:57 +000091/// \brief Helper class which uses a value handler to automatically deletes the
92/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000093class GVMemoryBlock : public CallbackVH {
94 GVMemoryBlock(const GlobalVariable *GV)
95 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
96
97public:
Daniel Dunbar48dd8752010-11-13 02:48:57 +000098 /// \brief Returns the address the GlobalVariable should be written into. The
99 /// GVMemoryBlock object prefixes that.
Micah Villmow3574eca2012-10-08 16:38:25 +0000100 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000101 Type *ElTy = GV->getType()->getElementType();
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000102 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
103 void *RawMemory = ::operator new(
Micah Villmow3574eca2012-10-08 16:38:25 +0000104 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000105 TD.getPreferredAlignment(GV))
106 + GVSize);
107 new(RawMemory) GVMemoryBlock(GV);
108 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
109 }
110
Stephen Hines36b56882014-04-23 16:57:46 -0700111 void deleted() override {
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000112 // We allocated with operator new and with some extra memory hanging off the
113 // end, so don't just delete this. I'm not sure if this is actually
114 // required.
115 this->~GVMemoryBlock();
116 ::operator delete(this);
117 }
118};
119} // anonymous namespace
120
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000121char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000122 return GVMemoryBlock::Create(GV, *getDataLayout());
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000123}
124
Stephen Hinesdce4a402014-05-29 02:49:00 -0700125void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
126 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
127}
128
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000129bool ExecutionEngine::removeModule(Module *M) {
Craig Topper6227d5c2013-07-04 01:31:24 +0000130 for(SmallVectorImpl<Module *>::iterator I = Modules.begin(),
Devang Patel73d0e212007-10-15 19:56:32 +0000131 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000132 Module *Found = *I;
133 if (Found == M) {
Devang Patel73d0e212007-10-15 19:56:32 +0000134 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000135 clearGlobalMappingsFromModule(M);
136 return true;
Devang Patel73d0e212007-10-15 19:56:32 +0000137 }
138 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000139 return false;
Nate Begeman60789e42009-01-23 19:27:28 +0000140}
141
Chris Lattnerfe854032006-08-16 01:24:12 +0000142Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
143 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000144 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +0000145 return F;
146 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700147 return nullptr;
Chris Lattnerfe854032006-08-16 01:24:12 +0000148}
149
150
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700151void *ExecutionEngineState::RemoveMapping(const GlobalValue *ToUnmap) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000152 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000153 void *OldVal;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000154
155 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
156 // GlobalAddressMap.
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000157 if (I == GlobalAddressMap.end())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700158 OldVal = nullptr;
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000159 else {
160 OldVal = I->second;
161 GlobalAddressMap.erase(I);
162 }
163
164 GlobalAddressReverseMap.erase(OldVal);
165 return OldVal;
166}
167
Chris Lattnere7fd5532006-05-08 22:00:52 +0000168void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
169 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000170
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000171 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000172 << "\' to [" << Addr << "]\n";);
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700173 void *&CurVal = EEState.getGlobalAddressMap()[GV];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700174 assert((!CurVal || !Addr) && "GlobalMapping already established!");
Chris Lattnere7fd5532006-05-08 22:00:52 +0000175 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000176
177 // If we are using the reverse mapping, add it too.
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700178 if (!EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000179 AssertingVH<const GlobalValue> &V =
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700180 EEState.getGlobalAddressReverseMap()[Addr];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700181 assert((!V || !GV) && "GlobalMapping already established!");
Chris Lattnere7fd5532006-05-08 22:00:52 +0000182 V = GV;
183 }
184}
185
Chris Lattnere7fd5532006-05-08 22:00:52 +0000186void ExecutionEngine::clearAllGlobalMappings() {
187 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000188
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700189 EEState.getGlobalAddressMap().clear();
190 EEState.getGlobalAddressReverseMap().clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000191}
192
Nate Begemanf049e072008-05-21 16:34:48 +0000193void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
194 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000195
196 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700197 EEState.RemoveMapping(FI);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000198 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
199 GI != GE; ++GI)
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700200 EEState.RemoveMapping(GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000201}
202
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000203void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000204 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000205
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000206 ExecutionEngineState::GlobalAddressMapTy &Map =
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700207 EEState.getGlobalAddressMap();
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000208
Chris Lattnere7fd5532006-05-08 22:00:52 +0000209 // Deleting from the mapping?
Stephen Hinesdce4a402014-05-29 02:49:00 -0700210 if (!Addr)
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700211 return EEState.RemoveMapping(GV);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000212
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000213 void *&CurVal = Map[GV];
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000214 void *OldVal = CurVal;
215
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700216 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
217 EEState.getGlobalAddressReverseMap().erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000218 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000219
220 // If we are using the reverse mapping, add it too.
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700221 if (!EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000222 AssertingVH<const GlobalValue> &V =
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700223 EEState.getGlobalAddressReverseMap()[Addr];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700224 assert((!V || !GV) && "GlobalMapping already established!");
Chris Lattnere7fd5532006-05-08 22:00:52 +0000225 V = GV;
226 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000227 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000228}
229
Chris Lattnere7fd5532006-05-08 22:00:52 +0000230void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
231 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000232
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000233 ExecutionEngineState::GlobalAddressMapTy::iterator I =
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700234 EEState.getGlobalAddressMap().find(GV);
235 return I != EEState.getGlobalAddressMap().end() ? I->second : nullptr;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000236}
237
Chris Lattner55d86482003-12-31 20:21:04 +0000238const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000239 MutexGuard locked(lock);
240
Chris Lattner55d86482003-12-31 20:21:04 +0000241 // If we haven't computed the reverse mapping yet, do so first.
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700242 if (EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000243 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700244 I = EEState.getGlobalAddressMap().begin(),
245 E = EEState.getGlobalAddressMap().end(); I != E; ++I)
246 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
Daniel Dunbarab19da42010-11-13 00:55:42 +0000247 I->second, I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000248 }
249
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000250 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700251 EEState.getGlobalAddressReverseMap().find(Addr);
252 return I != EEState.getGlobalAddressReverseMap().end() ? I->second : nullptr;
Chris Lattner55d86482003-12-31 20:21:04 +0000253}
Chris Lattner87f03102003-12-26 06:50:30 +0000254
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000255namespace {
256class ArgvArray {
257 char *Array;
258 std::vector<char*> Values;
259public:
Stephen Hinesdce4a402014-05-29 02:49:00 -0700260 ArgvArray() : Array(nullptr) {}
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000261 ~ArgvArray() { clear(); }
262 void clear() {
263 delete[] Array;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700264 Array = nullptr;
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000265 for (size_t I = 0, E = Values.size(); I != E; ++I) {
266 delete[] Values[I];
267 }
268 Values.clear();
269 }
270 /// Turn a vector of strings into a nice argv style array of pointers to null
271 /// terminated strings.
272 void *reset(LLVMContext &C, ExecutionEngine *EE,
273 const std::vector<std::string> &InputArgv);
274};
275} // anonymous namespace
276void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
277 const std::vector<std::string> &InputArgv) {
278 clear(); // Free the old contents.
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000279 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000280 Array = new char[(InputArgv.size()+1)*PtrSize];
Chris Lattner87f03102003-12-26 06:50:30 +0000281
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000282 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000283 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000284
285 for (unsigned i = 0; i != InputArgv.size(); ++i) {
286 unsigned Size = InputArgv[i].size()+1;
287 char *Dest = new char[Size];
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000288 Values.push_back(Dest);
David Greeneae7c59a2010-01-05 01:27:39 +0000289 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000290
Chris Lattner87f03102003-12-26 06:50:30 +0000291 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
292 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000293
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000294 // Endian safe: Array[i] = (PointerTy)Dest;
295 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000296 SBytePtr);
297 }
298
299 // Null terminate it
Stephen Hinesdce4a402014-05-29 02:49:00 -0700300 EE->StoreValueToMemory(PTOGV(nullptr),
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000301 (GenericValue*)(Array+InputArgv.size()*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000302 SBytePtr);
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000303 return Array;
Chris Lattner87f03102003-12-26 06:50:30 +0000304}
305
Chris Lattnerfbd39762009-09-23 01:46:04 +0000306void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
307 bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000308 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000309 GlobalVariable *GV = module->getNamedGlobal(Name);
Evan Cheng18314dc2008-09-30 15:51:21 +0000310
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000311 // If this global has internal linkage, or if it has a use, then it must be
312 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
313 // this is the case, don't execute any of the global ctors, __main will do
314 // it.
315 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
316
Nick Lewyckya040d472011-04-06 20:38:44 +0000317 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000318 // the init priority, which we ignore.
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000319 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
Stephen Hinesdce4a402014-05-29 02:49:00 -0700320 if (!InitList)
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000321 return;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000322 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000323 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
Stephen Hinesdce4a402014-05-29 02:49:00 -0700324 if (!CS) continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000325
326 Constant *FP = CS->getOperand(1);
327 if (FP->isNullValue())
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000328 continue; // Found a sentinal value, ignore.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000329
330 // Strip off constant expression casts.
331 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
332 if (CE->isCast())
333 FP = CE->getOperand(0);
334
335 // Execute the ctor/dtor function!
336 if (Function *F = dyn_cast<Function>(FP))
337 runFunction(F, std::vector<GenericValue>());
338
339 // FIXME: It is marginally lame that we just do nothing here if we see an
340 // entry we don't recognize. It might not be unreasonable for the verifier
341 // to not even allow this and just assert here.
342 }
Evan Cheng18314dc2008-09-30 15:51:21 +0000343}
344
Evan Cheng18314dc2008-09-30 15:51:21 +0000345void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
346 // Execute global ctors/dtors for each module in the program.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000347 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
348 runStaticConstructorsDestructors(Modules[i], isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000349}
350
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000351#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000352/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
353static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000354 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000355 for (unsigned i = 0; i < PtrSize; ++i)
356 if (*(i + (uint8_t*)Loc))
357 return false;
358 return true;
359}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000360#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000361
Chris Lattner87f03102003-12-26 06:50:30 +0000362int ExecutionEngine::runFunctionAsMain(Function *Fn,
363 const std::vector<std::string> &argv,
364 const char * const * envp) {
365 std::vector<GenericValue> GVArgs;
366 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000367 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000368
369 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000370 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000371 FunctionType *FTy = Fn->getFunctionType();
372 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000373
374 // Check the argument types.
375 if (NumArgs > 3)
376 report_fatal_error("Invalid number of arguments of main() supplied");
377 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
378 report_fatal_error("Invalid type for third argument of main() supplied");
379 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
380 report_fatal_error("Invalid type for second argument of main() supplied");
381 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
382 report_fatal_error("Invalid type for first argument of main() supplied");
383 if (!FTy->getReturnType()->isIntegerTy() &&
384 !FTy->getReturnType()->isVoidTy())
385 report_fatal_error("Invalid return type of main() supplied");
386
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000387 ArgvArray CArgv;
388 ArgvArray CEnv;
Chris Lattnerf24d0992004-08-16 01:05:35 +0000389 if (NumArgs) {
390 GVArgs.push_back(GVArgc); // Arg #0 = argc.
391 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000392 // Arg #1 = argv.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000393 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000394 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000395 "argv[0] was null after CreateArgv");
396 if (NumArgs > 2) {
397 std::vector<std::string> EnvVars;
398 for (unsigned i = 0; envp[i]; ++i)
399 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000400 // Arg #2 = envp.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000401 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000402 }
403 }
404 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000405
Reid Spencer8fb0f192007-03-06 03:04:04 +0000406 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000407}
408
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000409ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000410 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000411 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000412 CodeGenOpt::Level OptLevel,
413 bool GVsWithCode) {
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700414
415 EngineBuilder EB =
416 EngineBuilder(M)
417 .setEngineKind(ForceInterpreter ? EngineKind::Interpreter
418 : EngineKind::Either)
419 .setErrorStr(ErrorStr)
420 .setOptLevel(OptLevel)
421 .setAllocateGVsWithCode(GVsWithCode);
Owen Anderson8e1fc562012-03-23 17:40:56 +0000422
423 return EB.create();
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000424}
Brian Gaeke82d82772003-09-03 20:34:19 +0000425
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000426/// createJIT - This is the factory method for creating a JIT for the current
427/// machine, it does not fall back to the interpreter. This takes ownership
428/// of the module.
429ExecutionEngine *ExecutionEngine::createJIT(Module *M,
430 std::string *ErrorStr,
431 JITMemoryManager *JMM,
Dylan Noblesmithd95e67d2011-12-01 21:49:21 +0000432 CodeGenOpt::Level OL,
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000433 bool GVsWithCode,
Evan Cheng43966132011-07-19 06:37:02 +0000434 Reloc::Model RM,
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000435 CodeModel::Model CMM) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700436 if (!ExecutionEngine::JITCtor) {
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000437 if (ErrorStr)
438 *ErrorStr = "JIT has not been linked in.";
Stephen Hinesdce4a402014-05-29 02:49:00 -0700439 return nullptr;
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000440 }
441
442 // Use the defaults for extra parameters. Users can use EngineBuilder to
443 // set them.
Owen Anderson8e1fc562012-03-23 17:40:56 +0000444 EngineBuilder EB(M);
445 EB.setEngineKind(EngineKind::JIT);
446 EB.setErrorStr(ErrorStr);
447 EB.setRelocationModel(RM);
448 EB.setCodeModel(CMM);
449 EB.setAllocateGVsWithCode(GVsWithCode);
450 EB.setOptLevel(OL);
451 EB.setJITMemoryManager(JMM);
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000452
Peter Collingbourned40e1032011-12-07 23:58:57 +0000453 // TODO: permit custom TargetOptions here
Owen Anderson8e1fc562012-03-23 17:40:56 +0000454 TargetMachine *TM = EB.selectTarget();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700455 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return nullptr;
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000456
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000457 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000458}
459
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700460void EngineBuilder::InitEngine() {
461 WhichEngine = EngineKind::Either;
462 ErrorStr = nullptr;
463 OptLevel = CodeGenOpt::Default;
464 MCJMM = nullptr;
465 JMM = nullptr;
466 Options = TargetOptions();
467 AllocateGVsWithCode = false;
468 RelocModel = Reloc::Default;
469 CMModel = CodeModel::JITDefault;
470 UseMCJIT = false;
471
472// IR module verification is enabled by default in debug builds, and disabled
473// by default in release builds.
474#ifndef NDEBUG
475 VerifyModules = true;
476#else
477 VerifyModules = false;
478#endif
479}
480
Owen Anderson8e1fc562012-03-23 17:40:56 +0000481ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Stephen Hines36b56882014-04-23 16:57:46 -0700482 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
Benjamin Kramer0f554492012-04-08 14:53:14 +0000483
Nick Lewycky6456d862008-03-08 02:49:45 +0000484 // Make sure we can resolve symbols in the program as well. The zero arg
485 // to the function tells DynamicLibrary to load the program, not a library.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700486 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
487 return nullptr;
Nick Lewycky6456d862008-03-08 02:49:45 +0000488
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000489 assert(!(JMM && MCJMM));
490
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000491 // If the user specified a memory manager but didn't specify which engine to
492 // create, we assume they only want the JIT, and we fail if they only want
493 // the interpreter.
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000494 if (JMM || MCJMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000495 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000496 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000497 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000498 if (ErrorStr)
499 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Stephen Hinesdce4a402014-05-29 02:49:00 -0700500 return nullptr;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000501 }
502 }
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000503
504 if (MCJMM && ! UseMCJIT) {
505 if (ErrorStr)
506 *ErrorStr =
507 "Cannot create a legacy JIT with a runtime dyld memory "
508 "manager.";
Stephen Hinesdce4a402014-05-29 02:49:00 -0700509 return nullptr;
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000510 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000511
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000512 // Unless the interpreter was explicitly selected or the JIT is not linked,
513 // try making a JIT.
Benjamin Kramer0f554492012-04-08 14:53:14 +0000514 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000515 Triple TT(M->getTargetTriple());
Owen Anderson8e1fc562012-03-23 17:40:56 +0000516 if (!TM->getTarget().hasJIT()) {
517 errs() << "WARNING: This target JIT is not designed for the host"
518 << " you are running. If bad things happen, please choose"
519 << " a different -march switch.\n";
520 }
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000521
Stephen Hinesdce4a402014-05-29 02:49:00 -0700522 ExecutionEngine *EE = nullptr;
523 if (UseMCJIT && ExecutionEngine::MCJITCtor)
524 EE = ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM,
525 AllocateGVsWithCode, TheTM.release());
526 else if (ExecutionEngine::JITCtor)
527 EE = ExecutionEngine::JITCtor(M, ErrorStr, JMM,
528 AllocateGVsWithCode, TheTM.release());
529
530 if (EE) {
531 EE->setVerifyModules(VerifyModules);
532 return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000533 }
Reid Kleckner4b1511b2009-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 Lattnerfbd39762009-09-23 01:46:04 +0000538 if (WhichEngine & EngineKind::Interpreter) {
539 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000540 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000541 if (ErrorStr)
542 *ErrorStr = "Interpreter has not been linked in.";
Stephen Hinesdce4a402014-05-29 02:49:00 -0700543 return nullptr;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000544 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000545
Stephen Hinesdce4a402014-05-29 02:49:00 -0700546 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::JITCtor &&
547 !ExecutionEngine::MCJITCtor) {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000548 if (ErrorStr)
549 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000550 }
551
Stephen Hinesdce4a402014-05-29 02:49:00 -0700552 return nullptr;
Brian Gaeke82d82772003-09-03 20:34:19 +0000553}
554
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000555void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000556 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000557 return getPointerToFunction(F);
558
Reid Spenceree448632005-07-12 15:51:55 +0000559 MutexGuard locked(lock);
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700560 if (void *P = EEState.getGlobalAddressMap()[GV])
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000561 return P;
Jeff Cohen68835dd2006-02-07 05:11:57 +0000562
563 // Global variable might have been added since interpreter started.
564 if (GlobalVariable *GVar =
565 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
566 EmitGlobalVariable(GVar);
567 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000568 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000569
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700570 return EEState.getGlobalAddressMap()[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000571}
572
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000573/// \brief Converts a Constant* into a GenericValue, including handling of
574/// ConstantExpr values.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000575GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000576 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000577 if (isa<UndefValue>(C)) {
578 GenericValue Result;
579 switch (C->getType()->getTypeID()) {
Nadav Rotem953783e2013-04-01 15:53:30 +0000580 default:
581 break;
Jay Foad5b370122010-01-15 08:32:58 +0000582 case Type::IntegerTyID:
583 case Type::X86_FP80TyID:
584 case Type::FP128TyID:
585 case Type::PPC_FP128TyID:
586 // Although the value is undefined, we still have to construct an APInt
587 // with the correct bit width.
588 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
589 break;
Elena Demikhovsky3c5ce292013-09-12 10:48:23 +0000590 case Type::StructTyID: {
591 // if the whole struct is 'undef' just reserve memory for the value.
592 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
593 unsigned int elemNum = STy->getNumElements();
594 Result.AggregateVal.resize(elemNum);
595 for (unsigned int i = 0; i < elemNum; ++i) {
596 Type *ElemTy = STy->getElementType(i);
597 if (ElemTy->isIntegerTy())
598 Result.AggregateVal[i].IntVal =
599 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
600 else if (ElemTy->isAggregateType()) {
601 const Constant *ElemUndef = UndefValue::get(ElemTy);
602 Result.AggregateVal[i] = getConstantValue(ElemUndef);
603 }
604 }
605 }
606 }
607 break;
Nadav Rotem953783e2013-04-01 15:53:30 +0000608 case Type::VectorTyID:
609 // if the whole vector is 'undef' just reserve memory for the value.
610 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
611 const Type *ElemTy = VTy->getElementType();
612 unsigned int elemNum = VTy->getNumElements();
613 Result.AggregateVal.resize(elemNum);
614 if (ElemTy->isIntegerTy())
615 for (unsigned int i = 0; i < elemNum; ++i)
Elena Demikhovsky3c5ce292013-09-12 10:48:23 +0000616 Result.AggregateVal[i].IntVal =
Nadav Rotem953783e2013-04-01 15:53:30 +0000617 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foad5b370122010-01-15 08:32:58 +0000618 break;
619 }
620 return Result;
621 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000622
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000623 // Otherwise, if the value is a ConstantExpr...
Reid Spencer3da59db2006-11-27 01:05:10 +0000624 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000625 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000626 switch (CE->getOpcode()) {
627 case Instruction::GetElementPtr: {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000628 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000629 GenericValue Result = getConstantValue(Op0);
Stephen Hines36b56882014-04-23 16:57:46 -0700630 APInt Offset(DL->getPointerSizeInBits(), 0);
631 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000632
Reid Spencer8fb0f192007-03-06 03:04:04 +0000633 char* tmp = (char*) Result.PointerVal;
Nuno Lopes98281a22012-12-30 16:25:48 +0000634 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000635 return Result;
636 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000637 case Instruction::Trunc: {
638 GenericValue GV = getConstantValue(Op0);
639 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
640 GV.IntVal = GV.IntVal.trunc(BitWidth);
641 return GV;
642 }
643 case Instruction::ZExt: {
644 GenericValue GV = getConstantValue(Op0);
645 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
646 GV.IntVal = GV.IntVal.zext(BitWidth);
647 return GV;
648 }
649 case Instruction::SExt: {
650 GenericValue GV = getConstantValue(Op0);
651 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
652 GV.IntVal = GV.IntVal.sext(BitWidth);
653 return GV;
654 }
655 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000656 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000657 GenericValue GV = getConstantValue(Op0);
658 GV.FloatVal = float(GV.DoubleVal);
659 return GV;
660 }
661 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000662 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000663 GenericValue GV = getConstantValue(Op0);
664 GV.DoubleVal = double(GV.FloatVal);
665 return GV;
666 }
667 case Instruction::UIToFP: {
668 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000669 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000670 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000671 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000672 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000673 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000674 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000675 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000676 false,
677 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000678 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000679 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000680 return GV;
681 }
682 case Instruction::SIToFP: {
683 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000684 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000685 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000686 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000687 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000688 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000689 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000690 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000691 true,
692 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000693 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000694 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000695 return GV;
696 }
697 case Instruction::FPToUI: // double->APInt conversion handles sign
698 case Instruction::FPToSI: {
699 GenericValue GV = getConstantValue(Op0);
700 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000701 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000702 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000703 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000704 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000705 else if (Op0->getType()->isX86_FP80Ty()) {
Tim Northover0a29cb02013-01-22 09:46:31 +0000706 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000707 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000708 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000709 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000710 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000711 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000712 GV.IntVal = v; // endian?
713 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000714 return GV;
715 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000716 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000717 GenericValue GV = getConstantValue(Op0);
Stephen Hines36b56882014-04-23 16:57:46 -0700718 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000719 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencerbce30f12007-03-06 22:23:15 +0000720 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Stephen Hines36b56882014-04-23 16:57:46 -0700721 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000722 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencerbce30f12007-03-06 22:23:15 +0000723 return GV;
724 }
725 case Instruction::IntToPtr: {
726 GenericValue GV = getConstantValue(Op0);
Stephen Hines36b56882014-04-23 16:57:46 -0700727 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000728 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencerbce30f12007-03-06 22:23:15 +0000729 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
730 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000731 return GV;
732 }
733 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000734 GenericValue GV = getConstantValue(Op0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000735 Type* DestTy = CE->getType();
Reid Spencerbce30f12007-03-06 22:23:15 +0000736 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000737 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000738 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000739 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000740 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000741 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000742 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000743 GV.DoubleVal = GV.IntVal.bitsToDouble();
744 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000745 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000746 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000747 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000748 break;
749 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000750 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000751 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000752 break;
753 case Type::PointerTyID:
Duncan Sands1df98592010-02-16 11:11:14 +0000754 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000755 break; // getConstantValue(Op0) above already converted it
756 }
757 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000758 }
Chris Lattner9a231222003-05-14 17:51:49 +0000759 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000760 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000761 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000762 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000763 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000764 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000765 case Instruction::UDiv:
766 case Instruction::SDiv:
767 case Instruction::URem:
768 case Instruction::SRem:
769 case Instruction::And:
770 case Instruction::Or:
771 case Instruction::Xor: {
772 GenericValue LHS = getConstantValue(Op0);
773 GenericValue RHS = getConstantValue(CE->getOperand(1));
774 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000775 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000776 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000777 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000778 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000779 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000780 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
781 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
782 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
783 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
784 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
785 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
786 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
787 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
788 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
789 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
790 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000791 break;
792 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000793 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000794 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000795 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000796 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000797 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000798 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000799 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000800 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000801 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000802 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000803 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000804 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000805 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000806 break;
807 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000808 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000809 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000810 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000811 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000812 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000813 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000814 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000815 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000816 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000817 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000818 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000819 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000820 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000821 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000822 case Type::X86_FP80TyID:
823 case Type::PPC_FP128TyID:
824 case Type::FP128TyID: {
Tim Northover0a29cb02013-01-22 09:46:31 +0000825 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
826 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000827 switch (CE->getOpcode()) {
Daniel Dunbarab19da42010-11-13 00:55:42 +0000828 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000829 case Instruction::FAdd:
Tim Northover0a29cb02013-01-22 09:46:31 +0000830 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000831 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000832 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000833 case Instruction::FSub:
Tim Northover0a29cb02013-01-22 09:46:31 +0000834 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
835 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000836 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000837 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000838 case Instruction::FMul:
Tim Northover0a29cb02013-01-22 09:46:31 +0000839 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
840 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000841 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000842 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000843 case Instruction::FDiv:
Tim Northover0a29cb02013-01-22 09:46:31 +0000844 apfLHS.divide(APFloat(Sem, RHS.IntVal),
845 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000846 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000847 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000848 case Instruction::FRem:
Tim Northover0a29cb02013-01-22 09:46:31 +0000849 apfLHS.mod(APFloat(Sem, RHS.IntVal),
850 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000851 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000852 break;
853 }
854 }
855 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000856 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000857 return GV;
858 }
Chris Lattner9a231222003-05-14 17:51:49 +0000859 default:
860 break;
861 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000862
863 SmallString<256> Msg;
864 raw_svector_ostream OS(Msg);
865 OS << "ConstantExpr not handled: " << *CE;
866 report_fatal_error(OS.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000867 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000868
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000869 // Otherwise, we have a simple constant.
Reid Spencerbce30f12007-03-06 22:23:15 +0000870 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000871 switch (C->getType()->getTypeID()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000872 case Type::FloatTyID:
873 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000874 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000875 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000876 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000877 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000878 case Type::X86_FP80TyID:
879 case Type::FP128TyID:
880 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000881 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000882 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000883 case Type::IntegerTyID:
884 Result.IntVal = cast<ConstantInt>(C)->getValue();
885 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000886 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000887 if (isa<ConstantPointerNull>(C))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700888 Result.PointerVal = nullptr;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000889 else if (const Function *F = dyn_cast<Function>(C))
890 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000891 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000892 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000893 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
894 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
895 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000896 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000897 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000898 break;
Nadav Rotem953783e2013-04-01 15:53:30 +0000899 case Type::VectorTyID: {
900 unsigned elemNum;
901 Type* ElemTy;
902 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
903 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
904 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
905
906 if (CDV) {
907 elemNum = CDV->getNumElements();
908 ElemTy = CDV->getElementType();
909 } else if (CV || CAZ) {
910 VectorType* VTy = dyn_cast<VectorType>(C->getType());
911 elemNum = VTy->getNumElements();
912 ElemTy = VTy->getElementType();
913 } else {
914 llvm_unreachable("Unknown constant vector type!");
915 }
916
917 Result.AggregateVal.resize(elemNum);
918 // Check if vector holds floats.
919 if(ElemTy->isFloatTy()) {
920 if (CAZ) {
921 GenericValue floatZero;
922 floatZero.FloatVal = 0.f;
923 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
924 floatZero);
925 break;
926 }
927 if(CV) {
928 for (unsigned i = 0; i < elemNum; ++i)
929 if (!isa<UndefValue>(CV->getOperand(i)))
930 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
931 CV->getOperand(i))->getValueAPF().convertToFloat();
932 break;
933 }
934 if(CDV)
935 for (unsigned i = 0; i < elemNum; ++i)
936 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
937
938 break;
939 }
940 // Check if vector holds doubles.
941 if (ElemTy->isDoubleTy()) {
942 if (CAZ) {
943 GenericValue doubleZero;
944 doubleZero.DoubleVal = 0.0;
945 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
946 doubleZero);
947 break;
948 }
949 if(CV) {
950 for (unsigned i = 0; i < elemNum; ++i)
951 if (!isa<UndefValue>(CV->getOperand(i)))
952 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
953 CV->getOperand(i))->getValueAPF().convertToDouble();
954 break;
955 }
956 if(CDV)
957 for (unsigned i = 0; i < elemNum; ++i)
958 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
959
960 break;
961 }
962 // Check if vector holds integers.
963 if (ElemTy->isIntegerTy()) {
964 if (CAZ) {
965 GenericValue intZero;
966 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
967 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
968 intZero);
969 break;
970 }
971 if(CV) {
972 for (unsigned i = 0; i < elemNum; ++i)
973 if (!isa<UndefValue>(CV->getOperand(i)))
974 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
975 CV->getOperand(i))->getValue();
976 else {
977 Result.AggregateVal[i].IntVal =
978 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
979 }
980 break;
981 }
982 if(CDV)
983 for (unsigned i = 0; i < elemNum; ++i)
984 Result.AggregateVal[i].IntVal = APInt(
985 CDV->getElementType()->getPrimitiveSizeInBits(),
986 CDV->getElementAsInteger(i));
987
988 break;
989 }
990 llvm_unreachable("Unknown constant pointer type!");
991 }
992 break;
993
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000994 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000995 SmallString<256> Msg;
996 raw_svector_ostream OS(Msg);
997 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
998 report_fatal_error(OS.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000999 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001000
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001001 return Result;
1002}
1003
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001004/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1005/// with the integer held in IntVal.
1006static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1007 unsigned StoreBytes) {
1008 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divacky59324292012-09-05 22:26:57 +00001009 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001010
Rafael Espindola21a01d12013-04-15 14:44:24 +00001011 if (sys::IsLittleEndianHost) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001012 // Little-endian host - the source is ordered from LSB to MSB. Order the
1013 // destination from LSB to MSB: Do a straight copy.
1014 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001015 } else {
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001016 // Big-endian host - the source is an array of 64 bit words ordered from
1017 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1018 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1019 while (StoreBytes > sizeof(uint64_t)) {
1020 StoreBytes -= sizeof(uint64_t);
1021 // May not be aligned so use memcpy.
1022 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1023 Src += sizeof(uint64_t);
1024 }
1025
1026 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1027 }
1028}
1029
Evan Cheng89687e32008-11-04 06:10:31 +00001030void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001031 GenericValue *Ptr, Type *Ty) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001032 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001033
Reid Spencer8fb0f192007-03-06 03:04:04 +00001034 switch (Ty->getTypeID()) {
Nadav Rotem953783e2013-04-01 15:53:30 +00001035 default:
1036 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1037 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001038 case Type::IntegerTyID:
1039 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +00001040 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +00001041 case Type::FloatTyID:
1042 *((float*)Ptr) = Val.FloatVal;
1043 break;
1044 case Type::DoubleTyID:
1045 *((double*)Ptr) = Val.DoubleVal;
1046 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +00001047 case Type::X86_FP80TyID:
1048 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1049 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001050 case Type::PointerTyID:
1051 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1052 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth80d9e072011-04-28 08:37:18 +00001053 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001054
Reid Spencer8fb0f192007-03-06 03:04:04 +00001055 *((PointerTy*)Ptr) = Val.PointerVal;
1056 break;
Nadav Rotem953783e2013-04-01 15:53:30 +00001057 case Type::VectorTyID:
1058 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1059 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1060 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1061 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1062 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1063 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1064 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1065 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1066 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1067 }
1068 }
1069 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001070 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001071
Rafael Espindola21a01d12013-04-15 14:44:24 +00001072 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001073 // Host and target are different endian - reverse the stored bytes.
1074 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1075}
1076
1077/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1078/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1079static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1080 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greenec2680be2013-01-14 21:04:45 +00001081 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1082 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001083
Rafael Espindola21a01d12013-04-15 14:44:24 +00001084 if (sys::IsLittleEndianHost)
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001085 // Little-endian host - the destination must be ordered from LSB to MSB.
1086 // The source is ordered from LSB to MSB: Do a straight copy.
1087 memcpy(Dst, Src, LoadBytes);
1088 else {
1089 // Big-endian - the destination is an array of 64 bit words ordered from
1090 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1091 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1092 // a word.
1093 while (LoadBytes > sizeof(uint64_t)) {
1094 LoadBytes -= sizeof(uint64_t);
1095 // May not be aligned so use memcpy.
1096 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1097 Dst += sizeof(uint64_t);
1098 }
1099
1100 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1101 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001102}
1103
Misha Brukman4afac182003-10-10 17:45:12 +00001104/// FIXME: document
1105///
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001106void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +00001107 GenericValue *Ptr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001108 Type *Ty) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001109 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +00001110
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001111 switch (Ty->getTypeID()) {
1112 case Type::IntegerTyID:
1113 // An APInt with all words initially zero.
1114 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1115 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1116 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +00001117 case Type::FloatTyID:
1118 Result.FloatVal = *((float*)Ptr);
1119 break;
1120 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001121 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +00001122 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001123 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +00001124 Result.PointerVal = *((PointerTy*)Ptr);
1125 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +00001126 case Type::X86_FP80TyID: {
1127 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +00001128 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +00001129 uint64_t y[2];
1130 memcpy(y, Ptr, 10);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001131 Result.IntVal = APInt(80, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +00001132 break;
1133 }
Nadav Rotem953783e2013-04-01 15:53:30 +00001134 case Type::VectorTyID: {
1135 const VectorType *VT = cast<VectorType>(Ty);
1136 const Type *ElemT = VT->getElementType();
1137 const unsigned numElems = VT->getNumElements();
1138 if (ElemT->isFloatTy()) {
1139 Result.AggregateVal.resize(numElems);
1140 for (unsigned i = 0; i < numElems; ++i)
1141 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1142 }
1143 if (ElemT->isDoubleTy()) {
1144 Result.AggregateVal.resize(numElems);
1145 for (unsigned i = 0; i < numElems; ++i)
1146 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1147 }
1148 if (ElemT->isIntegerTy()) {
1149 GenericValue intZero;
1150 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1151 intZero.IntVal = APInt(elemBitWidth, 0);
1152 Result.AggregateVal.resize(numElems, intZero);
1153 for (unsigned i = 0; i < numElems; ++i)
1154 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1155 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1156 }
1157 break;
1158 }
Reid Spencer8fb0f192007-03-06 03:04:04 +00001159 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001160 SmallString<256> Msg;
1161 raw_svector_ostream OS(Msg);
1162 OS << "Cannot load value of type " << *Ty << "!";
1163 report_fatal_error(OS.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +00001164 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +00001165}
1166
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001167void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +00001168 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +00001169 DEBUG(Init->dump());
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001170 if (isa<UndefValue>(Init))
Chris Lattnerbd1d3822004-10-16 18:19:26 +00001171 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001172
1173 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +00001174 unsigned ElementSize =
Micah Villmow3574eca2012-10-08 16:38:25 +00001175 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +00001176 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1177 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1178 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001179 }
1180
1181 if (isa<ConstantAggregateZero>(Init)) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001182 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +00001183 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001184 }
1185
1186 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman638e3782008-05-20 03:20:09 +00001187 unsigned ElementSize =
Micah Villmow3574eca2012-10-08 16:38:25 +00001188 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +00001189 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1190 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1191 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001192 }
1193
1194 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman638e3782008-05-20 03:20:09 +00001195 const StructLayout *SL =
Micah Villmow3574eca2012-10-08 16:38:25 +00001196 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman638e3782008-05-20 03:20:09 +00001197 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1198 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1199 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001200 }
1201
1202 if (const ConstantDataSequential *CDS =
1203 dyn_cast<ConstantDataSequential>(Init)) {
1204 // CDS is already laid out in host memory order.
1205 StringRef Data = CDS->getRawDataValues();
1206 memcpy(Addr, Data.data(), Data.size());
1207 return;
1208 }
1209
1210 if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001211 GenericValue Val = getConstantValue(Init);
1212 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1213 return;
1214 }
1215
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001216 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinc23197a2009-07-14 16:55:14 +00001217 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001218}
1219
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001220/// EmitGlobals - Emit all of the global variables to memory, storing their
1221/// addresses into GlobalAddress. This must make sure to copy the contents of
1222/// their initializers into the memory.
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001223void ExecutionEngine::emitGlobals() {
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001224 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +00001225 // to hold them. If there is more than one module, do a prepass over globals
1226 // to figure out how the different modules should link together.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001227 std::map<std::pair<std::string, Type*>,
Chris Lattnerfe854032006-08-16 01:24:12 +00001228 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001229
Chris Lattnerfe854032006-08-16 01:24:12 +00001230 if (Modules.size() != 1) {
1231 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001232 Module &M = *Modules[m];
Stephen Hinesdce4a402014-05-29 02:49:00 -07001233 for (const auto &GV : M.globals()) {
1234 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1235 GV.hasAppendingLinkage() || !GV.hasName())
Chris Lattnerfe854032006-08-16 01:24:12 +00001236 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001237
1238 const GlobalValue *&GVEntry =
Stephen Hinesdce4a402014-05-29 02:49:00 -07001239 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
Chris Lattnerfe854032006-08-16 01:24:12 +00001240
1241 // If this is the first time we've seen this global, it is the canonical
1242 // version.
1243 if (!GVEntry) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001244 GVEntry = &GV;
Chris Lattnerfe854032006-08-16 01:24:12 +00001245 continue;
1246 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001247
Chris Lattnerfe854032006-08-16 01:24:12 +00001248 // If the existing global is strong, never replace it.
Stephen Hines36b56882014-04-23 16:57:46 -07001249 if (GVEntry->hasExternalLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +00001250 continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001251
Chris Lattnerfe854032006-08-16 01:24:12 +00001252 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +00001253 // symbol. FIXME is this right for common?
Stephen Hinesdce4a402014-05-29 02:49:00 -07001254 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1255 GVEntry = &GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +00001256 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001257 }
Chris Lattnerfe854032006-08-16 01:24:12 +00001258 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001259
Chris Lattnerfe854032006-08-16 01:24:12 +00001260 std::vector<const GlobalValue*> NonCanonicalGlobals;
1261 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001262 Module &M = *Modules[m];
Stephen Hinesdce4a402014-05-29 02:49:00 -07001263 for (const auto &GV : M.globals()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001264 // In the multi-module case, see what this global maps to.
1265 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001266 if (const GlobalValue *GVEntry =
Stephen Hinesdce4a402014-05-29 02:49:00 -07001267 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001268 // If something else is the canonical global, ignore this one.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001269 if (GVEntry != &GV) {
1270 NonCanonicalGlobals.push_back(&GV);
Chris Lattnerfe854032006-08-16 01:24:12 +00001271 continue;
1272 }
1273 }
1274 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001275
Stephen Hinesdce4a402014-05-29 02:49:00 -07001276 if (!GV.isDeclaration()) {
1277 addGlobalMapping(&GV, getMemoryForGV(&GV));
Chris Lattnerfe854032006-08-16 01:24:12 +00001278 } else {
1279 // External variable reference. Try to use the dynamic loader to
1280 // get a pointer to it.
1281 if (void *SymAddr =
Stephen Hinesdce4a402014-05-29 02:49:00 -07001282 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1283 addGlobalMapping(&GV, SymAddr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001284 else {
Chris Lattner75361b62010-04-07 22:58:41 +00001285 report_fatal_error("Could not resolve external global address: "
Stephen Hinesdce4a402014-05-29 02:49:00 -07001286 +GV.getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001287 }
1288 }
1289 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001290
Chris Lattnerfe854032006-08-16 01:24:12 +00001291 // If there are multiple modules, map the non-canonical globals to their
1292 // canonical location.
1293 if (!NonCanonicalGlobals.empty()) {
1294 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1295 const GlobalValue *GV = NonCanonicalGlobals[i];
1296 const GlobalValue *CGV =
1297 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1298 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1299 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001300 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001301 }
1302 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001303
1304 // Now that all of the globals are set up in memory, loop through them all
Reid Spencera54b7cb2007-01-12 07:05:14 +00001305 // and initialize their contents.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001306 for (const auto &GV : M.globals()) {
1307 if (!GV.isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001308 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001309 if (const GlobalValue *GVEntry =
Stephen Hinesdce4a402014-05-29 02:49:00 -07001310 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1311 if (GVEntry != &GV) // Not the canonical variable.
Chris Lattnerfe854032006-08-16 01:24:12 +00001312 continue;
1313 }
Stephen Hinesdce4a402014-05-29 02:49:00 -07001314 EmitGlobalVariable(&GV);
Chris Lattnerfe854032006-08-16 01:24:12 +00001315 }
1316 }
1317 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001318}
1319
1320// EmitGlobalVariable - This method emits the specified global variable to the
1321// address specified in GlobalAddresses, or allocates new memory if it's not
1322// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001323void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001324 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001325
Stephen Hinesdce4a402014-05-29 02:49:00 -07001326 if (!GA) {
Chris Lattner24b0a182003-12-20 02:45:37 +00001327 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001328 GA = getMemoryForGV(GV);
Andrew Kaylor48079e02013-11-15 17:52:54 +00001329
1330 // If we failed to allocate memory for this global, return.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001331 if (!GA) return;
Andrew Kaylor48079e02013-11-15 17:52:54 +00001332
Chris Lattner55d86482003-12-31 20:21:04 +00001333 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001334 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001335
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001336 // Don't initialize if it's thread local, let the client do it.
1337 if (!GV->isThreadLocal())
1338 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001339
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001340 Type *ElTy = GV->getType()->getElementType();
Micah Villmow3574eca2012-10-08 16:38:25 +00001341 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001342 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001343 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001344}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001345
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001346ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1347 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001348}
1349
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001350sys::Mutex *
1351ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001352 return &EES->EE.lock;
1353}
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001354
1355void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1356 const GlobalValue *Old) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001357 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1358 EES->GlobalAddressReverseMap.erase(OldVal);
1359}
1360
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001361void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1362 const GlobalValue *,
1363 const GlobalValue *) {
Craig Topper85814382012-02-07 05:05:23 +00001364 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1365 " RAUW on a value it has a global mapping for.");
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001366}