blob: 5a6d65624beebf2ff79cf132ef450cc29f370996 [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 Hines37ed9c12014-12-01 14:51:49 -080019#include "llvm/ExecutionEngine/ObjectBuffer.h"
Stephen Hines36b56882014-04-23 16:57:46 -070020#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 Hines37ed9c12014-12-01 14:51:49 -080027#include "llvm/Object/Archive.h"
Stephen Hinesdce4a402014-05-29 02:49:00 -070028#include "llvm/Object/ObjectFile.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000029#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000030#include "llvm/Support/DynamicLibrary.h"
Torok Edwin31e24662009-07-07 17:32:34 +000031#include "llvm/Support/ErrorHandling.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000032#include "llvm/Support/Host.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000033#include "llvm/Support/MutexGuard.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000034#include "llvm/Support/TargetRegistry.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000035#include "llvm/Support/raw_ostream.h"
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000036#include "llvm/Target/TargetMachine.h"
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000037#include <cmath>
38#include <cstring>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000039using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000040
Stephen Hinesdce4a402014-05-29 02:49:00 -070041#define DEBUG_TYPE "jit"
42
Chris Lattner36343732006-12-19 22:43:32 +000043STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
44STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000045
Juergen Ributzka35436252013-11-19 00:57:56 +000046// Pin the vtable to this file.
47void ObjectCache::anchor() {}
48void ObjectBuffer::anchor() {}
49void ObjectBufferStream::anchor() {}
50
Daniel Dunbar6d135972010-11-17 16:06:37 +000051ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
Stephen Hines37ed9c12014-12-01 14:51:49 -080052 std::unique_ptr<Module> M, std::string *ErrorStr,
53 RTDyldMemoryManager *MCJMM, std::unique_ptr<TargetMachine> TM) = nullptr;
54ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
Stephen Hinesdce4a402014-05-29 02:49:00 -070055 std::string *ErrorStr) =nullptr;
Chris Lattner2fe4bb02006-03-22 06:07:50 +000056
Stephen Hines37ed9c12014-12-01 14:51:49 -080057ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +000058 : EEState(*this),
Stephen Hinesdce4a402014-05-29 02:49:00 -070059 LazyFunctionCreator(nullptr) {
Jeffrey Yasskindc857242009-10-27 20:30:28 +000060 CompilingLazily = false;
Evan Cheng446531e2008-09-24 16:25:55 +000061 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000062 SymbolSearchingDisabled = false;
Stephen Hinesdce4a402014-05-29 02:49:00 -070063
64 // IR module verification is enabled by default in debug builds, and disabled
65 // by default in release builds.
66#ifndef NDEBUG
67 VerifyModules = true;
68#else
69 VerifyModules = false;
70#endif
71
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000072 assert(M && "Module is null?");
Stephen Hines37ed9c12014-12-01 14:51:49 -080073 Modules.push_back(std::move(M));
Misha Brukman19684162003-10-16 21:18:05 +000074}
75
Brian Gaeke8e539482003-09-04 22:57:27 +000076ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000077 clearAllGlobalMappings();
Brian Gaeke8e539482003-09-04 22:57:27 +000078}
79
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000080namespace {
Daniel Dunbar48dd8752010-11-13 02:48:57 +000081/// \brief Helper class which uses a value handler to automatically deletes the
82/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000083class GVMemoryBlock : public CallbackVH {
84 GVMemoryBlock(const GlobalVariable *GV)
85 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
86
87public:
Daniel Dunbar48dd8752010-11-13 02:48:57 +000088 /// \brief Returns the address the GlobalVariable should be written into. The
89 /// GVMemoryBlock object prefixes that.
Micah Villmow3574eca2012-10-08 16:38:25 +000090 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +000091 Type *ElTy = GV->getType()->getElementType();
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000092 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
93 void *RawMemory = ::operator new(
Stephen Hines37ed9c12014-12-01 14:51:49 -080094 RoundUpToAlignment(sizeof(GVMemoryBlock),
95 TD.getPreferredAlignment(GV))
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000096 + GVSize);
97 new(RawMemory) GVMemoryBlock(GV);
98 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
99 }
100
Stephen Hines36b56882014-04-23 16:57:46 -0700101 void deleted() override {
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000102 // We allocated with operator new and with some extra memory hanging off the
103 // end, so don't just delete this. I'm not sure if this is actually
104 // required.
105 this->~GVMemoryBlock();
106 ::operator delete(this);
107 }
108};
109} // anonymous namespace
110
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000111char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000112 return GVMemoryBlock::Create(GV, *getDataLayout());
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000113}
114
Stephen Hinesdce4a402014-05-29 02:49:00 -0700115void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
116 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
117}
118
Stephen Hines37ed9c12014-12-01 14:51:49 -0800119void
120ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
121 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
122}
123
124void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
125 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
126}
127
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000128bool ExecutionEngine::removeModule(Module *M) {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800129 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
130 Module *Found = I->get();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000131 if (Found == M) {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800132 I->release();
Devang Patel73d0e212007-10-15 19:56:32 +0000133 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000134 clearGlobalMappingsFromModule(M);
135 return true;
Devang Patel73d0e212007-10-15 19:56:32 +0000136 }
137 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000138 return false;
Nate Begeman60789e42009-01-23 19:27:28 +0000139}
140
Chris Lattnerfe854032006-08-16 01:24:12 +0000141Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
142 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000143 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +0000144 return F;
145 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700146 return nullptr;
Chris Lattnerfe854032006-08-16 01:24:12 +0000147}
148
149
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700150void *ExecutionEngineState::RemoveMapping(const GlobalValue *ToUnmap) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000151 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000152 void *OldVal;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000153
154 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
155 // GlobalAddressMap.
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000156 if (I == GlobalAddressMap.end())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700157 OldVal = nullptr;
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000158 else {
159 OldVal = I->second;
160 GlobalAddressMap.erase(I);
161 }
162
163 GlobalAddressReverseMap.erase(OldVal);
164 return OldVal;
165}
166
Chris Lattnere7fd5532006-05-08 22:00:52 +0000167void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
168 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000169
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000170 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000171 << "\' to [" << Addr << "]\n";);
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700172 void *&CurVal = EEState.getGlobalAddressMap()[GV];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700173 assert((!CurVal || !Addr) && "GlobalMapping already established!");
Chris Lattnere7fd5532006-05-08 22:00:52 +0000174 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000175
176 // If we are using the reverse mapping, add it too.
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700177 if (!EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000178 AssertingVH<const GlobalValue> &V =
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700179 EEState.getGlobalAddressReverseMap()[Addr];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700180 assert((!V || !GV) && "GlobalMapping already established!");
Chris Lattnere7fd5532006-05-08 22:00:52 +0000181 V = GV;
182 }
183}
184
Chris Lattnere7fd5532006-05-08 22:00:52 +0000185void ExecutionEngine::clearAllGlobalMappings() {
186 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000187
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700188 EEState.getGlobalAddressMap().clear();
189 EEState.getGlobalAddressReverseMap().clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000190}
191
Nate Begemanf049e072008-05-21 16:34:48 +0000192void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
193 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000194
195 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700196 EEState.RemoveMapping(FI);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000197 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
198 GI != GE; ++GI)
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700199 EEState.RemoveMapping(GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000200}
201
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000202void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000203 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000204
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000205 ExecutionEngineState::GlobalAddressMapTy &Map =
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700206 EEState.getGlobalAddressMap();
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000207
Chris Lattnere7fd5532006-05-08 22:00:52 +0000208 // Deleting from the mapping?
Stephen Hinesdce4a402014-05-29 02:49:00 -0700209 if (!Addr)
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700210 return EEState.RemoveMapping(GV);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000211
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000212 void *&CurVal = Map[GV];
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000213 void *OldVal = CurVal;
214
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700215 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
216 EEState.getGlobalAddressReverseMap().erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000217 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000218
219 // If we are using the reverse mapping, add it too.
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700220 if (!EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000221 AssertingVH<const GlobalValue> &V =
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700222 EEState.getGlobalAddressReverseMap()[Addr];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700223 assert((!V || !GV) && "GlobalMapping already established!");
Chris Lattnere7fd5532006-05-08 22:00:52 +0000224 V = GV;
225 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000226 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000227}
228
Chris Lattnere7fd5532006-05-08 22:00:52 +0000229void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
230 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000231
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000232 ExecutionEngineState::GlobalAddressMapTy::iterator I =
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700233 EEState.getGlobalAddressMap().find(GV);
234 return I != EEState.getGlobalAddressMap().end() ? I->second : nullptr;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000235}
236
Chris Lattner55d86482003-12-31 20:21:04 +0000237const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000238 MutexGuard locked(lock);
239
Chris Lattner55d86482003-12-31 20:21:04 +0000240 // If we haven't computed the reverse mapping yet, do so first.
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700241 if (EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000242 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700243 I = EEState.getGlobalAddressMap().begin(),
244 E = EEState.getGlobalAddressMap().end(); I != E; ++I)
245 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
Daniel Dunbarab19da42010-11-13 00:55:42 +0000246 I->second, I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000247 }
248
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000249 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700250 EEState.getGlobalAddressReverseMap().find(Addr);
251 return I != EEState.getGlobalAddressReverseMap().end() ? I->second : nullptr;
Chris Lattner55d86482003-12-31 20:21:04 +0000252}
Chris Lattner87f03102003-12-26 06:50:30 +0000253
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000254namespace {
255class ArgvArray {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800256 std::unique_ptr<char[]> Array;
257 std::vector<std::unique_ptr<char[]>> Values;
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000258public:
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000259 /// Turn a vector of strings into a nice argv style array of pointers to null
260 /// terminated strings.
261 void *reset(LLVMContext &C, ExecutionEngine *EE,
262 const std::vector<std::string> &InputArgv);
263};
264} // anonymous namespace
265void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
266 const std::vector<std::string> &InputArgv) {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800267 Values.clear(); // Free the old contents.
268 Values.reserve(InputArgv.size());
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000269 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Stephen Hines37ed9c12014-12-01 14:51:49 -0800270 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
Chris Lattner87f03102003-12-26 06:50:30 +0000271
Stephen Hines37ed9c12014-12-01 14:51:49 -0800272 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000273 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000274
275 for (unsigned i = 0; i != InputArgv.size(); ++i) {
276 unsigned Size = InputArgv[i].size()+1;
Stephen Hines37ed9c12014-12-01 14:51:49 -0800277 auto Dest = make_unique<char[]>(Size);
278 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000279
Stephen Hines37ed9c12014-12-01 14:51:49 -0800280 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
Chris Lattner87f03102003-12-26 06:50:30 +0000281 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000282
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000283 // Endian safe: Array[i] = (PointerTy)Dest;
Stephen Hines37ed9c12014-12-01 14:51:49 -0800284 EE->StoreValueToMemory(PTOGV(Dest.get()),
285 (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
286 Values.push_back(std::move(Dest));
Chris Lattner87f03102003-12-26 06:50:30 +0000287 }
288
289 // Null terminate it
Stephen Hinesdce4a402014-05-29 02:49:00 -0700290 EE->StoreValueToMemory(PTOGV(nullptr),
Stephen Hines37ed9c12014-12-01 14:51:49 -0800291 (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
Chris Lattner87f03102003-12-26 06:50:30 +0000292 SBytePtr);
Stephen Hines37ed9c12014-12-01 14:51:49 -0800293 return Array.get();
Chris Lattner87f03102003-12-26 06:50:30 +0000294}
295
Stephen Hines37ed9c12014-12-01 14:51:49 -0800296void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
Chris Lattnerfbd39762009-09-23 01:46:04 +0000297 bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000298 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Stephen Hines37ed9c12014-12-01 14:51:49 -0800299 GlobalVariable *GV = module.getNamedGlobal(Name);
Evan Cheng18314dc2008-09-30 15:51:21 +0000300
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000301 // If this global has internal linkage, or if it has a use, then it must be
302 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
303 // this is the case, don't execute any of the global ctors, __main will do
304 // it.
305 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
306
Nick Lewyckya040d472011-04-06 20:38:44 +0000307 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000308 // the init priority, which we ignore.
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000309 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
Stephen Hinesdce4a402014-05-29 02:49:00 -0700310 if (!InitList)
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000311 return;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000312 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000313 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
Stephen Hinesdce4a402014-05-29 02:49:00 -0700314 if (!CS) continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000315
316 Constant *FP = CS->getOperand(1);
317 if (FP->isNullValue())
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000318 continue; // Found a sentinal value, ignore.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000319
320 // Strip off constant expression casts.
321 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
322 if (CE->isCast())
323 FP = CE->getOperand(0);
324
325 // Execute the ctor/dtor function!
326 if (Function *F = dyn_cast<Function>(FP))
327 runFunction(F, std::vector<GenericValue>());
328
329 // FIXME: It is marginally lame that we just do nothing here if we see an
330 // entry we don't recognize. It might not be unreasonable for the verifier
331 // to not even allow this and just assert here.
332 }
Evan Cheng18314dc2008-09-30 15:51:21 +0000333}
334
Evan Cheng18314dc2008-09-30 15:51:21 +0000335void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
336 // Execute global ctors/dtors for each module in the program.
Stephen Hines37ed9c12014-12-01 14:51:49 -0800337 for (std::unique_ptr<Module> &M : Modules)
338 runStaticConstructorsDestructors(*M, isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000339}
340
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000341#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000342/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
343static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000344 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000345 for (unsigned i = 0; i < PtrSize; ++i)
346 if (*(i + (uint8_t*)Loc))
347 return false;
348 return true;
349}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000350#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000351
Chris Lattner87f03102003-12-26 06:50:30 +0000352int ExecutionEngine::runFunctionAsMain(Function *Fn,
353 const std::vector<std::string> &argv,
354 const char * const * envp) {
355 std::vector<GenericValue> GVArgs;
356 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000357 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000358
359 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000360 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000361 FunctionType *FTy = Fn->getFunctionType();
362 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000363
364 // Check the argument types.
365 if (NumArgs > 3)
366 report_fatal_error("Invalid number of arguments of main() supplied");
367 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
368 report_fatal_error("Invalid type for third argument of main() supplied");
369 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
370 report_fatal_error("Invalid type for second argument of main() supplied");
371 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
372 report_fatal_error("Invalid type for first argument of main() supplied");
373 if (!FTy->getReturnType()->isIntegerTy() &&
374 !FTy->getReturnType()->isVoidTy())
375 report_fatal_error("Invalid return type of main() supplied");
376
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000377 ArgvArray CArgv;
378 ArgvArray CEnv;
Chris Lattnerf24d0992004-08-16 01:05:35 +0000379 if (NumArgs) {
380 GVArgs.push_back(GVArgc); // Arg #0 = argc.
381 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000382 // Arg #1 = argv.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000383 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000384 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000385 "argv[0] was null after CreateArgv");
386 if (NumArgs > 2) {
387 std::vector<std::string> EnvVars;
388 for (unsigned i = 0; envp[i]; ++i)
389 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000390 // Arg #2 = envp.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000391 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000392 }
393 }
394 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000395
Reid Spencer8fb0f192007-03-06 03:04:04 +0000396 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000397}
398
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700399void EngineBuilder::InitEngine() {
400 WhichEngine = EngineKind::Either;
401 ErrorStr = nullptr;
402 OptLevel = CodeGenOpt::Default;
403 MCJMM = nullptr;
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700404 Options = TargetOptions();
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700405 RelocModel = Reloc::Default;
406 CMModel = CodeModel::JITDefault;
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700407
408// IR module verification is enabled by default in debug builds, and disabled
409// by default in release builds.
410#ifndef NDEBUG
411 VerifyModules = true;
412#else
413 VerifyModules = false;
414#endif
415}
416
Owen Anderson8e1fc562012-03-23 17:40:56 +0000417ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Stephen Hines36b56882014-04-23 16:57:46 -0700418 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
Benjamin Kramer0f554492012-04-08 14:53:14 +0000419
Nick Lewycky6456d862008-03-08 02:49:45 +0000420 // Make sure we can resolve symbols in the program as well. The zero arg
421 // to the function tells DynamicLibrary to load the program, not a library.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700422 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
423 return nullptr;
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000424
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000425 // If the user specified a memory manager but didn't specify which engine to
426 // create, we assume they only want the JIT, and we fail if they only want
427 // the interpreter.
Stephen Hines37ed9c12014-12-01 14:51:49 -0800428 if (MCJMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000429 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000430 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000431 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000432 if (ErrorStr)
433 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Stephen Hinesdce4a402014-05-29 02:49:00 -0700434 return nullptr;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000435 }
436 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000437
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000438 // Unless the interpreter was explicitly selected or the JIT is not linked,
439 // try making a JIT.
Benjamin Kramer0f554492012-04-08 14:53:14 +0000440 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000441 Triple TT(M->getTargetTriple());
Owen Anderson8e1fc562012-03-23 17:40:56 +0000442 if (!TM->getTarget().hasJIT()) {
443 errs() << "WARNING: This target JIT is not designed for the host"
444 << " you are running. If bad things happen, please choose"
445 << " a different -march switch.\n";
446 }
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000447
Stephen Hinesdce4a402014-05-29 02:49:00 -0700448 ExecutionEngine *EE = nullptr;
Stephen Hines37ed9c12014-12-01 14:51:49 -0800449 if (ExecutionEngine::MCJITCtor)
450 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, MCJMM,
451 std::move(TheTM));
Stephen Hinesdce4a402014-05-29 02:49:00 -0700452 if (EE) {
453 EE->setVerifyModules(VerifyModules);
454 return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000455 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000456 }
457
458 // If we can't make a JIT and we didn't request one specifically, try making
459 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000460 if (WhichEngine & EngineKind::Interpreter) {
461 if (ExecutionEngine::InterpCtor)
Stephen Hines37ed9c12014-12-01 14:51:49 -0800462 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000463 if (ErrorStr)
464 *ErrorStr = "Interpreter has not been linked in.";
Stephen Hinesdce4a402014-05-29 02:49:00 -0700465 return nullptr;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000466 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000467
Stephen Hines37ed9c12014-12-01 14:51:49 -0800468 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000469 if (ErrorStr)
470 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000471 }
472
Stephen Hinesdce4a402014-05-29 02:49:00 -0700473 return nullptr;
Brian Gaeke82d82772003-09-03 20:34:19 +0000474}
475
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000476void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000477 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000478 return getPointerToFunction(F);
479
Reid Spenceree448632005-07-12 15:51:55 +0000480 MutexGuard locked(lock);
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700481 if (void *P = EEState.getGlobalAddressMap()[GV])
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000482 return P;
Jeff Cohen68835dd2006-02-07 05:11:57 +0000483
484 // Global variable might have been added since interpreter started.
485 if (GlobalVariable *GVar =
486 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
487 EmitGlobalVariable(GVar);
488 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000489 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000490
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700491 return EEState.getGlobalAddressMap()[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000492}
493
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000494/// \brief Converts a Constant* into a GenericValue, including handling of
495/// ConstantExpr values.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000496GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000497 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000498 if (isa<UndefValue>(C)) {
499 GenericValue Result;
500 switch (C->getType()->getTypeID()) {
Nadav Rotem953783e2013-04-01 15:53:30 +0000501 default:
502 break;
Jay Foad5b370122010-01-15 08:32:58 +0000503 case Type::IntegerTyID:
504 case Type::X86_FP80TyID:
505 case Type::FP128TyID:
506 case Type::PPC_FP128TyID:
507 // Although the value is undefined, we still have to construct an APInt
508 // with the correct bit width.
509 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
510 break;
Elena Demikhovsky3c5ce292013-09-12 10:48:23 +0000511 case Type::StructTyID: {
512 // if the whole struct is 'undef' just reserve memory for the value.
513 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
514 unsigned int elemNum = STy->getNumElements();
515 Result.AggregateVal.resize(elemNum);
516 for (unsigned int i = 0; i < elemNum; ++i) {
517 Type *ElemTy = STy->getElementType(i);
518 if (ElemTy->isIntegerTy())
519 Result.AggregateVal[i].IntVal =
520 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
521 else if (ElemTy->isAggregateType()) {
522 const Constant *ElemUndef = UndefValue::get(ElemTy);
523 Result.AggregateVal[i] = getConstantValue(ElemUndef);
524 }
525 }
526 }
527 }
528 break;
Nadav Rotem953783e2013-04-01 15:53:30 +0000529 case Type::VectorTyID:
530 // if the whole vector is 'undef' just reserve memory for the value.
531 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
532 const Type *ElemTy = VTy->getElementType();
533 unsigned int elemNum = VTy->getNumElements();
534 Result.AggregateVal.resize(elemNum);
535 if (ElemTy->isIntegerTy())
536 for (unsigned int i = 0; i < elemNum; ++i)
Elena Demikhovsky3c5ce292013-09-12 10:48:23 +0000537 Result.AggregateVal[i].IntVal =
Nadav Rotem953783e2013-04-01 15:53:30 +0000538 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foad5b370122010-01-15 08:32:58 +0000539 break;
540 }
541 return Result;
542 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000543
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000544 // Otherwise, if the value is a ConstantExpr...
Reid Spencer3da59db2006-11-27 01:05:10 +0000545 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000546 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000547 switch (CE->getOpcode()) {
548 case Instruction::GetElementPtr: {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000549 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000550 GenericValue Result = getConstantValue(Op0);
Stephen Hines36b56882014-04-23 16:57:46 -0700551 APInt Offset(DL->getPointerSizeInBits(), 0);
552 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000553
Reid Spencer8fb0f192007-03-06 03:04:04 +0000554 char* tmp = (char*) Result.PointerVal;
Nuno Lopes98281a22012-12-30 16:25:48 +0000555 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000556 return Result;
557 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000558 case Instruction::Trunc: {
559 GenericValue GV = getConstantValue(Op0);
560 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
561 GV.IntVal = GV.IntVal.trunc(BitWidth);
562 return GV;
563 }
564 case Instruction::ZExt: {
565 GenericValue GV = getConstantValue(Op0);
566 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
567 GV.IntVal = GV.IntVal.zext(BitWidth);
568 return GV;
569 }
570 case Instruction::SExt: {
571 GenericValue GV = getConstantValue(Op0);
572 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
573 GV.IntVal = GV.IntVal.sext(BitWidth);
574 return GV;
575 }
576 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000577 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000578 GenericValue GV = getConstantValue(Op0);
579 GV.FloatVal = float(GV.DoubleVal);
580 return GV;
581 }
582 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000583 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000584 GenericValue GV = getConstantValue(Op0);
585 GV.DoubleVal = double(GV.FloatVal);
586 return GV;
587 }
588 case Instruction::UIToFP: {
589 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000590 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000591 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000592 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000593 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000594 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000595 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000596 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000597 false,
598 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000599 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000600 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000601 return GV;
602 }
603 case Instruction::SIToFP: {
604 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000605 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000606 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000607 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000608 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000609 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000610 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000611 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000612 true,
613 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000614 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000615 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000616 return GV;
617 }
618 case Instruction::FPToUI: // double->APInt conversion handles sign
619 case Instruction::FPToSI: {
620 GenericValue GV = getConstantValue(Op0);
621 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000622 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000623 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000624 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000625 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000626 else if (Op0->getType()->isX86_FP80Ty()) {
Tim Northover0a29cb02013-01-22 09:46:31 +0000627 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000628 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000629 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000630 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000631 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000632 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000633 GV.IntVal = v; // endian?
634 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000635 return GV;
636 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000637 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000638 GenericValue GV = getConstantValue(Op0);
Stephen Hines36b56882014-04-23 16:57:46 -0700639 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000640 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencerbce30f12007-03-06 22:23:15 +0000641 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Stephen Hines36b56882014-04-23 16:57:46 -0700642 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000643 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencerbce30f12007-03-06 22:23:15 +0000644 return GV;
645 }
646 case Instruction::IntToPtr: {
647 GenericValue GV = getConstantValue(Op0);
Stephen Hines36b56882014-04-23 16:57:46 -0700648 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000649 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencerbce30f12007-03-06 22:23:15 +0000650 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
651 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000652 return GV;
653 }
654 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000655 GenericValue GV = getConstantValue(Op0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000656 Type* DestTy = CE->getType();
Reid Spencerbce30f12007-03-06 22:23:15 +0000657 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000658 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000659 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000660 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000661 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000662 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000663 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000664 GV.DoubleVal = GV.IntVal.bitsToDouble();
665 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000666 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000667 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000668 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000669 break;
670 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000671 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000672 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000673 break;
674 case Type::PointerTyID:
Duncan Sands1df98592010-02-16 11:11:14 +0000675 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000676 break; // getConstantValue(Op0) above already converted it
677 }
678 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000679 }
Chris Lattner9a231222003-05-14 17:51:49 +0000680 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000681 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000682 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000683 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000684 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000685 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000686 case Instruction::UDiv:
687 case Instruction::SDiv:
688 case Instruction::URem:
689 case Instruction::SRem:
690 case Instruction::And:
691 case Instruction::Or:
692 case Instruction::Xor: {
693 GenericValue LHS = getConstantValue(Op0);
694 GenericValue RHS = getConstantValue(CE->getOperand(1));
695 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000696 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000697 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000698 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000699 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000700 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000701 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
702 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
703 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
704 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
705 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
706 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
707 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
708 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
709 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
710 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
711 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000712 break;
713 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000714 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000715 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000716 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000717 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000718 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000719 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000720 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000721 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000722 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000723 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000724 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000725 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000726 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000727 break;
728 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000729 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000730 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000731 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000732 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000733 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000734 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000735 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000736 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000737 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000738 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000739 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000740 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000741 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000742 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000743 case Type::X86_FP80TyID:
744 case Type::PPC_FP128TyID:
745 case Type::FP128TyID: {
Tim Northover0a29cb02013-01-22 09:46:31 +0000746 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
747 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000748 switch (CE->getOpcode()) {
Daniel Dunbarab19da42010-11-13 00:55:42 +0000749 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000750 case Instruction::FAdd:
Tim Northover0a29cb02013-01-22 09:46:31 +0000751 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000752 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000753 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000754 case Instruction::FSub:
Tim Northover0a29cb02013-01-22 09:46:31 +0000755 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
756 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000757 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000758 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000759 case Instruction::FMul:
Tim Northover0a29cb02013-01-22 09:46:31 +0000760 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
761 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000762 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000763 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000764 case Instruction::FDiv:
Tim Northover0a29cb02013-01-22 09:46:31 +0000765 apfLHS.divide(APFloat(Sem, RHS.IntVal),
766 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000767 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000768 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000769 case Instruction::FRem:
Tim Northover0a29cb02013-01-22 09:46:31 +0000770 apfLHS.mod(APFloat(Sem, RHS.IntVal),
771 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000772 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000773 break;
774 }
775 }
776 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000777 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000778 return GV;
779 }
Chris Lattner9a231222003-05-14 17:51:49 +0000780 default:
781 break;
782 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000783
784 SmallString<256> Msg;
785 raw_svector_ostream OS(Msg);
786 OS << "ConstantExpr not handled: " << *CE;
787 report_fatal_error(OS.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000788 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000789
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000790 // Otherwise, we have a simple constant.
Reid Spencerbce30f12007-03-06 22:23:15 +0000791 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000792 switch (C->getType()->getTypeID()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000793 case Type::FloatTyID:
794 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000795 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000796 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000797 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000798 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000799 case Type::X86_FP80TyID:
800 case Type::FP128TyID:
801 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000802 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000803 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000804 case Type::IntegerTyID:
805 Result.IntVal = cast<ConstantInt>(C)->getValue();
806 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000807 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000808 if (isa<ConstantPointerNull>(C))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700809 Result.PointerVal = nullptr;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000810 else if (const Function *F = dyn_cast<Function>(C))
811 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000812 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000813 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
814 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000815 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000816 break;
Nadav Rotem953783e2013-04-01 15:53:30 +0000817 case Type::VectorTyID: {
818 unsigned elemNum;
819 Type* ElemTy;
820 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
821 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
822 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
823
824 if (CDV) {
825 elemNum = CDV->getNumElements();
826 ElemTy = CDV->getElementType();
827 } else if (CV || CAZ) {
828 VectorType* VTy = dyn_cast<VectorType>(C->getType());
829 elemNum = VTy->getNumElements();
830 ElemTy = VTy->getElementType();
831 } else {
832 llvm_unreachable("Unknown constant vector type!");
833 }
834
835 Result.AggregateVal.resize(elemNum);
836 // Check if vector holds floats.
837 if(ElemTy->isFloatTy()) {
838 if (CAZ) {
839 GenericValue floatZero;
840 floatZero.FloatVal = 0.f;
841 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
842 floatZero);
843 break;
844 }
845 if(CV) {
846 for (unsigned i = 0; i < elemNum; ++i)
847 if (!isa<UndefValue>(CV->getOperand(i)))
848 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
849 CV->getOperand(i))->getValueAPF().convertToFloat();
850 break;
851 }
852 if(CDV)
853 for (unsigned i = 0; i < elemNum; ++i)
854 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
855
856 break;
857 }
858 // Check if vector holds doubles.
859 if (ElemTy->isDoubleTy()) {
860 if (CAZ) {
861 GenericValue doubleZero;
862 doubleZero.DoubleVal = 0.0;
863 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
864 doubleZero);
865 break;
866 }
867 if(CV) {
868 for (unsigned i = 0; i < elemNum; ++i)
869 if (!isa<UndefValue>(CV->getOperand(i)))
870 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
871 CV->getOperand(i))->getValueAPF().convertToDouble();
872 break;
873 }
874 if(CDV)
875 for (unsigned i = 0; i < elemNum; ++i)
876 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
877
878 break;
879 }
880 // Check if vector holds integers.
881 if (ElemTy->isIntegerTy()) {
882 if (CAZ) {
883 GenericValue intZero;
884 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
885 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
886 intZero);
887 break;
888 }
889 if(CV) {
890 for (unsigned i = 0; i < elemNum; ++i)
891 if (!isa<UndefValue>(CV->getOperand(i)))
892 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
893 CV->getOperand(i))->getValue();
894 else {
895 Result.AggregateVal[i].IntVal =
896 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
897 }
898 break;
899 }
900 if(CDV)
901 for (unsigned i = 0; i < elemNum; ++i)
902 Result.AggregateVal[i].IntVal = APInt(
903 CDV->getElementType()->getPrimitiveSizeInBits(),
904 CDV->getElementAsInteger(i));
905
906 break;
907 }
908 llvm_unreachable("Unknown constant pointer type!");
909 }
910 break;
911
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000912 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000913 SmallString<256> Msg;
914 raw_svector_ostream OS(Msg);
915 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
916 report_fatal_error(OS.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000917 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000918
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000919 return Result;
920}
921
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000922/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
923/// with the integer held in IntVal.
924static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
925 unsigned StoreBytes) {
926 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divacky59324292012-09-05 22:26:57 +0000927 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000928
Rafael Espindola21a01d12013-04-15 14:44:24 +0000929 if (sys::IsLittleEndianHost) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000930 // Little-endian host - the source is ordered from LSB to MSB. Order the
931 // destination from LSB to MSB: Do a straight copy.
932 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000933 } else {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000934 // Big-endian host - the source is an array of 64 bit words ordered from
935 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
936 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
937 while (StoreBytes > sizeof(uint64_t)) {
938 StoreBytes -= sizeof(uint64_t);
939 // May not be aligned so use memcpy.
940 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
941 Src += sizeof(uint64_t);
942 }
943
944 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
945 }
946}
947
Evan Cheng89687e32008-11-04 06:10:31 +0000948void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000949 GenericValue *Ptr, Type *Ty) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000950 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000951
Reid Spencer8fb0f192007-03-06 03:04:04 +0000952 switch (Ty->getTypeID()) {
Nadav Rotem953783e2013-04-01 15:53:30 +0000953 default:
954 dbgs() << "Cannot store value of type " << *Ty << "!\n";
955 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000956 case Type::IntegerTyID:
957 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000958 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000959 case Type::FloatTyID:
960 *((float*)Ptr) = Val.FloatVal;
961 break;
962 case Type::DoubleTyID:
963 *((double*)Ptr) = Val.DoubleVal;
964 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000965 case Type::X86_FP80TyID:
966 memcpy(Ptr, Val.IntVal.getRawData(), 10);
967 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000968 case Type::PointerTyID:
969 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
970 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth80d9e072011-04-28 08:37:18 +0000971 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000972
Reid Spencer8fb0f192007-03-06 03:04:04 +0000973 *((PointerTy*)Ptr) = Val.PointerVal;
974 break;
Nadav Rotem953783e2013-04-01 15:53:30 +0000975 case Type::VectorTyID:
976 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
977 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
978 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
979 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
980 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
981 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
982 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
983 StoreIntToMemory(Val.AggregateVal[i].IntVal,
984 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
985 }
986 }
987 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000988 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000989
Rafael Espindola21a01d12013-04-15 14:44:24 +0000990 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000991 // Host and target are different endian - reverse the stored bytes.
992 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
993}
994
995/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
996/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
997static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
998 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greenec2680be2013-01-14 21:04:45 +0000999 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1000 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001001
Rafael Espindola21a01d12013-04-15 14:44:24 +00001002 if (sys::IsLittleEndianHost)
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001003 // Little-endian host - the destination must be ordered from LSB to MSB.
1004 // The source is ordered from LSB to MSB: Do a straight copy.
1005 memcpy(Dst, Src, LoadBytes);
1006 else {
1007 // Big-endian - the destination is an array of 64 bit words ordered from
1008 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1009 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1010 // a word.
1011 while (LoadBytes > sizeof(uint64_t)) {
1012 LoadBytes -= sizeof(uint64_t);
1013 // May not be aligned so use memcpy.
1014 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1015 Dst += sizeof(uint64_t);
1016 }
1017
1018 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1019 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001020}
1021
Misha Brukman4afac182003-10-10 17:45:12 +00001022/// FIXME: document
1023///
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001024void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +00001025 GenericValue *Ptr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001026 Type *Ty) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001027 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +00001028
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001029 switch (Ty->getTypeID()) {
1030 case Type::IntegerTyID:
1031 // An APInt with all words initially zero.
1032 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1033 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1034 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +00001035 case Type::FloatTyID:
1036 Result.FloatVal = *((float*)Ptr);
1037 break;
1038 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001039 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +00001040 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001041 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +00001042 Result.PointerVal = *((PointerTy*)Ptr);
1043 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +00001044 case Type::X86_FP80TyID: {
1045 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +00001046 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +00001047 uint64_t y[2];
1048 memcpy(y, Ptr, 10);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001049 Result.IntVal = APInt(80, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +00001050 break;
1051 }
Nadav Rotem953783e2013-04-01 15:53:30 +00001052 case Type::VectorTyID: {
1053 const VectorType *VT = cast<VectorType>(Ty);
1054 const Type *ElemT = VT->getElementType();
1055 const unsigned numElems = VT->getNumElements();
1056 if (ElemT->isFloatTy()) {
1057 Result.AggregateVal.resize(numElems);
1058 for (unsigned i = 0; i < numElems; ++i)
1059 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1060 }
1061 if (ElemT->isDoubleTy()) {
1062 Result.AggregateVal.resize(numElems);
1063 for (unsigned i = 0; i < numElems; ++i)
1064 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1065 }
1066 if (ElemT->isIntegerTy()) {
1067 GenericValue intZero;
1068 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1069 intZero.IntVal = APInt(elemBitWidth, 0);
1070 Result.AggregateVal.resize(numElems, intZero);
1071 for (unsigned i = 0; i < numElems; ++i)
1072 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1073 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1074 }
1075 break;
1076 }
Reid Spencer8fb0f192007-03-06 03:04:04 +00001077 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001078 SmallString<256> Msg;
1079 raw_svector_ostream OS(Msg);
1080 OS << "Cannot load value of type " << *Ty << "!";
1081 report_fatal_error(OS.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +00001082 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +00001083}
1084
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001085void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +00001086 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +00001087 DEBUG(Init->dump());
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001088 if (isa<UndefValue>(Init))
Chris Lattnerbd1d3822004-10-16 18:19:26 +00001089 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001090
1091 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +00001092 unsigned ElementSize =
Micah Villmow3574eca2012-10-08 16:38:25 +00001093 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +00001094 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1095 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1096 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001097 }
1098
1099 if (isa<ConstantAggregateZero>(Init)) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001100 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +00001101 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001102 }
1103
1104 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman638e3782008-05-20 03:20:09 +00001105 unsigned ElementSize =
Micah Villmow3574eca2012-10-08 16:38:25 +00001106 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +00001107 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1108 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1109 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001110 }
1111
1112 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman638e3782008-05-20 03:20:09 +00001113 const StructLayout *SL =
Micah Villmow3574eca2012-10-08 16:38:25 +00001114 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman638e3782008-05-20 03:20:09 +00001115 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1116 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1117 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001118 }
1119
1120 if (const ConstantDataSequential *CDS =
1121 dyn_cast<ConstantDataSequential>(Init)) {
1122 // CDS is already laid out in host memory order.
1123 StringRef Data = CDS->getRawDataValues();
1124 memcpy(Addr, Data.data(), Data.size());
1125 return;
1126 }
1127
1128 if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001129 GenericValue Val = getConstantValue(Init);
1130 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1131 return;
1132 }
1133
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001134 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinc23197a2009-07-14 16:55:14 +00001135 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001136}
1137
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001138/// EmitGlobals - Emit all of the global variables to memory, storing their
1139/// addresses into GlobalAddress. This must make sure to copy the contents of
1140/// their initializers into the memory.
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001141void ExecutionEngine::emitGlobals() {
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001142 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +00001143 // to hold them. If there is more than one module, do a prepass over globals
1144 // to figure out how the different modules should link together.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001145 std::map<std::pair<std::string, Type*>,
Chris Lattnerfe854032006-08-16 01:24:12 +00001146 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001147
Chris Lattnerfe854032006-08-16 01:24:12 +00001148 if (Modules.size() != 1) {
1149 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001150 Module &M = *Modules[m];
Stephen Hinesdce4a402014-05-29 02:49:00 -07001151 for (const auto &GV : M.globals()) {
1152 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1153 GV.hasAppendingLinkage() || !GV.hasName())
Chris Lattnerfe854032006-08-16 01:24:12 +00001154 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001155
1156 const GlobalValue *&GVEntry =
Stephen Hinesdce4a402014-05-29 02:49:00 -07001157 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
Chris Lattnerfe854032006-08-16 01:24:12 +00001158
1159 // If this is the first time we've seen this global, it is the canonical
1160 // version.
1161 if (!GVEntry) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001162 GVEntry = &GV;
Chris Lattnerfe854032006-08-16 01:24:12 +00001163 continue;
1164 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001165
Chris Lattnerfe854032006-08-16 01:24:12 +00001166 // If the existing global is strong, never replace it.
Stephen Hines36b56882014-04-23 16:57:46 -07001167 if (GVEntry->hasExternalLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +00001168 continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001169
Chris Lattnerfe854032006-08-16 01:24:12 +00001170 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +00001171 // symbol. FIXME is this right for common?
Stephen Hinesdce4a402014-05-29 02:49:00 -07001172 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1173 GVEntry = &GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +00001174 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001175 }
Chris Lattnerfe854032006-08-16 01:24:12 +00001176 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001177
Chris Lattnerfe854032006-08-16 01:24:12 +00001178 std::vector<const GlobalValue*> NonCanonicalGlobals;
1179 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001180 Module &M = *Modules[m];
Stephen Hinesdce4a402014-05-29 02:49:00 -07001181 for (const auto &GV : M.globals()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001182 // In the multi-module case, see what this global maps to.
1183 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001184 if (const GlobalValue *GVEntry =
Stephen Hinesdce4a402014-05-29 02:49:00 -07001185 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001186 // If something else is the canonical global, ignore this one.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001187 if (GVEntry != &GV) {
1188 NonCanonicalGlobals.push_back(&GV);
Chris Lattnerfe854032006-08-16 01:24:12 +00001189 continue;
1190 }
1191 }
1192 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001193
Stephen Hinesdce4a402014-05-29 02:49:00 -07001194 if (!GV.isDeclaration()) {
1195 addGlobalMapping(&GV, getMemoryForGV(&GV));
Chris Lattnerfe854032006-08-16 01:24:12 +00001196 } else {
1197 // External variable reference. Try to use the dynamic loader to
1198 // get a pointer to it.
1199 if (void *SymAddr =
Stephen Hinesdce4a402014-05-29 02:49:00 -07001200 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1201 addGlobalMapping(&GV, SymAddr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001202 else {
Chris Lattner75361b62010-04-07 22:58:41 +00001203 report_fatal_error("Could not resolve external global address: "
Stephen Hinesdce4a402014-05-29 02:49:00 -07001204 +GV.getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001205 }
1206 }
1207 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001208
Chris Lattnerfe854032006-08-16 01:24:12 +00001209 // If there are multiple modules, map the non-canonical globals to their
1210 // canonical location.
1211 if (!NonCanonicalGlobals.empty()) {
1212 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1213 const GlobalValue *GV = NonCanonicalGlobals[i];
1214 const GlobalValue *CGV =
1215 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1216 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1217 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001218 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001219 }
1220 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001221
1222 // Now that all of the globals are set up in memory, loop through them all
Reid Spencera54b7cb2007-01-12 07:05:14 +00001223 // and initialize their contents.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001224 for (const auto &GV : M.globals()) {
1225 if (!GV.isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001226 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001227 if (const GlobalValue *GVEntry =
Stephen Hinesdce4a402014-05-29 02:49:00 -07001228 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1229 if (GVEntry != &GV) // Not the canonical variable.
Chris Lattnerfe854032006-08-16 01:24:12 +00001230 continue;
1231 }
Stephen Hinesdce4a402014-05-29 02:49:00 -07001232 EmitGlobalVariable(&GV);
Chris Lattnerfe854032006-08-16 01:24:12 +00001233 }
1234 }
1235 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001236}
1237
1238// EmitGlobalVariable - This method emits the specified global variable to the
1239// address specified in GlobalAddresses, or allocates new memory if it's not
1240// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001241void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001242 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001243
Stephen Hinesdce4a402014-05-29 02:49:00 -07001244 if (!GA) {
Chris Lattner24b0a182003-12-20 02:45:37 +00001245 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001246 GA = getMemoryForGV(GV);
Andrew Kaylor48079e02013-11-15 17:52:54 +00001247
1248 // If we failed to allocate memory for this global, return.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001249 if (!GA) return;
Andrew Kaylor48079e02013-11-15 17:52:54 +00001250
Chris Lattner55d86482003-12-31 20:21:04 +00001251 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001252 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001253
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001254 // Don't initialize if it's thread local, let the client do it.
1255 if (!GV->isThreadLocal())
1256 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001257
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001258 Type *ElTy = GV->getType()->getElementType();
Micah Villmow3574eca2012-10-08 16:38:25 +00001259 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001260 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001261 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001262}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001263
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001264ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1265 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001266}
1267
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001268sys::Mutex *
1269ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001270 return &EES->EE.lock;
1271}
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001272
1273void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1274 const GlobalValue *Old) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001275 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1276 EES->GlobalAddressReverseMap.erase(OldVal);
1277}
1278
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001279void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1280 const GlobalValue *,
1281 const GlobalValue *) {
Craig Topper85814382012-02-07 05:05:23 +00001282 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1283 " RAUW on a value it has a global mapping for.");
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001284}