blob: c2ff8e27af47a4ac65a14d4c206fa63b506089fd [file] [log] [blame]
Misha Brukman857c21b2003-10-10 17:45:12 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukman835702a2005-04-21 22:36:52 +00009//
Chris Lattner996fe012002-12-24 00:01:05 +000010// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +000015#include "llvm/ExecutionEngine/ExecutionEngine.h"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000016#include "llvm/ADT/STLExtras.h"
Daniel Dunbar868e3f02010-11-13 02:48:57 +000017#include "llvm/ADT/SmallString.h"
Chris Lattner390d78b2009-08-23 22:49:13 +000018#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ExecutionEngine/GenericValue.h"
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000020#include "llvm/ExecutionEngine/JITEventListener.h"
Lang Hames633fe142015-03-30 03:37:06 +000021#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DerivedTypes.h"
Lang Hames3dac3f72015-03-31 20:31:14 +000025#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Module.h"
27#include "llvm/IR/Operator.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000028#include "llvm/IR/ValueHandle.h"
Rafael Espindoladd396572014-08-01 19:28:15 +000029#include "llvm/Object/Archive.h"
David Blaikie35907d82014-04-29 22:04:55 +000030#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000031#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Support/DynamicLibrary.h"
Torok Edwin6c2d2332009-07-07 17:32:34 +000033#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/Host.h"
Chris Lattner6d8dd182006-05-08 22:00:52 +000035#include "llvm/Support/MutexGuard.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Support/TargetRegistry.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000037#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +000038#include "llvm/Target/TargetMachine.h"
Anton Korobeynikov579f0712008-02-20 11:08:44 +000039#include <cmath>
40#include <cstring>
Chris Lattner29681de2003-11-19 21:08:57 +000041using namespace llvm;
Chris Lattner996fe012002-12-24 00:01:05 +000042
Chandler Carruthf58e3762014-04-22 03:04:17 +000043#define DEBUG_TYPE "jit"
44
Chris Lattnerc346ecd2006-12-19 22:43:32 +000045STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
46STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattner996fe012002-12-24 00:01:05 +000047
Daniel Dunbar70ff8b02010-11-17 16:06:37 +000048ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
David Blaikie196e3232014-09-02 22:41:07 +000049 std::unique_ptr<Module> M, std::string *ErrorStr,
Lang Hames633fe142015-03-30 03:37:06 +000050 std::shared_ptr<MCJITMemoryManager> MemMgr,
51 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
Lang Hames4a5697e2014-12-03 00:51:19 +000052 std::unique_ptr<TargetMachine> TM) = nullptr;
Lang Hames93de2a12015-01-23 21:25:00 +000053
54ExecutionEngine *(*ExecutionEngine::OrcMCJITReplacementCtor)(
Lang Hames633fe142015-03-30 03:37:06 +000055 std::string *ErrorStr, std::shared_ptr<MCJITMemoryManager> MemMgr,
56 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
Lang Hames93de2a12015-01-23 21:25:00 +000057 std::unique_ptr<TargetMachine> TM) = nullptr;
58
Rafael Espindola2a8a2792014-08-19 04:04:25 +000059ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
Craig Topper2617dcc2014-04-15 06:32:26 +000060 std::string *ErrorStr) =nullptr;
Chris Lattner2d52c1b2006-03-22 06:07:50 +000061
Lang Hames7ea98e12014-11-27 01:41:16 +000062void JITEventListener::anchor() {}
63
Rafael Espindola2a8a2792014-08-19 04:04:25 +000064ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
Lang Hames3dac3f72015-03-31 20:31:14 +000065 : LazyFunctionCreator(nullptr) {
Jeffrey Yasskin4567db42009-10-27 20:30:28 +000066 CompilingLazily = false;
Evan Chengcdc00602008-09-24 16:25:55 +000067 GVCompilationDisabled = false;
Evan Cheng84a90552008-06-17 16:49:02 +000068 SymbolSearchingDisabled = false;
Lang Hamesbc876012014-04-18 06:48:23 +000069
70 // IR module verification is enabled by default in debug builds, and disabled
71 // by default in release builds.
72#ifndef NDEBUG
73 VerifyModules = true;
74#else
75 VerifyModules = false;
76#endif
77
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000078 assert(M && "Module is null?");
Rafael Espindola2a8a2792014-08-19 04:04:25 +000079 Modules.push_back(std::move(M));
Misha Brukman260b0c82003-10-16 21:18:05 +000080}
81
Brian Gaeke92f8b302003-09-04 22:57:27 +000082ExecutionEngine::~ExecutionEngine() {
Reid Spencer603682a2007-03-03 18:19:18 +000083 clearAllGlobalMappings();
Brian Gaeke92f8b302003-09-04 22:57:27 +000084}
85
Jeffrey Yasskina4044332010-03-27 04:53:56 +000086namespace {
Daniel Dunbar868e3f02010-11-13 02:48:57 +000087/// \brief Helper class which uses a value handler to automatically deletes the
88/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskina4044332010-03-27 04:53:56 +000089class GVMemoryBlock : public CallbackVH {
90 GVMemoryBlock(const GlobalVariable *GV)
91 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
92
93public:
Daniel Dunbar868e3f02010-11-13 02:48:57 +000094 /// \brief Returns the address the GlobalVariable should be written into. The
95 /// GVMemoryBlock object prefixes that.
Micah Villmowcdfe20b2012-10-08 16:38:25 +000096 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
Chris Lattner229907c2011-07-18 04:54:35 +000097 Type *ElTy = GV->getType()->getElementType();
Jeffrey Yasskina4044332010-03-27 04:53:56 +000098 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
99 void *RawMemory = ::operator new(
David Majnemerf3cadce2014-10-20 06:13:33 +0000100 RoundUpToAlignment(sizeof(GVMemoryBlock),
101 TD.getPreferredAlignment(GV))
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000102 + GVSize);
103 new(RawMemory) GVMemoryBlock(GV);
104 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
105 }
106
Craig Topperb51ff602014-03-08 07:51:20 +0000107 void deleted() override {
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000108 // We allocated with operator new and with some extra memory hanging off the
109 // end, so don't just delete this. I'm not sure if this is actually
110 // required.
111 this->~GVMemoryBlock();
112 ::operator delete(this);
113 }
114};
115} // anonymous namespace
116
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000117char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000118 return GVMemoryBlock::Create(GV, *getDataLayout());
Nicolas Geoffray5457ce92008-10-25 15:41:43 +0000119}
120
David Blaikie35907d82014-04-29 22:04:55 +0000121void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
122 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
123}
124
Rafael Espindola7271c192014-08-26 21:04:04 +0000125void
126ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
127 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
128}
129
Rafael Espindola48af1c22014-08-19 18:44:46 +0000130void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolaacfd6282014-08-01 18:49:24 +0000131 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
132}
133
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000134bool ExecutionEngine::removeModule(Module *M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000135 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
136 Module *Found = I->get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000137 if (Found == M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000138 I->release();
Devang Patel324fe892007-10-15 19:56:32 +0000139 Modules.erase(I);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000140 clearGlobalMappingsFromModule(M);
141 return true;
Devang Patel324fe892007-10-15 19:56:32 +0000142 }
143 }
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000144 return false;
Nate Begeman617001d2009-01-23 19:27:28 +0000145}
146
Chris Lattner0621cae2006-08-16 01:24:12 +0000147Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
148 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Keno Fischer5f92a082015-01-27 19:29:00 +0000149 Function *F = Modules[i]->getFunction(FnName);
150 if (F && !F->isDeclaration())
Chris Lattner0621cae2006-08-16 01:24:12 +0000151 return F;
152 }
Craig Topper2617dcc2014-04-15 06:32:26 +0000153 return nullptr;
Chris Lattner0621cae2006-08-16 01:24:12 +0000154}
155
Keno Fischer73378eb2015-06-20 00:55:58 +0000156GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
157 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
158 GlobalVariable *GV = Modules[i]->getGlobalVariable(Name,AllowInternal);
159 if (GV && !GV->isDeclaration())
160 return GV;
161 }
162 return nullptr;
163}
Chris Lattner0621cae2006-08-16 01:24:12 +0000164
Lang Hames3dac3f72015-03-31 20:31:14 +0000165uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
166 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
167 uint64_t OldVal;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000168
169 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
170 // GlobalAddressMap.
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000171 if (I == GlobalAddressMap.end())
Lang Hames3dac3f72015-03-31 20:31:14 +0000172 OldVal = 0;
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000173 else {
Lang Hames3dac3f72015-03-31 20:31:14 +0000174 GlobalAddressReverseMap.erase(I->second);
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000175 OldVal = I->second;
176 GlobalAddressMap.erase(I);
177 }
178
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000179 return OldVal;
180}
181
Lang Hames3dac3f72015-03-31 20:31:14 +0000182std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
183 MutexGuard locked(lock);
Rafael Espindolac233f742015-06-23 13:59:29 +0000184 Mangler Mang;
Lang Hames3dac3f72015-03-31 20:31:14 +0000185 SmallString<128> FullName;
Rafael Espindolac233f742015-06-23 13:59:29 +0000186 Mang.getNameWithPrefix(FullName, GV, false);
Lang Hames3dac3f72015-03-31 20:31:14 +0000187 return FullName.str();
188}
189
Chris Lattner6d8dd182006-05-08 22:00:52 +0000190void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000191 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000192 addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
193}
Evan Cheng5cc53c32008-09-18 07:54:21 +0000194
Lang Hames3dac3f72015-03-31 20:31:14 +0000195void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
196 MutexGuard locked(lock);
197
198 assert(!Name.empty() && "Empty GlobalMapping symbol name!");
199
200 DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
201 uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
Craig Topper2617dcc2014-04-15 06:32:26 +0000202 assert((!CurVal || !Addr) && "GlobalMapping already established!");
Chris Lattner6d8dd182006-05-08 22:00:52 +0000203 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000204
205 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000206 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames3dac3f72015-03-31 20:31:14 +0000207 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
208 assert((!V.empty() || !Name.empty()) &&
209 "GlobalMapping already established!");
210 V = Name;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000211 }
212}
213
Chris Lattner6d8dd182006-05-08 22:00:52 +0000214void ExecutionEngine::clearAllGlobalMappings() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000215 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000216
Zachary Turner2f825df2014-06-16 20:54:28 +0000217 EEState.getGlobalAddressMap().clear();
218 EEState.getGlobalAddressReverseMap().clear();
Chris Lattner6d8dd182006-05-08 22:00:52 +0000219}
220
Nate Begeman8f83fc42008-05-21 16:34:48 +0000221void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000222 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000223
224 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Lang Hames3dac3f72015-03-31 20:31:14 +0000225 EEState.RemoveMapping(getMangledName(FI));
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000226 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
227 GI != GE; ++GI)
Lang Hames3dac3f72015-03-31 20:31:14 +0000228 EEState.RemoveMapping(getMangledName(GI));
Nate Begeman8f83fc42008-05-21 16:34:48 +0000229}
230
Lang Hames3dac3f72015-03-31 20:31:14 +0000231uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
232 void *Addr) {
233 MutexGuard locked(lock);
234 return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
235}
236
237uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000238 MutexGuard locked(lock);
Chris Lattneree181732008-04-04 04:47:41 +0000239
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000240 ExecutionEngineState::GlobalAddressMapTy &Map =
Zachary Turner2f825df2014-06-16 20:54:28 +0000241 EEState.getGlobalAddressMap();
Chris Lattneree181732008-04-04 04:47:41 +0000242
Chris Lattner6d8dd182006-05-08 22:00:52 +0000243 // Deleting from the mapping?
Craig Topper2617dcc2014-04-15 06:32:26 +0000244 if (!Addr)
Lang Hames3dac3f72015-03-31 20:31:14 +0000245 return EEState.RemoveMapping(Name);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000246
Lang Hames3dac3f72015-03-31 20:31:14 +0000247 uint64_t &CurVal = Map[Name];
248 uint64_t OldVal = CurVal;
Chris Lattneree181732008-04-04 04:47:41 +0000249
Zachary Turner2f825df2014-06-16 20:54:28 +0000250 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
251 EEState.getGlobalAddressReverseMap().erase(CurVal);
Chris Lattner6d8dd182006-05-08 22:00:52 +0000252 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000253
254 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000255 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames3dac3f72015-03-31 20:31:14 +0000256 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
257 assert((!V.empty() || !Name.empty()) &&
258 "GlobalMapping already established!");
259 V = Name;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000260 }
Chris Lattneree181732008-04-04 04:47:41 +0000261 return OldVal;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000262}
263
Lang Hames3dac3f72015-03-31 20:31:14 +0000264uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
265 MutexGuard locked(lock);
266 uint64_t Address = 0;
267 ExecutionEngineState::GlobalAddressMapTy::iterator I =
268 EEState.getGlobalAddressMap().find(S);
269 if (I != EEState.getGlobalAddressMap().end())
270 Address = I->second;
271 return Address;
272}
273
274
275void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
276 MutexGuard locked(lock);
277 if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
278 return Address;
279 return nullptr;
280}
281
Chris Lattner6d8dd182006-05-08 22:00:52 +0000282void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000283 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000284 return getPointerToGlobalIfAvailable(getMangledName(GV));
Chris Lattner6d8dd182006-05-08 22:00:52 +0000285}
286
Chris Lattner748e8572003-12-31 20:21:04 +0000287const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000288 MutexGuard locked(lock);
Reid Spencer79876f52005-07-12 15:51:55 +0000289
Chris Lattner748e8572003-12-31 20:21:04 +0000290 // If we haven't computed the reverse mapping yet, do so first.
Zachary Turner2f825df2014-06-16 20:54:28 +0000291 if (EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000292 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Lang Hames3dac3f72015-03-31 20:31:14 +0000293 I = EEState.getGlobalAddressMap().begin(),
294 E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
295 StringRef Name = I->first();
296 uint64_t Addr = I->second;
Zachary Turner2f825df2014-06-16 20:54:28 +0000297 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
Lang Hames3dac3f72015-03-31 20:31:14 +0000298 Addr, Name));
299 }
Chris Lattner748e8572003-12-31 20:21:04 +0000300 }
301
Lang Hames3dac3f72015-03-31 20:31:14 +0000302 std::map<uint64_t, std::string>::iterator I =
303 EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);
304
305 if (I != EEState.getGlobalAddressReverseMap().end()) {
306 StringRef Name = I->second;
307 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
308 if (GlobalValue *GV = Modules[i]->getNamedValue(Name))
309 return GV;
310 }
311 return nullptr;
Chris Lattner748e8572003-12-31 20:21:04 +0000312}
Chris Lattner5a0d4822003-12-26 06:50:30 +0000313
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000314namespace {
315class ArgvArray {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000316 std::unique_ptr<char[]> Array;
317 std::vector<std::unique_ptr<char[]>> Values;
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000318public:
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000319 /// Turn a vector of strings into a nice argv style array of pointers to null
320 /// terminated strings.
321 void *reset(LLVMContext &C, ExecutionEngine *EE,
322 const std::vector<std::string> &InputArgv);
323};
324} // anonymous namespace
325void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
326 const std::vector<std::string> &InputArgv) {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000327 Values.clear(); // Free the old contents.
328 Values.reserve(InputArgv.size());
Chandler Carruth5da3f052012-11-01 09:14:31 +0000329 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000330 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000331
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000332 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
Chris Lattner229907c2011-07-18 04:54:35 +0000333 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000334
335 for (unsigned i = 0; i != InputArgv.size(); ++i) {
336 unsigned Size = InputArgv[i].size()+1;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000337 auto Dest = make_unique<char[]>(Size);
338 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
Misha Brukman835702a2005-04-21 22:36:52 +0000339
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000340 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
Chris Lattner5a0d4822003-12-26 06:50:30 +0000341 Dest[Size-1] = 0;
Misha Brukman835702a2005-04-21 22:36:52 +0000342
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000343 // Endian safe: Array[i] = (PointerTy)Dest;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000344 EE->StoreValueToMemory(PTOGV(Dest.get()),
345 (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
346 Values.push_back(std::move(Dest));
Chris Lattner5a0d4822003-12-26 06:50:30 +0000347 }
348
349 // Null terminate it
Craig Topper2617dcc2014-04-15 06:32:26 +0000350 EE->StoreValueToMemory(PTOGV(nullptr),
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000351 (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
Chris Lattner5a0d4822003-12-26 06:50:30 +0000352 SBytePtr);
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000353 return Array.get();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000354}
355
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000356void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000357 bool isDtors) {
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000358 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000359 GlobalVariable *GV = module.getNamedGlobal(Name);
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000360
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000361 // If this global has internal linkage, or if it has a use, then it must be
362 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
363 // this is the case, don't execute any of the global ctors, __main will do
364 // it.
365 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
366
Nick Lewycky0cbfcb22011-04-06 20:38:44 +0000367 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000368 // the init priority, which we ignore.
Chris Lattner00245f42012-01-24 13:41:11 +0000369 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
Craig Topper2617dcc2014-04-15 06:32:26 +0000370 if (!InitList)
Nick Lewycky0f857892011-04-11 22:11:20 +0000371 return;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000372 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner00245f42012-01-24 13:41:11 +0000373 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
Craig Topper2617dcc2014-04-15 06:32:26 +0000374 if (!CS) continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000375
376 Constant *FP = CS->getOperand(1);
377 if (FP->isNullValue())
Nick Lewycky0f857892011-04-11 22:11:20 +0000378 continue; // Found a sentinal value, ignore.
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000379
380 // Strip off constant expression casts.
381 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
382 if (CE->isCast())
383 FP = CE->getOperand(0);
384
385 // Execute the ctor/dtor function!
386 if (Function *F = dyn_cast<Function>(FP))
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000387 runFunction(F, None);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000388
389 // FIXME: It is marginally lame that we just do nothing here if we see an
390 // entry we don't recognize. It might not be unreasonable for the verifier
391 // to not even allow this and just assert here.
392 }
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000393}
394
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000395void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
396 // Execute global ctors/dtors for each module in the program.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000397 for (std::unique_ptr<Module> &M : Modules)
398 runStaticConstructorsDestructors(*M, isDtors);
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000399}
400
Dan Gohmancf3e3012008-08-26 01:38:29 +0000401#ifndef NDEBUG
Duncan Sands1202d1b2007-12-14 19:38:31 +0000402/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
403static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
Chandler Carruth5da3f052012-11-01 09:14:31 +0000404 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Duncan Sands1202d1b2007-12-14 19:38:31 +0000405 for (unsigned i = 0; i < PtrSize; ++i)
406 if (*(i + (uint8_t*)Loc))
407 return false;
408 return true;
409}
Dan Gohmancf3e3012008-08-26 01:38:29 +0000410#endif
Duncan Sands1202d1b2007-12-14 19:38:31 +0000411
Chris Lattner5a0d4822003-12-26 06:50:30 +0000412int ExecutionEngine::runFunctionAsMain(Function *Fn,
413 const std::vector<std::string> &argv,
414 const char * const * envp) {
415 std::vector<GenericValue> GVArgs;
416 GenericValue GVArgc;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000417 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000418
419 // Check main() type
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000420 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattner229907c2011-07-18 04:54:35 +0000421 FunctionType *FTy = Fn->getFunctionType();
422 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000423
424 // Check the argument types.
425 if (NumArgs > 3)
426 report_fatal_error("Invalid number of arguments of main() supplied");
427 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
428 report_fatal_error("Invalid type for third argument of main() supplied");
429 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
430 report_fatal_error("Invalid type for second argument of main() supplied");
431 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
432 report_fatal_error("Invalid type for first argument of main() supplied");
433 if (!FTy->getReturnType()->isIntegerTy() &&
434 !FTy->getReturnType()->isVoidTy())
435 report_fatal_error("Invalid return type of main() supplied");
436
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000437 ArgvArray CArgv;
438 ArgvArray CEnv;
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000439 if (NumArgs) {
440 GVArgs.push_back(GVArgc); // Arg #0 = argc.
441 if (NumArgs > 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000442 // Arg #1 = argv.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000443 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands1202d1b2007-12-14 19:38:31 +0000444 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000445 "argv[0] was null after CreateArgv");
446 if (NumArgs > 2) {
447 std::vector<std::string> EnvVars;
448 for (unsigned i = 0; envp[i]; ++i)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000449 EnvVars.emplace_back(envp[i]);
Owen Anderson55f1c092009-08-13 21:58:54 +0000450 // Arg #2 = envp.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000451 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000452 }
453 }
454 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000455
Reid Spencer87aa65f2007-03-06 03:04:04 +0000456 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000457}
458
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000459EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
Lang Hames93de2a12015-01-23 21:25:00 +0000460
Lang Hames4a5697e2014-12-03 00:51:19 +0000461EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000462 : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
Lang Hames633fe142015-03-30 03:37:06 +0000463 OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr),
464 RelocModel(Reloc::Default), CMModel(CodeModel::JITDefault),
465 UseOrcMCJITReplacement(false) {
Alp Toker322db9e2014-05-31 21:26:17 +0000466// IR module verification is enabled by default in debug builds, and disabled
467// by default in release builds.
468#ifndef NDEBUG
469 VerifyModules = true;
470#else
471 VerifyModules = false;
472#endif
473}
474
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000475EngineBuilder::~EngineBuilder() = default;
476
477EngineBuilder &EngineBuilder::setMCJITMemoryManager(
478 std::unique_ptr<RTDyldMemoryManager> mcjmm) {
Lang Hames633fe142015-03-30 03:37:06 +0000479 auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
480 MemMgr = SharedMM;
481 Resolver = SharedMM;
482 return *this;
483}
484
485EngineBuilder&
486EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
487 MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
488 return *this;
489}
490
491EngineBuilder&
492EngineBuilder::setSymbolResolver(std::unique_ptr<RuntimeDyld::SymbolResolver> SR) {
493 Resolver = std::shared_ptr<RuntimeDyld::SymbolResolver>(std::move(SR));
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000494 return *this;
495}
496
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000497ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000498 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000499
Nick Lewyckya53414f2008-03-08 02:49:45 +0000500 // Make sure we can resolve symbols in the program as well. The zero arg
501 // to the function tells DynamicLibrary to load the program, not a library.
Craig Topper2617dcc2014-04-15 06:32:26 +0000502 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
503 return nullptr;
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000504
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000505 // If the user specified a memory manager but didn't specify which engine to
506 // create, we assume they only want the JIT, and we fail if they only want
507 // the interpreter.
Lang Hames633fe142015-03-30 03:37:06 +0000508 if (MemMgr) {
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000509 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000510 WhichEngine = EngineKind::JIT;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000511 else {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000512 if (ErrorStr)
513 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000514 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000515 }
516 }
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000517
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000518 // Unless the interpreter was explicitly selected or the JIT is not linked,
519 // try making a JIT.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000520 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000521 Triple TT(M->getTargetTriple());
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000522 if (!TM->getTarget().hasJIT()) {
523 errs() << "WARNING: This target JIT is not designed for the host"
524 << " you are running. If bad things happen, please choose"
525 << " a different -march switch.\n";
526 }
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000527
Lang Hamesbc876012014-04-18 06:48:23 +0000528 ExecutionEngine *EE = nullptr;
Lang Hames93de2a12015-01-23 21:25:00 +0000529 if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
Lang Hames633fe142015-03-30 03:37:06 +0000530 EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
531 std::move(Resolver),
Lang Hames93de2a12015-01-23 21:25:00 +0000532 std::move(TheTM));
533 EE->addModule(std::move(M));
534 } else if (ExecutionEngine::MCJITCtor)
Lang Hames633fe142015-03-30 03:37:06 +0000535 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
536 std::move(Resolver), std::move(TheTM));
Lang Hames93de2a12015-01-23 21:25:00 +0000537
Lang Hamesbc876012014-04-18 06:48:23 +0000538 if (EE) {
539 EE->setVerifyModules(VerifyModules);
540 return EE;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000541 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000542 }
543
544 // If we can't make a JIT and we didn't request one specifically, try making
545 // an interpreter instead.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000546 if (WhichEngine & EngineKind::Interpreter) {
547 if (ExecutionEngine::InterpCtor)
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000548 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
Chris Lattner8bcc6442009-09-23 02:03:49 +0000549 if (ErrorStr)
550 *ErrorStr = "Interpreter has not been linked in.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000551 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000552 }
Chris Lattner8bcc6442009-09-23 02:03:49 +0000553
Eric Christopher79cc1e32014-09-02 22:28:02 +0000554 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000555 if (ErrorStr)
556 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000557 }
558
Craig Topper2617dcc2014-04-15 06:32:26 +0000559 return nullptr;
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000560}
561
Chris Lattner996fe012002-12-24 00:01:05 +0000562void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke1678e852003-08-13 18:16:14 +0000563 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattner996fe012002-12-24 00:01:05 +0000564 return getPointerToFunction(F);
565
Zachary Turnerc04b8922014-06-20 21:07:14 +0000566 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000567 if (void* P = getPointerToGlobalIfAvailable(GV))
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000568 return P;
Jeff Cohen69e849012006-02-07 05:11:57 +0000569
570 // Global variable might have been added since interpreter started.
571 if (GlobalVariable *GVar =
572 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
573 EmitGlobalVariable(GVar);
574 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000575 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000576
Lang Hames3dac3f72015-03-31 20:31:14 +0000577 return getPointerToGlobalIfAvailable(GV);
Chris Lattner996fe012002-12-24 00:01:05 +0000578}
579
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000580/// \brief Converts a Constant* into a GenericValue, including handling of
581/// ConstantExpr values.
Chris Lattner996fe012002-12-24 00:01:05 +0000582GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000583 // If its undefined, return the garbage.
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000584 if (isa<UndefValue>(C)) {
585 GenericValue Result;
586 switch (C->getType()->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000587 default:
588 break;
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000589 case Type::IntegerTyID:
590 case Type::X86_FP80TyID:
591 case Type::FP128TyID:
592 case Type::PPC_FP128TyID:
593 // Although the value is undefined, we still have to construct an APInt
594 // with the correct bit width.
595 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
596 break;
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000597 case Type::StructTyID: {
598 // if the whole struct is 'undef' just reserve memory for the value.
599 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
600 unsigned int elemNum = STy->getNumElements();
601 Result.AggregateVal.resize(elemNum);
602 for (unsigned int i = 0; i < elemNum; ++i) {
603 Type *ElemTy = STy->getElementType(i);
604 if (ElemTy->isIntegerTy())
605 Result.AggregateVal[i].IntVal =
606 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
607 else if (ElemTy->isAggregateType()) {
608 const Constant *ElemUndef = UndefValue::get(ElemTy);
609 Result.AggregateVal[i] = getConstantValue(ElemUndef);
610 }
611 }
612 }
613 }
614 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000615 case Type::VectorTyID:
616 // if the whole vector is 'undef' just reserve memory for the value.
617 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
618 const Type *ElemTy = VTy->getElementType();
619 unsigned int elemNum = VTy->getNumElements();
620 Result.AggregateVal.resize(elemNum);
621 if (ElemTy->isIntegerTy())
622 for (unsigned int i = 0; i < elemNum; ++i)
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000623 Result.AggregateVal[i].IntVal =
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000624 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000625 break;
626 }
627 return Result;
628 }
Chris Lattner9de0d142003-04-23 19:01:49 +0000629
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000630 // Otherwise, if the value is a ConstantExpr...
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000631 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000632 Constant *Op0 = CE->getOperand(0);
Chris Lattner9de0d142003-04-23 19:01:49 +0000633 switch (CE->getOpcode()) {
634 case Instruction::GetElementPtr: {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000635 // Compute the index
Reid Spencer4fd528f2007-03-06 22:23:15 +0000636 GenericValue Result = getConstantValue(Op0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000637 APInt Offset(DL->getPointerSizeInBits(), 0);
638 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
Misha Brukman835702a2005-04-21 22:36:52 +0000639
Reid Spencer87aa65f2007-03-06 03:04:04 +0000640 char* tmp = (char*) Result.PointerVal;
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000641 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattner9de0d142003-04-23 19:01:49 +0000642 return Result;
643 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000644 case Instruction::Trunc: {
645 GenericValue GV = getConstantValue(Op0);
646 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
647 GV.IntVal = GV.IntVal.trunc(BitWidth);
648 return GV;
649 }
650 case Instruction::ZExt: {
651 GenericValue GV = getConstantValue(Op0);
652 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
653 GV.IntVal = GV.IntVal.zext(BitWidth);
654 return GV;
655 }
656 case Instruction::SExt: {
657 GenericValue GV = getConstantValue(Op0);
658 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
659 GV.IntVal = GV.IntVal.sext(BitWidth);
660 return GV;
661 }
662 case Instruction::FPTrunc: {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000663 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000664 GenericValue GV = getConstantValue(Op0);
665 GV.FloatVal = float(GV.DoubleVal);
666 return GV;
667 }
668 case Instruction::FPExt:{
Dale Johannesena1336cf2007-09-17 18:44:13 +0000669 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000670 GenericValue GV = getConstantValue(Op0);
671 GV.DoubleVal = double(GV.FloatVal);
672 return GV;
673 }
674 case Instruction::UIToFP: {
675 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000676 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000677 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000678 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000679 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000680 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000681 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000682 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000683 false,
684 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000685 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000686 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000687 return GV;
688 }
689 case Instruction::SIToFP: {
690 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000691 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000692 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000693 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000694 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000695 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000696 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000697 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000698 true,
699 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000700 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000701 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000702 return GV;
703 }
704 case Instruction::FPToUI: // double->APInt conversion handles sign
705 case Instruction::FPToSI: {
706 GenericValue GV = getConstantValue(Op0);
707 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000708 if (Op0->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000709 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000710 else if (Op0->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000711 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000712 else if (Op0->getType()->isX86_FP80Ty()) {
Tim Northover29178a32013-01-22 09:46:31 +0000713 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000714 uint64_t v;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000715 bool ignored;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000716 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000717 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000718 APFloat::rmTowardZero, &ignored);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000719 GV.IntVal = v; // endian?
720 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000721 return GV;
722 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000723 case Instruction::PtrToInt: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000724 GenericValue GV = getConstantValue(Op0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000725 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000726 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000727 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000728 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000729 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000730 return GV;
731 }
732 case Instruction::IntToPtr: {
733 GenericValue GV = getConstantValue(Op0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000734 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000735 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000736 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
737 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000738 return GV;
739 }
740 case Instruction::BitCast: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000741 GenericValue GV = getConstantValue(Op0);
Chris Lattner229907c2011-07-18 04:54:35 +0000742 Type* DestTy = CE->getType();
Reid Spencer4fd528f2007-03-06 22:23:15 +0000743 switch (Op0->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000744 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000745 case Type::IntegerTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000746 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnerfdd87902009-10-05 05:54:46 +0000747 if (DestTy->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000748 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000749 else if (DestTy->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000750 GV.DoubleVal = GV.IntVal.bitsToDouble();
751 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000752 case Type::FloatTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000753 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000754 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000755 break;
756 case Type::DoubleTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000757 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000758 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000759 break;
760 case Type::PointerTyID:
Duncan Sands19d0b472010-02-16 11:11:14 +0000761 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000762 break; // getConstantValue(Op0) above already converted it
763 }
764 return GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000765 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000766 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +0000767 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000768 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +0000769 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000770 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +0000771 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000772 case Instruction::UDiv:
773 case Instruction::SDiv:
774 case Instruction::URem:
775 case Instruction::SRem:
776 case Instruction::And:
777 case Instruction::Or:
778 case Instruction::Xor: {
779 GenericValue LHS = getConstantValue(Op0);
780 GenericValue RHS = getConstantValue(CE->getOperand(1));
781 GenericValue GV;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000782 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000783 default: llvm_unreachable("Bad add type!");
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000784 case Type::IntegerTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000785 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000786 default: llvm_unreachable("Invalid integer opcode");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000787 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
788 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
789 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
790 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
791 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
792 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
793 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
794 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
795 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
796 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
797 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000798 break;
799 case Type::FloatTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000800 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000801 default: llvm_unreachable("Invalid float opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000802 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000803 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000804 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000805 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000806 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000807 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000808 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000809 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000810 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000811 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000812 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000813 break;
814 case Type::DoubleTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000815 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000816 default: llvm_unreachable("Invalid double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000817 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000818 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000819 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000820 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000821 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000822 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000823 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000824 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000825 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000826 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000827 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000828 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000829 case Type::X86_FP80TyID:
830 case Type::PPC_FP128TyID:
831 case Type::FP128TyID: {
Tim Northover29178a32013-01-22 09:46:31 +0000832 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
833 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000834 switch (CE->getOpcode()) {
Daniel Dunbare4f47432010-11-13 00:55:42 +0000835 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000836 case Instruction::FAdd:
Tim Northover29178a32013-01-22 09:46:31 +0000837 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000838 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000839 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000840 case Instruction::FSub:
Tim Northover29178a32013-01-22 09:46:31 +0000841 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
842 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000843 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000844 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000845 case Instruction::FMul:
Tim Northover29178a32013-01-22 09:46:31 +0000846 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
847 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000848 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000849 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000850 case Instruction::FDiv:
Tim Northover29178a32013-01-22 09:46:31 +0000851 apfLHS.divide(APFloat(Sem, RHS.IntVal),
852 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000853 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000854 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000855 case Instruction::FRem:
Tim Northover29178a32013-01-22 09:46:31 +0000856 apfLHS.mod(APFloat(Sem, RHS.IntVal),
857 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000858 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000859 break;
860 }
861 }
862 break;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000863 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000864 return GV;
865 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000866 default:
867 break;
868 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000869
870 SmallString<256> Msg;
871 raw_svector_ostream OS(Msg);
872 OS << "ConstantExpr not handled: " << *CE;
873 report_fatal_error(OS.str());
Chris Lattner68cbcc32003-05-14 17:51:49 +0000874 }
Misha Brukman835702a2005-04-21 22:36:52 +0000875
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000876 // Otherwise, we have a simple constant.
Reid Spencer4fd528f2007-03-06 22:23:15 +0000877 GenericValue Result;
Chris Lattner6b727592004-06-17 18:19:28 +0000878 switch (C->getType()->getTypeID()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000879 case Type::FloatTyID:
880 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000881 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000882 case Type::DoubleTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000883 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer87aa65f2007-03-06 03:04:04 +0000884 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000885 case Type::X86_FP80TyID:
886 case Type::FP128TyID:
887 case Type::PPC_FP128TyID:
Dale Johannesen54306fe2008-10-09 18:53:47 +0000888 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000889 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000890 case Type::IntegerTyID:
891 Result.IntVal = cast<ConstantInt>(C)->getValue();
892 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000893 case Type::PointerTyID:
Reid Spencer6a0fd732004-07-18 00:41:27 +0000894 if (isa<ConstantPointerNull>(C))
Craig Topper2617dcc2014-04-15 06:32:26 +0000895 Result.PointerVal = nullptr;
Reid Spencer6a0fd732004-07-18 00:41:27 +0000896 else if (const Function *F = dyn_cast<Function>(C))
897 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000898 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer6a0fd732004-07-18 00:41:27 +0000899 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
900 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000901 llvm_unreachable("Unknown constant pointer type!");
Chris Lattner996fe012002-12-24 00:01:05 +0000902 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000903 case Type::VectorTyID: {
904 unsigned elemNum;
905 Type* ElemTy;
906 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
907 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
908 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
909
910 if (CDV) {
911 elemNum = CDV->getNumElements();
912 ElemTy = CDV->getElementType();
913 } else if (CV || CAZ) {
914 VectorType* VTy = dyn_cast<VectorType>(C->getType());
915 elemNum = VTy->getNumElements();
916 ElemTy = VTy->getElementType();
917 } else {
918 llvm_unreachable("Unknown constant vector type!");
919 }
920
921 Result.AggregateVal.resize(elemNum);
922 // Check if vector holds floats.
923 if(ElemTy->isFloatTy()) {
924 if (CAZ) {
925 GenericValue floatZero;
926 floatZero.FloatVal = 0.f;
927 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
928 floatZero);
929 break;
930 }
931 if(CV) {
932 for (unsigned i = 0; i < elemNum; ++i)
933 if (!isa<UndefValue>(CV->getOperand(i)))
934 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
935 CV->getOperand(i))->getValueAPF().convertToFloat();
936 break;
937 }
938 if(CDV)
939 for (unsigned i = 0; i < elemNum; ++i)
940 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
941
942 break;
943 }
944 // Check if vector holds doubles.
945 if (ElemTy->isDoubleTy()) {
946 if (CAZ) {
947 GenericValue doubleZero;
948 doubleZero.DoubleVal = 0.0;
949 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
950 doubleZero);
951 break;
952 }
953 if(CV) {
954 for (unsigned i = 0; i < elemNum; ++i)
955 if (!isa<UndefValue>(CV->getOperand(i)))
956 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
957 CV->getOperand(i))->getValueAPF().convertToDouble();
958 break;
959 }
960 if(CDV)
961 for (unsigned i = 0; i < elemNum; ++i)
962 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
963
964 break;
965 }
966 // Check if vector holds integers.
967 if (ElemTy->isIntegerTy()) {
968 if (CAZ) {
969 GenericValue intZero;
970 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
971 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
972 intZero);
973 break;
974 }
975 if(CV) {
976 for (unsigned i = 0; i < elemNum; ++i)
977 if (!isa<UndefValue>(CV->getOperand(i)))
978 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
979 CV->getOperand(i))->getValue();
980 else {
981 Result.AggregateVal[i].IntVal =
982 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
983 }
984 break;
985 }
986 if(CDV)
987 for (unsigned i = 0; i < elemNum; ++i)
988 Result.AggregateVal[i].IntVal = APInt(
989 CDV->getElementType()->getPrimitiveSizeInBits(),
990 CDV->getElementAsInteger(i));
991
992 break;
993 }
994 llvm_unreachable("Unknown constant pointer type!");
995 }
996 break;
997
Chris Lattner996fe012002-12-24 00:01:05 +0000998 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000999 SmallString<256> Msg;
1000 raw_svector_ostream OS(Msg);
1001 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
1002 report_fatal_error(OS.str());
Chris Lattner996fe012002-12-24 00:01:05 +00001003 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001004
Chris Lattner996fe012002-12-24 00:01:05 +00001005 return Result;
1006}
1007
Duncan Sands1202d1b2007-12-14 19:38:31 +00001008/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1009/// with the integer held in IntVal.
1010static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1011 unsigned StoreBytes) {
1012 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divackyad06cee2012-09-05 22:26:57 +00001013 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands1202d1b2007-12-14 19:38:31 +00001014
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001015 if (sys::IsLittleEndianHost) {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001016 // Little-endian host - the source is ordered from LSB to MSB. Order the
1017 // destination from LSB to MSB: Do a straight copy.
1018 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001019 } else {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001020 // Big-endian host - the source is an array of 64 bit words ordered from
1021 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1022 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1023 while (StoreBytes > sizeof(uint64_t)) {
1024 StoreBytes -= sizeof(uint64_t);
1025 // May not be aligned so use memcpy.
1026 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1027 Src += sizeof(uint64_t);
1028 }
1029
1030 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1031 }
1032}
1033
Evan Cheng09053e62008-11-04 06:10:31 +00001034void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattner229907c2011-07-18 04:54:35 +00001035 GenericValue *Ptr, Type *Ty) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001036 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001037
Reid Spencer87aa65f2007-03-06 03:04:04 +00001038 switch (Ty->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001039 default:
1040 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1041 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001042 case Type::IntegerTyID:
1043 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001044 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001045 case Type::FloatTyID:
1046 *((float*)Ptr) = Val.FloatVal;
1047 break;
1048 case Type::DoubleTyID:
1049 *((double*)Ptr) = Val.DoubleVal;
1050 break;
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001051 case Type::X86_FP80TyID:
1052 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1053 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001054 case Type::PointerTyID:
1055 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1056 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth93da3c82011-04-28 08:37:18 +00001057 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001058
Reid Spencer87aa65f2007-03-06 03:04:04 +00001059 *((PointerTy*)Ptr) = Val.PointerVal;
1060 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001061 case Type::VectorTyID:
1062 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1063 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1064 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1065 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1066 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1067 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1068 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1069 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1070 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1071 }
1072 }
1073 break;
Chris Lattner996fe012002-12-24 00:01:05 +00001074 }
Duncan Sands1202d1b2007-12-14 19:38:31 +00001075
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001076 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
Duncan Sands1202d1b2007-12-14 19:38:31 +00001077 // Host and target are different endian - reverse the stored bytes.
1078 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1079}
1080
1081/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1082/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1083static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1084 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greene82b63572013-01-14 21:04:45 +00001085 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1086 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands1202d1b2007-12-14 19:38:31 +00001087
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001088 if (sys::IsLittleEndianHost)
Duncan Sands1202d1b2007-12-14 19:38:31 +00001089 // Little-endian host - the destination must be ordered from LSB to MSB.
1090 // The source is ordered from LSB to MSB: Do a straight copy.
1091 memcpy(Dst, Src, LoadBytes);
1092 else {
1093 // Big-endian - the destination is an array of 64 bit words ordered from
1094 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1095 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1096 // a word.
1097 while (LoadBytes > sizeof(uint64_t)) {
1098 LoadBytes -= sizeof(uint64_t);
1099 // May not be aligned so use memcpy.
1100 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1101 Dst += sizeof(uint64_t);
1102 }
1103
1104 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1105 }
Chris Lattner996fe012002-12-24 00:01:05 +00001106}
1107
Misha Brukman857c21b2003-10-10 17:45:12 +00001108/// FIXME: document
1109///
Duncan Sands1202d1b2007-12-14 19:38:31 +00001110void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandscd4a6be2008-03-10 16:38:37 +00001111 GenericValue *Ptr,
Chris Lattner229907c2011-07-18 04:54:35 +00001112 Type *Ty) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001113 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands5c65cb42007-12-10 17:43:13 +00001114
Duncan Sands1202d1b2007-12-14 19:38:31 +00001115 switch (Ty->getTypeID()) {
1116 case Type::IntegerTyID:
1117 // An APInt with all words initially zero.
1118 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1119 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1120 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001121 case Type::FloatTyID:
1122 Result.FloatVal = *((float*)Ptr);
1123 break;
1124 case Type::DoubleTyID:
Duncan Sands1202d1b2007-12-14 19:38:31 +00001125 Result.DoubleVal = *((double*)Ptr);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001126 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001127 case Type::PointerTyID:
Reid Spencer87aa65f2007-03-06 03:04:04 +00001128 Result.PointerVal = *((PointerTy*)Ptr);
1129 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +00001130 case Type::X86_FP80TyID: {
1131 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands26d65392007-12-15 17:37:40 +00001132 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001133 uint64_t y[2];
1134 memcpy(y, Ptr, 10);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00001135 Result.IntVal = APInt(80, y);
Dale Johannesena1336cf2007-09-17 18:44:13 +00001136 break;
1137 }
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001138 case Type::VectorTyID: {
1139 const VectorType *VT = cast<VectorType>(Ty);
1140 const Type *ElemT = VT->getElementType();
1141 const unsigned numElems = VT->getNumElements();
1142 if (ElemT->isFloatTy()) {
1143 Result.AggregateVal.resize(numElems);
1144 for (unsigned i = 0; i < numElems; ++i)
1145 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1146 }
1147 if (ElemT->isDoubleTy()) {
1148 Result.AggregateVal.resize(numElems);
1149 for (unsigned i = 0; i < numElems; ++i)
1150 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1151 }
1152 if (ElemT->isIntegerTy()) {
1153 GenericValue intZero;
1154 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1155 intZero.IntVal = APInt(elemBitWidth, 0);
1156 Result.AggregateVal.resize(numElems, intZero);
1157 for (unsigned i = 0; i < numElems; ++i)
1158 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1159 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1160 }
1161 break;
1162 }
Reid Spencer87aa65f2007-03-06 03:04:04 +00001163 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001164 SmallString<256> Msg;
1165 raw_svector_ostream OS(Msg);
1166 OS << "Cannot load value of type " << *Ty << "!";
1167 report_fatal_error(OS.str());
Chris Lattner7f389e82003-05-08 16:52:16 +00001168 }
Chris Lattner7f389e82003-05-08 16:52:16 +00001169}
1170
Chris Lattner996fe012002-12-24 00:01:05 +00001171void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene0967d2d2010-01-05 01:27:39 +00001172 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesenb086d382008-08-07 01:30:15 +00001173 DEBUG(Init->dump());
Chris Lattner00245f42012-01-24 13:41:11 +00001174 if (isa<UndefValue>(Init))
Chris Lattner61753bf2004-10-16 18:19:26 +00001175 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001176
1177 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino69d62132006-01-20 18:18:40 +00001178 unsigned ElementSize =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001179 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino69d62132006-01-20 18:18:40 +00001180 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1181 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1182 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001183 }
1184
1185 if (isa<ConstantAggregateZero>(Init)) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001186 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
Chris Lattner1dd86b12008-02-15 00:57:28 +00001187 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001188 }
1189
1190 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001191 unsigned ElementSize =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001192 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001193 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1194 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1195 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001196 }
1197
1198 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001199 const StructLayout *SL =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001200 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001201 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1202 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1203 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001204 }
1205
1206 if (const ConstantDataSequential *CDS =
1207 dyn_cast<ConstantDataSequential>(Init)) {
1208 // CDS is already laid out in host memory order.
1209 StringRef Data = CDS->getRawDataValues();
1210 memcpy(Addr, Data.data(), Data.size());
1211 return;
1212 }
1213
1214 if (Init->getType()->isFirstClassType()) {
Chris Lattner996fe012002-12-24 00:01:05 +00001215 GenericValue Val = getConstantValue(Init);
1216 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1217 return;
1218 }
1219
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001220 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinfbcc6632009-07-14 16:55:14 +00001221 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattner996fe012002-12-24 00:01:05 +00001222}
1223
Chris Lattner996fe012002-12-24 00:01:05 +00001224/// EmitGlobals - Emit all of the global variables to memory, storing their
1225/// addresses into GlobalAddress. This must make sure to copy the contents of
1226/// their initializers into the memory.
Chris Lattner996fe012002-12-24 00:01:05 +00001227void ExecutionEngine::emitGlobals() {
Chris Lattner996fe012002-12-24 00:01:05 +00001228 // Loop over all of the global variables in the program, allocating the memory
Chris Lattner0621cae2006-08-16 01:24:12 +00001229 // to hold them. If there is more than one module, do a prepass over globals
1230 // to figure out how the different modules should link together.
Chris Lattner229907c2011-07-18 04:54:35 +00001231 std::map<std::pair<std::string, Type*>,
Chris Lattner0621cae2006-08-16 01:24:12 +00001232 const GlobalValue*> LinkedGlobalsMap;
Misha Brukman835702a2005-04-21 22:36:52 +00001233
Chris Lattner0621cae2006-08-16 01:24:12 +00001234 if (Modules.size() != 1) {
1235 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001236 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001237 for (const auto &GV : M.globals()) {
1238 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1239 GV.hasAppendingLinkage() || !GV.hasName())
Chris Lattner0621cae2006-08-16 01:24:12 +00001240 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001241
1242 const GlobalValue *&GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001243 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
Chris Lattner0621cae2006-08-16 01:24:12 +00001244
1245 // If this is the first time we've seen this global, it is the canonical
1246 // version.
1247 if (!GVEntry) {
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001248 GVEntry = &GV;
Chris Lattner0621cae2006-08-16 01:24:12 +00001249 continue;
1250 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001251
Chris Lattner0621cae2006-08-16 01:24:12 +00001252 // If the existing global is strong, never replace it.
Nico Rieck7157bb72014-01-14 15:22:47 +00001253 if (GVEntry->hasExternalLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +00001254 continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001255
Chris Lattner0621cae2006-08-16 01:24:12 +00001256 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesence4396b2008-05-14 20:12:51 +00001257 // symbol. FIXME is this right for common?
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001258 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1259 GVEntry = &GV;
Chris Lattner9de0d142003-04-23 19:01:49 +00001260 }
Chris Lattner996fe012002-12-24 00:01:05 +00001261 }
Chris Lattner0621cae2006-08-16 01:24:12 +00001262 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001263
Chris Lattner0621cae2006-08-16 01:24:12 +00001264 std::vector<const GlobalValue*> NonCanonicalGlobals;
1265 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001266 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001267 for (const auto &GV : M.globals()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001268 // In the multi-module case, see what this global maps to.
1269 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001270 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001271 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001272 // If something else is the canonical global, ignore this one.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001273 if (GVEntry != &GV) {
1274 NonCanonicalGlobals.push_back(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001275 continue;
1276 }
1277 }
1278 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001279
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001280 if (!GV.isDeclaration()) {
1281 addGlobalMapping(&GV, getMemoryForGV(&GV));
Chris Lattner0621cae2006-08-16 01:24:12 +00001282 } else {
1283 // External variable reference. Try to use the dynamic loader to
1284 // get a pointer to it.
1285 if (void *SymAddr =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001286 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1287 addGlobalMapping(&GV, SymAddr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001288 else {
Chris Lattner2104b8d2010-04-07 22:58:41 +00001289 report_fatal_error("Could not resolve external global address: "
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001290 +GV.getName());
Chris Lattner0621cae2006-08-16 01:24:12 +00001291 }
1292 }
1293 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001294
Chris Lattner0621cae2006-08-16 01:24:12 +00001295 // If there are multiple modules, map the non-canonical globals to their
1296 // canonical location.
1297 if (!NonCanonicalGlobals.empty()) {
1298 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1299 const GlobalValue *GV = NonCanonicalGlobals[i];
1300 const GlobalValue *CGV =
1301 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1302 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1303 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesa67f06b2008-10-14 10:04:52 +00001304 addGlobalMapping(GV, Ptr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001305 }
1306 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001307
1308 // Now that all of the globals are set up in memory, loop through them all
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001309 // and initialize their contents.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001310 for (const auto &GV : M.globals()) {
1311 if (!GV.isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001312 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001313 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001314 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1315 if (GVEntry != &GV) // Not the canonical variable.
Chris Lattner0621cae2006-08-16 01:24:12 +00001316 continue;
1317 }
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001318 EmitGlobalVariable(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001319 }
1320 }
1321 }
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001322}
1323
1324// EmitGlobalVariable - This method emits the specified global variable to the
1325// address specified in GlobalAddresses, or allocates new memory if it's not
1326// already in the map.
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +00001327void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner748e8572003-12-31 20:21:04 +00001328 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattnerdc631732004-02-08 19:33:23 +00001329
Craig Topper2617dcc2014-04-15 06:32:26 +00001330 if (!GA) {
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001331 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001332 GA = getMemoryForGV(GV);
Andrew Kaylor3b442372013-11-15 17:52:54 +00001333
1334 // If we failed to allocate memory for this global, return.
Craig Topper2617dcc2014-04-15 06:32:26 +00001335 if (!GA) return;
Andrew Kaylor3b442372013-11-15 17:52:54 +00001336
Chris Lattner748e8572003-12-31 20:21:04 +00001337 addGlobalMapping(GV, GA);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001338 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001339
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001340 // Don't initialize if it's thread local, let the client do it.
1341 if (!GV->isThreadLocal())
1342 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001343
Chris Lattner229907c2011-07-18 04:54:35 +00001344 Type *ElTy = GV->getType()->getElementType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001345 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
Chris Lattnerdf1f1522005-01-08 20:13:19 +00001346 NumInitBytes += (unsigned)GVSize;
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001347 ++NumGlobals;
Chris Lattner996fe012002-12-24 00:01:05 +00001348}