blob: 32d20ea0e304bb93f3b29036d06e0a6d9df6c8cb [file] [log] [blame]
Misha Brukman857c21b2003-10-10 17:45:12 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukman835702a2005-04-21 22:36:52 +00009//
Chris Lattner996fe012002-12-24 00:01:05 +000010// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +000015#include "llvm/ExecutionEngine/ExecutionEngine.h"
Daniel Dunbar868e3f02010-11-13 02:48:57 +000016#include "llvm/ADT/SmallString.h"
Chris Lattner390d78b2009-08-23 22:49:13 +000017#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ExecutionEngine/GenericValue.h"
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000019#include "llvm/ExecutionEngine/JITEventListener.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/Constants.h"
21#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/DerivedTypes.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/Operator.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000025#include "llvm/IR/ValueHandle.h"
Rafael Espindoladd396572014-08-01 19:28:15 +000026#include "llvm/Object/Archive.h"
David Blaikie35907d82014-04-29 22:04:55 +000027#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Support/DynamicLibrary.h"
Torok Edwin6c2d2332009-07-07 17:32:34 +000030#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Support/Host.h"
Chris Lattner6d8dd182006-05-08 22:00:52 +000032#include "llvm/Support/MutexGuard.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/TargetRegistry.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000034#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +000035#include "llvm/Target/TargetMachine.h"
Anton Korobeynikov579f0712008-02-20 11:08:44 +000036#include <cmath>
37#include <cstring>
Chris Lattner29681de2003-11-19 21:08:57 +000038using namespace llvm;
Chris Lattner996fe012002-12-24 00:01:05 +000039
Chandler Carruthf58e3762014-04-22 03:04:17 +000040#define DEBUG_TYPE "jit"
41
Chris Lattnerc346ecd2006-12-19 22:43:32 +000042STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
43STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattner996fe012002-12-24 00:01:05 +000044
Daniel Dunbar70ff8b02010-11-17 16:06:37 +000045ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
David Blaikie196e3232014-09-02 22:41:07 +000046 std::unique_ptr<Module> M, std::string *ErrorStr,
Lang Hames4a5697e2014-12-03 00:51:19 +000047 std::unique_ptr<RTDyldMemoryManager> MCJMM,
48 std::unique_ptr<TargetMachine> TM) = nullptr;
Rafael Espindola2a8a2792014-08-19 04:04:25 +000049ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
Craig Topper2617dcc2014-04-15 06:32:26 +000050 std::string *ErrorStr) =nullptr;
Chris Lattner2d52c1b2006-03-22 06:07:50 +000051
Lang Hames7ea98e12014-11-27 01:41:16 +000052void JITEventListener::anchor() {}
53
Rafael Espindola2a8a2792014-08-19 04:04:25 +000054ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +000055 : EEState(*this),
Craig Topper2617dcc2014-04-15 06:32:26 +000056 LazyFunctionCreator(nullptr) {
Jeffrey Yasskin4567db42009-10-27 20:30:28 +000057 CompilingLazily = false;
Evan Chengcdc00602008-09-24 16:25:55 +000058 GVCompilationDisabled = false;
Evan Cheng84a90552008-06-17 16:49:02 +000059 SymbolSearchingDisabled = false;
Lang Hamesbc876012014-04-18 06:48:23 +000060
61 // IR module verification is enabled by default in debug builds, and disabled
62 // by default in release builds.
63#ifndef NDEBUG
64 VerifyModules = true;
65#else
66 VerifyModules = false;
67#endif
68
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000069 assert(M && "Module is null?");
Rafael Espindola2a8a2792014-08-19 04:04:25 +000070 Modules.push_back(std::move(M));
Misha Brukman260b0c82003-10-16 21:18:05 +000071}
72
Brian Gaeke92f8b302003-09-04 22:57:27 +000073ExecutionEngine::~ExecutionEngine() {
Reid Spencer603682a2007-03-03 18:19:18 +000074 clearAllGlobalMappings();
Brian Gaeke92f8b302003-09-04 22:57:27 +000075}
76
Jeffrey Yasskina4044332010-03-27 04:53:56 +000077namespace {
Daniel Dunbar868e3f02010-11-13 02:48:57 +000078/// \brief Helper class which uses a value handler to automatically deletes the
79/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskina4044332010-03-27 04:53:56 +000080class GVMemoryBlock : public CallbackVH {
81 GVMemoryBlock(const GlobalVariable *GV)
82 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
83
84public:
Daniel Dunbar868e3f02010-11-13 02:48:57 +000085 /// \brief Returns the address the GlobalVariable should be written into. The
86 /// GVMemoryBlock object prefixes that.
Micah Villmowcdfe20b2012-10-08 16:38:25 +000087 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
Chris Lattner229907c2011-07-18 04:54:35 +000088 Type *ElTy = GV->getType()->getElementType();
Jeffrey Yasskina4044332010-03-27 04:53:56 +000089 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
90 void *RawMemory = ::operator new(
David Majnemerf3cadce2014-10-20 06:13:33 +000091 RoundUpToAlignment(sizeof(GVMemoryBlock),
92 TD.getPreferredAlignment(GV))
Jeffrey Yasskina4044332010-03-27 04:53:56 +000093 + GVSize);
94 new(RawMemory) GVMemoryBlock(GV);
95 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
96 }
97
Craig Topperb51ff602014-03-08 07:51:20 +000098 void deleted() override {
Jeffrey Yasskina4044332010-03-27 04:53:56 +000099 // We allocated with operator new and with some extra memory hanging off the
100 // end, so don't just delete this. I'm not sure if this is actually
101 // required.
102 this->~GVMemoryBlock();
103 ::operator delete(this);
104 }
105};
106} // anonymous namespace
107
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000108char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000109 return GVMemoryBlock::Create(GV, *getDataLayout());
Nicolas Geoffray5457ce92008-10-25 15:41:43 +0000110}
111
David Blaikie35907d82014-04-29 22:04:55 +0000112void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
113 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
114}
115
Rafael Espindola7271c192014-08-26 21:04:04 +0000116void
117ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
118 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
119}
120
Rafael Espindola48af1c22014-08-19 18:44:46 +0000121void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolaacfd6282014-08-01 18:49:24 +0000122 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
123}
124
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000125bool ExecutionEngine::removeModule(Module *M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000126 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
127 Module *Found = I->get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000128 if (Found == M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000129 I->release();
Devang Patel324fe892007-10-15 19:56:32 +0000130 Modules.erase(I);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000131 clearGlobalMappingsFromModule(M);
132 return true;
Devang Patel324fe892007-10-15 19:56:32 +0000133 }
134 }
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000135 return false;
Nate Begeman617001d2009-01-23 19:27:28 +0000136}
137
Chris Lattner0621cae2006-08-16 01:24:12 +0000138Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
139 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000140 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattner0621cae2006-08-16 01:24:12 +0000141 return F;
142 }
Craig Topper2617dcc2014-04-15 06:32:26 +0000143 return nullptr;
Chris Lattner0621cae2006-08-16 01:24:12 +0000144}
145
146
Zachary Turner2f825df2014-06-16 20:54:28 +0000147void *ExecutionEngineState::RemoveMapping(const GlobalValue *ToUnmap) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000148 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000149 void *OldVal;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000150
151 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
152 // GlobalAddressMap.
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000153 if (I == GlobalAddressMap.end())
Craig Topper2617dcc2014-04-15 06:32:26 +0000154 OldVal = nullptr;
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000155 else {
156 OldVal = I->second;
157 GlobalAddressMap.erase(I);
158 }
159
160 GlobalAddressReverseMap.erase(OldVal);
161 return OldVal;
162}
163
Chris Lattner6d8dd182006-05-08 22:00:52 +0000164void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000165 MutexGuard locked(lock);
Evan Cheng5cc53c32008-09-18 07:54:21 +0000166
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000167 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar9813b0b2009-07-26 07:49:05 +0000168 << "\' to [" << Addr << "]\n";);
Zachary Turner2f825df2014-06-16 20:54:28 +0000169 void *&CurVal = EEState.getGlobalAddressMap()[GV];
Craig Topper2617dcc2014-04-15 06:32:26 +0000170 assert((!CurVal || !Addr) && "GlobalMapping already established!");
Chris Lattner6d8dd182006-05-08 22:00:52 +0000171 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000172
173 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000174 if (!EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000175 AssertingVH<const GlobalValue> &V =
Zachary Turner2f825df2014-06-16 20:54:28 +0000176 EEState.getGlobalAddressReverseMap()[Addr];
Craig Topper2617dcc2014-04-15 06:32:26 +0000177 assert((!V || !GV) && "GlobalMapping already established!");
Chris Lattner6d8dd182006-05-08 22:00:52 +0000178 V = GV;
179 }
180}
181
Chris Lattner6d8dd182006-05-08 22:00:52 +0000182void ExecutionEngine::clearAllGlobalMappings() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000183 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000184
Zachary Turner2f825df2014-06-16 20:54:28 +0000185 EEState.getGlobalAddressMap().clear();
186 EEState.getGlobalAddressReverseMap().clear();
Chris Lattner6d8dd182006-05-08 22:00:52 +0000187}
188
Nate Begeman8f83fc42008-05-21 16:34:48 +0000189void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000190 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000191
192 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Zachary Turner2f825df2014-06-16 20:54:28 +0000193 EEState.RemoveMapping(FI);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000194 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
195 GI != GE; ++GI)
Zachary Turner2f825df2014-06-16 20:54:28 +0000196 EEState.RemoveMapping(GI);
Nate Begeman8f83fc42008-05-21 16:34:48 +0000197}
198
Chris Lattneree181732008-04-04 04:47:41 +0000199void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000200 MutexGuard locked(lock);
Chris Lattneree181732008-04-04 04:47:41 +0000201
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000202 ExecutionEngineState::GlobalAddressMapTy &Map =
Zachary Turner2f825df2014-06-16 20:54:28 +0000203 EEState.getGlobalAddressMap();
Chris Lattneree181732008-04-04 04:47:41 +0000204
Chris Lattner6d8dd182006-05-08 22:00:52 +0000205 // Deleting from the mapping?
Craig Topper2617dcc2014-04-15 06:32:26 +0000206 if (!Addr)
Zachary Turner2f825df2014-06-16 20:54:28 +0000207 return EEState.RemoveMapping(GV);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000208
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000209 void *&CurVal = Map[GV];
Chris Lattneree181732008-04-04 04:47:41 +0000210 void *OldVal = CurVal;
211
Zachary Turner2f825df2014-06-16 20:54:28 +0000212 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
213 EEState.getGlobalAddressReverseMap().erase(CurVal);
Chris Lattner6d8dd182006-05-08 22:00:52 +0000214 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000215
216 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000217 if (!EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000218 AssertingVH<const GlobalValue> &V =
Zachary Turner2f825df2014-06-16 20:54:28 +0000219 EEState.getGlobalAddressReverseMap()[Addr];
Craig Topper2617dcc2014-04-15 06:32:26 +0000220 assert((!V || !GV) && "GlobalMapping already established!");
Chris Lattner6d8dd182006-05-08 22:00:52 +0000221 V = GV;
222 }
Chris Lattneree181732008-04-04 04:47:41 +0000223 return OldVal;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000224}
225
Chris Lattner6d8dd182006-05-08 22:00:52 +0000226void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000227 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000228
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000229 ExecutionEngineState::GlobalAddressMapTy::iterator I =
Zachary Turner2f825df2014-06-16 20:54:28 +0000230 EEState.getGlobalAddressMap().find(GV);
231 return I != EEState.getGlobalAddressMap().end() ? I->second : nullptr;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000232}
233
Chris Lattner748e8572003-12-31 20:21:04 +0000234const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000235 MutexGuard locked(lock);
Reid Spencer79876f52005-07-12 15:51:55 +0000236
Chris Lattner748e8572003-12-31 20:21:04 +0000237 // If we haven't computed the reverse mapping yet, do so first.
Zachary Turner2f825df2014-06-16 20:54:28 +0000238 if (EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000239 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Zachary Turner2f825df2014-06-16 20:54:28 +0000240 I = EEState.getGlobalAddressMap().begin(),
241 E = EEState.getGlobalAddressMap().end(); I != E; ++I)
242 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
Daniel Dunbare4f47432010-11-13 00:55:42 +0000243 I->second, I->first));
Chris Lattner748e8572003-12-31 20:21:04 +0000244 }
245
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000246 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Zachary Turner2f825df2014-06-16 20:54:28 +0000247 EEState.getGlobalAddressReverseMap().find(Addr);
248 return I != EEState.getGlobalAddressReverseMap().end() ? I->second : nullptr;
Chris Lattner748e8572003-12-31 20:21:04 +0000249}
Chris Lattner5a0d4822003-12-26 06:50:30 +0000250
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000251namespace {
252class ArgvArray {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000253 std::unique_ptr<char[]> Array;
254 std::vector<std::unique_ptr<char[]>> Values;
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000255public:
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000256 /// Turn a vector of strings into a nice argv style array of pointers to null
257 /// terminated strings.
258 void *reset(LLVMContext &C, ExecutionEngine *EE,
259 const std::vector<std::string> &InputArgv);
260};
261} // anonymous namespace
262void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
263 const std::vector<std::string> &InputArgv) {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000264 Values.clear(); // Free the old contents.
265 Values.reserve(InputArgv.size());
Chandler Carruth5da3f052012-11-01 09:14:31 +0000266 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000267 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000268
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000269 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
Chris Lattner229907c2011-07-18 04:54:35 +0000270 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000271
272 for (unsigned i = 0; i != InputArgv.size(); ++i) {
273 unsigned Size = InputArgv[i].size()+1;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000274 auto Dest = make_unique<char[]>(Size);
275 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
Misha Brukman835702a2005-04-21 22:36:52 +0000276
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000277 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
Chris Lattner5a0d4822003-12-26 06:50:30 +0000278 Dest[Size-1] = 0;
Misha Brukman835702a2005-04-21 22:36:52 +0000279
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000280 // Endian safe: Array[i] = (PointerTy)Dest;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000281 EE->StoreValueToMemory(PTOGV(Dest.get()),
282 (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
283 Values.push_back(std::move(Dest));
Chris Lattner5a0d4822003-12-26 06:50:30 +0000284 }
285
286 // Null terminate it
Craig Topper2617dcc2014-04-15 06:32:26 +0000287 EE->StoreValueToMemory(PTOGV(nullptr),
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000288 (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
Chris Lattner5a0d4822003-12-26 06:50:30 +0000289 SBytePtr);
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000290 return Array.get();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000291}
292
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000293void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000294 bool isDtors) {
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000295 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000296 GlobalVariable *GV = module.getNamedGlobal(Name);
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000297
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000298 // If this global has internal linkage, or if it has a use, then it must be
299 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
300 // this is the case, don't execute any of the global ctors, __main will do
301 // it.
302 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
303
Nick Lewycky0cbfcb22011-04-06 20:38:44 +0000304 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000305 // the init priority, which we ignore.
Chris Lattner00245f42012-01-24 13:41:11 +0000306 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
Craig Topper2617dcc2014-04-15 06:32:26 +0000307 if (!InitList)
Nick Lewycky0f857892011-04-11 22:11:20 +0000308 return;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000309 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner00245f42012-01-24 13:41:11 +0000310 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
Craig Topper2617dcc2014-04-15 06:32:26 +0000311 if (!CS) continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000312
313 Constant *FP = CS->getOperand(1);
314 if (FP->isNullValue())
Nick Lewycky0f857892011-04-11 22:11:20 +0000315 continue; // Found a sentinal value, ignore.
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000316
317 // Strip off constant expression casts.
318 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
319 if (CE->isCast())
320 FP = CE->getOperand(0);
321
322 // Execute the ctor/dtor function!
323 if (Function *F = dyn_cast<Function>(FP))
324 runFunction(F, std::vector<GenericValue>());
325
326 // FIXME: It is marginally lame that we just do nothing here if we see an
327 // entry we don't recognize. It might not be unreasonable for the verifier
328 // to not even allow this and just assert here.
329 }
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000330}
331
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000332void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
333 // Execute global ctors/dtors for each module in the program.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000334 for (std::unique_ptr<Module> &M : Modules)
335 runStaticConstructorsDestructors(*M, isDtors);
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000336}
337
Dan Gohmancf3e3012008-08-26 01:38:29 +0000338#ifndef NDEBUG
Duncan Sands1202d1b2007-12-14 19:38:31 +0000339/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
340static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
Chandler Carruth5da3f052012-11-01 09:14:31 +0000341 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Duncan Sands1202d1b2007-12-14 19:38:31 +0000342 for (unsigned i = 0; i < PtrSize; ++i)
343 if (*(i + (uint8_t*)Loc))
344 return false;
345 return true;
346}
Dan Gohmancf3e3012008-08-26 01:38:29 +0000347#endif
Duncan Sands1202d1b2007-12-14 19:38:31 +0000348
Chris Lattner5a0d4822003-12-26 06:50:30 +0000349int ExecutionEngine::runFunctionAsMain(Function *Fn,
350 const std::vector<std::string> &argv,
351 const char * const * envp) {
352 std::vector<GenericValue> GVArgs;
353 GenericValue GVArgc;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000354 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000355
356 // Check main() type
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000357 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattner229907c2011-07-18 04:54:35 +0000358 FunctionType *FTy = Fn->getFunctionType();
359 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000360
361 // Check the argument types.
362 if (NumArgs > 3)
363 report_fatal_error("Invalid number of arguments of main() supplied");
364 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
365 report_fatal_error("Invalid type for third argument of main() supplied");
366 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
367 report_fatal_error("Invalid type for second argument of main() supplied");
368 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
369 report_fatal_error("Invalid type for first argument of main() supplied");
370 if (!FTy->getReturnType()->isIntegerTy() &&
371 !FTy->getReturnType()->isVoidTy())
372 report_fatal_error("Invalid return type of main() supplied");
373
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000374 ArgvArray CArgv;
375 ArgvArray CEnv;
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000376 if (NumArgs) {
377 GVArgs.push_back(GVArgc); // Arg #0 = argc.
378 if (NumArgs > 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000379 // Arg #1 = argv.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000380 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands1202d1b2007-12-14 19:38:31 +0000381 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000382 "argv[0] was null after CreateArgv");
383 if (NumArgs > 2) {
384 std::vector<std::string> EnvVars;
385 for (unsigned i = 0; envp[i]; ++i)
386 EnvVars.push_back(envp[i]);
Owen Anderson55f1c092009-08-13 21:58:54 +0000387 // Arg #2 = envp.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000388 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000389 }
390 }
391 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000392
Reid Spencer87aa65f2007-03-06 03:04:04 +0000393 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000394}
395
Lang Hames4a5697e2014-12-03 00:51:19 +0000396EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
397 : M(std::move(M)), MCJMM(nullptr) {
398 InitEngine();
399}
400
401EngineBuilder::~EngineBuilder() {}
402
403EngineBuilder &EngineBuilder::setMCJITMemoryManager(
404 std::unique_ptr<RTDyldMemoryManager> mcjmm) {
405 MCJMM = std::move(mcjmm);
406 return *this;
407}
408
Alp Toker322db9e2014-05-31 21:26:17 +0000409void EngineBuilder::InitEngine() {
410 WhichEngine = EngineKind::Either;
411 ErrorStr = nullptr;
412 OptLevel = CodeGenOpt::Default;
413 MCJMM = nullptr;
Alp Toker322db9e2014-05-31 21:26:17 +0000414 Options = TargetOptions();
Alp Toker322db9e2014-05-31 21:26:17 +0000415 RelocModel = Reloc::Default;
416 CMModel = CodeModel::JITDefault;
Alp Toker322db9e2014-05-31 21:26:17 +0000417
418// IR module verification is enabled by default in debug builds, and disabled
419// by default in release builds.
420#ifndef NDEBUG
421 VerifyModules = true;
422#else
423 VerifyModules = false;
424#endif
425}
426
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000427ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000428 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000429
Nick Lewyckya53414f2008-03-08 02:49:45 +0000430 // Make sure we can resolve symbols in the program as well. The zero arg
431 // to the function tells DynamicLibrary to load the program, not a library.
Craig Topper2617dcc2014-04-15 06:32:26 +0000432 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
433 return nullptr;
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000434
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000435 // If the user specified a memory manager but didn't specify which engine to
436 // create, we assume they only want the JIT, and we fail if they only want
437 // the interpreter.
Lang Hames0f154902014-09-23 16:56:02 +0000438 if (MCJMM) {
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000439 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000440 WhichEngine = EngineKind::JIT;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000441 else {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000442 if (ErrorStr)
443 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000444 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000445 }
446 }
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000447
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000448 // Unless the interpreter was explicitly selected or the JIT is not linked,
449 // try making a JIT.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000450 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000451 Triple TT(M->getTargetTriple());
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000452 if (!TM->getTarget().hasJIT()) {
453 errs() << "WARNING: This target JIT is not designed for the host"
454 << " you are running. If bad things happen, please choose"
455 << " a different -march switch.\n";
456 }
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000457
Lang Hamesbc876012014-04-18 06:48:23 +0000458 ExecutionEngine *EE = nullptr;
Eric Christopher79cc1e32014-09-02 22:28:02 +0000459 if (ExecutionEngine::MCJITCtor)
Lang Hames4a5697e2014-12-03 00:51:19 +0000460 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MCJMM),
Lang Hames0f154902014-09-23 16:56:02 +0000461 std::move(TheTM));
Lang Hamesbc876012014-04-18 06:48:23 +0000462 if (EE) {
463 EE->setVerifyModules(VerifyModules);
464 return EE;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000465 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000466 }
467
468 // If we can't make a JIT and we didn't request one specifically, try making
469 // an interpreter instead.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000470 if (WhichEngine & EngineKind::Interpreter) {
471 if (ExecutionEngine::InterpCtor)
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000472 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
Chris Lattner8bcc6442009-09-23 02:03:49 +0000473 if (ErrorStr)
474 *ErrorStr = "Interpreter has not been linked in.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000475 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000476 }
Chris Lattner8bcc6442009-09-23 02:03:49 +0000477
Eric Christopher79cc1e32014-09-02 22:28:02 +0000478 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000479 if (ErrorStr)
480 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000481 }
482
Craig Topper2617dcc2014-04-15 06:32:26 +0000483 return nullptr;
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000484}
485
Chris Lattner996fe012002-12-24 00:01:05 +0000486void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke1678e852003-08-13 18:16:14 +0000487 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattner996fe012002-12-24 00:01:05 +0000488 return getPointerToFunction(F);
489
Zachary Turnerc04b8922014-06-20 21:07:14 +0000490 MutexGuard locked(lock);
Zachary Turner2f825df2014-06-16 20:54:28 +0000491 if (void *P = EEState.getGlobalAddressMap()[GV])
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000492 return P;
Jeff Cohen69e849012006-02-07 05:11:57 +0000493
494 // Global variable might have been added since interpreter started.
495 if (GlobalVariable *GVar =
496 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
497 EmitGlobalVariable(GVar);
498 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000499 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000500
Zachary Turner2f825df2014-06-16 20:54:28 +0000501 return EEState.getGlobalAddressMap()[GV];
Chris Lattner996fe012002-12-24 00:01:05 +0000502}
503
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000504/// \brief Converts a Constant* into a GenericValue, including handling of
505/// ConstantExpr values.
Chris Lattner996fe012002-12-24 00:01:05 +0000506GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000507 // If its undefined, return the garbage.
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000508 if (isa<UndefValue>(C)) {
509 GenericValue Result;
510 switch (C->getType()->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000511 default:
512 break;
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000513 case Type::IntegerTyID:
514 case Type::X86_FP80TyID:
515 case Type::FP128TyID:
516 case Type::PPC_FP128TyID:
517 // Although the value is undefined, we still have to construct an APInt
518 // with the correct bit width.
519 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
520 break;
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000521 case Type::StructTyID: {
522 // if the whole struct is 'undef' just reserve memory for the value.
523 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
524 unsigned int elemNum = STy->getNumElements();
525 Result.AggregateVal.resize(elemNum);
526 for (unsigned int i = 0; i < elemNum; ++i) {
527 Type *ElemTy = STy->getElementType(i);
528 if (ElemTy->isIntegerTy())
529 Result.AggregateVal[i].IntVal =
530 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
531 else if (ElemTy->isAggregateType()) {
532 const Constant *ElemUndef = UndefValue::get(ElemTy);
533 Result.AggregateVal[i] = getConstantValue(ElemUndef);
534 }
535 }
536 }
537 }
538 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000539 case Type::VectorTyID:
540 // if the whole vector is 'undef' just reserve memory for the value.
541 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
542 const Type *ElemTy = VTy->getElementType();
543 unsigned int elemNum = VTy->getNumElements();
544 Result.AggregateVal.resize(elemNum);
545 if (ElemTy->isIntegerTy())
546 for (unsigned int i = 0; i < elemNum; ++i)
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000547 Result.AggregateVal[i].IntVal =
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000548 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000549 break;
550 }
551 return Result;
552 }
Chris Lattner9de0d142003-04-23 19:01:49 +0000553
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000554 // Otherwise, if the value is a ConstantExpr...
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000555 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000556 Constant *Op0 = CE->getOperand(0);
Chris Lattner9de0d142003-04-23 19:01:49 +0000557 switch (CE->getOpcode()) {
558 case Instruction::GetElementPtr: {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000559 // Compute the index
Reid Spencer4fd528f2007-03-06 22:23:15 +0000560 GenericValue Result = getConstantValue(Op0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000561 APInt Offset(DL->getPointerSizeInBits(), 0);
562 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
Misha Brukman835702a2005-04-21 22:36:52 +0000563
Reid Spencer87aa65f2007-03-06 03:04:04 +0000564 char* tmp = (char*) Result.PointerVal;
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000565 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattner9de0d142003-04-23 19:01:49 +0000566 return Result;
567 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000568 case Instruction::Trunc: {
569 GenericValue GV = getConstantValue(Op0);
570 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
571 GV.IntVal = GV.IntVal.trunc(BitWidth);
572 return GV;
573 }
574 case Instruction::ZExt: {
575 GenericValue GV = getConstantValue(Op0);
576 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
577 GV.IntVal = GV.IntVal.zext(BitWidth);
578 return GV;
579 }
580 case Instruction::SExt: {
581 GenericValue GV = getConstantValue(Op0);
582 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
583 GV.IntVal = GV.IntVal.sext(BitWidth);
584 return GV;
585 }
586 case Instruction::FPTrunc: {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000587 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000588 GenericValue GV = getConstantValue(Op0);
589 GV.FloatVal = float(GV.DoubleVal);
590 return GV;
591 }
592 case Instruction::FPExt:{
Dale Johannesena1336cf2007-09-17 18:44:13 +0000593 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000594 GenericValue GV = getConstantValue(Op0);
595 GV.DoubleVal = double(GV.FloatVal);
596 return GV;
597 }
598 case Instruction::UIToFP: {
599 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000600 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000601 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000602 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000603 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000604 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000605 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000606 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000607 false,
608 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000609 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000610 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000611 return GV;
612 }
613 case Instruction::SIToFP: {
614 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000615 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000616 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000617 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000618 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000619 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000620 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000621 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000622 true,
623 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000624 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000625 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000626 return GV;
627 }
628 case Instruction::FPToUI: // double->APInt conversion handles sign
629 case Instruction::FPToSI: {
630 GenericValue GV = getConstantValue(Op0);
631 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000632 if (Op0->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000633 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000634 else if (Op0->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000635 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000636 else if (Op0->getType()->isX86_FP80Ty()) {
Tim Northover29178a32013-01-22 09:46:31 +0000637 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000638 uint64_t v;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000639 bool ignored;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000640 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000641 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000642 APFloat::rmTowardZero, &ignored);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000643 GV.IntVal = v; // endian?
644 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000645 return GV;
646 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000647 case Instruction::PtrToInt: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000648 GenericValue GV = getConstantValue(Op0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000649 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000650 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000651 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000652 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000653 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000654 return GV;
655 }
656 case Instruction::IntToPtr: {
657 GenericValue GV = getConstantValue(Op0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000658 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000659 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000660 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
661 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000662 return GV;
663 }
664 case Instruction::BitCast: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000665 GenericValue GV = getConstantValue(Op0);
Chris Lattner229907c2011-07-18 04:54:35 +0000666 Type* DestTy = CE->getType();
Reid Spencer4fd528f2007-03-06 22:23:15 +0000667 switch (Op0->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000668 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000669 case Type::IntegerTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000670 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnerfdd87902009-10-05 05:54:46 +0000671 if (DestTy->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000672 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000673 else if (DestTy->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000674 GV.DoubleVal = GV.IntVal.bitsToDouble();
675 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000676 case Type::FloatTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000677 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000678 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000679 break;
680 case Type::DoubleTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000681 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000682 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000683 break;
684 case Type::PointerTyID:
Duncan Sands19d0b472010-02-16 11:11:14 +0000685 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000686 break; // getConstantValue(Op0) above already converted it
687 }
688 return GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000689 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000690 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +0000691 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000692 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +0000693 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000694 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +0000695 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000696 case Instruction::UDiv:
697 case Instruction::SDiv:
698 case Instruction::URem:
699 case Instruction::SRem:
700 case Instruction::And:
701 case Instruction::Or:
702 case Instruction::Xor: {
703 GenericValue LHS = getConstantValue(Op0);
704 GenericValue RHS = getConstantValue(CE->getOperand(1));
705 GenericValue GV;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000706 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000707 default: llvm_unreachable("Bad add type!");
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000708 case Type::IntegerTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000709 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000710 default: llvm_unreachable("Invalid integer opcode");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000711 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
712 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
713 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
714 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
715 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
716 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
717 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
718 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
719 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
720 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
721 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000722 break;
723 case Type::FloatTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000724 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000725 default: llvm_unreachable("Invalid float opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000726 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000727 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000728 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000729 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000730 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000731 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000732 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000733 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000734 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000735 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000736 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000737 break;
738 case Type::DoubleTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000739 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000740 default: llvm_unreachable("Invalid double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000741 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000742 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000743 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000744 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000745 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000746 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000747 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000748 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000749 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000750 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000751 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000752 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000753 case Type::X86_FP80TyID:
754 case Type::PPC_FP128TyID:
755 case Type::FP128TyID: {
Tim Northover29178a32013-01-22 09:46:31 +0000756 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
757 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000758 switch (CE->getOpcode()) {
Daniel Dunbare4f47432010-11-13 00:55:42 +0000759 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000760 case Instruction::FAdd:
Tim Northover29178a32013-01-22 09:46:31 +0000761 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000762 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000763 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000764 case Instruction::FSub:
Tim Northover29178a32013-01-22 09:46:31 +0000765 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
766 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000767 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000768 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000769 case Instruction::FMul:
Tim Northover29178a32013-01-22 09:46:31 +0000770 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
771 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000772 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000773 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000774 case Instruction::FDiv:
Tim Northover29178a32013-01-22 09:46:31 +0000775 apfLHS.divide(APFloat(Sem, RHS.IntVal),
776 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000777 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000778 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000779 case Instruction::FRem:
Tim Northover29178a32013-01-22 09:46:31 +0000780 apfLHS.mod(APFloat(Sem, RHS.IntVal),
781 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000782 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000783 break;
784 }
785 }
786 break;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000787 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000788 return GV;
789 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000790 default:
791 break;
792 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000793
794 SmallString<256> Msg;
795 raw_svector_ostream OS(Msg);
796 OS << "ConstantExpr not handled: " << *CE;
797 report_fatal_error(OS.str());
Chris Lattner68cbcc32003-05-14 17:51:49 +0000798 }
Misha Brukman835702a2005-04-21 22:36:52 +0000799
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000800 // Otherwise, we have a simple constant.
Reid Spencer4fd528f2007-03-06 22:23:15 +0000801 GenericValue Result;
Chris Lattner6b727592004-06-17 18:19:28 +0000802 switch (C->getType()->getTypeID()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000803 case Type::FloatTyID:
804 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000805 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000806 case Type::DoubleTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000807 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer87aa65f2007-03-06 03:04:04 +0000808 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000809 case Type::X86_FP80TyID:
810 case Type::FP128TyID:
811 case Type::PPC_FP128TyID:
Dale Johannesen54306fe2008-10-09 18:53:47 +0000812 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000813 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000814 case Type::IntegerTyID:
815 Result.IntVal = cast<ConstantInt>(C)->getValue();
816 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000817 case Type::PointerTyID:
Reid Spencer6a0fd732004-07-18 00:41:27 +0000818 if (isa<ConstantPointerNull>(C))
Craig Topper2617dcc2014-04-15 06:32:26 +0000819 Result.PointerVal = nullptr;
Reid Spencer6a0fd732004-07-18 00:41:27 +0000820 else if (const Function *F = dyn_cast<Function>(C))
821 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000822 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer6a0fd732004-07-18 00:41:27 +0000823 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
824 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000825 llvm_unreachable("Unknown constant pointer type!");
Chris Lattner996fe012002-12-24 00:01:05 +0000826 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000827 case Type::VectorTyID: {
828 unsigned elemNum;
829 Type* ElemTy;
830 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
831 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
832 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
833
834 if (CDV) {
835 elemNum = CDV->getNumElements();
836 ElemTy = CDV->getElementType();
837 } else if (CV || CAZ) {
838 VectorType* VTy = dyn_cast<VectorType>(C->getType());
839 elemNum = VTy->getNumElements();
840 ElemTy = VTy->getElementType();
841 } else {
842 llvm_unreachable("Unknown constant vector type!");
843 }
844
845 Result.AggregateVal.resize(elemNum);
846 // Check if vector holds floats.
847 if(ElemTy->isFloatTy()) {
848 if (CAZ) {
849 GenericValue floatZero;
850 floatZero.FloatVal = 0.f;
851 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
852 floatZero);
853 break;
854 }
855 if(CV) {
856 for (unsigned i = 0; i < elemNum; ++i)
857 if (!isa<UndefValue>(CV->getOperand(i)))
858 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
859 CV->getOperand(i))->getValueAPF().convertToFloat();
860 break;
861 }
862 if(CDV)
863 for (unsigned i = 0; i < elemNum; ++i)
864 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
865
866 break;
867 }
868 // Check if vector holds doubles.
869 if (ElemTy->isDoubleTy()) {
870 if (CAZ) {
871 GenericValue doubleZero;
872 doubleZero.DoubleVal = 0.0;
873 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
874 doubleZero);
875 break;
876 }
877 if(CV) {
878 for (unsigned i = 0; i < elemNum; ++i)
879 if (!isa<UndefValue>(CV->getOperand(i)))
880 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
881 CV->getOperand(i))->getValueAPF().convertToDouble();
882 break;
883 }
884 if(CDV)
885 for (unsigned i = 0; i < elemNum; ++i)
886 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
887
888 break;
889 }
890 // Check if vector holds integers.
891 if (ElemTy->isIntegerTy()) {
892 if (CAZ) {
893 GenericValue intZero;
894 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
895 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
896 intZero);
897 break;
898 }
899 if(CV) {
900 for (unsigned i = 0; i < elemNum; ++i)
901 if (!isa<UndefValue>(CV->getOperand(i)))
902 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
903 CV->getOperand(i))->getValue();
904 else {
905 Result.AggregateVal[i].IntVal =
906 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
907 }
908 break;
909 }
910 if(CDV)
911 for (unsigned i = 0; i < elemNum; ++i)
912 Result.AggregateVal[i].IntVal = APInt(
913 CDV->getElementType()->getPrimitiveSizeInBits(),
914 CDV->getElementAsInteger(i));
915
916 break;
917 }
918 llvm_unreachable("Unknown constant pointer type!");
919 }
920 break;
921
Chris Lattner996fe012002-12-24 00:01:05 +0000922 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000923 SmallString<256> Msg;
924 raw_svector_ostream OS(Msg);
925 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
926 report_fatal_error(OS.str());
Chris Lattner996fe012002-12-24 00:01:05 +0000927 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000928
Chris Lattner996fe012002-12-24 00:01:05 +0000929 return Result;
930}
931
Duncan Sands1202d1b2007-12-14 19:38:31 +0000932/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
933/// with the integer held in IntVal.
934static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
935 unsigned StoreBytes) {
936 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divackyad06cee2012-09-05 22:26:57 +0000937 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands1202d1b2007-12-14 19:38:31 +0000938
Rafael Espindola41cb64f2013-04-15 14:44:24 +0000939 if (sys::IsLittleEndianHost) {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000940 // Little-endian host - the source is ordered from LSB to MSB. Order the
941 // destination from LSB to MSB: Do a straight copy.
942 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000943 } else {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000944 // Big-endian host - the source is an array of 64 bit words ordered from
945 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
946 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
947 while (StoreBytes > sizeof(uint64_t)) {
948 StoreBytes -= sizeof(uint64_t);
949 // May not be aligned so use memcpy.
950 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
951 Src += sizeof(uint64_t);
952 }
953
954 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
955 }
956}
957
Evan Cheng09053e62008-11-04 06:10:31 +0000958void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattner229907c2011-07-18 04:54:35 +0000959 GenericValue *Ptr, Type *Ty) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000960 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands1202d1b2007-12-14 19:38:31 +0000961
Reid Spencer87aa65f2007-03-06 03:04:04 +0000962 switch (Ty->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000963 default:
964 dbgs() << "Cannot store value of type " << *Ty << "!\n";
965 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +0000966 case Type::IntegerTyID:
967 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer87aa65f2007-03-06 03:04:04 +0000968 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000969 case Type::FloatTyID:
970 *((float*)Ptr) = Val.FloatVal;
971 break;
972 case Type::DoubleTyID:
973 *((double*)Ptr) = Val.DoubleVal;
974 break;
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +0000975 case Type::X86_FP80TyID:
976 memcpy(Ptr, Val.IntVal.getRawData(), 10);
977 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +0000978 case Type::PointerTyID:
979 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
980 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth93da3c82011-04-28 08:37:18 +0000981 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands1202d1b2007-12-14 19:38:31 +0000982
Reid Spencer87aa65f2007-03-06 03:04:04 +0000983 *((PointerTy*)Ptr) = Val.PointerVal;
984 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000985 case Type::VectorTyID:
986 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
987 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
988 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
989 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
990 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
991 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
992 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
993 StoreIntToMemory(Val.AggregateVal[i].IntVal,
994 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
995 }
996 }
997 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000998 }
Duncan Sands1202d1b2007-12-14 19:38:31 +0000999
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001000 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
Duncan Sands1202d1b2007-12-14 19:38:31 +00001001 // Host and target are different endian - reverse the stored bytes.
1002 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1003}
1004
1005/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1006/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1007static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1008 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greene82b63572013-01-14 21:04:45 +00001009 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1010 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands1202d1b2007-12-14 19:38:31 +00001011
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001012 if (sys::IsLittleEndianHost)
Duncan Sands1202d1b2007-12-14 19:38:31 +00001013 // Little-endian host - the destination must be ordered from LSB to MSB.
1014 // The source is ordered from LSB to MSB: Do a straight copy.
1015 memcpy(Dst, Src, LoadBytes);
1016 else {
1017 // Big-endian - the destination is an array of 64 bit words ordered from
1018 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1019 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1020 // a word.
1021 while (LoadBytes > sizeof(uint64_t)) {
1022 LoadBytes -= sizeof(uint64_t);
1023 // May not be aligned so use memcpy.
1024 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1025 Dst += sizeof(uint64_t);
1026 }
1027
1028 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1029 }
Chris Lattner996fe012002-12-24 00:01:05 +00001030}
1031
Misha Brukman857c21b2003-10-10 17:45:12 +00001032/// FIXME: document
1033///
Duncan Sands1202d1b2007-12-14 19:38:31 +00001034void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandscd4a6be2008-03-10 16:38:37 +00001035 GenericValue *Ptr,
Chris Lattner229907c2011-07-18 04:54:35 +00001036 Type *Ty) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001037 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands5c65cb42007-12-10 17:43:13 +00001038
Duncan Sands1202d1b2007-12-14 19:38:31 +00001039 switch (Ty->getTypeID()) {
1040 case Type::IntegerTyID:
1041 // An APInt with all words initially zero.
1042 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1043 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1044 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001045 case Type::FloatTyID:
1046 Result.FloatVal = *((float*)Ptr);
1047 break;
1048 case Type::DoubleTyID:
Duncan Sands1202d1b2007-12-14 19:38:31 +00001049 Result.DoubleVal = *((double*)Ptr);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001050 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001051 case Type::PointerTyID:
Reid Spencer87aa65f2007-03-06 03:04:04 +00001052 Result.PointerVal = *((PointerTy*)Ptr);
1053 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +00001054 case Type::X86_FP80TyID: {
1055 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands26d65392007-12-15 17:37:40 +00001056 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001057 uint64_t y[2];
1058 memcpy(y, Ptr, 10);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00001059 Result.IntVal = APInt(80, y);
Dale Johannesena1336cf2007-09-17 18:44:13 +00001060 break;
1061 }
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001062 case Type::VectorTyID: {
1063 const VectorType *VT = cast<VectorType>(Ty);
1064 const Type *ElemT = VT->getElementType();
1065 const unsigned numElems = VT->getNumElements();
1066 if (ElemT->isFloatTy()) {
1067 Result.AggregateVal.resize(numElems);
1068 for (unsigned i = 0; i < numElems; ++i)
1069 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1070 }
1071 if (ElemT->isDoubleTy()) {
1072 Result.AggregateVal.resize(numElems);
1073 for (unsigned i = 0; i < numElems; ++i)
1074 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1075 }
1076 if (ElemT->isIntegerTy()) {
1077 GenericValue intZero;
1078 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1079 intZero.IntVal = APInt(elemBitWidth, 0);
1080 Result.AggregateVal.resize(numElems, intZero);
1081 for (unsigned i = 0; i < numElems; ++i)
1082 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1083 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1084 }
1085 break;
1086 }
Reid Spencer87aa65f2007-03-06 03:04:04 +00001087 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001088 SmallString<256> Msg;
1089 raw_svector_ostream OS(Msg);
1090 OS << "Cannot load value of type " << *Ty << "!";
1091 report_fatal_error(OS.str());
Chris Lattner7f389e82003-05-08 16:52:16 +00001092 }
Chris Lattner7f389e82003-05-08 16:52:16 +00001093}
1094
Chris Lattner996fe012002-12-24 00:01:05 +00001095void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene0967d2d2010-01-05 01:27:39 +00001096 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesenb086d382008-08-07 01:30:15 +00001097 DEBUG(Init->dump());
Chris Lattner00245f42012-01-24 13:41:11 +00001098 if (isa<UndefValue>(Init))
Chris Lattner61753bf2004-10-16 18:19:26 +00001099 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001100
1101 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino69d62132006-01-20 18:18:40 +00001102 unsigned ElementSize =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001103 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino69d62132006-01-20 18:18:40 +00001104 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1105 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1106 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001107 }
1108
1109 if (isa<ConstantAggregateZero>(Init)) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001110 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
Chris Lattner1dd86b12008-02-15 00:57:28 +00001111 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001112 }
1113
1114 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001115 unsigned ElementSize =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001116 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001117 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1118 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1119 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001120 }
1121
1122 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001123 const StructLayout *SL =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001124 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001125 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1126 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1127 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001128 }
1129
1130 if (const ConstantDataSequential *CDS =
1131 dyn_cast<ConstantDataSequential>(Init)) {
1132 // CDS is already laid out in host memory order.
1133 StringRef Data = CDS->getRawDataValues();
1134 memcpy(Addr, Data.data(), Data.size());
1135 return;
1136 }
1137
1138 if (Init->getType()->isFirstClassType()) {
Chris Lattner996fe012002-12-24 00:01:05 +00001139 GenericValue Val = getConstantValue(Init);
1140 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1141 return;
1142 }
1143
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001144 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinfbcc6632009-07-14 16:55:14 +00001145 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattner996fe012002-12-24 00:01:05 +00001146}
1147
Chris Lattner996fe012002-12-24 00:01:05 +00001148/// EmitGlobals - Emit all of the global variables to memory, storing their
1149/// addresses into GlobalAddress. This must make sure to copy the contents of
1150/// their initializers into the memory.
Chris Lattner996fe012002-12-24 00:01:05 +00001151void ExecutionEngine::emitGlobals() {
Chris Lattner996fe012002-12-24 00:01:05 +00001152 // Loop over all of the global variables in the program, allocating the memory
Chris Lattner0621cae2006-08-16 01:24:12 +00001153 // to hold them. If there is more than one module, do a prepass over globals
1154 // to figure out how the different modules should link together.
Chris Lattner229907c2011-07-18 04:54:35 +00001155 std::map<std::pair<std::string, Type*>,
Chris Lattner0621cae2006-08-16 01:24:12 +00001156 const GlobalValue*> LinkedGlobalsMap;
Misha Brukman835702a2005-04-21 22:36:52 +00001157
Chris Lattner0621cae2006-08-16 01:24:12 +00001158 if (Modules.size() != 1) {
1159 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001160 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001161 for (const auto &GV : M.globals()) {
1162 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1163 GV.hasAppendingLinkage() || !GV.hasName())
Chris Lattner0621cae2006-08-16 01:24:12 +00001164 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001165
1166 const GlobalValue *&GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001167 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
Chris Lattner0621cae2006-08-16 01:24:12 +00001168
1169 // If this is the first time we've seen this global, it is the canonical
1170 // version.
1171 if (!GVEntry) {
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001172 GVEntry = &GV;
Chris Lattner0621cae2006-08-16 01:24:12 +00001173 continue;
1174 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001175
Chris Lattner0621cae2006-08-16 01:24:12 +00001176 // If the existing global is strong, never replace it.
Nico Rieck7157bb72014-01-14 15:22:47 +00001177 if (GVEntry->hasExternalLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +00001178 continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001179
Chris Lattner0621cae2006-08-16 01:24:12 +00001180 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesence4396b2008-05-14 20:12:51 +00001181 // symbol. FIXME is this right for common?
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001182 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1183 GVEntry = &GV;
Chris Lattner9de0d142003-04-23 19:01:49 +00001184 }
Chris Lattner996fe012002-12-24 00:01:05 +00001185 }
Chris Lattner0621cae2006-08-16 01:24:12 +00001186 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001187
Chris Lattner0621cae2006-08-16 01:24:12 +00001188 std::vector<const GlobalValue*> NonCanonicalGlobals;
1189 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001190 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001191 for (const auto &GV : M.globals()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001192 // In the multi-module case, see what this global maps to.
1193 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001194 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001195 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001196 // If something else is the canonical global, ignore this one.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001197 if (GVEntry != &GV) {
1198 NonCanonicalGlobals.push_back(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001199 continue;
1200 }
1201 }
1202 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001203
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001204 if (!GV.isDeclaration()) {
1205 addGlobalMapping(&GV, getMemoryForGV(&GV));
Chris Lattner0621cae2006-08-16 01:24:12 +00001206 } else {
1207 // External variable reference. Try to use the dynamic loader to
1208 // get a pointer to it.
1209 if (void *SymAddr =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001210 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1211 addGlobalMapping(&GV, SymAddr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001212 else {
Chris Lattner2104b8d2010-04-07 22:58:41 +00001213 report_fatal_error("Could not resolve external global address: "
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001214 +GV.getName());
Chris Lattner0621cae2006-08-16 01:24:12 +00001215 }
1216 }
1217 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001218
Chris Lattner0621cae2006-08-16 01:24:12 +00001219 // If there are multiple modules, map the non-canonical globals to their
1220 // canonical location.
1221 if (!NonCanonicalGlobals.empty()) {
1222 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1223 const GlobalValue *GV = NonCanonicalGlobals[i];
1224 const GlobalValue *CGV =
1225 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1226 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1227 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesa67f06b2008-10-14 10:04:52 +00001228 addGlobalMapping(GV, Ptr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001229 }
1230 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001231
1232 // Now that all of the globals are set up in memory, loop through them all
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001233 // and initialize their contents.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001234 for (const auto &GV : M.globals()) {
1235 if (!GV.isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001236 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001237 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001238 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1239 if (GVEntry != &GV) // Not the canonical variable.
Chris Lattner0621cae2006-08-16 01:24:12 +00001240 continue;
1241 }
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001242 EmitGlobalVariable(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001243 }
1244 }
1245 }
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001246}
1247
1248// EmitGlobalVariable - This method emits the specified global variable to the
1249// address specified in GlobalAddresses, or allocates new memory if it's not
1250// already in the map.
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +00001251void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner748e8572003-12-31 20:21:04 +00001252 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattnerdc631732004-02-08 19:33:23 +00001253
Craig Topper2617dcc2014-04-15 06:32:26 +00001254 if (!GA) {
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001255 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001256 GA = getMemoryForGV(GV);
Andrew Kaylor3b442372013-11-15 17:52:54 +00001257
1258 // If we failed to allocate memory for this global, return.
Craig Topper2617dcc2014-04-15 06:32:26 +00001259 if (!GA) return;
Andrew Kaylor3b442372013-11-15 17:52:54 +00001260
Chris Lattner748e8572003-12-31 20:21:04 +00001261 addGlobalMapping(GV, GA);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001262 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001263
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001264 // Don't initialize if it's thread local, let the client do it.
1265 if (!GV->isThreadLocal())
1266 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001267
Chris Lattner229907c2011-07-18 04:54:35 +00001268 Type *ElTy = GV->getType()->getElementType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001269 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
Chris Lattnerdf1f1522005-01-08 20:13:19 +00001270 NumInitBytes += (unsigned)GVSize;
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001271 ++NumGlobals;
Chris Lattner996fe012002-12-24 00:01:05 +00001272}
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001273
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +00001274ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1275 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001276}
1277
Zachary Turnerc04b8922014-06-20 21:07:14 +00001278sys::Mutex *
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001279ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +00001280 return &EES->EE.lock;
1281}
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001282
1283void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1284 const GlobalValue *Old) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +00001285 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1286 EES->GlobalAddressReverseMap.erase(OldVal);
1287}
1288
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001289void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1290 const GlobalValue *,
1291 const GlobalValue *) {
Craig Toppera2886c22012-02-07 05:05:23 +00001292 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1293 " RAUW on a value it has a global mapping for.");
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001294}