blob: 1dd1812ce14dc7dfa8db3ad0b60645ff8fe74349 [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 Hames3301c7e2016-09-04 07:24:11 +000021#include "llvm/ExecutionEngine/ObjectCache.h"
Lang Hames633fe142015-03-30 03:37:06 +000022#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
Lang Hames3dac3f72015-03-31 20:31:14 +000026#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
28#include "llvm/IR/Operator.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000029#include "llvm/IR/ValueHandle.h"
Rafael Espindoladd396572014-08-01 19:28:15 +000030#include "llvm/Object/Archive.h"
David Blaikie35907d82014-04-29 22:04:55 +000031#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000032#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/DynamicLibrary.h"
Torok Edwin6c2d2332009-07-07 17:32:34 +000034#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Support/Host.h"
Chris Lattner6d8dd182006-05-08 22:00:52 +000036#include "llvm/Support/MutexGuard.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Support/TargetRegistry.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000038#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +000039#include "llvm/Target/TargetMachine.h"
Anton Korobeynikov579f0712008-02-20 11:08:44 +000040#include <cmath>
41#include <cstring>
Chris Lattner29681de2003-11-19 21:08:57 +000042using namespace llvm;
Chris Lattner996fe012002-12-24 00:01:05 +000043
Chandler Carruthf58e3762014-04-22 03:04:17 +000044#define DEBUG_TYPE "jit"
45
Chris Lattnerc346ecd2006-12-19 22:43:32 +000046STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
47STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattner996fe012002-12-24 00:01:05 +000048
Daniel Dunbar70ff8b02010-11-17 16:06:37 +000049ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
David Blaikie196e3232014-09-02 22:41:07 +000050 std::unique_ptr<Module> M, std::string *ErrorStr,
Lang Hames633fe142015-03-30 03:37:06 +000051 std::shared_ptr<MCJITMemoryManager> MemMgr,
Lang Hamesad4a9112016-08-01 20:49:11 +000052
53 std::shared_ptr<JITSymbolResolver> Resolver,
Lang Hames4a5697e2014-12-03 00:51:19 +000054 std::unique_ptr<TargetMachine> TM) = nullptr;
Lang Hames93de2a12015-01-23 21:25:00 +000055
56ExecutionEngine *(*ExecutionEngine::OrcMCJITReplacementCtor)(
Lang Hames633fe142015-03-30 03:37:06 +000057 std::string *ErrorStr, std::shared_ptr<MCJITMemoryManager> MemMgr,
Lang Hamesad4a9112016-08-01 20:49:11 +000058 std::shared_ptr<JITSymbolResolver> Resolver,
Lang Hames93de2a12015-01-23 21:25:00 +000059 std::unique_ptr<TargetMachine> TM) = nullptr;
60
Rafael Espindola2a8a2792014-08-19 04:04:25 +000061ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
Craig Topper2617dcc2014-04-15 06:32:26 +000062 std::string *ErrorStr) =nullptr;
Chris Lattner2d52c1b2006-03-22 06:07:50 +000063
Lang Hames7ea98e12014-11-27 01:41:16 +000064void JITEventListener::anchor() {}
65
Lang Hames3301c7e2016-09-04 07:24:11 +000066void ObjectCache::anchor() {}
67
Mehdi Aminia3fcefb2015-07-16 16:34:23 +000068void ExecutionEngine::Init(std::unique_ptr<Module> M) {
Jeffrey Yasskin4567db42009-10-27 20:30:28 +000069 CompilingLazily = false;
Evan Chengcdc00602008-09-24 16:25:55 +000070 GVCompilationDisabled = false;
Evan Cheng84a90552008-06-17 16:49:02 +000071 SymbolSearchingDisabled = false;
Lang Hamesbc876012014-04-18 06:48:23 +000072
73 // IR module verification is enabled by default in debug builds, and disabled
74 // by default in release builds.
75#ifndef NDEBUG
76 VerifyModules = true;
77#else
78 VerifyModules = false;
79#endif
80
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000081 assert(M && "Module is null?");
Rafael Espindola2a8a2792014-08-19 04:04:25 +000082 Modules.push_back(std::move(M));
Misha Brukman260b0c82003-10-16 21:18:05 +000083}
84
Mehdi Aminia3fcefb2015-07-16 16:34:23 +000085ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
86 : DL(M->getDataLayout()), LazyFunctionCreator(nullptr) {
87 Init(std::move(M));
88}
89
90ExecutionEngine::ExecutionEngine(DataLayout DL, std::unique_ptr<Module> M)
91 : DL(std::move(DL)), LazyFunctionCreator(nullptr) {
92 Init(std::move(M));
93}
94
Brian Gaeke92f8b302003-09-04 22:57:27 +000095ExecutionEngine::~ExecutionEngine() {
Reid Spencer603682a2007-03-03 18:19:18 +000096 clearAllGlobalMappings();
Brian Gaeke92f8b302003-09-04 22:57:27 +000097}
98
Jeffrey Yasskina4044332010-03-27 04:53:56 +000099namespace {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000100/// \brief Helper class which uses a value handler to automatically deletes the
101/// memory block when the GlobalVariable is destroyed.
David Blaikie774b5842015-08-03 22:30:24 +0000102class GVMemoryBlock final : public CallbackVH {
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000103 GVMemoryBlock(const GlobalVariable *GV)
104 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
105
106public:
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000107 /// \brief Returns the address the GlobalVariable should be written into. The
108 /// GVMemoryBlock object prefixes that.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000109 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000110 Type *ElTy = GV->getValueType();
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000111 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
112 void *RawMemory = ::operator new(
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000113 alignTo(sizeof(GVMemoryBlock), TD.getPreferredAlignment(GV)) + GVSize);
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000114 new(RawMemory) GVMemoryBlock(GV);
115 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
116 }
117
Craig Topperb51ff602014-03-08 07:51:20 +0000118 void deleted() override {
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000119 // We allocated with operator new and with some extra memory hanging off the
120 // end, so don't just delete this. I'm not sure if this is actually
121 // required.
122 this->~GVMemoryBlock();
123 ::operator delete(this);
124 }
125};
126} // anonymous namespace
127
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000128char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000129 return GVMemoryBlock::Create(GV, getDataLayout());
Nicolas Geoffray5457ce92008-10-25 15:41:43 +0000130}
131
David Blaikie35907d82014-04-29 22:04:55 +0000132void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
133 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
134}
135
Rafael Espindola7271c192014-08-26 21:04:04 +0000136void
137ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
138 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
139}
140
Rafael Espindola48af1c22014-08-19 18:44:46 +0000141void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolaacfd6282014-08-01 18:49:24 +0000142 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
143}
144
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000145bool ExecutionEngine::removeModule(Module *M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000146 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
147 Module *Found = I->get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000148 if (Found == M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000149 I->release();
Devang Patel324fe892007-10-15 19:56:32 +0000150 Modules.erase(I);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000151 clearGlobalMappingsFromModule(M);
152 return true;
Devang Patel324fe892007-10-15 19:56:32 +0000153 }
154 }
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000155 return false;
Nate Begeman617001d2009-01-23 19:27:28 +0000156}
157
Mehdi Amini7419e942016-10-01 06:22:04 +0000158Function *ExecutionEngine::FindFunctionNamed(StringRef FnName) {
Chris Lattner0621cae2006-08-16 01:24:12 +0000159 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Keno Fischer5f92a082015-01-27 19:29:00 +0000160 Function *F = Modules[i]->getFunction(FnName);
161 if (F && !F->isDeclaration())
Chris Lattner0621cae2006-08-16 01:24:12 +0000162 return F;
163 }
Craig Topper2617dcc2014-04-15 06:32:26 +0000164 return nullptr;
Chris Lattner0621cae2006-08-16 01:24:12 +0000165}
166
Mehdi Amini7419e942016-10-01 06:22:04 +0000167GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(StringRef Name, bool AllowInternal) {
Keno Fischer73378eb2015-06-20 00:55:58 +0000168 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
169 GlobalVariable *GV = Modules[i]->getGlobalVariable(Name,AllowInternal);
170 if (GV && !GV->isDeclaration())
171 return GV;
172 }
173 return nullptr;
174}
Chris Lattner0621cae2006-08-16 01:24:12 +0000175
Lang Hames3dac3f72015-03-31 20:31:14 +0000176uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
177 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
178 uint64_t OldVal;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000179
180 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
181 // GlobalAddressMap.
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000182 if (I == GlobalAddressMap.end())
Lang Hames3dac3f72015-03-31 20:31:14 +0000183 OldVal = 0;
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000184 else {
Lang Hames3dac3f72015-03-31 20:31:14 +0000185 GlobalAddressReverseMap.erase(I->second);
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000186 OldVal = I->second;
187 GlobalAddressMap.erase(I);
188 }
189
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000190 return OldVal;
191}
192
Lang Hames3dac3f72015-03-31 20:31:14 +0000193std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
Lang Hames3393cfd2015-07-29 23:12:33 +0000194 assert(GV->hasName() && "Global must have name.");
195
Lang Hames3dac3f72015-03-31 20:31:14 +0000196 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000197 SmallString<128> FullName;
Lang Hames3393cfd2015-07-29 23:12:33 +0000198
199 const DataLayout &DL =
200 GV->getParent()->getDataLayout().isDefault()
201 ? getDataLayout()
202 : GV->getParent()->getDataLayout();
203
204 Mangler::getNameWithPrefix(FullName, GV->getName(), DL);
Lang Hames3dac3f72015-03-31 20:31:14 +0000205 return FullName.str();
206}
207
Chris Lattner6d8dd182006-05-08 22:00:52 +0000208void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000209 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000210 addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
211}
Evan Cheng5cc53c32008-09-18 07:54:21 +0000212
Lang Hames3dac3f72015-03-31 20:31:14 +0000213void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
214 MutexGuard locked(lock);
215
216 assert(!Name.empty() && "Empty GlobalMapping symbol name!");
217
218 DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
219 uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
Craig Topper2617dcc2014-04-15 06:32:26 +0000220 assert((!CurVal || !Addr) && "GlobalMapping already established!");
Chris Lattner6d8dd182006-05-08 22:00:52 +0000221 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000222
223 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000224 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames3dac3f72015-03-31 20:31:14 +0000225 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
226 assert((!V.empty() || !Name.empty()) &&
227 "GlobalMapping already established!");
228 V = Name;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000229 }
230}
231
Chris Lattner6d8dd182006-05-08 22:00:52 +0000232void ExecutionEngine::clearAllGlobalMappings() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000233 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000234
Zachary Turner2f825df2014-06-16 20:54:28 +0000235 EEState.getGlobalAddressMap().clear();
236 EEState.getGlobalAddressReverseMap().clear();
Chris Lattner6d8dd182006-05-08 22:00:52 +0000237}
238
Nate Begeman8f83fc42008-05-21 16:34:48 +0000239void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000240 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000241
Peter Collingbourne6d88fde2016-06-22 20:29:42 +0000242 for (GlobalObject &GO : M->global_objects())
243 EEState.RemoveMapping(getMangledName(&GO));
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) {
Mehdi Amini7419e942016-10-01 06:22:04 +0000373 StringRef 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),
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000479 CMModel(CodeModel::JITDefault), UseOrcMCJITReplacement(false) {
Alp Toker322db9e2014-05-31 21:26:17 +0000480// IR module verification is enabled by default in debug builds, and disabled
481// by default in release builds.
482#ifndef NDEBUG
483 VerifyModules = true;
484#else
485 VerifyModules = false;
486#endif
487}
488
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000489EngineBuilder::~EngineBuilder() = default;
490
491EngineBuilder &EngineBuilder::setMCJITMemoryManager(
492 std::unique_ptr<RTDyldMemoryManager> mcjmm) {
Lang Hames633fe142015-03-30 03:37:06 +0000493 auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
494 MemMgr = SharedMM;
495 Resolver = SharedMM;
496 return *this;
497}
498
499EngineBuilder&
500EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
501 MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
502 return *this;
503}
504
505EngineBuilder&
Lang Hamesad4a9112016-08-01 20:49:11 +0000506EngineBuilder::setSymbolResolver(std::unique_ptr<JITSymbolResolver> SR) {
507 Resolver = std::shared_ptr<JITSymbolResolver>(std::move(SR));
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000508 return *this;
509}
510
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000511ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000512 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000513
Nick Lewyckya53414f2008-03-08 02:49:45 +0000514 // Make sure we can resolve symbols in the program as well. The zero arg
515 // to the function tells DynamicLibrary to load the program, not a library.
Craig Topper2617dcc2014-04-15 06:32:26 +0000516 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
517 return nullptr;
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000518
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000519 // If the user specified a memory manager but didn't specify which engine to
520 // create, we assume they only want the JIT, and we fail if they only want
521 // the interpreter.
Lang Hames633fe142015-03-30 03:37:06 +0000522 if (MemMgr) {
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000523 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000524 WhichEngine = EngineKind::JIT;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000525 else {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000526 if (ErrorStr)
527 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000528 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000529 }
530 }
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000531
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000532 // Unless the interpreter was explicitly selected or the JIT is not linked,
533 // try making a JIT.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000534 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000535 Triple TT(M->getTargetTriple());
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000536 if (!TM->getTarget().hasJIT()) {
537 errs() << "WARNING: This target JIT is not designed for the host"
538 << " you are running. If bad things happen, please choose"
539 << " a different -march switch.\n";
540 }
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000541
Lang Hamesbc876012014-04-18 06:48:23 +0000542 ExecutionEngine *EE = nullptr;
Lang Hames93de2a12015-01-23 21:25:00 +0000543 if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
Lang Hames633fe142015-03-30 03:37:06 +0000544 EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
545 std::move(Resolver),
Lang Hames93de2a12015-01-23 21:25:00 +0000546 std::move(TheTM));
547 EE->addModule(std::move(M));
548 } else if (ExecutionEngine::MCJITCtor)
Lang Hames633fe142015-03-30 03:37:06 +0000549 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
550 std::move(Resolver), std::move(TheTM));
Lang Hames93de2a12015-01-23 21:25:00 +0000551
Lang Hamesbc876012014-04-18 06:48:23 +0000552 if (EE) {
553 EE->setVerifyModules(VerifyModules);
554 return EE;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000555 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000556 }
557
558 // If we can't make a JIT and we didn't request one specifically, try making
559 // an interpreter instead.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000560 if (WhichEngine & EngineKind::Interpreter) {
561 if (ExecutionEngine::InterpCtor)
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000562 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
Chris Lattner8bcc6442009-09-23 02:03:49 +0000563 if (ErrorStr)
564 *ErrorStr = "Interpreter has not been linked in.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000565 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000566 }
Chris Lattner8bcc6442009-09-23 02:03:49 +0000567
Eric Christopher79cc1e32014-09-02 22:28:02 +0000568 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000569 if (ErrorStr)
570 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000571 }
572
Craig Topper2617dcc2014-04-15 06:32:26 +0000573 return nullptr;
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000574}
575
Chris Lattner996fe012002-12-24 00:01:05 +0000576void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke1678e852003-08-13 18:16:14 +0000577 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattner996fe012002-12-24 00:01:05 +0000578 return getPointerToFunction(F);
579
Zachary Turnerc04b8922014-06-20 21:07:14 +0000580 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000581 if (void* P = getPointerToGlobalIfAvailable(GV))
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000582 return P;
Jeff Cohen69e849012006-02-07 05:11:57 +0000583
584 // Global variable might have been added since interpreter started.
585 if (GlobalVariable *GVar =
586 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
587 EmitGlobalVariable(GVar);
588 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000589 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000590
Lang Hames3dac3f72015-03-31 20:31:14 +0000591 return getPointerToGlobalIfAvailable(GV);
Chris Lattner996fe012002-12-24 00:01:05 +0000592}
593
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000594/// \brief Converts a Constant* into a GenericValue, including handling of
595/// ConstantExpr values.
Chris Lattner996fe012002-12-24 00:01:05 +0000596GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000597 // If its undefined, return the garbage.
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000598 if (isa<UndefValue>(C)) {
599 GenericValue Result;
600 switch (C->getType()->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000601 default:
602 break;
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000603 case Type::IntegerTyID:
604 case Type::X86_FP80TyID:
605 case Type::FP128TyID:
606 case Type::PPC_FP128TyID:
607 // Although the value is undefined, we still have to construct an APInt
608 // with the correct bit width.
609 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
610 break;
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000611 case Type::StructTyID: {
612 // if the whole struct is 'undef' just reserve memory for the value.
613 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
614 unsigned int elemNum = STy->getNumElements();
615 Result.AggregateVal.resize(elemNum);
616 for (unsigned int i = 0; i < elemNum; ++i) {
617 Type *ElemTy = STy->getElementType(i);
618 if (ElemTy->isIntegerTy())
619 Result.AggregateVal[i].IntVal =
620 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
621 else if (ElemTy->isAggregateType()) {
622 const Constant *ElemUndef = UndefValue::get(ElemTy);
623 Result.AggregateVal[i] = getConstantValue(ElemUndef);
624 }
625 }
626 }
627 }
628 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000629 case Type::VectorTyID:
630 // if the whole vector is 'undef' just reserve memory for the value.
Craig Toppere3dcce92015-08-01 22:20:21 +0000631 auto* VTy = dyn_cast<VectorType>(C->getType());
632 Type *ElemTy = VTy->getElementType();
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000633 unsigned int elemNum = VTy->getNumElements();
634 Result.AggregateVal.resize(elemNum);
635 if (ElemTy->isIntegerTy())
636 for (unsigned int i = 0; i < elemNum; ++i)
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000637 Result.AggregateVal[i].IntVal =
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000638 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000639 break;
640 }
641 return Result;
642 }
Chris Lattner9de0d142003-04-23 19:01:49 +0000643
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000644 // Otherwise, if the value is a ConstantExpr...
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000645 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000646 Constant *Op0 = CE->getOperand(0);
Chris Lattner9de0d142003-04-23 19:01:49 +0000647 switch (CE->getOpcode()) {
648 case Instruction::GetElementPtr: {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000649 // Compute the index
Reid Spencer4fd528f2007-03-06 22:23:15 +0000650 GenericValue Result = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000651 APInt Offset(DL.getPointerSizeInBits(), 0);
652 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, Offset);
Misha Brukman835702a2005-04-21 22:36:52 +0000653
Reid Spencer87aa65f2007-03-06 03:04:04 +0000654 char* tmp = (char*) Result.PointerVal;
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000655 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattner9de0d142003-04-23 19:01:49 +0000656 return Result;
657 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000658 case Instruction::Trunc: {
659 GenericValue GV = getConstantValue(Op0);
660 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
661 GV.IntVal = GV.IntVal.trunc(BitWidth);
662 return GV;
663 }
664 case Instruction::ZExt: {
665 GenericValue GV = getConstantValue(Op0);
666 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
667 GV.IntVal = GV.IntVal.zext(BitWidth);
668 return GV;
669 }
670 case Instruction::SExt: {
671 GenericValue GV = getConstantValue(Op0);
672 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
673 GV.IntVal = GV.IntVal.sext(BitWidth);
674 return GV;
675 }
676 case Instruction::FPTrunc: {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000677 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000678 GenericValue GV = getConstantValue(Op0);
679 GV.FloatVal = float(GV.DoubleVal);
680 return GV;
681 }
682 case Instruction::FPExt:{
Dale Johannesena1336cf2007-09-17 18:44:13 +0000683 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000684 GenericValue GV = getConstantValue(Op0);
685 GV.DoubleVal = double(GV.FloatVal);
686 return GV;
687 }
688 case Instruction::UIToFP: {
689 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000690 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000691 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000692 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000693 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000694 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000695 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000696 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000697 false,
698 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000699 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000700 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000701 return GV;
702 }
703 case Instruction::SIToFP: {
704 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000705 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000706 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000707 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000708 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000709 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000710 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000711 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000712 true,
713 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000714 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000715 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000716 return GV;
717 }
718 case Instruction::FPToUI: // double->APInt conversion handles sign
719 case Instruction::FPToSI: {
720 GenericValue GV = getConstantValue(Op0);
721 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000722 if (Op0->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000723 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000724 else if (Op0->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000725 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000726 else if (Op0->getType()->isX86_FP80Ty()) {
Tim Northover29178a32013-01-22 09:46:31 +0000727 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000728 uint64_t v;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000729 bool ignored;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000730 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000731 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000732 APFloat::rmTowardZero, &ignored);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000733 GV.IntVal = v; // endian?
734 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000735 return GV;
736 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000737 case Instruction::PtrToInt: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000738 GenericValue GV = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000739 uint32_t PtrWidth = DL.getTypeSizeInBits(Op0->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000740 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000741 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000742 uint32_t IntWidth = DL.getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000743 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000744 return GV;
745 }
746 case Instruction::IntToPtr: {
747 GenericValue GV = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000748 uint32_t PtrWidth = DL.getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000749 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000750 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
751 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000752 return GV;
753 }
754 case Instruction::BitCast: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000755 GenericValue GV = getConstantValue(Op0);
Chris Lattner229907c2011-07-18 04:54:35 +0000756 Type* DestTy = CE->getType();
Reid Spencer4fd528f2007-03-06 22:23:15 +0000757 switch (Op0->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000758 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000759 case Type::IntegerTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000760 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnerfdd87902009-10-05 05:54:46 +0000761 if (DestTy->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000762 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000763 else if (DestTy->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000764 GV.DoubleVal = GV.IntVal.bitsToDouble();
765 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000766 case Type::FloatTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000767 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000768 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000769 break;
770 case Type::DoubleTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000771 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000772 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000773 break;
774 case Type::PointerTyID:
Duncan Sands19d0b472010-02-16 11:11:14 +0000775 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000776 break; // getConstantValue(Op0) above already converted it
777 }
778 return GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000779 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000780 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +0000781 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000782 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +0000783 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000784 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +0000785 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000786 case Instruction::UDiv:
787 case Instruction::SDiv:
788 case Instruction::URem:
789 case Instruction::SRem:
790 case Instruction::And:
791 case Instruction::Or:
792 case Instruction::Xor: {
793 GenericValue LHS = getConstantValue(Op0);
794 GenericValue RHS = getConstantValue(CE->getOperand(1));
795 GenericValue GV;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000796 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000797 default: llvm_unreachable("Bad add type!");
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000798 case Type::IntegerTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000799 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000800 default: llvm_unreachable("Invalid integer opcode");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000801 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
802 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
803 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
804 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
805 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
806 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
807 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
808 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
809 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
810 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
811 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000812 break;
813 case Type::FloatTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000814 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000815 default: llvm_unreachable("Invalid float opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000816 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000817 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000818 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000819 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000820 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000821 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000822 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000823 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000824 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000825 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000826 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000827 break;
828 case Type::DoubleTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000829 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000830 default: llvm_unreachable("Invalid double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000831 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000832 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000833 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000834 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000835 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000836 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000837 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000838 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000839 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000840 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000841 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000842 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000843 case Type::X86_FP80TyID:
844 case Type::PPC_FP128TyID:
845 case Type::FP128TyID: {
Tim Northover29178a32013-01-22 09:46:31 +0000846 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
847 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000848 switch (CE->getOpcode()) {
Daniel Dunbare4f47432010-11-13 00:55:42 +0000849 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000850 case Instruction::FAdd:
Tim Northover29178a32013-01-22 09:46:31 +0000851 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000852 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000853 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000854 case Instruction::FSub:
Tim Northover29178a32013-01-22 09:46:31 +0000855 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
856 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000857 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000858 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000859 case Instruction::FMul:
Tim Northover29178a32013-01-22 09:46:31 +0000860 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
861 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000862 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000863 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000864 case Instruction::FDiv:
Tim Northover29178a32013-01-22 09:46:31 +0000865 apfLHS.divide(APFloat(Sem, RHS.IntVal),
866 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000867 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000868 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000869 case Instruction::FRem:
Stephen Canonb12db0e2015-09-21 19:29:25 +0000870 apfLHS.mod(APFloat(Sem, RHS.IntVal));
Dale Johannesen54306fe2008-10-09 18:53:47 +0000871 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000872 break;
873 }
874 }
875 break;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000876 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000877 return GV;
878 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000879 default:
880 break;
881 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000882
883 SmallString<256> Msg;
884 raw_svector_ostream OS(Msg);
885 OS << "ConstantExpr not handled: " << *CE;
886 report_fatal_error(OS.str());
Chris Lattner68cbcc32003-05-14 17:51:49 +0000887 }
Misha Brukman835702a2005-04-21 22:36:52 +0000888
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000889 // Otherwise, we have a simple constant.
Reid Spencer4fd528f2007-03-06 22:23:15 +0000890 GenericValue Result;
Chris Lattner6b727592004-06-17 18:19:28 +0000891 switch (C->getType()->getTypeID()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000892 case Type::FloatTyID:
893 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000894 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000895 case Type::DoubleTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000896 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer87aa65f2007-03-06 03:04:04 +0000897 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000898 case Type::X86_FP80TyID:
899 case Type::FP128TyID:
900 case Type::PPC_FP128TyID:
Dale Johannesen54306fe2008-10-09 18:53:47 +0000901 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000902 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000903 case Type::IntegerTyID:
904 Result.IntVal = cast<ConstantInt>(C)->getValue();
905 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000906 case Type::PointerTyID:
Reid Spencer6a0fd732004-07-18 00:41:27 +0000907 if (isa<ConstantPointerNull>(C))
Craig Topper2617dcc2014-04-15 06:32:26 +0000908 Result.PointerVal = nullptr;
Reid Spencer6a0fd732004-07-18 00:41:27 +0000909 else if (const Function *F = dyn_cast<Function>(C))
910 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000911 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer6a0fd732004-07-18 00:41:27 +0000912 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
913 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000914 llvm_unreachable("Unknown constant pointer type!");
Chris Lattner996fe012002-12-24 00:01:05 +0000915 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000916 case Type::VectorTyID: {
917 unsigned elemNum;
918 Type* ElemTy;
919 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
920 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
921 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
922
923 if (CDV) {
924 elemNum = CDV->getNumElements();
925 ElemTy = CDV->getElementType();
926 } else if (CV || CAZ) {
927 VectorType* VTy = dyn_cast<VectorType>(C->getType());
928 elemNum = VTy->getNumElements();
929 ElemTy = VTy->getElementType();
930 } else {
931 llvm_unreachable("Unknown constant vector type!");
932 }
933
934 Result.AggregateVal.resize(elemNum);
935 // Check if vector holds floats.
936 if(ElemTy->isFloatTy()) {
937 if (CAZ) {
938 GenericValue floatZero;
939 floatZero.FloatVal = 0.f;
940 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
941 floatZero);
942 break;
943 }
944 if(CV) {
945 for (unsigned i = 0; i < elemNum; ++i)
946 if (!isa<UndefValue>(CV->getOperand(i)))
947 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
948 CV->getOperand(i))->getValueAPF().convertToFloat();
949 break;
950 }
951 if(CDV)
952 for (unsigned i = 0; i < elemNum; ++i)
953 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
954
955 break;
956 }
957 // Check if vector holds doubles.
958 if (ElemTy->isDoubleTy()) {
959 if (CAZ) {
960 GenericValue doubleZero;
961 doubleZero.DoubleVal = 0.0;
962 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
963 doubleZero);
964 break;
965 }
966 if(CV) {
967 for (unsigned i = 0; i < elemNum; ++i)
968 if (!isa<UndefValue>(CV->getOperand(i)))
969 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
970 CV->getOperand(i))->getValueAPF().convertToDouble();
971 break;
972 }
973 if(CDV)
974 for (unsigned i = 0; i < elemNum; ++i)
975 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
976
977 break;
978 }
979 // Check if vector holds integers.
980 if (ElemTy->isIntegerTy()) {
981 if (CAZ) {
982 GenericValue intZero;
983 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
984 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
985 intZero);
986 break;
987 }
988 if(CV) {
989 for (unsigned i = 0; i < elemNum; ++i)
990 if (!isa<UndefValue>(CV->getOperand(i)))
991 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
992 CV->getOperand(i))->getValue();
993 else {
994 Result.AggregateVal[i].IntVal =
995 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
996 }
997 break;
998 }
999 if(CDV)
1000 for (unsigned i = 0; i < elemNum; ++i)
1001 Result.AggregateVal[i].IntVal = APInt(
1002 CDV->getElementType()->getPrimitiveSizeInBits(),
1003 CDV->getElementAsInteger(i));
1004
1005 break;
1006 }
1007 llvm_unreachable("Unknown constant pointer type!");
1008 }
1009 break;
1010
Chris Lattner996fe012002-12-24 00:01:05 +00001011 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001012 SmallString<256> Msg;
1013 raw_svector_ostream OS(Msg);
1014 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
1015 report_fatal_error(OS.str());
Chris Lattner996fe012002-12-24 00:01:05 +00001016 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001017
Chris Lattner996fe012002-12-24 00:01:05 +00001018 return Result;
1019}
1020
Duncan Sands1202d1b2007-12-14 19:38:31 +00001021/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1022/// with the integer held in IntVal.
1023static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1024 unsigned StoreBytes) {
1025 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divackyad06cee2012-09-05 22:26:57 +00001026 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands1202d1b2007-12-14 19:38:31 +00001027
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001028 if (sys::IsLittleEndianHost) {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001029 // Little-endian host - the source is ordered from LSB to MSB. Order the
1030 // destination from LSB to MSB: Do a straight copy.
1031 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001032 } else {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001033 // Big-endian host - the source is an array of 64 bit words ordered from
1034 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1035 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1036 while (StoreBytes > sizeof(uint64_t)) {
1037 StoreBytes -= sizeof(uint64_t);
1038 // May not be aligned so use memcpy.
1039 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1040 Src += sizeof(uint64_t);
1041 }
1042
1043 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1044 }
1045}
1046
Evan Cheng09053e62008-11-04 06:10:31 +00001047void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattner229907c2011-07-18 04:54:35 +00001048 GenericValue *Ptr, Type *Ty) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001049 const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001050
Reid Spencer87aa65f2007-03-06 03:04:04 +00001051 switch (Ty->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001052 default:
1053 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1054 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001055 case Type::IntegerTyID:
1056 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001057 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001058 case Type::FloatTyID:
1059 *((float*)Ptr) = Val.FloatVal;
1060 break;
1061 case Type::DoubleTyID:
1062 *((double*)Ptr) = Val.DoubleVal;
1063 break;
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001064 case Type::X86_FP80TyID:
1065 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1066 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001067 case Type::PointerTyID:
1068 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1069 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth93da3c82011-04-28 08:37:18 +00001070 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001071
Reid Spencer87aa65f2007-03-06 03:04:04 +00001072 *((PointerTy*)Ptr) = Val.PointerVal;
1073 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001074 case Type::VectorTyID:
1075 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1076 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1077 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1078 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1079 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1080 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1081 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1082 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1083 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1084 }
1085 }
1086 break;
Chris Lattner996fe012002-12-24 00:01:05 +00001087 }
Duncan Sands1202d1b2007-12-14 19:38:31 +00001088
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001089 if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
Duncan Sands1202d1b2007-12-14 19:38:31 +00001090 // Host and target are different endian - reverse the stored bytes.
1091 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1092}
1093
1094/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1095/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1096static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1097 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greene82b63572013-01-14 21:04:45 +00001098 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1099 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands1202d1b2007-12-14 19:38:31 +00001100
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001101 if (sys::IsLittleEndianHost)
Duncan Sands1202d1b2007-12-14 19:38:31 +00001102 // Little-endian host - the destination must be ordered from LSB to MSB.
1103 // The source is ordered from LSB to MSB: Do a straight copy.
1104 memcpy(Dst, Src, LoadBytes);
1105 else {
1106 // Big-endian - the destination is an array of 64 bit words ordered from
1107 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1108 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1109 // a word.
1110 while (LoadBytes > sizeof(uint64_t)) {
1111 LoadBytes -= sizeof(uint64_t);
1112 // May not be aligned so use memcpy.
1113 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1114 Dst += sizeof(uint64_t);
1115 }
1116
1117 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1118 }
Chris Lattner996fe012002-12-24 00:01:05 +00001119}
1120
Misha Brukman857c21b2003-10-10 17:45:12 +00001121/// FIXME: document
1122///
Duncan Sands1202d1b2007-12-14 19:38:31 +00001123void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandscd4a6be2008-03-10 16:38:37 +00001124 GenericValue *Ptr,
Chris Lattner229907c2011-07-18 04:54:35 +00001125 Type *Ty) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001126 const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
Duncan Sands5c65cb42007-12-10 17:43:13 +00001127
Duncan Sands1202d1b2007-12-14 19:38:31 +00001128 switch (Ty->getTypeID()) {
1129 case Type::IntegerTyID:
1130 // An APInt with all words initially zero.
1131 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1132 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1133 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001134 case Type::FloatTyID:
1135 Result.FloatVal = *((float*)Ptr);
1136 break;
1137 case Type::DoubleTyID:
Duncan Sands1202d1b2007-12-14 19:38:31 +00001138 Result.DoubleVal = *((double*)Ptr);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001139 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001140 case Type::PointerTyID:
Reid Spencer87aa65f2007-03-06 03:04:04 +00001141 Result.PointerVal = *((PointerTy*)Ptr);
1142 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +00001143 case Type::X86_FP80TyID: {
1144 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands26d65392007-12-15 17:37:40 +00001145 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001146 uint64_t y[2];
1147 memcpy(y, Ptr, 10);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00001148 Result.IntVal = APInt(80, y);
Dale Johannesena1336cf2007-09-17 18:44:13 +00001149 break;
1150 }
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001151 case Type::VectorTyID: {
Craig Toppere3dcce92015-08-01 22:20:21 +00001152 auto *VT = cast<VectorType>(Ty);
1153 Type *ElemT = VT->getElementType();
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001154 const unsigned numElems = VT->getNumElements();
1155 if (ElemT->isFloatTy()) {
1156 Result.AggregateVal.resize(numElems);
1157 for (unsigned i = 0; i < numElems; ++i)
1158 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1159 }
1160 if (ElemT->isDoubleTy()) {
1161 Result.AggregateVal.resize(numElems);
1162 for (unsigned i = 0; i < numElems; ++i)
1163 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1164 }
1165 if (ElemT->isIntegerTy()) {
1166 GenericValue intZero;
1167 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1168 intZero.IntVal = APInt(elemBitWidth, 0);
1169 Result.AggregateVal.resize(numElems, intZero);
1170 for (unsigned i = 0; i < numElems; ++i)
1171 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1172 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1173 }
1174 break;
1175 }
Reid Spencer87aa65f2007-03-06 03:04:04 +00001176 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001177 SmallString<256> Msg;
1178 raw_svector_ostream OS(Msg);
1179 OS << "Cannot load value of type " << *Ty << "!";
1180 report_fatal_error(OS.str());
Chris Lattner7f389e82003-05-08 16:52:16 +00001181 }
Chris Lattner7f389e82003-05-08 16:52:16 +00001182}
1183
Chris Lattner996fe012002-12-24 00:01:05 +00001184void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene0967d2d2010-01-05 01:27:39 +00001185 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesenb086d382008-08-07 01:30:15 +00001186 DEBUG(Init->dump());
Chris Lattner00245f42012-01-24 13:41:11 +00001187 if (isa<UndefValue>(Init))
Chris Lattner61753bf2004-10-16 18:19:26 +00001188 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001189
1190 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino69d62132006-01-20 18:18:40 +00001191 unsigned ElementSize =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001192 getDataLayout().getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino69d62132006-01-20 18:18:40 +00001193 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1194 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1195 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001196 }
1197
1198 if (isa<ConstantAggregateZero>(Init)) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001199 memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));
Chris Lattner1dd86b12008-02-15 00:57:28 +00001200 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001201 }
1202
1203 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001204 unsigned ElementSize =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001205 getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001206 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1207 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1208 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001209 }
1210
1211 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001212 const StructLayout *SL =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001213 getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001214 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1215 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1216 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001217 }
1218
1219 if (const ConstantDataSequential *CDS =
1220 dyn_cast<ConstantDataSequential>(Init)) {
1221 // CDS is already laid out in host memory order.
1222 StringRef Data = CDS->getRawDataValues();
1223 memcpy(Addr, Data.data(), Data.size());
1224 return;
1225 }
1226
1227 if (Init->getType()->isFirstClassType()) {
Chris Lattner996fe012002-12-24 00:01:05 +00001228 GenericValue Val = getConstantValue(Init);
1229 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1230 return;
1231 }
1232
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001233 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinfbcc6632009-07-14 16:55:14 +00001234 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattner996fe012002-12-24 00:01:05 +00001235}
1236
Chris Lattner996fe012002-12-24 00:01:05 +00001237/// EmitGlobals - Emit all of the global variables to memory, storing their
1238/// addresses into GlobalAddress. This must make sure to copy the contents of
1239/// their initializers into the memory.
Chris Lattner996fe012002-12-24 00:01:05 +00001240void ExecutionEngine::emitGlobals() {
Chris Lattner996fe012002-12-24 00:01:05 +00001241 // Loop over all of the global variables in the program, allocating the memory
Chris Lattner0621cae2006-08-16 01:24:12 +00001242 // to hold them. If there is more than one module, do a prepass over globals
1243 // to figure out how the different modules should link together.
Chris Lattner229907c2011-07-18 04:54:35 +00001244 std::map<std::pair<std::string, Type*>,
Chris Lattner0621cae2006-08-16 01:24:12 +00001245 const GlobalValue*> LinkedGlobalsMap;
Misha Brukman835702a2005-04-21 22:36:52 +00001246
Chris Lattner0621cae2006-08-16 01:24:12 +00001247 if (Modules.size() != 1) {
1248 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001249 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001250 for (const auto &GV : M.globals()) {
1251 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1252 GV.hasAppendingLinkage() || !GV.hasName())
Chris Lattner0621cae2006-08-16 01:24:12 +00001253 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001254
1255 const GlobalValue *&GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001256 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
Chris Lattner0621cae2006-08-16 01:24:12 +00001257
1258 // If this is the first time we've seen this global, it is the canonical
1259 // version.
1260 if (!GVEntry) {
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001261 GVEntry = &GV;
Chris Lattner0621cae2006-08-16 01:24:12 +00001262 continue;
1263 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001264
Chris Lattner0621cae2006-08-16 01:24:12 +00001265 // If the existing global is strong, never replace it.
Nico Rieck7157bb72014-01-14 15:22:47 +00001266 if (GVEntry->hasExternalLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +00001267 continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001268
Chris Lattner0621cae2006-08-16 01:24:12 +00001269 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesence4396b2008-05-14 20:12:51 +00001270 // symbol. FIXME is this right for common?
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001271 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1272 GVEntry = &GV;
Chris Lattner9de0d142003-04-23 19:01:49 +00001273 }
Chris Lattner996fe012002-12-24 00:01:05 +00001274 }
Chris Lattner0621cae2006-08-16 01:24:12 +00001275 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001276
Chris Lattner0621cae2006-08-16 01:24:12 +00001277 std::vector<const GlobalValue*> NonCanonicalGlobals;
1278 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001279 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001280 for (const auto &GV : M.globals()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001281 // In the multi-module case, see what this global maps to.
1282 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001283 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001284 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001285 // If something else is the canonical global, ignore this one.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001286 if (GVEntry != &GV) {
1287 NonCanonicalGlobals.push_back(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001288 continue;
1289 }
1290 }
1291 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001292
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001293 if (!GV.isDeclaration()) {
1294 addGlobalMapping(&GV, getMemoryForGV(&GV));
Chris Lattner0621cae2006-08-16 01:24:12 +00001295 } else {
1296 // External variable reference. Try to use the dynamic loader to
1297 // get a pointer to it.
1298 if (void *SymAddr =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001299 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1300 addGlobalMapping(&GV, SymAddr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001301 else {
Chris Lattner2104b8d2010-04-07 22:58:41 +00001302 report_fatal_error("Could not resolve external global address: "
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001303 +GV.getName());
Chris Lattner0621cae2006-08-16 01:24:12 +00001304 }
1305 }
1306 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001307
Chris Lattner0621cae2006-08-16 01:24:12 +00001308 // If there are multiple modules, map the non-canonical globals to their
1309 // canonical location.
1310 if (!NonCanonicalGlobals.empty()) {
1311 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1312 const GlobalValue *GV = NonCanonicalGlobals[i];
1313 const GlobalValue *CGV =
1314 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1315 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1316 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesa67f06b2008-10-14 10:04:52 +00001317 addGlobalMapping(GV, Ptr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001318 }
1319 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001320
1321 // Now that all of the globals are set up in memory, loop through them all
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001322 // and initialize their contents.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001323 for (const auto &GV : M.globals()) {
1324 if (!GV.isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001325 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001326 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001327 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1328 if (GVEntry != &GV) // Not the canonical variable.
Chris Lattner0621cae2006-08-16 01:24:12 +00001329 continue;
1330 }
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001331 EmitGlobalVariable(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001332 }
1333 }
1334 }
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001335}
1336
1337// EmitGlobalVariable - This method emits the specified global variable to the
1338// address specified in GlobalAddresses, or allocates new memory if it's not
1339// already in the map.
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +00001340void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner748e8572003-12-31 20:21:04 +00001341 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattnerdc631732004-02-08 19:33:23 +00001342
Craig Topper2617dcc2014-04-15 06:32:26 +00001343 if (!GA) {
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001344 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001345 GA = getMemoryForGV(GV);
Andrew Kaylor3b442372013-11-15 17:52:54 +00001346
1347 // If we failed to allocate memory for this global, return.
Craig Topper2617dcc2014-04-15 06:32:26 +00001348 if (!GA) return;
Andrew Kaylor3b442372013-11-15 17:52:54 +00001349
Chris Lattner748e8572003-12-31 20:21:04 +00001350 addGlobalMapping(GV, GA);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001351 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001352
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001353 // Don't initialize if it's thread local, let the client do it.
1354 if (!GV->isThreadLocal())
1355 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001356
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001357 Type *ElTy = GV->getValueType();
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001358 size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);
Chris Lattnerdf1f1522005-01-08 20:13:19 +00001359 NumInitBytes += (unsigned)GVSize;
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001360 ++NumGlobals;
Chris Lattner996fe012002-12-24 00:01:05 +00001361}