blob: 41c8da40346ac50024baf07e0bf2a4ebbfd26047 [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
Mehdi Aminia3fcefb2015-07-16 16:34:23 +000064void ExecutionEngine::Init(std::unique_ptr<Module> M) {
Jeffrey Yasskin4567db42009-10-27 20:30:28 +000065 CompilingLazily = false;
Evan Chengcdc00602008-09-24 16:25:55 +000066 GVCompilationDisabled = false;
Evan Cheng84a90552008-06-17 16:49:02 +000067 SymbolSearchingDisabled = false;
Lang Hamesbc876012014-04-18 06:48:23 +000068
69 // IR module verification is enabled by default in debug builds, and disabled
70 // by default in release builds.
71#ifndef NDEBUG
72 VerifyModules = true;
73#else
74 VerifyModules = false;
75#endif
76
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000077 assert(M && "Module is null?");
Rafael Espindola2a8a2792014-08-19 04:04:25 +000078 Modules.push_back(std::move(M));
Misha Brukman260b0c82003-10-16 21:18:05 +000079}
80
Mehdi Aminia3fcefb2015-07-16 16:34:23 +000081ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
82 : DL(M->getDataLayout()), LazyFunctionCreator(nullptr) {
83 Init(std::move(M));
84}
85
86ExecutionEngine::ExecutionEngine(DataLayout DL, std::unique_ptr<Module> M)
87 : DL(std::move(DL)), LazyFunctionCreator(nullptr) {
88 Init(std::move(M));
89}
90
Brian Gaeke92f8b302003-09-04 22:57:27 +000091ExecutionEngine::~ExecutionEngine() {
Reid Spencer603682a2007-03-03 18:19:18 +000092 clearAllGlobalMappings();
Brian Gaeke92f8b302003-09-04 22:57:27 +000093}
94
Jeffrey Yasskina4044332010-03-27 04:53:56 +000095namespace {
Daniel Dunbar868e3f02010-11-13 02:48:57 +000096/// \brief Helper class which uses a value handler to automatically deletes the
97/// memory block when the GlobalVariable is destroyed.
David Blaikie774b5842015-08-03 22:30:24 +000098class GVMemoryBlock final : public CallbackVH {
Jeffrey Yasskina4044332010-03-27 04:53:56 +000099 GVMemoryBlock(const GlobalVariable *GV)
100 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
101
102public:
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000103 /// \brief Returns the address the GlobalVariable should be written into. The
104 /// GVMemoryBlock object prefixes that.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000105 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
Chris Lattner229907c2011-07-18 04:54:35 +0000106 Type *ElTy = GV->getType()->getElementType();
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000107 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
108 void *RawMemory = ::operator new(
David Majnemerf3cadce2014-10-20 06:13:33 +0000109 RoundUpToAlignment(sizeof(GVMemoryBlock),
110 TD.getPreferredAlignment(GV))
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000111 + GVSize);
112 new(RawMemory) GVMemoryBlock(GV);
113 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
114 }
115
Craig Topperb51ff602014-03-08 07:51:20 +0000116 void deleted() override {
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000117 // We allocated with operator new and with some extra memory hanging off the
118 // end, so don't just delete this. I'm not sure if this is actually
119 // required.
120 this->~GVMemoryBlock();
121 ::operator delete(this);
122 }
123};
124} // anonymous namespace
125
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000126char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000127 return GVMemoryBlock::Create(GV, getDataLayout());
Nicolas Geoffray5457ce92008-10-25 15:41:43 +0000128}
129
David Blaikie35907d82014-04-29 22:04:55 +0000130void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
131 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
132}
133
Rafael Espindola7271c192014-08-26 21:04:04 +0000134void
135ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
136 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
137}
138
Rafael Espindola48af1c22014-08-19 18:44:46 +0000139void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolaacfd6282014-08-01 18:49:24 +0000140 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
141}
142
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000143bool ExecutionEngine::removeModule(Module *M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000144 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
145 Module *Found = I->get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000146 if (Found == M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000147 I->release();
Devang Patel324fe892007-10-15 19:56:32 +0000148 Modules.erase(I);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000149 clearGlobalMappingsFromModule(M);
150 return true;
Devang Patel324fe892007-10-15 19:56:32 +0000151 }
152 }
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000153 return false;
Nate Begeman617001d2009-01-23 19:27:28 +0000154}
155
Chris Lattner0621cae2006-08-16 01:24:12 +0000156Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
157 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Keno Fischer5f92a082015-01-27 19:29:00 +0000158 Function *F = Modules[i]->getFunction(FnName);
159 if (F && !F->isDeclaration())
Chris Lattner0621cae2006-08-16 01:24:12 +0000160 return F;
161 }
Craig Topper2617dcc2014-04-15 06:32:26 +0000162 return nullptr;
Chris Lattner0621cae2006-08-16 01:24:12 +0000163}
164
Keno Fischer73378eb2015-06-20 00:55:58 +0000165GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
166 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
167 GlobalVariable *GV = Modules[i]->getGlobalVariable(Name,AllowInternal);
168 if (GV && !GV->isDeclaration())
169 return GV;
170 }
171 return nullptr;
172}
Chris Lattner0621cae2006-08-16 01:24:12 +0000173
Lang Hames3dac3f72015-03-31 20:31:14 +0000174uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
175 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
176 uint64_t OldVal;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000177
178 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
179 // GlobalAddressMap.
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000180 if (I == GlobalAddressMap.end())
Lang Hames3dac3f72015-03-31 20:31:14 +0000181 OldVal = 0;
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000182 else {
Lang Hames3dac3f72015-03-31 20:31:14 +0000183 GlobalAddressReverseMap.erase(I->second);
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000184 OldVal = I->second;
185 GlobalAddressMap.erase(I);
186 }
187
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000188 return OldVal;
189}
190
Lang Hames3dac3f72015-03-31 20:31:14 +0000191std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
Lang Hames3393cfd2015-07-29 23:12:33 +0000192 assert(GV->hasName() && "Global must have name.");
193
Lang Hames3dac3f72015-03-31 20:31:14 +0000194 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000195 SmallString<128> FullName;
Lang Hames3393cfd2015-07-29 23:12:33 +0000196
197 const DataLayout &DL =
198 GV->getParent()->getDataLayout().isDefault()
199 ? getDataLayout()
200 : GV->getParent()->getDataLayout();
201
202 Mangler::getNameWithPrefix(FullName, GV->getName(), DL);
Lang Hames3dac3f72015-03-31 20:31:14 +0000203 return FullName.str();
204}
205
Chris Lattner6d8dd182006-05-08 22:00:52 +0000206void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000207 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000208 addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
209}
Evan Cheng5cc53c32008-09-18 07:54:21 +0000210
Lang Hames3dac3f72015-03-31 20:31:14 +0000211void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
212 MutexGuard locked(lock);
213
214 assert(!Name.empty() && "Empty GlobalMapping symbol name!");
215
216 DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
217 uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
Craig Topper2617dcc2014-04-15 06:32:26 +0000218 assert((!CurVal || !Addr) && "GlobalMapping already established!");
Chris Lattner6d8dd182006-05-08 22:00:52 +0000219 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000220
221 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000222 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames3dac3f72015-03-31 20:31:14 +0000223 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
224 assert((!V.empty() || !Name.empty()) &&
225 "GlobalMapping already established!");
226 V = Name;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000227 }
228}
229
Chris Lattner6d8dd182006-05-08 22:00:52 +0000230void ExecutionEngine::clearAllGlobalMappings() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000231 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000232
Zachary Turner2f825df2014-06-16 20:54:28 +0000233 EEState.getGlobalAddressMap().clear();
234 EEState.getGlobalAddressReverseMap().clear();
Chris Lattner6d8dd182006-05-08 22:00:52 +0000235}
236
Nate Begeman8f83fc42008-05-21 16:34:48 +0000237void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000238 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000239
Duncan P. N. Exon Smith4ead9202015-10-13 18:11:02 +0000240 for (Function &FI : *M)
241 EEState.RemoveMapping(getMangledName(&FI));
242 for (GlobalVariable &GI : M->globals())
243 EEState.RemoveMapping(getMangledName(&GI));
Nate Begeman8f83fc42008-05-21 16:34:48 +0000244}
245
Lang Hames3dac3f72015-03-31 20:31:14 +0000246uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
247 void *Addr) {
248 MutexGuard locked(lock);
249 return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
250}
251
252uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000253 MutexGuard locked(lock);
Chris Lattneree181732008-04-04 04:47:41 +0000254
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000255 ExecutionEngineState::GlobalAddressMapTy &Map =
Zachary Turner2f825df2014-06-16 20:54:28 +0000256 EEState.getGlobalAddressMap();
Chris Lattneree181732008-04-04 04:47:41 +0000257
Chris Lattner6d8dd182006-05-08 22:00:52 +0000258 // Deleting from the mapping?
Craig Topper2617dcc2014-04-15 06:32:26 +0000259 if (!Addr)
Lang Hames3dac3f72015-03-31 20:31:14 +0000260 return EEState.RemoveMapping(Name);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000261
Lang Hames3dac3f72015-03-31 20:31:14 +0000262 uint64_t &CurVal = Map[Name];
263 uint64_t OldVal = CurVal;
Chris Lattneree181732008-04-04 04:47:41 +0000264
Zachary Turner2f825df2014-06-16 20:54:28 +0000265 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
266 EEState.getGlobalAddressReverseMap().erase(CurVal);
Chris Lattner6d8dd182006-05-08 22:00:52 +0000267 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000268
269 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000270 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames3dac3f72015-03-31 20:31:14 +0000271 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
272 assert((!V.empty() || !Name.empty()) &&
273 "GlobalMapping already established!");
274 V = Name;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000275 }
Chris Lattneree181732008-04-04 04:47:41 +0000276 return OldVal;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000277}
278
Lang Hames3dac3f72015-03-31 20:31:14 +0000279uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
280 MutexGuard locked(lock);
281 uint64_t Address = 0;
282 ExecutionEngineState::GlobalAddressMapTy::iterator I =
283 EEState.getGlobalAddressMap().find(S);
284 if (I != EEState.getGlobalAddressMap().end())
285 Address = I->second;
286 return Address;
287}
288
289
290void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
291 MutexGuard locked(lock);
292 if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
293 return Address;
294 return nullptr;
295}
296
Chris Lattner6d8dd182006-05-08 22:00:52 +0000297void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000298 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000299 return getPointerToGlobalIfAvailable(getMangledName(GV));
Chris Lattner6d8dd182006-05-08 22:00:52 +0000300}
301
Chris Lattner748e8572003-12-31 20:21:04 +0000302const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000303 MutexGuard locked(lock);
Reid Spencer79876f52005-07-12 15:51:55 +0000304
Chris Lattner748e8572003-12-31 20:21:04 +0000305 // If we haven't computed the reverse mapping yet, do so first.
Zachary Turner2f825df2014-06-16 20:54:28 +0000306 if (EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000307 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Lang Hames3dac3f72015-03-31 20:31:14 +0000308 I = EEState.getGlobalAddressMap().begin(),
309 E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
310 StringRef Name = I->first();
311 uint64_t Addr = I->second;
Zachary Turner2f825df2014-06-16 20:54:28 +0000312 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
Lang Hames3dac3f72015-03-31 20:31:14 +0000313 Addr, Name));
314 }
Chris Lattner748e8572003-12-31 20:21:04 +0000315 }
316
Lang Hames3dac3f72015-03-31 20:31:14 +0000317 std::map<uint64_t, std::string>::iterator I =
318 EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);
319
320 if (I != EEState.getGlobalAddressReverseMap().end()) {
321 StringRef Name = I->second;
322 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
323 if (GlobalValue *GV = Modules[i]->getNamedValue(Name))
324 return GV;
325 }
326 return nullptr;
Chris Lattner748e8572003-12-31 20:21:04 +0000327}
Chris Lattner5a0d4822003-12-26 06:50:30 +0000328
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000329namespace {
330class ArgvArray {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000331 std::unique_ptr<char[]> Array;
332 std::vector<std::unique_ptr<char[]>> Values;
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000333public:
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000334 /// Turn a vector of strings into a nice argv style array of pointers to null
335 /// terminated strings.
336 void *reset(LLVMContext &C, ExecutionEngine *EE,
337 const std::vector<std::string> &InputArgv);
338};
339} // anonymous namespace
340void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
341 const std::vector<std::string> &InputArgv) {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000342 Values.clear(); // Free the old contents.
343 Values.reserve(InputArgv.size());
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000344 unsigned PtrSize = EE->getDataLayout().getPointerSize();
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000345 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000346
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000347 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
Chris Lattner229907c2011-07-18 04:54:35 +0000348 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000349
350 for (unsigned i = 0; i != InputArgv.size(); ++i) {
351 unsigned Size = InputArgv[i].size()+1;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000352 auto Dest = make_unique<char[]>(Size);
353 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
Misha Brukman835702a2005-04-21 22:36:52 +0000354
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000355 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
Chris Lattner5a0d4822003-12-26 06:50:30 +0000356 Dest[Size-1] = 0;
Misha Brukman835702a2005-04-21 22:36:52 +0000357
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000358 // Endian safe: Array[i] = (PointerTy)Dest;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000359 EE->StoreValueToMemory(PTOGV(Dest.get()),
360 (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
361 Values.push_back(std::move(Dest));
Chris Lattner5a0d4822003-12-26 06:50:30 +0000362 }
363
364 // Null terminate it
Craig Topper2617dcc2014-04-15 06:32:26 +0000365 EE->StoreValueToMemory(PTOGV(nullptr),
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000366 (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
Chris Lattner5a0d4822003-12-26 06:50:30 +0000367 SBytePtr);
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000368 return Array.get();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000369}
370
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000371void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000372 bool isDtors) {
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000373 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000374 GlobalVariable *GV = module.getNamedGlobal(Name);
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000375
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000376 // If this global has internal linkage, or if it has a use, then it must be
377 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
378 // this is the case, don't execute any of the global ctors, __main will do
379 // it.
380 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
381
Nick Lewycky0cbfcb22011-04-06 20:38:44 +0000382 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000383 // the init priority, which we ignore.
Chris Lattner00245f42012-01-24 13:41:11 +0000384 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
Craig Topper2617dcc2014-04-15 06:32:26 +0000385 if (!InitList)
Nick Lewycky0f857892011-04-11 22:11:20 +0000386 return;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000387 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner00245f42012-01-24 13:41:11 +0000388 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
Craig Topper2617dcc2014-04-15 06:32:26 +0000389 if (!CS) continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000390
391 Constant *FP = CS->getOperand(1);
392 if (FP->isNullValue())
Nick Lewycky0f857892011-04-11 22:11:20 +0000393 continue; // Found a sentinal value, ignore.
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000394
395 // Strip off constant expression casts.
396 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
397 if (CE->isCast())
398 FP = CE->getOperand(0);
399
400 // Execute the ctor/dtor function!
401 if (Function *F = dyn_cast<Function>(FP))
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000402 runFunction(F, None);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000403
404 // FIXME: It is marginally lame that we just do nothing here if we see an
405 // entry we don't recognize. It might not be unreasonable for the verifier
406 // to not even allow this and just assert here.
407 }
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000408}
409
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000410void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
411 // Execute global ctors/dtors for each module in the program.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000412 for (std::unique_ptr<Module> &M : Modules)
413 runStaticConstructorsDestructors(*M, isDtors);
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000414}
415
Dan Gohmancf3e3012008-08-26 01:38:29 +0000416#ifndef NDEBUG
Duncan Sands1202d1b2007-12-14 19:38:31 +0000417/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
418static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000419 unsigned PtrSize = EE->getDataLayout().getPointerSize();
Duncan Sands1202d1b2007-12-14 19:38:31 +0000420 for (unsigned i = 0; i < PtrSize; ++i)
421 if (*(i + (uint8_t*)Loc))
422 return false;
423 return true;
424}
Dan Gohmancf3e3012008-08-26 01:38:29 +0000425#endif
Duncan Sands1202d1b2007-12-14 19:38:31 +0000426
Chris Lattner5a0d4822003-12-26 06:50:30 +0000427int ExecutionEngine::runFunctionAsMain(Function *Fn,
428 const std::vector<std::string> &argv,
429 const char * const * envp) {
430 std::vector<GenericValue> GVArgs;
431 GenericValue GVArgc;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000432 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000433
434 // Check main() type
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000435 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattner229907c2011-07-18 04:54:35 +0000436 FunctionType *FTy = Fn->getFunctionType();
437 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000438
439 // Check the argument types.
440 if (NumArgs > 3)
441 report_fatal_error("Invalid number of arguments of main() supplied");
442 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
443 report_fatal_error("Invalid type for third argument of main() supplied");
444 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
445 report_fatal_error("Invalid type for second argument of main() supplied");
446 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
447 report_fatal_error("Invalid type for first argument of main() supplied");
448 if (!FTy->getReturnType()->isIntegerTy() &&
449 !FTy->getReturnType()->isVoidTy())
450 report_fatal_error("Invalid return type of main() supplied");
451
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000452 ArgvArray CArgv;
453 ArgvArray CEnv;
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000454 if (NumArgs) {
455 GVArgs.push_back(GVArgc); // Arg #0 = argc.
456 if (NumArgs > 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000457 // Arg #1 = argv.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000458 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands1202d1b2007-12-14 19:38:31 +0000459 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000460 "argv[0] was null after CreateArgv");
461 if (NumArgs > 2) {
462 std::vector<std::string> EnvVars;
463 for (unsigned i = 0; envp[i]; ++i)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000464 EnvVars.emplace_back(envp[i]);
Owen Anderson55f1c092009-08-13 21:58:54 +0000465 // Arg #2 = envp.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000466 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000467 }
468 }
469 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000470
Reid Spencer87aa65f2007-03-06 03:04:04 +0000471 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000472}
473
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000474EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
Lang Hames93de2a12015-01-23 21:25:00 +0000475
Lang Hames4a5697e2014-12-03 00:51:19 +0000476EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000477 : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
Lang Hames633fe142015-03-30 03:37:06 +0000478 OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr),
479 RelocModel(Reloc::Default), CMModel(CodeModel::JITDefault),
480 UseOrcMCJITReplacement(false) {
Alp Toker322db9e2014-05-31 21:26:17 +0000481// IR module verification is enabled by default in debug builds, and disabled
482// by default in release builds.
483#ifndef NDEBUG
484 VerifyModules = true;
485#else
486 VerifyModules = false;
487#endif
488}
489
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000490EngineBuilder::~EngineBuilder() = default;
491
492EngineBuilder &EngineBuilder::setMCJITMemoryManager(
493 std::unique_ptr<RTDyldMemoryManager> mcjmm) {
Lang Hames633fe142015-03-30 03:37:06 +0000494 auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
495 MemMgr = SharedMM;
496 Resolver = SharedMM;
497 return *this;
498}
499
500EngineBuilder&
501EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
502 MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
503 return *this;
504}
505
506EngineBuilder&
507EngineBuilder::setSymbolResolver(std::unique_ptr<RuntimeDyld::SymbolResolver> SR) {
508 Resolver = std::shared_ptr<RuntimeDyld::SymbolResolver>(std::move(SR));
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000509 return *this;
510}
511
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000512ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000513 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000514
Nick Lewyckya53414f2008-03-08 02:49:45 +0000515 // Make sure we can resolve symbols in the program as well. The zero arg
516 // to the function tells DynamicLibrary to load the program, not a library.
Craig Topper2617dcc2014-04-15 06:32:26 +0000517 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
518 return nullptr;
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000519
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000520 // If the user specified a memory manager but didn't specify which engine to
521 // create, we assume they only want the JIT, and we fail if they only want
522 // the interpreter.
Lang Hames633fe142015-03-30 03:37:06 +0000523 if (MemMgr) {
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000524 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000525 WhichEngine = EngineKind::JIT;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000526 else {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000527 if (ErrorStr)
528 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000529 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000530 }
531 }
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000532
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000533 // Unless the interpreter was explicitly selected or the JIT is not linked,
534 // try making a JIT.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000535 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000536 Triple TT(M->getTargetTriple());
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000537 if (!TM->getTarget().hasJIT()) {
538 errs() << "WARNING: This target JIT is not designed for the host"
539 << " you are running. If bad things happen, please choose"
540 << " a different -march switch.\n";
541 }
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000542
Lang Hamesbc876012014-04-18 06:48:23 +0000543 ExecutionEngine *EE = nullptr;
Lang Hames93de2a12015-01-23 21:25:00 +0000544 if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
Lang Hames633fe142015-03-30 03:37:06 +0000545 EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
546 std::move(Resolver),
Lang Hames93de2a12015-01-23 21:25:00 +0000547 std::move(TheTM));
548 EE->addModule(std::move(M));
549 } else if (ExecutionEngine::MCJITCtor)
Lang Hames633fe142015-03-30 03:37:06 +0000550 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
551 std::move(Resolver), std::move(TheTM));
Lang Hames93de2a12015-01-23 21:25:00 +0000552
Lang Hamesbc876012014-04-18 06:48:23 +0000553 if (EE) {
554 EE->setVerifyModules(VerifyModules);
555 return EE;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000556 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000557 }
558
559 // If we can't make a JIT and we didn't request one specifically, try making
560 // an interpreter instead.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000561 if (WhichEngine & EngineKind::Interpreter) {
562 if (ExecutionEngine::InterpCtor)
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000563 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
Chris Lattner8bcc6442009-09-23 02:03:49 +0000564 if (ErrorStr)
565 *ErrorStr = "Interpreter has not been linked in.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000566 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000567 }
Chris Lattner8bcc6442009-09-23 02:03:49 +0000568
Eric Christopher79cc1e32014-09-02 22:28:02 +0000569 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000570 if (ErrorStr)
571 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000572 }
573
Craig Topper2617dcc2014-04-15 06:32:26 +0000574 return nullptr;
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000575}
576
Chris Lattner996fe012002-12-24 00:01:05 +0000577void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke1678e852003-08-13 18:16:14 +0000578 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattner996fe012002-12-24 00:01:05 +0000579 return getPointerToFunction(F);
580
Zachary Turnerc04b8922014-06-20 21:07:14 +0000581 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000582 if (void* P = getPointerToGlobalIfAvailable(GV))
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000583 return P;
Jeff Cohen69e849012006-02-07 05:11:57 +0000584
585 // Global variable might have been added since interpreter started.
586 if (GlobalVariable *GVar =
587 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
588 EmitGlobalVariable(GVar);
589 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000590 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000591
Lang Hames3dac3f72015-03-31 20:31:14 +0000592 return getPointerToGlobalIfAvailable(GV);
Chris Lattner996fe012002-12-24 00:01:05 +0000593}
594
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000595/// \brief Converts a Constant* into a GenericValue, including handling of
596/// ConstantExpr values.
Chris Lattner996fe012002-12-24 00:01:05 +0000597GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000598 // If its undefined, return the garbage.
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000599 if (isa<UndefValue>(C)) {
600 GenericValue Result;
601 switch (C->getType()->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000602 default:
603 break;
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000604 case Type::IntegerTyID:
605 case Type::X86_FP80TyID:
606 case Type::FP128TyID:
607 case Type::PPC_FP128TyID:
608 // Although the value is undefined, we still have to construct an APInt
609 // with the correct bit width.
610 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
611 break;
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000612 case Type::StructTyID: {
613 // if the whole struct is 'undef' just reserve memory for the value.
614 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
615 unsigned int elemNum = STy->getNumElements();
616 Result.AggregateVal.resize(elemNum);
617 for (unsigned int i = 0; i < elemNum; ++i) {
618 Type *ElemTy = STy->getElementType(i);
619 if (ElemTy->isIntegerTy())
620 Result.AggregateVal[i].IntVal =
621 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
622 else if (ElemTy->isAggregateType()) {
623 const Constant *ElemUndef = UndefValue::get(ElemTy);
624 Result.AggregateVal[i] = getConstantValue(ElemUndef);
625 }
626 }
627 }
628 }
629 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000630 case Type::VectorTyID:
631 // if the whole vector is 'undef' just reserve memory for the value.
Craig Toppere3dcce92015-08-01 22:20:21 +0000632 auto* VTy = dyn_cast<VectorType>(C->getType());
633 Type *ElemTy = VTy->getElementType();
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000634 unsigned int elemNum = VTy->getNumElements();
635 Result.AggregateVal.resize(elemNum);
636 if (ElemTy->isIntegerTy())
637 for (unsigned int i = 0; i < elemNum; ++i)
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000638 Result.AggregateVal[i].IntVal =
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000639 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000640 break;
641 }
642 return Result;
643 }
Chris Lattner9de0d142003-04-23 19:01:49 +0000644
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000645 // Otherwise, if the value is a ConstantExpr...
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000646 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000647 Constant *Op0 = CE->getOperand(0);
Chris Lattner9de0d142003-04-23 19:01:49 +0000648 switch (CE->getOpcode()) {
649 case Instruction::GetElementPtr: {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000650 // Compute the index
Reid Spencer4fd528f2007-03-06 22:23:15 +0000651 GenericValue Result = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000652 APInt Offset(DL.getPointerSizeInBits(), 0);
653 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, Offset);
Misha Brukman835702a2005-04-21 22:36:52 +0000654
Reid Spencer87aa65f2007-03-06 03:04:04 +0000655 char* tmp = (char*) Result.PointerVal;
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000656 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattner9de0d142003-04-23 19:01:49 +0000657 return Result;
658 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000659 case Instruction::Trunc: {
660 GenericValue GV = getConstantValue(Op0);
661 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
662 GV.IntVal = GV.IntVal.trunc(BitWidth);
663 return GV;
664 }
665 case Instruction::ZExt: {
666 GenericValue GV = getConstantValue(Op0);
667 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
668 GV.IntVal = GV.IntVal.zext(BitWidth);
669 return GV;
670 }
671 case Instruction::SExt: {
672 GenericValue GV = getConstantValue(Op0);
673 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
674 GV.IntVal = GV.IntVal.sext(BitWidth);
675 return GV;
676 }
677 case Instruction::FPTrunc: {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000678 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000679 GenericValue GV = getConstantValue(Op0);
680 GV.FloatVal = float(GV.DoubleVal);
681 return GV;
682 }
683 case Instruction::FPExt:{
Dale Johannesena1336cf2007-09-17 18:44:13 +0000684 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000685 GenericValue GV = getConstantValue(Op0);
686 GV.DoubleVal = double(GV.FloatVal);
687 return GV;
688 }
689 case Instruction::UIToFP: {
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.roundToDouble());
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.roundToDouble();
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 false,
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::SIToFP: {
705 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000706 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000707 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000708 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000709 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000710 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000711 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000712 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000713 true,
714 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000715 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000716 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000717 return GV;
718 }
719 case Instruction::FPToUI: // double->APInt conversion handles sign
720 case Instruction::FPToSI: {
721 GenericValue GV = getConstantValue(Op0);
722 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000723 if (Op0->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000724 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000725 else if (Op0->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000726 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000727 else if (Op0->getType()->isX86_FP80Ty()) {
Tim Northover29178a32013-01-22 09:46:31 +0000728 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000729 uint64_t v;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000730 bool ignored;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000731 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000732 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000733 APFloat::rmTowardZero, &ignored);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000734 GV.IntVal = v; // endian?
735 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000736 return GV;
737 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000738 case Instruction::PtrToInt: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000739 GenericValue GV = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000740 uint32_t PtrWidth = DL.getTypeSizeInBits(Op0->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000741 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000742 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000743 uint32_t IntWidth = DL.getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000744 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000745 return GV;
746 }
747 case Instruction::IntToPtr: {
748 GenericValue GV = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000749 uint32_t PtrWidth = DL.getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000750 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000751 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
752 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000753 return GV;
754 }
755 case Instruction::BitCast: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000756 GenericValue GV = getConstantValue(Op0);
Chris Lattner229907c2011-07-18 04:54:35 +0000757 Type* DestTy = CE->getType();
Reid Spencer4fd528f2007-03-06 22:23:15 +0000758 switch (Op0->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000759 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000760 case Type::IntegerTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000761 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnerfdd87902009-10-05 05:54:46 +0000762 if (DestTy->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000763 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000764 else if (DestTy->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000765 GV.DoubleVal = GV.IntVal.bitsToDouble();
766 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000767 case Type::FloatTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000768 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000769 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000770 break;
771 case Type::DoubleTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000772 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000773 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000774 break;
775 case Type::PointerTyID:
Duncan Sands19d0b472010-02-16 11:11:14 +0000776 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000777 break; // getConstantValue(Op0) above already converted it
778 }
779 return GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000780 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000781 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +0000782 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000783 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +0000784 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000785 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +0000786 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000787 case Instruction::UDiv:
788 case Instruction::SDiv:
789 case Instruction::URem:
790 case Instruction::SRem:
791 case Instruction::And:
792 case Instruction::Or:
793 case Instruction::Xor: {
794 GenericValue LHS = getConstantValue(Op0);
795 GenericValue RHS = getConstantValue(CE->getOperand(1));
796 GenericValue GV;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000797 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000798 default: llvm_unreachable("Bad add type!");
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000799 case Type::IntegerTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000800 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000801 default: llvm_unreachable("Invalid integer opcode");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000802 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
803 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
804 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
805 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
806 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
807 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
808 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
809 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
810 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
811 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
812 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000813 break;
814 case Type::FloatTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000815 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000816 default: llvm_unreachable("Invalid float opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000817 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000818 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000819 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000820 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000821 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000822 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000823 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000824 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000825 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000826 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000827 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000828 break;
829 case Type::DoubleTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000830 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000831 default: llvm_unreachable("Invalid double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000832 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000833 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000834 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000835 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000836 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000837 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000838 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000839 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000840 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000841 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000842 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000843 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000844 case Type::X86_FP80TyID:
845 case Type::PPC_FP128TyID:
846 case Type::FP128TyID: {
Tim Northover29178a32013-01-22 09:46:31 +0000847 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
848 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000849 switch (CE->getOpcode()) {
Daniel Dunbare4f47432010-11-13 00:55:42 +0000850 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000851 case Instruction::FAdd:
Tim Northover29178a32013-01-22 09:46:31 +0000852 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000853 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000854 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000855 case Instruction::FSub:
Tim Northover29178a32013-01-22 09:46:31 +0000856 apfLHS.subtract(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;
Dan Gohmana5b96452009-06-04 22:49:04 +0000860 case Instruction::FMul:
Tim Northover29178a32013-01-22 09:46:31 +0000861 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
862 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000863 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000864 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000865 case Instruction::FDiv:
Tim Northover29178a32013-01-22 09:46:31 +0000866 apfLHS.divide(APFloat(Sem, RHS.IntVal),
867 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000868 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000869 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000870 case Instruction::FRem:
Stephen Canonb12db0e2015-09-21 19:29:25 +0000871 apfLHS.mod(APFloat(Sem, RHS.IntVal));
Dale Johannesen54306fe2008-10-09 18:53:47 +0000872 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000873 break;
874 }
875 }
876 break;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000877 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000878 return GV;
879 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000880 default:
881 break;
882 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000883
884 SmallString<256> Msg;
885 raw_svector_ostream OS(Msg);
886 OS << "ConstantExpr not handled: " << *CE;
887 report_fatal_error(OS.str());
Chris Lattner68cbcc32003-05-14 17:51:49 +0000888 }
Misha Brukman835702a2005-04-21 22:36:52 +0000889
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000890 // Otherwise, we have a simple constant.
Reid Spencer4fd528f2007-03-06 22:23:15 +0000891 GenericValue Result;
Chris Lattner6b727592004-06-17 18:19:28 +0000892 switch (C->getType()->getTypeID()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000893 case Type::FloatTyID:
894 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000895 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000896 case Type::DoubleTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000897 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer87aa65f2007-03-06 03:04:04 +0000898 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000899 case Type::X86_FP80TyID:
900 case Type::FP128TyID:
901 case Type::PPC_FP128TyID:
Dale Johannesen54306fe2008-10-09 18:53:47 +0000902 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000903 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000904 case Type::IntegerTyID:
905 Result.IntVal = cast<ConstantInt>(C)->getValue();
906 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000907 case Type::PointerTyID:
Reid Spencer6a0fd732004-07-18 00:41:27 +0000908 if (isa<ConstantPointerNull>(C))
Craig Topper2617dcc2014-04-15 06:32:26 +0000909 Result.PointerVal = nullptr;
Reid Spencer6a0fd732004-07-18 00:41:27 +0000910 else if (const Function *F = dyn_cast<Function>(C))
911 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000912 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer6a0fd732004-07-18 00:41:27 +0000913 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
914 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000915 llvm_unreachable("Unknown constant pointer type!");
Chris Lattner996fe012002-12-24 00:01:05 +0000916 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000917 case Type::VectorTyID: {
918 unsigned elemNum;
919 Type* ElemTy;
920 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
921 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
922 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
923
924 if (CDV) {
925 elemNum = CDV->getNumElements();
926 ElemTy = CDV->getElementType();
927 } else if (CV || CAZ) {
928 VectorType* VTy = dyn_cast<VectorType>(C->getType());
929 elemNum = VTy->getNumElements();
930 ElemTy = VTy->getElementType();
931 } else {
932 llvm_unreachable("Unknown constant vector type!");
933 }
934
935 Result.AggregateVal.resize(elemNum);
936 // Check if vector holds floats.
937 if(ElemTy->isFloatTy()) {
938 if (CAZ) {
939 GenericValue floatZero;
940 floatZero.FloatVal = 0.f;
941 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
942 floatZero);
943 break;
944 }
945 if(CV) {
946 for (unsigned i = 0; i < elemNum; ++i)
947 if (!isa<UndefValue>(CV->getOperand(i)))
948 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
949 CV->getOperand(i))->getValueAPF().convertToFloat();
950 break;
951 }
952 if(CDV)
953 for (unsigned i = 0; i < elemNum; ++i)
954 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
955
956 break;
957 }
958 // Check if vector holds doubles.
959 if (ElemTy->isDoubleTy()) {
960 if (CAZ) {
961 GenericValue doubleZero;
962 doubleZero.DoubleVal = 0.0;
963 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
964 doubleZero);
965 break;
966 }
967 if(CV) {
968 for (unsigned i = 0; i < elemNum; ++i)
969 if (!isa<UndefValue>(CV->getOperand(i)))
970 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
971 CV->getOperand(i))->getValueAPF().convertToDouble();
972 break;
973 }
974 if(CDV)
975 for (unsigned i = 0; i < elemNum; ++i)
976 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
977
978 break;
979 }
980 // Check if vector holds integers.
981 if (ElemTy->isIntegerTy()) {
982 if (CAZ) {
983 GenericValue intZero;
984 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
985 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
986 intZero);
987 break;
988 }
989 if(CV) {
990 for (unsigned i = 0; i < elemNum; ++i)
991 if (!isa<UndefValue>(CV->getOperand(i)))
992 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
993 CV->getOperand(i))->getValue();
994 else {
995 Result.AggregateVal[i].IntVal =
996 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
997 }
998 break;
999 }
1000 if(CDV)
1001 for (unsigned i = 0; i < elemNum; ++i)
1002 Result.AggregateVal[i].IntVal = APInt(
1003 CDV->getElementType()->getPrimitiveSizeInBits(),
1004 CDV->getElementAsInteger(i));
1005
1006 break;
1007 }
1008 llvm_unreachable("Unknown constant pointer type!");
1009 }
1010 break;
1011
Chris Lattner996fe012002-12-24 00:01:05 +00001012 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001013 SmallString<256> Msg;
1014 raw_svector_ostream OS(Msg);
1015 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
1016 report_fatal_error(OS.str());
Chris Lattner996fe012002-12-24 00:01:05 +00001017 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001018
Chris Lattner996fe012002-12-24 00:01:05 +00001019 return Result;
1020}
1021
Duncan Sands1202d1b2007-12-14 19:38:31 +00001022/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1023/// with the integer held in IntVal.
1024static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1025 unsigned StoreBytes) {
1026 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divackyad06cee2012-09-05 22:26:57 +00001027 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands1202d1b2007-12-14 19:38:31 +00001028
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001029 if (sys::IsLittleEndianHost) {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001030 // Little-endian host - the source is ordered from LSB to MSB. Order the
1031 // destination from LSB to MSB: Do a straight copy.
1032 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001033 } else {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001034 // Big-endian host - the source is an array of 64 bit words ordered from
1035 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1036 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1037 while (StoreBytes > sizeof(uint64_t)) {
1038 StoreBytes -= sizeof(uint64_t);
1039 // May not be aligned so use memcpy.
1040 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1041 Src += sizeof(uint64_t);
1042 }
1043
1044 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1045 }
1046}
1047
Evan Cheng09053e62008-11-04 06:10:31 +00001048void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattner229907c2011-07-18 04:54:35 +00001049 GenericValue *Ptr, Type *Ty) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001050 const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001051
Reid Spencer87aa65f2007-03-06 03:04:04 +00001052 switch (Ty->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001053 default:
1054 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1055 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001056 case Type::IntegerTyID:
1057 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001058 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001059 case Type::FloatTyID:
1060 *((float*)Ptr) = Val.FloatVal;
1061 break;
1062 case Type::DoubleTyID:
1063 *((double*)Ptr) = Val.DoubleVal;
1064 break;
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001065 case Type::X86_FP80TyID:
1066 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1067 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001068 case Type::PointerTyID:
1069 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1070 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth93da3c82011-04-28 08:37:18 +00001071 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001072
Reid Spencer87aa65f2007-03-06 03:04:04 +00001073 *((PointerTy*)Ptr) = Val.PointerVal;
1074 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001075 case Type::VectorTyID:
1076 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1077 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1078 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1079 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1080 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1081 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1082 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1083 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1084 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1085 }
1086 }
1087 break;
Chris Lattner996fe012002-12-24 00:01:05 +00001088 }
Duncan Sands1202d1b2007-12-14 19:38:31 +00001089
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001090 if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
Duncan Sands1202d1b2007-12-14 19:38:31 +00001091 // Host and target are different endian - reverse the stored bytes.
1092 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1093}
1094
1095/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1096/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1097static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1098 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greene82b63572013-01-14 21:04:45 +00001099 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1100 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands1202d1b2007-12-14 19:38:31 +00001101
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001102 if (sys::IsLittleEndianHost)
Duncan Sands1202d1b2007-12-14 19:38:31 +00001103 // Little-endian host - the destination must be ordered from LSB to MSB.
1104 // The source is ordered from LSB to MSB: Do a straight copy.
1105 memcpy(Dst, Src, LoadBytes);
1106 else {
1107 // Big-endian - the destination is an array of 64 bit words ordered from
1108 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1109 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1110 // a word.
1111 while (LoadBytes > sizeof(uint64_t)) {
1112 LoadBytes -= sizeof(uint64_t);
1113 // May not be aligned so use memcpy.
1114 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1115 Dst += sizeof(uint64_t);
1116 }
1117
1118 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1119 }
Chris Lattner996fe012002-12-24 00:01:05 +00001120}
1121
Misha Brukman857c21b2003-10-10 17:45:12 +00001122/// FIXME: document
1123///
Duncan Sands1202d1b2007-12-14 19:38:31 +00001124void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandscd4a6be2008-03-10 16:38:37 +00001125 GenericValue *Ptr,
Chris Lattner229907c2011-07-18 04:54:35 +00001126 Type *Ty) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001127 const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
Duncan Sands5c65cb42007-12-10 17:43:13 +00001128
Duncan Sands1202d1b2007-12-14 19:38:31 +00001129 switch (Ty->getTypeID()) {
1130 case Type::IntegerTyID:
1131 // An APInt with all words initially zero.
1132 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1133 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1134 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001135 case Type::FloatTyID:
1136 Result.FloatVal = *((float*)Ptr);
1137 break;
1138 case Type::DoubleTyID:
Duncan Sands1202d1b2007-12-14 19:38:31 +00001139 Result.DoubleVal = *((double*)Ptr);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001140 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001141 case Type::PointerTyID:
Reid Spencer87aa65f2007-03-06 03:04:04 +00001142 Result.PointerVal = *((PointerTy*)Ptr);
1143 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +00001144 case Type::X86_FP80TyID: {
1145 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands26d65392007-12-15 17:37:40 +00001146 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001147 uint64_t y[2];
1148 memcpy(y, Ptr, 10);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00001149 Result.IntVal = APInt(80, y);
Dale Johannesena1336cf2007-09-17 18:44:13 +00001150 break;
1151 }
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001152 case Type::VectorTyID: {
Craig Toppere3dcce92015-08-01 22:20:21 +00001153 auto *VT = cast<VectorType>(Ty);
1154 Type *ElemT = VT->getElementType();
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001155 const unsigned numElems = VT->getNumElements();
1156 if (ElemT->isFloatTy()) {
1157 Result.AggregateVal.resize(numElems);
1158 for (unsigned i = 0; i < numElems; ++i)
1159 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1160 }
1161 if (ElemT->isDoubleTy()) {
1162 Result.AggregateVal.resize(numElems);
1163 for (unsigned i = 0; i < numElems; ++i)
1164 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1165 }
1166 if (ElemT->isIntegerTy()) {
1167 GenericValue intZero;
1168 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1169 intZero.IntVal = APInt(elemBitWidth, 0);
1170 Result.AggregateVal.resize(numElems, intZero);
1171 for (unsigned i = 0; i < numElems; ++i)
1172 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1173 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1174 }
1175 break;
1176 }
Reid Spencer87aa65f2007-03-06 03:04:04 +00001177 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001178 SmallString<256> Msg;
1179 raw_svector_ostream OS(Msg);
1180 OS << "Cannot load value of type " << *Ty << "!";
1181 report_fatal_error(OS.str());
Chris Lattner7f389e82003-05-08 16:52:16 +00001182 }
Chris Lattner7f389e82003-05-08 16:52:16 +00001183}
1184
Chris Lattner996fe012002-12-24 00:01:05 +00001185void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene0967d2d2010-01-05 01:27:39 +00001186 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesenb086d382008-08-07 01:30:15 +00001187 DEBUG(Init->dump());
Chris Lattner00245f42012-01-24 13:41:11 +00001188 if (isa<UndefValue>(Init))
Chris Lattner61753bf2004-10-16 18:19:26 +00001189 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001190
1191 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino69d62132006-01-20 18:18:40 +00001192 unsigned ElementSize =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001193 getDataLayout().getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino69d62132006-01-20 18:18:40 +00001194 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1195 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1196 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001197 }
1198
1199 if (isa<ConstantAggregateZero>(Init)) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001200 memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));
Chris Lattner1dd86b12008-02-15 00:57:28 +00001201 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001202 }
1203
1204 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001205 unsigned ElementSize =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001206 getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001207 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1208 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1209 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001210 }
1211
1212 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001213 const StructLayout *SL =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001214 getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001215 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1216 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1217 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001218 }
1219
1220 if (const ConstantDataSequential *CDS =
1221 dyn_cast<ConstantDataSequential>(Init)) {
1222 // CDS is already laid out in host memory order.
1223 StringRef Data = CDS->getRawDataValues();
1224 memcpy(Addr, Data.data(), Data.size());
1225 return;
1226 }
1227
1228 if (Init->getType()->isFirstClassType()) {
Chris Lattner996fe012002-12-24 00:01:05 +00001229 GenericValue Val = getConstantValue(Init);
1230 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1231 return;
1232 }
1233
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001234 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinfbcc6632009-07-14 16:55:14 +00001235 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattner996fe012002-12-24 00:01:05 +00001236}
1237
Chris Lattner996fe012002-12-24 00:01:05 +00001238/// EmitGlobals - Emit all of the global variables to memory, storing their
1239/// addresses into GlobalAddress. This must make sure to copy the contents of
1240/// their initializers into the memory.
Chris Lattner996fe012002-12-24 00:01:05 +00001241void ExecutionEngine::emitGlobals() {
Chris Lattner996fe012002-12-24 00:01:05 +00001242 // Loop over all of the global variables in the program, allocating the memory
Chris Lattner0621cae2006-08-16 01:24:12 +00001243 // to hold them. If there is more than one module, do a prepass over globals
1244 // to figure out how the different modules should link together.
Chris Lattner229907c2011-07-18 04:54:35 +00001245 std::map<std::pair<std::string, Type*>,
Chris Lattner0621cae2006-08-16 01:24:12 +00001246 const GlobalValue*> LinkedGlobalsMap;
Misha Brukman835702a2005-04-21 22:36:52 +00001247
Chris Lattner0621cae2006-08-16 01:24:12 +00001248 if (Modules.size() != 1) {
1249 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001250 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001251 for (const auto &GV : M.globals()) {
1252 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1253 GV.hasAppendingLinkage() || !GV.hasName())
Chris Lattner0621cae2006-08-16 01:24:12 +00001254 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001255
1256 const GlobalValue *&GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001257 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
Chris Lattner0621cae2006-08-16 01:24:12 +00001258
1259 // If this is the first time we've seen this global, it is the canonical
1260 // version.
1261 if (!GVEntry) {
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001262 GVEntry = &GV;
Chris Lattner0621cae2006-08-16 01:24:12 +00001263 continue;
1264 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001265
Chris Lattner0621cae2006-08-16 01:24:12 +00001266 // If the existing global is strong, never replace it.
Nico Rieck7157bb72014-01-14 15:22:47 +00001267 if (GVEntry->hasExternalLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +00001268 continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001269
Chris Lattner0621cae2006-08-16 01:24:12 +00001270 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesence4396b2008-05-14 20:12:51 +00001271 // symbol. FIXME is this right for common?
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001272 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1273 GVEntry = &GV;
Chris Lattner9de0d142003-04-23 19:01:49 +00001274 }
Chris Lattner996fe012002-12-24 00:01:05 +00001275 }
Chris Lattner0621cae2006-08-16 01:24:12 +00001276 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001277
Chris Lattner0621cae2006-08-16 01:24:12 +00001278 std::vector<const GlobalValue*> NonCanonicalGlobals;
1279 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001280 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001281 for (const auto &GV : M.globals()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001282 // In the multi-module case, see what this global maps to.
1283 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001284 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001285 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001286 // If something else is the canonical global, ignore this one.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001287 if (GVEntry != &GV) {
1288 NonCanonicalGlobals.push_back(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001289 continue;
1290 }
1291 }
1292 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001293
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001294 if (!GV.isDeclaration()) {
1295 addGlobalMapping(&GV, getMemoryForGV(&GV));
Chris Lattner0621cae2006-08-16 01:24:12 +00001296 } else {
1297 // External variable reference. Try to use the dynamic loader to
1298 // get a pointer to it.
1299 if (void *SymAddr =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001300 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1301 addGlobalMapping(&GV, SymAddr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001302 else {
Chris Lattner2104b8d2010-04-07 22:58:41 +00001303 report_fatal_error("Could not resolve external global address: "
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001304 +GV.getName());
Chris Lattner0621cae2006-08-16 01:24:12 +00001305 }
1306 }
1307 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001308
Chris Lattner0621cae2006-08-16 01:24:12 +00001309 // If there are multiple modules, map the non-canonical globals to their
1310 // canonical location.
1311 if (!NonCanonicalGlobals.empty()) {
1312 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1313 const GlobalValue *GV = NonCanonicalGlobals[i];
1314 const GlobalValue *CGV =
1315 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1316 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1317 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesa67f06b2008-10-14 10:04:52 +00001318 addGlobalMapping(GV, Ptr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001319 }
1320 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001321
1322 // Now that all of the globals are set up in memory, loop through them all
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001323 // and initialize their contents.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001324 for (const auto &GV : M.globals()) {
1325 if (!GV.isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001326 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001327 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001328 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1329 if (GVEntry != &GV) // Not the canonical variable.
Chris Lattner0621cae2006-08-16 01:24:12 +00001330 continue;
1331 }
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001332 EmitGlobalVariable(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001333 }
1334 }
1335 }
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001336}
1337
1338// EmitGlobalVariable - This method emits the specified global variable to the
1339// address specified in GlobalAddresses, or allocates new memory if it's not
1340// already in the map.
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +00001341void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner748e8572003-12-31 20:21:04 +00001342 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattnerdc631732004-02-08 19:33:23 +00001343
Craig Topper2617dcc2014-04-15 06:32:26 +00001344 if (!GA) {
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001345 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001346 GA = getMemoryForGV(GV);
Andrew Kaylor3b442372013-11-15 17:52:54 +00001347
1348 // If we failed to allocate memory for this global, return.
Craig Topper2617dcc2014-04-15 06:32:26 +00001349 if (!GA) return;
Andrew Kaylor3b442372013-11-15 17:52:54 +00001350
Chris Lattner748e8572003-12-31 20:21:04 +00001351 addGlobalMapping(GV, GA);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001352 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001353
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001354 // Don't initialize if it's thread local, let the client do it.
1355 if (!GV->isThreadLocal())
1356 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001357
Chris Lattner229907c2011-07-18 04:54:35 +00001358 Type *ElTy = GV->getType()->getElementType();
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001359 size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);
Chris Lattnerdf1f1522005-01-08 20:13:19 +00001360 NumInitBytes += (unsigned)GVSize;
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001361 ++NumGlobals;
Chris Lattner996fe012002-12-24 00:01:05 +00001362}