blob: ae96c7f5955fef2cd7f73006129cf714b772734b [file] [log] [blame]
Misha Brukman4afac182003-10-10 17:45:12 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00009//
Chris Lattnerbd199fb2002-12-24 00:01:05 +000010// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000015#include "llvm/ExecutionEngine/ExecutionEngine.h"
Benjamin Kramerd59c5f92015-03-01 21:28:53 +000016#include "llvm/ADT/STLExtras.h"
Daniel Dunbar48dd8752010-11-13 02:48:57 +000017#include "llvm/ADT/SmallString.h"
Chris Lattner9f3ff922009-08-23 22:49:13 +000018#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000019#include "llvm/ExecutionEngine/GenericValue.h"
Lang Hames216e5322014-11-26 16:54:40 +000020#include "llvm/ExecutionEngine/JITEventListener.h"
Lang Hamesc6f214b2016-09-04 07:24:11 +000021#include "llvm/ExecutionEngine/ObjectCache.h"
Lang Hamesda621552015-03-30 03:37:06 +000022#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
Lang Hames83b5f342015-03-31 20:31:14 +000026#include "llvm/IR/Mangler.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
28#include "llvm/IR/Operator.h"
Chandler Carrutheb3d76d2014-03-04 11:17:44 +000029#include "llvm/IR/ValueHandle.h"
Rafael Espindola74856692014-08-01 19:28:15 +000030#include "llvm/Object/Archive.h"
David Blaikie167cb012014-04-29 22:04:55 +000031#include "llvm/Object/ObjectFile.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000033#include "llvm/Support/DynamicLibrary.h"
Torok Edwin31e24662009-07-07 17:32:34 +000034#include "llvm/Support/ErrorHandling.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000035#include "llvm/Support/Host.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000036#include "llvm/Support/MutexGuard.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000037#include "llvm/Support/TargetRegistry.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000038#include "llvm/Support/raw_ostream.h"
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000039#include "llvm/Target/TargetMachine.h"
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000040#include <cmath>
41#include <cstring>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000042using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000043
Chandler Carruth0d338a52014-04-22 03:04:17 +000044#define DEBUG_TYPE "jit"
45
Chris Lattner36343732006-12-19 22:43:32 +000046STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
47STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000048
Daniel Dunbar6d135972010-11-17 16:06:37 +000049ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
David Blaikie4becee12014-09-02 22:41:07 +000050 std::unique_ptr<Module> M, std::string *ErrorStr,
Lang Hamesda621552015-03-30 03:37:06 +000051 std::shared_ptr<MCJITMemoryManager> MemMgr,
Lang Hames156b9942018-01-19 22:24:13 +000052 std::shared_ptr<LegacyJITSymbolResolver> Resolver,
Lang Hames5ab94e72014-12-03 00:51:19 +000053 std::unique_ptr<TargetMachine> TM) = nullptr;
Lang Hames63cc4f52015-01-23 21:25:00 +000054
55ExecutionEngine *(*ExecutionEngine::OrcMCJITReplacementCtor)(
Lang Hames156b9942018-01-19 22:24:13 +000056 std::string *ErrorStr, std::shared_ptr<MCJITMemoryManager> MemMgr,
57 std::shared_ptr<LegacyJITSymbolResolver> Resolver,
58 std::unique_ptr<TargetMachine> TM) = nullptr;
Lang Hames63cc4f52015-01-23 21:25:00 +000059
Rafael Espindola3f4ed322014-08-19 04:04:25 +000060ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
Craig Topper0b6cb712014-04-15 06:32:26 +000061 std::string *ErrorStr) =nullptr;
Chris Lattner2fe4bb02006-03-22 06:07:50 +000062
Lang Hames7032f3c2014-11-27 01:41:16 +000063void JITEventListener::anchor() {}
64
Lang Hamesc6f214b2016-09-04 07:24:11 +000065void ObjectCache::anchor() {}
66
Mehdi Aminie02fce02015-07-16 16:34:23 +000067void ExecutionEngine::Init(std::unique_ptr<Module> M) {
Jeffrey Yasskindc857242009-10-27 20:30:28 +000068 CompilingLazily = false;
Evan Cheng446531e2008-09-24 16:25:55 +000069 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000070 SymbolSearchingDisabled = false;
Lang Hamesc3097bf2014-04-18 06:48:23 +000071
72 // IR module verification is enabled by default in debug builds, and disabled
73 // by default in release builds.
74#ifndef NDEBUG
75 VerifyModules = true;
76#else
77 VerifyModules = false;
78#endif
79
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000080 assert(M && "Module is null?");
Rafael Espindola3f4ed322014-08-19 04:04:25 +000081 Modules.push_back(std::move(M));
Misha Brukman19684162003-10-16 21:18:05 +000082}
83
Mehdi Aminie02fce02015-07-16 16:34:23 +000084ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
85 : DL(M->getDataLayout()), LazyFunctionCreator(nullptr) {
86 Init(std::move(M));
87}
88
89ExecutionEngine::ExecutionEngine(DataLayout DL, std::unique_ptr<Module> M)
90 : DL(std::move(DL)), LazyFunctionCreator(nullptr) {
91 Init(std::move(M));
92}
93
Brian Gaeke8e539482003-09-04 22:57:27 +000094ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000095 clearAllGlobalMappings();
Brian Gaeke8e539482003-09-04 22:57:27 +000096}
97
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000098namespace {
Adrian Prantl26b584c2018-05-01 15:54:18 +000099/// Helper class which uses a value handler to automatically deletes the
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000100/// memory block when the GlobalVariable is destroyed.
David Blaikiec4423f02015-08-03 22:30:24 +0000101class GVMemoryBlock final : public CallbackVH {
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000102 GVMemoryBlock(const GlobalVariable *GV)
103 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
104
105public:
Adrian Prantl26b584c2018-05-01 15:54:18 +0000106 /// Returns the address the GlobalVariable should be written into. The
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000107 /// GVMemoryBlock object prefixes that.
Micah Villmow3574eca2012-10-08 16:38:25 +0000108 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
Manuel Jacob75e1cfb2016-01-16 20:30:46 +0000109 Type *ElTy = GV->getValueType();
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000110 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
111 void *RawMemory = ::operator new(
Rui Ueyama3edb0ec2016-01-14 21:06:47 +0000112 alignTo(sizeof(GVMemoryBlock), TD.getPreferredAlignment(GV)) + GVSize);
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000113 new(RawMemory) GVMemoryBlock(GV);
114 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
115 }
116
Craig Topper838cb742014-03-08 07:51:20 +0000117 void deleted() override {
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000118 // We allocated with operator new and with some extra memory hanging off the
119 // end, so don't just delete this. I'm not sure if this is actually
120 // required.
121 this->~GVMemoryBlock();
122 ::operator delete(this);
123 }
124};
125} // anonymous namespace
126
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000127char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Mehdi Aminie02fce02015-07-16 16:34:23 +0000128 return GVMemoryBlock::Create(GV, getDataLayout());
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000129}
130
David Blaikie167cb012014-04-29 22:04:55 +0000131void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
132 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
133}
134
Rafael Espindolaaf074032014-08-26 21:04:04 +0000135void
136ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
137 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
138}
139
Rafael Espindola548f2b62014-08-19 18:44:46 +0000140void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindoladb117122014-08-01 18:49:24 +0000141 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
142}
143
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000144bool ExecutionEngine::removeModule(Module *M) {
Rafael Espindola3f4ed322014-08-19 04:04:25 +0000145 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
146 Module *Found = I->get();
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000147 if (Found == M) {
Rafael Espindola3f4ed322014-08-19 04:04:25 +0000148 I->release();
Devang Patel73d0e212007-10-15 19:56:32 +0000149 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000150 clearGlobalMappingsFromModule(M);
151 return true;
Devang Patel73d0e212007-10-15 19:56:32 +0000152 }
153 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000154 return false;
Nate Begeman60789e42009-01-23 19:27:28 +0000155}
156
Mehdi Aminid1fa61b2016-10-01 06:22:04 +0000157Function *ExecutionEngine::FindFunctionNamed(StringRef FnName) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000158 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Keno Fischer99b52292015-01-27 19:29:00 +0000159 Function *F = Modules[i]->getFunction(FnName);
160 if (F && !F->isDeclaration())
Chris Lattnerfe854032006-08-16 01:24:12 +0000161 return F;
162 }
Craig Topper0b6cb712014-04-15 06:32:26 +0000163 return nullptr;
Chris Lattnerfe854032006-08-16 01:24:12 +0000164}
165
Mehdi Aminid1fa61b2016-10-01 06:22:04 +0000166GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(StringRef Name, bool AllowInternal) {
Keno Fischerbea6fb92015-06-20 00:55:58 +0000167 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
168 GlobalVariable *GV = Modules[i]->getGlobalVariable(Name,AllowInternal);
169 if (GV && !GV->isDeclaration())
170 return GV;
171 }
172 return nullptr;
173}
Chris Lattnerfe854032006-08-16 01:24:12 +0000174
Lang Hames83b5f342015-03-31 20:31:14 +0000175uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
176 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
177 uint64_t OldVal;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000178
179 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
180 // GlobalAddressMap.
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000181 if (I == GlobalAddressMap.end())
Lang Hames83b5f342015-03-31 20:31:14 +0000182 OldVal = 0;
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000183 else {
Lang Hames83b5f342015-03-31 20:31:14 +0000184 GlobalAddressReverseMap.erase(I->second);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000185 OldVal = I->second;
186 GlobalAddressMap.erase(I);
187 }
188
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000189 return OldVal;
190}
191
Lang Hames83b5f342015-03-31 20:31:14 +0000192std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
Lang Hames7fe19722015-07-29 23:12:33 +0000193 assert(GV->hasName() && "Global must have name.");
194
Lang Hames83b5f342015-03-31 20:31:14 +0000195 MutexGuard locked(lock);
Lang Hames83b5f342015-03-31 20:31:14 +0000196 SmallString<128> FullName;
Lang Hames7fe19722015-07-29 23:12:33 +0000197
198 const DataLayout &DL =
199 GV->getParent()->getDataLayout().isDefault()
200 ? getDataLayout()
201 : GV->getParent()->getDataLayout();
202
203 Mangler::getNameWithPrefix(FullName, GV->getName(), DL);
Lang Hames83b5f342015-03-31 20:31:14 +0000204 return FullName.str();
205}
206
Chris Lattnere7fd5532006-05-08 22:00:52 +0000207void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
Zachary Turner91e18f72014-06-20 21:07:14 +0000208 MutexGuard locked(lock);
Lang Hames83b5f342015-03-31 20:31:14 +0000209 addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
210}
Evan Chengbc4707a2008-09-18 07:54:21 +0000211
Lang Hames83b5f342015-03-31 20:31:14 +0000212void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
213 MutexGuard locked(lock);
214
215 assert(!Name.empty() && "Empty GlobalMapping symbol name!");
216
Nicola Zaghen0818e782018-05-14 12:53:11 +0000217 LLVM_DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
Lang Hames83b5f342015-03-31 20:31:14 +0000218 uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
Craig Topper0b6cb712014-04-15 06:32:26 +0000219 assert((!CurVal || !Addr) && "GlobalMapping already established!");
Chris Lattnere7fd5532006-05-08 22:00:52 +0000220 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000221
222 // If we are using the reverse mapping, add it too.
Zachary Turner4031acb2014-06-16 20:54:28 +0000223 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames83b5f342015-03-31 20:31:14 +0000224 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
225 assert((!V.empty() || !Name.empty()) &&
226 "GlobalMapping already established!");
227 V = Name;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000228 }
229}
230
Chris Lattnere7fd5532006-05-08 22:00:52 +0000231void ExecutionEngine::clearAllGlobalMappings() {
Zachary Turner91e18f72014-06-20 21:07:14 +0000232 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000233
Zachary Turner4031acb2014-06-16 20:54:28 +0000234 EEState.getGlobalAddressMap().clear();
235 EEState.getGlobalAddressReverseMap().clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000236}
237
Nate Begemanf049e07e2008-05-21 16:34:48 +0000238void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
Zachary Turner91e18f72014-06-20 21:07:14 +0000239 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000240
Peter Collingbourne27725842016-06-22 20:29:42 +0000241 for (GlobalObject &GO : M->global_objects())
242 EEState.RemoveMapping(getMangledName(&GO));
Nate Begemanf049e07e2008-05-21 16:34:48 +0000243}
244
Lang Hames83b5f342015-03-31 20:31:14 +0000245uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
246 void *Addr) {
247 MutexGuard locked(lock);
248 return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
249}
250
251uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
Zachary Turner91e18f72014-06-20 21:07:14 +0000252 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000253
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000254 ExecutionEngineState::GlobalAddressMapTy &Map =
Zachary Turner4031acb2014-06-16 20:54:28 +0000255 EEState.getGlobalAddressMap();
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000256
Chris Lattnere7fd5532006-05-08 22:00:52 +0000257 // Deleting from the mapping?
Craig Topper0b6cb712014-04-15 06:32:26 +0000258 if (!Addr)
Lang Hames83b5f342015-03-31 20:31:14 +0000259 return EEState.RemoveMapping(Name);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000260
Lang Hames83b5f342015-03-31 20:31:14 +0000261 uint64_t &CurVal = Map[Name];
262 uint64_t OldVal = CurVal;
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000263
Zachary Turner4031acb2014-06-16 20:54:28 +0000264 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
265 EEState.getGlobalAddressReverseMap().erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000266 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000267
268 // If we are using the reverse mapping, add it too.
Zachary Turner4031acb2014-06-16 20:54:28 +0000269 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames83b5f342015-03-31 20:31:14 +0000270 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
271 assert((!V.empty() || !Name.empty()) &&
272 "GlobalMapping already established!");
273 V = Name;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000274 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000275 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000276}
277
Lang Hames83b5f342015-03-31 20:31:14 +0000278uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
279 MutexGuard locked(lock);
280 uint64_t Address = 0;
281 ExecutionEngineState::GlobalAddressMapTy::iterator I =
282 EEState.getGlobalAddressMap().find(S);
283 if (I != EEState.getGlobalAddressMap().end())
284 Address = I->second;
285 return Address;
286}
287
288
289void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
290 MutexGuard locked(lock);
291 if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
292 return Address;
293 return nullptr;
294}
295
Chris Lattnere7fd5532006-05-08 22:00:52 +0000296void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
Zachary Turner91e18f72014-06-20 21:07:14 +0000297 MutexGuard locked(lock);
Lang Hames83b5f342015-03-31 20:31:14 +0000298 return getPointerToGlobalIfAvailable(getMangledName(GV));
Chris Lattnere7fd5532006-05-08 22:00:52 +0000299}
300
Chris Lattner55d86482003-12-31 20:21:04 +0000301const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Zachary Turner91e18f72014-06-20 21:07:14 +0000302 MutexGuard locked(lock);
Reid Spenceree448632005-07-12 15:51:55 +0000303
Chris Lattner55d86482003-12-31 20:21:04 +0000304 // If we haven't computed the reverse mapping yet, do so first.
Zachary Turner4031acb2014-06-16 20:54:28 +0000305 if (EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000306 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Lang Hames83b5f342015-03-31 20:31:14 +0000307 I = EEState.getGlobalAddressMap().begin(),
308 E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
309 StringRef Name = I->first();
310 uint64_t Addr = I->second;
Zachary Turner4031acb2014-06-16 20:54:28 +0000311 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
Lang Hames83b5f342015-03-31 20:31:14 +0000312 Addr, Name));
313 }
Chris Lattner55d86482003-12-31 20:21:04 +0000314 }
315
Lang Hames83b5f342015-03-31 20:31:14 +0000316 std::map<uint64_t, std::string>::iterator I =
317 EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);
318
319 if (I != EEState.getGlobalAddressReverseMap().end()) {
320 StringRef Name = I->second;
321 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
322 if (GlobalValue *GV = Modules[i]->getNamedValue(Name))
323 return GV;
324 }
325 return nullptr;
Chris Lattner55d86482003-12-31 20:21:04 +0000326}
Chris Lattner87f03102003-12-26 06:50:30 +0000327
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000328namespace {
329class ArgvArray {
Dylan Noblesmith1e321bb2014-08-25 00:58:18 +0000330 std::unique_ptr<char[]> Array;
331 std::vector<std::unique_ptr<char[]>> Values;
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000332public:
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000333 /// Turn a vector of strings into a nice argv style array of pointers to null
334 /// terminated strings.
335 void *reset(LLVMContext &C, ExecutionEngine *EE,
336 const std::vector<std::string> &InputArgv);
337};
338} // anonymous namespace
339void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
340 const std::vector<std::string> &InputArgv) {
Dylan Noblesmith1e321bb2014-08-25 00:58:18 +0000341 Values.clear(); // Free the old contents.
342 Values.reserve(InputArgv.size());
Mehdi Aminie02fce02015-07-16 16:34:23 +0000343 unsigned PtrSize = EE->getDataLayout().getPointerSize();
Dylan Noblesmith1e321bb2014-08-25 00:58:18 +0000344 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
Chris Lattner87f03102003-12-26 06:50:30 +0000345
Nicola Zaghen0818e782018-05-14 12:53:11 +0000346 LLVM_DEBUG(dbgs() << "JIT: ARGV = " << (void *)Array.get() << "\n");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000347 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000348
349 for (unsigned i = 0; i != InputArgv.size(); ++i) {
350 unsigned Size = InputArgv[i].size()+1;
Dylan Noblesmith759a71a2014-08-26 02:03:28 +0000351 auto Dest = make_unique<char[]>(Size);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000352 LLVM_DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void *)Dest.get()
353 << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000354
Dylan Noblesmith759a71a2014-08-26 02:03:28 +0000355 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
Chris Lattner87f03102003-12-26 06:50:30 +0000356 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000357
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000358 // Endian safe: Array[i] = (PointerTy)Dest;
Dylan Noblesmith759a71a2014-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 Lattner87f03102003-12-26 06:50:30 +0000362 }
363
364 // Null terminate it
Craig Topper0b6cb712014-04-15 06:32:26 +0000365 EE->StoreValueToMemory(PTOGV(nullptr),
Dylan Noblesmith1e321bb2014-08-25 00:58:18 +0000366 (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
Chris Lattner87f03102003-12-26 06:50:30 +0000367 SBytePtr);
Dylan Noblesmith1e321bb2014-08-25 00:58:18 +0000368 return Array.get();
Chris Lattner87f03102003-12-26 06:50:30 +0000369}
370
Rafael Espindola3f4ed322014-08-19 04:04:25 +0000371void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
Chris Lattnerfbd39762009-09-23 01:46:04 +0000372 bool isDtors) {
Mehdi Aminid1fa61b2016-10-01 06:22:04 +0000373 StringRef Name(isDtors ? "llvm.global_dtors" : "llvm.global_ctors");
Rafael Espindola3f4ed322014-08-19 04:04:25 +0000374 GlobalVariable *GV = module.getNamedGlobal(Name);
Evan Cheng18314dc2008-09-30 15:51:21 +0000375
Daniel Dunbar48dd8752010-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 Lewyckya040d472011-04-06 20:38:44 +0000382 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000383 // the init priority, which we ignore.
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000384 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
Craig Topper0b6cb712014-04-15 06:32:26 +0000385 if (!InitList)
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000386 return;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000387 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000388 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
Craig Topper0b6cb712014-04-15 06:32:26 +0000389 if (!CS) continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000390
391 Constant *FP = CS->getOperand(1);
392 if (FP->isNullValue())
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000393 continue; // Found a sentinal value, ignore.
Daniel Dunbar48dd8752010-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 Kramer4bb355e2015-06-13 19:50:29 +0000402 runFunction(F, None);
Daniel Dunbar48dd8752010-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 Cheng18314dc2008-09-30 15:51:21 +0000408}
409
Evan Cheng18314dc2008-09-30 15:51:21 +0000410void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
411 // Execute global ctors/dtors for each module in the program.
Rafael Espindola3f4ed322014-08-19 04:04:25 +0000412 for (std::unique_ptr<Module> &M : Modules)
413 runStaticConstructorsDestructors(*M, isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000414}
415
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000416#ifndef NDEBUG
Duncan Sands8a43e9e2007-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 Aminie02fce02015-07-16 16:34:23 +0000419 unsigned PtrSize = EE->getDataLayout().getPointerSize();
Duncan Sands8a43e9e2007-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 Gohmanb6e3d6c2008-08-26 01:38:29 +0000425#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000426
Chris Lattner87f03102003-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 Spencer8fb0f192007-03-06 03:04:04 +0000432 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000433
434 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000435 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000436 FunctionType *FTy = Fn->getFunctionType();
437 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar48dd8752010-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 Yasskinb1938382010-03-26 00:59:12 +0000452 ArgvArray CArgv;
453 ArgvArray CEnv;
Chris Lattnerf24d0992004-08-16 01:05:35 +0000454 if (NumArgs) {
455 GVArgs.push_back(GVArgc); // Arg #0 = argc.
456 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000457 // Arg #1 = argv.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000458 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000459 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-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 Kramer9589ff82015-05-29 19:43:39 +0000464 EnvVars.emplace_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000465 // Arg #2 = envp.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000466 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000467 }
468 }
469 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000470
Reid Spencer8fb0f192007-03-06 03:04:04 +0000471 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000472}
473
Benjamin Kramera8c40492015-03-06 16:21:15 +0000474EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
Lang Hames63cc4f52015-01-23 21:25:00 +0000475
Lang Hames5ab94e72014-12-03 00:51:19 +0000476EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
Benjamin Kramera8c40492015-03-06 16:21:15 +0000477 : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
Lang Hamesda621552015-03-30 03:37:06 +0000478 OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr),
Rafael Espindola9aafb852017-08-03 02:16:21 +0000479 UseOrcMCJITReplacement(false) {
Alp Tokeref10f992014-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 Kramera8c40492015-03-06 16:21:15 +0000489EngineBuilder::~EngineBuilder() = default;
490
491EngineBuilder &EngineBuilder::setMCJITMemoryManager(
492 std::unique_ptr<RTDyldMemoryManager> mcjmm) {
Lang Hamesda621552015-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
Lang Hames156b9942018-01-19 22:24:13 +0000505EngineBuilder &
506EngineBuilder::setSymbolResolver(std::unique_ptr<LegacyJITSymbolResolver> SR) {
507 Resolver = std::shared_ptr<LegacyJITSymbolResolver>(std::move(SR));
Benjamin Kramera8c40492015-03-06 16:21:15 +0000508 return *this;
509}
510
Owen Anderson8e1fc562012-03-23 17:40:56 +0000511ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Ahmed Charlesf4ccd112014-03-06 05:51:42 +0000512 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
Benjamin Kramer0f554492012-04-08 14:53:14 +0000513
Nick Lewycky6456d862008-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 Topper0b6cb712014-04-15 06:32:26 +0000516 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
517 return nullptr;
Simon Pilgrim7d260e02017-03-20 13:54:44 +0000518
Reid Kleckner4b1511b2009-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 Hamesda621552015-03-30 03:37:06 +0000522 if (MemMgr) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000523 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000524 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000525 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000526 if (ErrorStr)
527 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Craig Topper0b6cb712014-04-15 06:32:26 +0000528 return nullptr;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000529 }
530 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000531
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000532 // Unless the interpreter was explicitly selected or the JIT is not linked,
533 // try making a JIT.
Benjamin Kramer0f554492012-04-08 14:53:14 +0000534 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Owen Anderson8e1fc562012-03-23 17:40:56 +0000535 if (!TM->getTarget().hasJIT()) {
536 errs() << "WARNING: This target JIT is not designed for the host"
537 << " you are running. If bad things happen, please choose"
538 << " a different -march switch.\n";
539 }
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000540
Lang Hamesc3097bf2014-04-18 06:48:23 +0000541 ExecutionEngine *EE = nullptr;
Lang Hames63cc4f52015-01-23 21:25:00 +0000542 if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
Lang Hamesda621552015-03-30 03:37:06 +0000543 EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
544 std::move(Resolver),
Lang Hames63cc4f52015-01-23 21:25:00 +0000545 std::move(TheTM));
546 EE->addModule(std::move(M));
547 } else if (ExecutionEngine::MCJITCtor)
Lang Hamesda621552015-03-30 03:37:06 +0000548 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
549 std::move(Resolver), std::move(TheTM));
Lang Hames63cc4f52015-01-23 21:25:00 +0000550
Lang Hamesc3097bf2014-04-18 06:48:23 +0000551 if (EE) {
552 EE->setVerifyModules(VerifyModules);
553 return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000554 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000555 }
556
557 // If we can't make a JIT and we didn't request one specifically, try making
558 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000559 if (WhichEngine & EngineKind::Interpreter) {
560 if (ExecutionEngine::InterpCtor)
Rafael Espindola3f4ed322014-08-19 04:04:25 +0000561 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000562 if (ErrorStr)
563 *ErrorStr = "Interpreter has not been linked in.";
Craig Topper0b6cb712014-04-15 06:32:26 +0000564 return nullptr;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000565 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000566
Eric Christopherd5dd8ce2014-09-02 22:28:02 +0000567 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000568 if (ErrorStr)
569 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000570 }
571
Craig Topper0b6cb712014-04-15 06:32:26 +0000572 return nullptr;
Brian Gaeke82d82772003-09-03 20:34:19 +0000573}
574
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000575void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000576 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000577 return getPointerToFunction(F);
578
Zachary Turner91e18f72014-06-20 21:07:14 +0000579 MutexGuard locked(lock);
Lang Hames83b5f342015-03-31 20:31:14 +0000580 if (void* P = getPointerToGlobalIfAvailable(GV))
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000581 return P;
Jeff Cohen68835dd2006-02-07 05:11:57 +0000582
583 // Global variable might have been added since interpreter started.
584 if (GlobalVariable *GVar =
585 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
586 EmitGlobalVariable(GVar);
587 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000588 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000589
Lang Hames83b5f342015-03-31 20:31:14 +0000590 return getPointerToGlobalIfAvailable(GV);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000591}
592
Adrian Prantl26b584c2018-05-01 15:54:18 +0000593/// Converts a Constant* into a GenericValue, including handling of
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000594/// ConstantExpr values.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000595GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000596 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000597 if (isa<UndefValue>(C)) {
598 GenericValue Result;
599 switch (C->getType()->getTypeID()) {
Nadav Rotem953783e2013-04-01 15:53:30 +0000600 default:
601 break;
Jay Foad5b370122010-01-15 08:32:58 +0000602 case Type::IntegerTyID:
603 case Type::X86_FP80TyID:
604 case Type::FP128TyID:
605 case Type::PPC_FP128TyID:
606 // Although the value is undefined, we still have to construct an APInt
607 // with the correct bit width.
608 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
609 break;
Elena Demikhovsky3c5ce292013-09-12 10:48:23 +0000610 case Type::StructTyID: {
611 // if the whole struct is 'undef' just reserve memory for the value.
612 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
613 unsigned int elemNum = STy->getNumElements();
614 Result.AggregateVal.resize(elemNum);
615 for (unsigned int i = 0; i < elemNum; ++i) {
616 Type *ElemTy = STy->getElementType(i);
617 if (ElemTy->isIntegerTy())
Simon Pilgrim7d260e02017-03-20 13:54:44 +0000618 Result.AggregateVal[i].IntVal =
Elena Demikhovsky3c5ce292013-09-12 10:48:23 +0000619 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
620 else if (ElemTy->isAggregateType()) {
621 const Constant *ElemUndef = UndefValue::get(ElemTy);
622 Result.AggregateVal[i] = getConstantValue(ElemUndef);
623 }
624 }
625 }
626 }
627 break;
Nadav Rotem953783e2013-04-01 15:53:30 +0000628 case Type::VectorTyID:
629 // if the whole vector is 'undef' just reserve memory for the value.
Craig Topper84bbcfe2015-08-01 22:20:21 +0000630 auto* VTy = dyn_cast<VectorType>(C->getType());
631 Type *ElemTy = VTy->getElementType();
Nadav Rotem953783e2013-04-01 15:53:30 +0000632 unsigned int elemNum = VTy->getNumElements();
633 Result.AggregateVal.resize(elemNum);
634 if (ElemTy->isIntegerTy())
635 for (unsigned int i = 0; i < elemNum; ++i)
Elena Demikhovsky3c5ce292013-09-12 10:48:23 +0000636 Result.AggregateVal[i].IntVal =
Nadav Rotem953783e2013-04-01 15:53:30 +0000637 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foad5b370122010-01-15 08:32:58 +0000638 break;
639 }
640 return Result;
641 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000642
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000643 // Otherwise, if the value is a ConstantExpr...
Reid Spencer3da59db2006-11-27 01:05:10 +0000644 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000645 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000646 switch (CE->getOpcode()) {
647 case Instruction::GetElementPtr: {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000648 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000649 GenericValue Result = getConstantValue(Op0);
Mehdi Aminie02fce02015-07-16 16:34:23 +0000650 APInt Offset(DL.getPointerSizeInBits(), 0);
651 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, Offset);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000652
Reid Spencer8fb0f192007-03-06 03:04:04 +0000653 char* tmp = (char*) Result.PointerVal;
Nuno Lopes98281a22012-12-30 16:25:48 +0000654 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000655 return Result;
656 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000657 case Instruction::Trunc: {
658 GenericValue GV = getConstantValue(Op0);
659 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
660 GV.IntVal = GV.IntVal.trunc(BitWidth);
661 return GV;
662 }
663 case Instruction::ZExt: {
664 GenericValue GV = getConstantValue(Op0);
665 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
666 GV.IntVal = GV.IntVal.zext(BitWidth);
667 return GV;
668 }
669 case Instruction::SExt: {
670 GenericValue GV = getConstantValue(Op0);
671 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
672 GV.IntVal = GV.IntVal.sext(BitWidth);
673 return GV;
674 }
675 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000676 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000677 GenericValue GV = getConstantValue(Op0);
678 GV.FloatVal = float(GV.DoubleVal);
679 return GV;
680 }
681 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000682 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000683 GenericValue GV = getConstantValue(Op0);
684 GV.DoubleVal = double(GV.FloatVal);
685 return GV;
686 }
687 case Instruction::UIToFP: {
688 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000689 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000690 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000691 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000692 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000693 else if (CE->getType()->isX86_FP80Ty()) {
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000694 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended());
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000695 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000696 false,
697 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000698 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000699 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000700 return GV;
701 }
702 case Instruction::SIToFP: {
703 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000704 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000705 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000706 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000707 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000708 else if (CE->getType()->isX86_FP80Ty()) {
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000709 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended());
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000710 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000711 true,
712 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000713 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000714 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000715 return GV;
716 }
717 case Instruction::FPToUI: // double->APInt conversion handles sign
718 case Instruction::FPToSI: {
719 GenericValue GV = getConstantValue(Op0);
720 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000721 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000722 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000723 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000724 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000725 else if (Op0->getType()->isX86_FP80Ty()) {
Stephan Bergmann20a600c2016-12-14 11:57:17 +0000726 APFloat apf = APFloat(APFloat::x87DoubleExtended(), GV.IntVal);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000727 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000728 bool ignored;
Simon Pilgrim957caa22017-03-20 14:40:12 +0000729 (void)apf.convertToInteger(makeMutableArrayRef(v), BitWidth,
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000730 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000731 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000732 GV.IntVal = v; // endian?
733 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000734 return GV;
735 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000736 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000737 GenericValue GV = getConstantValue(Op0);
Mehdi Aminie02fce02015-07-16 16:34:23 +0000738 uint32_t PtrWidth = DL.getTypeSizeInBits(Op0->getType());
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000739 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencerbce30f12007-03-06 22:23:15 +0000740 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Mehdi Aminie02fce02015-07-16 16:34:23 +0000741 uint32_t IntWidth = DL.getTypeSizeInBits(CE->getType());
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000742 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencerbce30f12007-03-06 22:23:15 +0000743 return GV;
744 }
745 case Instruction::IntToPtr: {
746 GenericValue GV = getConstantValue(Op0);
Mehdi Aminie02fce02015-07-16 16:34:23 +0000747 uint32_t PtrWidth = DL.getTypeSizeInBits(CE->getType());
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000748 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencerbce30f12007-03-06 22:23:15 +0000749 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
750 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000751 return GV;
752 }
753 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000754 GenericValue GV = getConstantValue(Op0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000755 Type* DestTy = CE->getType();
Reid Spencerbce30f12007-03-06 22:23:15 +0000756 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000757 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000758 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000759 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000760 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000761 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000762 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000763 GV.DoubleVal = GV.IntVal.bitsToDouble();
764 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000765 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000766 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000767 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000768 break;
769 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000770 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000771 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000772 break;
773 case Type::PointerTyID:
Duncan Sands1df98592010-02-16 11:11:14 +0000774 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000775 break; // getConstantValue(Op0) above already converted it
776 }
777 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000778 }
Chris Lattner9a231222003-05-14 17:51:49 +0000779 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000780 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000781 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000782 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000783 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000784 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000785 case Instruction::UDiv:
786 case Instruction::SDiv:
787 case Instruction::URem:
788 case Instruction::SRem:
789 case Instruction::And:
790 case Instruction::Or:
791 case Instruction::Xor: {
792 GenericValue LHS = getConstantValue(Op0);
793 GenericValue RHS = getConstantValue(CE->getOperand(1));
794 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000795 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000796 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000797 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000798 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000799 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000800 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
801 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
802 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
803 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
804 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
805 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
806 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
807 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
808 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
809 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
810 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000811 break;
812 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000813 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000814 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000815 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000816 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000817 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000818 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000819 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000820 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000821 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000822 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000823 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000824 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000825 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000826 break;
827 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000828 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000829 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000830 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000831 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000832 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000833 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000834 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000835 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000836 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000837 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000838 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000839 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000840 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000841 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000842 case Type::X86_FP80TyID:
843 case Type::PPC_FP128TyID:
844 case Type::FP128TyID: {
Tim Northover0a29cb02013-01-22 09:46:31 +0000845 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
846 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000847 switch (CE->getOpcode()) {
Daniel Dunbarab19da42010-11-13 00:55:42 +0000848 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000849 case Instruction::FAdd:
Tim Northover0a29cb02013-01-22 09:46:31 +0000850 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000851 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000852 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000853 case Instruction::FSub:
Tim Northover0a29cb02013-01-22 09:46:31 +0000854 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
855 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000856 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000857 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000858 case Instruction::FMul:
Tim Northover0a29cb02013-01-22 09:46:31 +0000859 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
860 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000861 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000862 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000863 case Instruction::FDiv:
Tim Northover0a29cb02013-01-22 09:46:31 +0000864 apfLHS.divide(APFloat(Sem, RHS.IntVal),
865 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000866 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000867 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000868 case Instruction::FRem:
Stephen Canonff278be2015-09-21 19:29:25 +0000869 apfLHS.mod(APFloat(Sem, RHS.IntVal));
Dale Johannesen7111b022008-10-09 18:53:47 +0000870 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000871 break;
872 }
873 }
874 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000875 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000876 return GV;
877 }
Chris Lattner9a231222003-05-14 17:51:49 +0000878 default:
879 break;
880 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000881
882 SmallString<256> Msg;
883 raw_svector_ostream OS(Msg);
884 OS << "ConstantExpr not handled: " << *CE;
885 report_fatal_error(OS.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000886 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000887
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000888 // Otherwise, we have a simple constant.
Reid Spencerbce30f12007-03-06 22:23:15 +0000889 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000890 switch (C->getType()->getTypeID()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000891 case Type::FloatTyID:
892 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000893 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000894 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000895 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000896 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000897 case Type::X86_FP80TyID:
898 case Type::FP128TyID:
899 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000900 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000901 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000902 case Type::IntegerTyID:
903 Result.IntVal = cast<ConstantInt>(C)->getValue();
904 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000905 case Type::PointerTyID:
Lang Hames91b60922018-05-24 19:07:34 +0000906 while (auto *A = dyn_cast<GlobalAlias>(C)) {
907 C = A->getAliasee();
908 }
Reid Spencer40cf2f92004-07-18 00:41:27 +0000909 if (isa<ConstantPointerNull>(C))
Craig Topper0b6cb712014-04-15 06:32:26 +0000910 Result.PointerVal = nullptr;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000911 else if (const Function *F = dyn_cast<Function>(C))
912 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000913 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000914 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
915 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000916 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000917 break;
Nadav Rotem953783e2013-04-01 15:53:30 +0000918 case Type::VectorTyID: {
919 unsigned elemNum;
920 Type* ElemTy;
921 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
922 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
923 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
924
925 if (CDV) {
926 elemNum = CDV->getNumElements();
927 ElemTy = CDV->getElementType();
928 } else if (CV || CAZ) {
929 VectorType* VTy = dyn_cast<VectorType>(C->getType());
930 elemNum = VTy->getNumElements();
931 ElemTy = VTy->getElementType();
932 } else {
933 llvm_unreachable("Unknown constant vector type!");
934 }
935
936 Result.AggregateVal.resize(elemNum);
937 // Check if vector holds floats.
938 if(ElemTy->isFloatTy()) {
939 if (CAZ) {
940 GenericValue floatZero;
941 floatZero.FloatVal = 0.f;
942 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
943 floatZero);
944 break;
945 }
946 if(CV) {
947 for (unsigned i = 0; i < elemNum; ++i)
948 if (!isa<UndefValue>(CV->getOperand(i)))
949 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
950 CV->getOperand(i))->getValueAPF().convertToFloat();
951 break;
952 }
953 if(CDV)
954 for (unsigned i = 0; i < elemNum; ++i)
955 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
956
957 break;
958 }
959 // Check if vector holds doubles.
960 if (ElemTy->isDoubleTy()) {
961 if (CAZ) {
962 GenericValue doubleZero;
963 doubleZero.DoubleVal = 0.0;
964 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
965 doubleZero);
966 break;
967 }
968 if(CV) {
969 for (unsigned i = 0; i < elemNum; ++i)
970 if (!isa<UndefValue>(CV->getOperand(i)))
971 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
972 CV->getOperand(i))->getValueAPF().convertToDouble();
973 break;
974 }
975 if(CDV)
976 for (unsigned i = 0; i < elemNum; ++i)
977 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
978
979 break;
980 }
981 // Check if vector holds integers.
982 if (ElemTy->isIntegerTy()) {
983 if (CAZ) {
Simon Pilgrim7d260e02017-03-20 13:54:44 +0000984 GenericValue intZero;
Nadav Rotem953783e2013-04-01 15:53:30 +0000985 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
986 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
987 intZero);
988 break;
989 }
990 if(CV) {
991 for (unsigned i = 0; i < elemNum; ++i)
992 if (!isa<UndefValue>(CV->getOperand(i)))
993 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
994 CV->getOperand(i))->getValue();
995 else {
996 Result.AggregateVal[i].IntVal =
997 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
998 }
999 break;
1000 }
1001 if(CDV)
1002 for (unsigned i = 0; i < elemNum; ++i)
1003 Result.AggregateVal[i].IntVal = APInt(
1004 CDV->getElementType()->getPrimitiveSizeInBits(),
1005 CDV->getElementAsInteger(i));
1006
1007 break;
1008 }
1009 llvm_unreachable("Unknown constant pointer type!");
1010 }
1011 break;
1012
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001013 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001014 SmallString<256> Msg;
1015 raw_svector_ostream OS(Msg);
1016 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
1017 report_fatal_error(OS.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001018 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001019
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001020 return Result;
1021}
1022
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001023/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1024/// with the integer held in IntVal.
1025static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1026 unsigned StoreBytes) {
1027 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divacky59324292012-09-05 22:26:57 +00001028 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001029
Rafael Espindola21a01d12013-04-15 14:44:24 +00001030 if (sys::IsLittleEndianHost) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001031 // Little-endian host - the source is ordered from LSB to MSB. Order the
1032 // destination from LSB to MSB: Do a straight copy.
1033 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001034 } else {
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001035 // Big-endian host - the source is an array of 64 bit words ordered from
1036 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1037 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1038 while (StoreBytes > sizeof(uint64_t)) {
1039 StoreBytes -= sizeof(uint64_t);
1040 // May not be aligned so use memcpy.
1041 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1042 Src += sizeof(uint64_t);
1043 }
1044
1045 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1046 }
1047}
1048
Evan Cheng89687e32008-11-04 06:10:31 +00001049void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001050 GenericValue *Ptr, Type *Ty) {
Mehdi Aminie02fce02015-07-16 16:34:23 +00001051 const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001052
Reid Spencer8fb0f192007-03-06 03:04:04 +00001053 switch (Ty->getTypeID()) {
Nadav Rotem953783e2013-04-01 15:53:30 +00001054 default:
1055 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1056 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001057 case Type::IntegerTyID:
1058 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +00001059 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +00001060 case Type::FloatTyID:
1061 *((float*)Ptr) = Val.FloatVal;
1062 break;
1063 case Type::DoubleTyID:
1064 *((double*)Ptr) = Val.DoubleVal;
1065 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +00001066 case Type::X86_FP80TyID:
1067 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1068 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001069 case Type::PointerTyID:
1070 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1071 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth80d9e072011-04-28 08:37:18 +00001072 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001073
Reid Spencer8fb0f192007-03-06 03:04:04 +00001074 *((PointerTy*)Ptr) = Val.PointerVal;
1075 break;
Nadav Rotem953783e2013-04-01 15:53:30 +00001076 case Type::VectorTyID:
1077 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1078 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1079 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1080 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1081 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1082 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1083 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
Simon Pilgrim7d260e02017-03-20 13:54:44 +00001084 StoreIntToMemory(Val.AggregateVal[i].IntVal,
Nadav Rotem953783e2013-04-01 15:53:30 +00001085 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1086 }
1087 }
1088 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001089 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001090
Mehdi Aminie02fce02015-07-16 16:34:23 +00001091 if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001092 // Host and target are different endian - reverse the stored bytes.
1093 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1094}
1095
1096/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1097/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1098static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1099 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greenec2680be2013-01-14 21:04:45 +00001100 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1101 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001102
Rafael Espindola21a01d12013-04-15 14:44:24 +00001103 if (sys::IsLittleEndianHost)
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001104 // Little-endian host - the destination must be ordered from LSB to MSB.
1105 // The source is ordered from LSB to MSB: Do a straight copy.
1106 memcpy(Dst, Src, LoadBytes);
1107 else {
1108 // Big-endian - the destination is an array of 64 bit words ordered from
1109 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1110 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1111 // a word.
1112 while (LoadBytes > sizeof(uint64_t)) {
1113 LoadBytes -= sizeof(uint64_t);
1114 // May not be aligned so use memcpy.
1115 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1116 Dst += sizeof(uint64_t);
1117 }
1118
1119 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1120 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001121}
1122
Misha Brukman4afac182003-10-10 17:45:12 +00001123/// FIXME: document
1124///
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001125void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +00001126 GenericValue *Ptr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001127 Type *Ty) {
Mehdi Aminie02fce02015-07-16 16:34:23 +00001128 const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +00001129
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001130 switch (Ty->getTypeID()) {
1131 case Type::IntegerTyID:
1132 // An APInt with all words initially zero.
1133 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1134 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1135 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +00001136 case Type::FloatTyID:
1137 Result.FloatVal = *((float*)Ptr);
1138 break;
1139 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001140 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +00001141 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001142 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +00001143 Result.PointerVal = *((PointerTy*)Ptr);
1144 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +00001145 case Type::X86_FP80TyID: {
1146 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +00001147 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +00001148 uint64_t y[2];
1149 memcpy(y, Ptr, 10);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001150 Result.IntVal = APInt(80, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +00001151 break;
1152 }
Nadav Rotem953783e2013-04-01 15:53:30 +00001153 case Type::VectorTyID: {
Craig Topper84bbcfe2015-08-01 22:20:21 +00001154 auto *VT = cast<VectorType>(Ty);
1155 Type *ElemT = VT->getElementType();
Nadav Rotem953783e2013-04-01 15:53:30 +00001156 const unsigned numElems = VT->getNumElements();
1157 if (ElemT->isFloatTy()) {
1158 Result.AggregateVal.resize(numElems);
1159 for (unsigned i = 0; i < numElems; ++i)
1160 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1161 }
1162 if (ElemT->isDoubleTy()) {
1163 Result.AggregateVal.resize(numElems);
1164 for (unsigned i = 0; i < numElems; ++i)
1165 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1166 }
1167 if (ElemT->isIntegerTy()) {
1168 GenericValue intZero;
1169 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1170 intZero.IntVal = APInt(elemBitWidth, 0);
1171 Result.AggregateVal.resize(numElems, intZero);
1172 for (unsigned i = 0; i < numElems; ++i)
1173 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1174 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1175 }
1176 break;
1177 }
Reid Spencer8fb0f192007-03-06 03:04:04 +00001178 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001179 SmallString<256> Msg;
1180 raw_svector_ostream OS(Msg);
1181 OS << "Cannot load value of type " << *Ty << "!";
1182 report_fatal_error(OS.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +00001183 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +00001184}
1185
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001186void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001187 LLVM_DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1188 LLVM_DEBUG(Init->dump());
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001189 if (isa<UndefValue>(Init))
Chris Lattnerbd1d3822004-10-16 18:19:26 +00001190 return;
Simon Pilgrim7d260e02017-03-20 13:54:44 +00001191
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001192 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +00001193 unsigned ElementSize =
Mehdi Aminie02fce02015-07-16 16:34:23 +00001194 getDataLayout().getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +00001195 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1196 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1197 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001198 }
Simon Pilgrim7d260e02017-03-20 13:54:44 +00001199
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001200 if (isa<ConstantAggregateZero>(Init)) {
Mehdi Aminie02fce02015-07-16 16:34:23 +00001201 memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +00001202 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001203 }
Simon Pilgrim7d260e02017-03-20 13:54:44 +00001204
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001205 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman638e3782008-05-20 03:20:09 +00001206 unsigned ElementSize =
Mehdi Aminie02fce02015-07-16 16:34:23 +00001207 getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +00001208 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1209 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1210 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001211 }
Simon Pilgrim7d260e02017-03-20 13:54:44 +00001212
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001213 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman638e3782008-05-20 03:20:09 +00001214 const StructLayout *SL =
Mehdi Aminie02fce02015-07-16 16:34:23 +00001215 getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman638e3782008-05-20 03:20:09 +00001216 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1217 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1218 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001219 }
1220
1221 if (const ConstantDataSequential *CDS =
1222 dyn_cast<ConstantDataSequential>(Init)) {
1223 // CDS is already laid out in host memory order.
1224 StringRef Data = CDS->getRawDataValues();
1225 memcpy(Addr, Data.data(), Data.size());
1226 return;
1227 }
1228
1229 if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001230 GenericValue Val = getConstantValue(Init);
1231 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1232 return;
1233 }
1234
Nicola Zaghen0818e782018-05-14 12:53:11 +00001235 LLVM_DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinc23197a2009-07-14 16:55:14 +00001236 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001237}
1238
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001239/// EmitGlobals - Emit all of the global variables to memory, storing their
1240/// addresses into GlobalAddress. This must make sure to copy the contents of
1241/// their initializers into the memory.
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001242void ExecutionEngine::emitGlobals() {
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001243 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +00001244 // to hold them. If there is more than one module, do a prepass over globals
1245 // to figure out how the different modules should link together.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001246 std::map<std::pair<std::string, Type*>,
Chris Lattnerfe854032006-08-16 01:24:12 +00001247 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001248
Chris Lattnerfe854032006-08-16 01:24:12 +00001249 if (Modules.size() != 1) {
1250 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001251 Module &M = *Modules[m];
Rafael Espindolae4b1c812014-05-08 18:17:44 +00001252 for (const auto &GV : M.globals()) {
1253 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1254 GV.hasAppendingLinkage() || !GV.hasName())
Chris Lattnerfe854032006-08-16 01:24:12 +00001255 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001256
1257 const GlobalValue *&GVEntry =
Rafael Espindolae4b1c812014-05-08 18:17:44 +00001258 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
Chris Lattnerfe854032006-08-16 01:24:12 +00001259
1260 // If this is the first time we've seen this global, it is the canonical
1261 // version.
1262 if (!GVEntry) {
Rafael Espindolae4b1c812014-05-08 18:17:44 +00001263 GVEntry = &GV;
Chris Lattnerfe854032006-08-16 01:24:12 +00001264 continue;
1265 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001266
Chris Lattnerfe854032006-08-16 01:24:12 +00001267 // If the existing global is strong, never replace it.
Nico Rieck38f68c52014-01-14 15:22:47 +00001268 if (GVEntry->hasExternalLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +00001269 continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001270
Chris Lattnerfe854032006-08-16 01:24:12 +00001271 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +00001272 // symbol. FIXME is this right for common?
Rafael Espindolae4b1c812014-05-08 18:17:44 +00001273 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1274 GVEntry = &GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +00001275 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001276 }
Chris Lattnerfe854032006-08-16 01:24:12 +00001277 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001278
Chris Lattnerfe854032006-08-16 01:24:12 +00001279 std::vector<const GlobalValue*> NonCanonicalGlobals;
1280 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001281 Module &M = *Modules[m];
Rafael Espindolae4b1c812014-05-08 18:17:44 +00001282 for (const auto &GV : M.globals()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001283 // In the multi-module case, see what this global maps to.
1284 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001285 if (const GlobalValue *GVEntry =
Rafael Espindolae4b1c812014-05-08 18:17:44 +00001286 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001287 // If something else is the canonical global, ignore this one.
Rafael Espindolae4b1c812014-05-08 18:17:44 +00001288 if (GVEntry != &GV) {
1289 NonCanonicalGlobals.push_back(&GV);
Chris Lattnerfe854032006-08-16 01:24:12 +00001290 continue;
1291 }
1292 }
1293 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001294
Rafael Espindolae4b1c812014-05-08 18:17:44 +00001295 if (!GV.isDeclaration()) {
1296 addGlobalMapping(&GV, getMemoryForGV(&GV));
Chris Lattnerfe854032006-08-16 01:24:12 +00001297 } else {
1298 // External variable reference. Try to use the dynamic loader to
1299 // get a pointer to it.
1300 if (void *SymAddr =
Rafael Espindolae4b1c812014-05-08 18:17:44 +00001301 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1302 addGlobalMapping(&GV, SymAddr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001303 else {
Chris Lattner75361b62010-04-07 22:58:41 +00001304 report_fatal_error("Could not resolve external global address: "
Rafael Espindolae4b1c812014-05-08 18:17:44 +00001305 +GV.getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001306 }
1307 }
1308 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001309
Chris Lattnerfe854032006-08-16 01:24:12 +00001310 // If there are multiple modules, map the non-canonical globals to their
1311 // canonical location.
1312 if (!NonCanonicalGlobals.empty()) {
1313 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1314 const GlobalValue *GV = NonCanonicalGlobals[i];
1315 const GlobalValue *CGV =
1316 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1317 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1318 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001319 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001320 }
1321 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001322
1323 // Now that all of the globals are set up in memory, loop through them all
Reid Spencera54b7cb2007-01-12 07:05:14 +00001324 // and initialize their contents.
Rafael Espindolae4b1c812014-05-08 18:17:44 +00001325 for (const auto &GV : M.globals()) {
1326 if (!GV.isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001327 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001328 if (const GlobalValue *GVEntry =
Rafael Espindolae4b1c812014-05-08 18:17:44 +00001329 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1330 if (GVEntry != &GV) // Not the canonical variable.
Chris Lattnerfe854032006-08-16 01:24:12 +00001331 continue;
1332 }
Rafael Espindolae4b1c812014-05-08 18:17:44 +00001333 EmitGlobalVariable(&GV);
Chris Lattnerfe854032006-08-16 01:24:12 +00001334 }
1335 }
1336 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001337}
1338
1339// EmitGlobalVariable - This method emits the specified global variable to the
1340// address specified in GlobalAddresses, or allocates new memory if it's not
1341// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001342void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001343 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001344
Craig Topper0b6cb712014-04-15 06:32:26 +00001345 if (!GA) {
Chris Lattner24b0a182003-12-20 02:45:37 +00001346 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001347 GA = getMemoryForGV(GV);
Andrew Kaylor48079e02013-11-15 17:52:54 +00001348
1349 // If we failed to allocate memory for this global, return.
Craig Topper0b6cb712014-04-15 06:32:26 +00001350 if (!GA) return;
Andrew Kaylor48079e02013-11-15 17:52:54 +00001351
Chris Lattner55d86482003-12-31 20:21:04 +00001352 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001353 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001354
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001355 // Don't initialize if it's thread local, let the client do it.
1356 if (!GV->isThreadLocal())
1357 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001358
Manuel Jacob75e1cfb2016-01-16 20:30:46 +00001359 Type *ElTy = GV->getValueType();
Mehdi Aminie02fce02015-07-16 16:34:23 +00001360 size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001361 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001362 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001363}