1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the common interface used by the various execution engine
11 // subclasses.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/ExecutionEngine/ExecutionEngine.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ExecutionEngine/GenericValue.h"
19 #include "llvm/ExecutionEngine/JITEventListener.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueHandle.h"
26 #include "llvm/Object/Archive.h"
27 #include "llvm/Object/ObjectFile.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/DynamicLibrary.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/MutexGuard.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include <cmath>
37 #include <cstring>
38 using namespace llvm;
39
40 #define DEBUG_TYPE "jit"
41
42 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
43 STATISTIC(NumGlobals , "Number of global vars initialized");
44
45 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
46 std::unique_ptr<Module> M, std::string *ErrorStr,
47 std::unique_ptr<RTDyldMemoryManager> MCJMM,
48 std::unique_ptr<TargetMachine> TM) = nullptr;
49 ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
50 std::string *ErrorStr) =nullptr;
51
anchor()52 void JITEventListener::anchor() {}
53
ExecutionEngine(std::unique_ptr<Module> M)54 ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
55 : EEState(*this),
56 LazyFunctionCreator(nullptr) {
57 CompilingLazily = false;
58 GVCompilationDisabled = false;
59 SymbolSearchingDisabled = false;
60
61 // IR module verification is enabled by default in debug builds, and disabled
62 // by default in release builds.
63 #ifndef NDEBUG
64 VerifyModules = true;
65 #else
66 VerifyModules = false;
67 #endif
68
69 assert(M && "Module is null?");
70 Modules.push_back(std::move(M));
71 }
72
~ExecutionEngine()73 ExecutionEngine::~ExecutionEngine() {
74 clearAllGlobalMappings();
75 }
76
77 namespace {
78 /// \brief Helper class which uses a value handler to automatically deletes the
79 /// memory block when the GlobalVariable is destroyed.
80 class GVMemoryBlock : public CallbackVH {
GVMemoryBlock(const GlobalVariable * GV)81 GVMemoryBlock(const GlobalVariable *GV)
82 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
83
84 public:
85 /// \brief Returns the address the GlobalVariable should be written into. The
86 /// GVMemoryBlock object prefixes that.
Create(const GlobalVariable * GV,const DataLayout & TD)87 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
88 Type *ElTy = GV->getType()->getElementType();
89 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
90 void *RawMemory = ::operator new(
91 RoundUpToAlignment(sizeof(GVMemoryBlock),
92 TD.getPreferredAlignment(GV))
93 + GVSize);
94 new(RawMemory) GVMemoryBlock(GV);
95 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
96 }
97
deleted()98 void deleted() override {
99 // We allocated with operator new and with some extra memory hanging off the
100 // end, so don't just delete this. I'm not sure if this is actually
101 // required.
102 this->~GVMemoryBlock();
103 ::operator delete(this);
104 }
105 };
106 } // anonymous namespace
107
getMemoryForGV(const GlobalVariable * GV)108 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
109 return GVMemoryBlock::Create(GV, *getDataLayout());
110 }
111
addObjectFile(std::unique_ptr<object::ObjectFile> O)112 void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
113 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
114 }
115
116 void
addObjectFile(object::OwningBinary<object::ObjectFile> O)117 ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
118 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
119 }
120
addArchive(object::OwningBinary<object::Archive> A)121 void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
122 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
123 }
124
removeModule(Module * M)125 bool ExecutionEngine::removeModule(Module *M) {
126 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
127 Module *Found = I->get();
128 if (Found == M) {
129 I->release();
130 Modules.erase(I);
131 clearGlobalMappingsFromModule(M);
132 return true;
133 }
134 }
135 return false;
136 }
137
FindFunctionNamed(const char * FnName)138 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
139 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
140 if (Function *F = Modules[i]->getFunction(FnName))
141 return F;
142 }
143 return nullptr;
144 }
145
146
RemoveMapping(const GlobalValue * ToUnmap)147 void *ExecutionEngineState::RemoveMapping(const GlobalValue *ToUnmap) {
148 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
149 void *OldVal;
150
151 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
152 // GlobalAddressMap.
153 if (I == GlobalAddressMap.end())
154 OldVal = nullptr;
155 else {
156 OldVal = I->second;
157 GlobalAddressMap.erase(I);
158 }
159
160 GlobalAddressReverseMap.erase(OldVal);
161 return OldVal;
162 }
163
addGlobalMapping(const GlobalValue * GV,void * Addr)164 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
165 MutexGuard locked(lock);
166
167 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
168 << "\' to [" << Addr << "]\n";);
169 void *&CurVal = EEState.getGlobalAddressMap()[GV];
170 assert((!CurVal || !Addr) && "GlobalMapping already established!");
171 CurVal = Addr;
172
173 // If we are using the reverse mapping, add it too.
174 if (!EEState.getGlobalAddressReverseMap().empty()) {
175 AssertingVH<const GlobalValue> &V =
176 EEState.getGlobalAddressReverseMap()[Addr];
177 assert((!V || !GV) && "GlobalMapping already established!");
178 V = GV;
179 }
180 }
181
clearAllGlobalMappings()182 void ExecutionEngine::clearAllGlobalMappings() {
183 MutexGuard locked(lock);
184
185 EEState.getGlobalAddressMap().clear();
186 EEState.getGlobalAddressReverseMap().clear();
187 }
188
clearGlobalMappingsFromModule(Module * M)189 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
190 MutexGuard locked(lock);
191
192 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
193 EEState.RemoveMapping(FI);
194 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
195 GI != GE; ++GI)
196 EEState.RemoveMapping(GI);
197 }
198
updateGlobalMapping(const GlobalValue * GV,void * Addr)199 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
200 MutexGuard locked(lock);
201
202 ExecutionEngineState::GlobalAddressMapTy &Map =
203 EEState.getGlobalAddressMap();
204
205 // Deleting from the mapping?
206 if (!Addr)
207 return EEState.RemoveMapping(GV);
208
209 void *&CurVal = Map[GV];
210 void *OldVal = CurVal;
211
212 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
213 EEState.getGlobalAddressReverseMap().erase(CurVal);
214 CurVal = Addr;
215
216 // If we are using the reverse mapping, add it too.
217 if (!EEState.getGlobalAddressReverseMap().empty()) {
218 AssertingVH<const GlobalValue> &V =
219 EEState.getGlobalAddressReverseMap()[Addr];
220 assert((!V || !GV) && "GlobalMapping already established!");
221 V = GV;
222 }
223 return OldVal;
224 }
225
getPointerToGlobalIfAvailable(const GlobalValue * GV)226 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
227 MutexGuard locked(lock);
228
229 ExecutionEngineState::GlobalAddressMapTy::iterator I =
230 EEState.getGlobalAddressMap().find(GV);
231 return I != EEState.getGlobalAddressMap().end() ? I->second : nullptr;
232 }
233
getGlobalValueAtAddress(void * Addr)234 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
235 MutexGuard locked(lock);
236
237 // If we haven't computed the reverse mapping yet, do so first.
238 if (EEState.getGlobalAddressReverseMap().empty()) {
239 for (ExecutionEngineState::GlobalAddressMapTy::iterator
240 I = EEState.getGlobalAddressMap().begin(),
241 E = EEState.getGlobalAddressMap().end(); I != E; ++I)
242 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
243 I->second, I->first));
244 }
245
246 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
247 EEState.getGlobalAddressReverseMap().find(Addr);
248 return I != EEState.getGlobalAddressReverseMap().end() ? I->second : nullptr;
249 }
250
251 namespace {
252 class ArgvArray {
253 std::unique_ptr<char[]> Array;
254 std::vector<std::unique_ptr<char[]>> Values;
255 public:
256 /// Turn a vector of strings into a nice argv style array of pointers to null
257 /// terminated strings.
258 void *reset(LLVMContext &C, ExecutionEngine *EE,
259 const std::vector<std::string> &InputArgv);
260 };
261 } // anonymous namespace
reset(LLVMContext & C,ExecutionEngine * EE,const std::vector<std::string> & InputArgv)262 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
263 const std::vector<std::string> &InputArgv) {
264 Values.clear(); // Free the old contents.
265 Values.reserve(InputArgv.size());
266 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
267 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
268
269 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
270 Type *SBytePtr = Type::getInt8PtrTy(C);
271
272 for (unsigned i = 0; i != InputArgv.size(); ++i) {
273 unsigned Size = InputArgv[i].size()+1;
274 auto Dest = make_unique<char[]>(Size);
275 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
276
277 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
278 Dest[Size-1] = 0;
279
280 // Endian safe: Array[i] = (PointerTy)Dest;
281 EE->StoreValueToMemory(PTOGV(Dest.get()),
282 (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
283 Values.push_back(std::move(Dest));
284 }
285
286 // Null terminate it
287 EE->StoreValueToMemory(PTOGV(nullptr),
288 (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
289 SBytePtr);
290 return Array.get();
291 }
292
runStaticConstructorsDestructors(Module & module,bool isDtors)293 void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
294 bool isDtors) {
295 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
296 GlobalVariable *GV = module.getNamedGlobal(Name);
297
298 // If this global has internal linkage, or if it has a use, then it must be
299 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
300 // this is the case, don't execute any of the global ctors, __main will do
301 // it.
302 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
303
304 // Should be an array of '{ i32, void ()* }' structs. The first value is
305 // the init priority, which we ignore.
306 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
307 if (!InitList)
308 return;
309 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
310 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
311 if (!CS) continue;
312
313 Constant *FP = CS->getOperand(1);
314 if (FP->isNullValue())
315 continue; // Found a sentinal value, ignore.
316
317 // Strip off constant expression casts.
318 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
319 if (CE->isCast())
320 FP = CE->getOperand(0);
321
322 // Execute the ctor/dtor function!
323 if (Function *F = dyn_cast<Function>(FP))
324 runFunction(F, std::vector<GenericValue>());
325
326 // FIXME: It is marginally lame that we just do nothing here if we see an
327 // entry we don't recognize. It might not be unreasonable for the verifier
328 // to not even allow this and just assert here.
329 }
330 }
331
runStaticConstructorsDestructors(bool isDtors)332 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
333 // Execute global ctors/dtors for each module in the program.
334 for (std::unique_ptr<Module> &M : Modules)
335 runStaticConstructorsDestructors(*M, isDtors);
336 }
337
338 #ifndef NDEBUG
339 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
isTargetNullPtr(ExecutionEngine * EE,void * Loc)340 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
341 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
342 for (unsigned i = 0; i < PtrSize; ++i)
343 if (*(i + (uint8_t*)Loc))
344 return false;
345 return true;
346 }
347 #endif
348
runFunctionAsMain(Function * Fn,const std::vector<std::string> & argv,const char * const * envp)349 int ExecutionEngine::runFunctionAsMain(Function *Fn,
350 const std::vector<std::string> &argv,
351 const char * const * envp) {
352 std::vector<GenericValue> GVArgs;
353 GenericValue GVArgc;
354 GVArgc.IntVal = APInt(32, argv.size());
355
356 // Check main() type
357 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
358 FunctionType *FTy = Fn->getFunctionType();
359 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
360
361 // Check the argument types.
362 if (NumArgs > 3)
363 report_fatal_error("Invalid number of arguments of main() supplied");
364 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
365 report_fatal_error("Invalid type for third argument of main() supplied");
366 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
367 report_fatal_error("Invalid type for second argument of main() supplied");
368 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
369 report_fatal_error("Invalid type for first argument of main() supplied");
370 if (!FTy->getReturnType()->isIntegerTy() &&
371 !FTy->getReturnType()->isVoidTy())
372 report_fatal_error("Invalid return type of main() supplied");
373
374 ArgvArray CArgv;
375 ArgvArray CEnv;
376 if (NumArgs) {
377 GVArgs.push_back(GVArgc); // Arg #0 = argc.
378 if (NumArgs > 1) {
379 // Arg #1 = argv.
380 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
381 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
382 "argv[0] was null after CreateArgv");
383 if (NumArgs > 2) {
384 std::vector<std::string> EnvVars;
385 for (unsigned i = 0; envp[i]; ++i)
386 EnvVars.push_back(envp[i]);
387 // Arg #2 = envp.
388 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
389 }
390 }
391 }
392
393 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
394 }
395
EngineBuilder(std::unique_ptr<Module> M)396 EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
397 : M(std::move(M)), MCJMM(nullptr) {
398 InitEngine();
399 }
400
~EngineBuilder()401 EngineBuilder::~EngineBuilder() {}
402
setMCJITMemoryManager(std::unique_ptr<RTDyldMemoryManager> mcjmm)403 EngineBuilder &EngineBuilder::setMCJITMemoryManager(
404 std::unique_ptr<RTDyldMemoryManager> mcjmm) {
405 MCJMM = std::move(mcjmm);
406 return *this;
407 }
408
InitEngine()409 void EngineBuilder::InitEngine() {
410 WhichEngine = EngineKind::Either;
411 ErrorStr = nullptr;
412 OptLevel = CodeGenOpt::Default;
413 MCJMM = nullptr;
414 Options = TargetOptions();
415 RelocModel = Reloc::Default;
416 CMModel = CodeModel::JITDefault;
417
418 // IR module verification is enabled by default in debug builds, and disabled
419 // by default in release builds.
420 #ifndef NDEBUG
421 VerifyModules = true;
422 #else
423 VerifyModules = false;
424 #endif
425 }
426
create(TargetMachine * TM)427 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
428 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
429
430 // Make sure we can resolve symbols in the program as well. The zero arg
431 // to the function tells DynamicLibrary to load the program, not a library.
432 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
433 return nullptr;
434
435 // If the user specified a memory manager but didn't specify which engine to
436 // create, we assume they only want the JIT, and we fail if they only want
437 // the interpreter.
438 if (MCJMM) {
439 if (WhichEngine & EngineKind::JIT)
440 WhichEngine = EngineKind::JIT;
441 else {
442 if (ErrorStr)
443 *ErrorStr = "Cannot create an interpreter with a memory manager.";
444 return nullptr;
445 }
446 }
447
448 // Unless the interpreter was explicitly selected or the JIT is not linked,
449 // try making a JIT.
450 if ((WhichEngine & EngineKind::JIT) && TheTM) {
451 Triple TT(M->getTargetTriple());
452 if (!TM->getTarget().hasJIT()) {
453 errs() << "WARNING: This target JIT is not designed for the host"
454 << " you are running. If bad things happen, please choose"
455 << " a different -march switch.\n";
456 }
457
458 ExecutionEngine *EE = nullptr;
459 if (ExecutionEngine::MCJITCtor)
460 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MCJMM),
461 std::move(TheTM));
462 if (EE) {
463 EE->setVerifyModules(VerifyModules);
464 return EE;
465 }
466 }
467
468 // If we can't make a JIT and we didn't request one specifically, try making
469 // an interpreter instead.
470 if (WhichEngine & EngineKind::Interpreter) {
471 if (ExecutionEngine::InterpCtor)
472 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
473 if (ErrorStr)
474 *ErrorStr = "Interpreter has not been linked in.";
475 return nullptr;
476 }
477
478 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
479 if (ErrorStr)
480 *ErrorStr = "JIT has not been linked in.";
481 }
482
483 return nullptr;
484 }
485
getPointerToGlobal(const GlobalValue * GV)486 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
487 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
488 return getPointerToFunction(F);
489
490 MutexGuard locked(lock);
491 if (void *P = EEState.getGlobalAddressMap()[GV])
492 return P;
493
494 // Global variable might have been added since interpreter started.
495 if (GlobalVariable *GVar =
496 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
497 EmitGlobalVariable(GVar);
498 else
499 llvm_unreachable("Global hasn't had an address allocated yet!");
500
501 return EEState.getGlobalAddressMap()[GV];
502 }
503
504 /// \brief Converts a Constant* into a GenericValue, including handling of
505 /// ConstantExpr values.
getConstantValue(const Constant * C)506 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
507 // If its undefined, return the garbage.
508 if (isa<UndefValue>(C)) {
509 GenericValue Result;
510 switch (C->getType()->getTypeID()) {
511 default:
512 break;
513 case Type::IntegerTyID:
514 case Type::X86_FP80TyID:
515 case Type::FP128TyID:
516 case Type::PPC_FP128TyID:
517 // Although the value is undefined, we still have to construct an APInt
518 // with the correct bit width.
519 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
520 break;
521 case Type::StructTyID: {
522 // if the whole struct is 'undef' just reserve memory for the value.
523 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
524 unsigned int elemNum = STy->getNumElements();
525 Result.AggregateVal.resize(elemNum);
526 for (unsigned int i = 0; i < elemNum; ++i) {
527 Type *ElemTy = STy->getElementType(i);
528 if (ElemTy->isIntegerTy())
529 Result.AggregateVal[i].IntVal =
530 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
531 else if (ElemTy->isAggregateType()) {
532 const Constant *ElemUndef = UndefValue::get(ElemTy);
533 Result.AggregateVal[i] = getConstantValue(ElemUndef);
534 }
535 }
536 }
537 }
538 break;
539 case Type::VectorTyID:
540 // if the whole vector is 'undef' just reserve memory for the value.
541 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
542 const Type *ElemTy = VTy->getElementType();
543 unsigned int elemNum = VTy->getNumElements();
544 Result.AggregateVal.resize(elemNum);
545 if (ElemTy->isIntegerTy())
546 for (unsigned int i = 0; i < elemNum; ++i)
547 Result.AggregateVal[i].IntVal =
548 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
549 break;
550 }
551 return Result;
552 }
553
554 // Otherwise, if the value is a ConstantExpr...
555 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
556 Constant *Op0 = CE->getOperand(0);
557 switch (CE->getOpcode()) {
558 case Instruction::GetElementPtr: {
559 // Compute the index
560 GenericValue Result = getConstantValue(Op0);
561 APInt Offset(DL->getPointerSizeInBits(), 0);
562 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
563
564 char* tmp = (char*) Result.PointerVal;
565 Result = PTOGV(tmp + Offset.getSExtValue());
566 return Result;
567 }
568 case Instruction::Trunc: {
569 GenericValue GV = getConstantValue(Op0);
570 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
571 GV.IntVal = GV.IntVal.trunc(BitWidth);
572 return GV;
573 }
574 case Instruction::ZExt: {
575 GenericValue GV = getConstantValue(Op0);
576 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
577 GV.IntVal = GV.IntVal.zext(BitWidth);
578 return GV;
579 }
580 case Instruction::SExt: {
581 GenericValue GV = getConstantValue(Op0);
582 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
583 GV.IntVal = GV.IntVal.sext(BitWidth);
584 return GV;
585 }
586 case Instruction::FPTrunc: {
587 // FIXME long double
588 GenericValue GV = getConstantValue(Op0);
589 GV.FloatVal = float(GV.DoubleVal);
590 return GV;
591 }
592 case Instruction::FPExt:{
593 // FIXME long double
594 GenericValue GV = getConstantValue(Op0);
595 GV.DoubleVal = double(GV.FloatVal);
596 return GV;
597 }
598 case Instruction::UIToFP: {
599 GenericValue GV = getConstantValue(Op0);
600 if (CE->getType()->isFloatTy())
601 GV.FloatVal = float(GV.IntVal.roundToDouble());
602 else if (CE->getType()->isDoubleTy())
603 GV.DoubleVal = GV.IntVal.roundToDouble();
604 else if (CE->getType()->isX86_FP80Ty()) {
605 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
606 (void)apf.convertFromAPInt(GV.IntVal,
607 false,
608 APFloat::rmNearestTiesToEven);
609 GV.IntVal = apf.bitcastToAPInt();
610 }
611 return GV;
612 }
613 case Instruction::SIToFP: {
614 GenericValue GV = getConstantValue(Op0);
615 if (CE->getType()->isFloatTy())
616 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
617 else if (CE->getType()->isDoubleTy())
618 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
619 else if (CE->getType()->isX86_FP80Ty()) {
620 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
621 (void)apf.convertFromAPInt(GV.IntVal,
622 true,
623 APFloat::rmNearestTiesToEven);
624 GV.IntVal = apf.bitcastToAPInt();
625 }
626 return GV;
627 }
628 case Instruction::FPToUI: // double->APInt conversion handles sign
629 case Instruction::FPToSI: {
630 GenericValue GV = getConstantValue(Op0);
631 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
632 if (Op0->getType()->isFloatTy())
633 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
634 else if (Op0->getType()->isDoubleTy())
635 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
636 else if (Op0->getType()->isX86_FP80Ty()) {
637 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
638 uint64_t v;
639 bool ignored;
640 (void)apf.convertToInteger(&v, BitWidth,
641 CE->getOpcode()==Instruction::FPToSI,
642 APFloat::rmTowardZero, &ignored);
643 GV.IntVal = v; // endian?
644 }
645 return GV;
646 }
647 case Instruction::PtrToInt: {
648 GenericValue GV = getConstantValue(Op0);
649 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
650 assert(PtrWidth <= 64 && "Bad pointer width");
651 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
652 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
653 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
654 return GV;
655 }
656 case Instruction::IntToPtr: {
657 GenericValue GV = getConstantValue(Op0);
658 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
659 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
660 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
661 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
662 return GV;
663 }
664 case Instruction::BitCast: {
665 GenericValue GV = getConstantValue(Op0);
666 Type* DestTy = CE->getType();
667 switch (Op0->getType()->getTypeID()) {
668 default: llvm_unreachable("Invalid bitcast operand");
669 case Type::IntegerTyID:
670 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
671 if (DestTy->isFloatTy())
672 GV.FloatVal = GV.IntVal.bitsToFloat();
673 else if (DestTy->isDoubleTy())
674 GV.DoubleVal = GV.IntVal.bitsToDouble();
675 break;
676 case Type::FloatTyID:
677 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
678 GV.IntVal = APInt::floatToBits(GV.FloatVal);
679 break;
680 case Type::DoubleTyID:
681 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
682 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
683 break;
684 case Type::PointerTyID:
685 assert(DestTy->isPointerTy() && "Invalid bitcast");
686 break; // getConstantValue(Op0) above already converted it
687 }
688 return GV;
689 }
690 case Instruction::Add:
691 case Instruction::FAdd:
692 case Instruction::Sub:
693 case Instruction::FSub:
694 case Instruction::Mul:
695 case Instruction::FMul:
696 case Instruction::UDiv:
697 case Instruction::SDiv:
698 case Instruction::URem:
699 case Instruction::SRem:
700 case Instruction::And:
701 case Instruction::Or:
702 case Instruction::Xor: {
703 GenericValue LHS = getConstantValue(Op0);
704 GenericValue RHS = getConstantValue(CE->getOperand(1));
705 GenericValue GV;
706 switch (CE->getOperand(0)->getType()->getTypeID()) {
707 default: llvm_unreachable("Bad add type!");
708 case Type::IntegerTyID:
709 switch (CE->getOpcode()) {
710 default: llvm_unreachable("Invalid integer opcode");
711 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
712 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
713 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
714 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
715 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
716 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
717 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
718 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
719 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
720 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
721 }
722 break;
723 case Type::FloatTyID:
724 switch (CE->getOpcode()) {
725 default: llvm_unreachable("Invalid float opcode");
726 case Instruction::FAdd:
727 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
728 case Instruction::FSub:
729 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
730 case Instruction::FMul:
731 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
732 case Instruction::FDiv:
733 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
734 case Instruction::FRem:
735 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
736 }
737 break;
738 case Type::DoubleTyID:
739 switch (CE->getOpcode()) {
740 default: llvm_unreachable("Invalid double opcode");
741 case Instruction::FAdd:
742 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
743 case Instruction::FSub:
744 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
745 case Instruction::FMul:
746 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
747 case Instruction::FDiv:
748 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
749 case Instruction::FRem:
750 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
751 }
752 break;
753 case Type::X86_FP80TyID:
754 case Type::PPC_FP128TyID:
755 case Type::FP128TyID: {
756 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
757 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
758 switch (CE->getOpcode()) {
759 default: llvm_unreachable("Invalid long double opcode");
760 case Instruction::FAdd:
761 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
762 GV.IntVal = apfLHS.bitcastToAPInt();
763 break;
764 case Instruction::FSub:
765 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
766 APFloat::rmNearestTiesToEven);
767 GV.IntVal = apfLHS.bitcastToAPInt();
768 break;
769 case Instruction::FMul:
770 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
771 APFloat::rmNearestTiesToEven);
772 GV.IntVal = apfLHS.bitcastToAPInt();
773 break;
774 case Instruction::FDiv:
775 apfLHS.divide(APFloat(Sem, RHS.IntVal),
776 APFloat::rmNearestTiesToEven);
777 GV.IntVal = apfLHS.bitcastToAPInt();
778 break;
779 case Instruction::FRem:
780 apfLHS.mod(APFloat(Sem, RHS.IntVal),
781 APFloat::rmNearestTiesToEven);
782 GV.IntVal = apfLHS.bitcastToAPInt();
783 break;
784 }
785 }
786 break;
787 }
788 return GV;
789 }
790 default:
791 break;
792 }
793
794 SmallString<256> Msg;
795 raw_svector_ostream OS(Msg);
796 OS << "ConstantExpr not handled: " << *CE;
797 report_fatal_error(OS.str());
798 }
799
800 // Otherwise, we have a simple constant.
801 GenericValue Result;
802 switch (C->getType()->getTypeID()) {
803 case Type::FloatTyID:
804 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
805 break;
806 case Type::DoubleTyID:
807 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
808 break;
809 case Type::X86_FP80TyID:
810 case Type::FP128TyID:
811 case Type::PPC_FP128TyID:
812 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
813 break;
814 case Type::IntegerTyID:
815 Result.IntVal = cast<ConstantInt>(C)->getValue();
816 break;
817 case Type::PointerTyID:
818 if (isa<ConstantPointerNull>(C))
819 Result.PointerVal = nullptr;
820 else if (const Function *F = dyn_cast<Function>(C))
821 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
822 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
823 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
824 else
825 llvm_unreachable("Unknown constant pointer type!");
826 break;
827 case Type::VectorTyID: {
828 unsigned elemNum;
829 Type* ElemTy;
830 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
831 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
832 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
833
834 if (CDV) {
835 elemNum = CDV->getNumElements();
836 ElemTy = CDV->getElementType();
837 } else if (CV || CAZ) {
838 VectorType* VTy = dyn_cast<VectorType>(C->getType());
839 elemNum = VTy->getNumElements();
840 ElemTy = VTy->getElementType();
841 } else {
842 llvm_unreachable("Unknown constant vector type!");
843 }
844
845 Result.AggregateVal.resize(elemNum);
846 // Check if vector holds floats.
847 if(ElemTy->isFloatTy()) {
848 if (CAZ) {
849 GenericValue floatZero;
850 floatZero.FloatVal = 0.f;
851 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
852 floatZero);
853 break;
854 }
855 if(CV) {
856 for (unsigned i = 0; i < elemNum; ++i)
857 if (!isa<UndefValue>(CV->getOperand(i)))
858 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
859 CV->getOperand(i))->getValueAPF().convertToFloat();
860 break;
861 }
862 if(CDV)
863 for (unsigned i = 0; i < elemNum; ++i)
864 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
865
866 break;
867 }
868 // Check if vector holds doubles.
869 if (ElemTy->isDoubleTy()) {
870 if (CAZ) {
871 GenericValue doubleZero;
872 doubleZero.DoubleVal = 0.0;
873 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
874 doubleZero);
875 break;
876 }
877 if(CV) {
878 for (unsigned i = 0; i < elemNum; ++i)
879 if (!isa<UndefValue>(CV->getOperand(i)))
880 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
881 CV->getOperand(i))->getValueAPF().convertToDouble();
882 break;
883 }
884 if(CDV)
885 for (unsigned i = 0; i < elemNum; ++i)
886 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
887
888 break;
889 }
890 // Check if vector holds integers.
891 if (ElemTy->isIntegerTy()) {
892 if (CAZ) {
893 GenericValue intZero;
894 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
895 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
896 intZero);
897 break;
898 }
899 if(CV) {
900 for (unsigned i = 0; i < elemNum; ++i)
901 if (!isa<UndefValue>(CV->getOperand(i)))
902 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
903 CV->getOperand(i))->getValue();
904 else {
905 Result.AggregateVal[i].IntVal =
906 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
907 }
908 break;
909 }
910 if(CDV)
911 for (unsigned i = 0; i < elemNum; ++i)
912 Result.AggregateVal[i].IntVal = APInt(
913 CDV->getElementType()->getPrimitiveSizeInBits(),
914 CDV->getElementAsInteger(i));
915
916 break;
917 }
918 llvm_unreachable("Unknown constant pointer type!");
919 }
920 break;
921
922 default:
923 SmallString<256> Msg;
924 raw_svector_ostream OS(Msg);
925 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
926 report_fatal_error(OS.str());
927 }
928
929 return Result;
930 }
931
932 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
933 /// with the integer held in IntVal.
StoreIntToMemory(const APInt & IntVal,uint8_t * Dst,unsigned StoreBytes)934 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
935 unsigned StoreBytes) {
936 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
937 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
938
939 if (sys::IsLittleEndianHost) {
940 // Little-endian host - the source is ordered from LSB to MSB. Order the
941 // destination from LSB to MSB: Do a straight copy.
942 memcpy(Dst, Src, StoreBytes);
943 } else {
944 // Big-endian host - the source is an array of 64 bit words ordered from
945 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
946 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
947 while (StoreBytes > sizeof(uint64_t)) {
948 StoreBytes -= sizeof(uint64_t);
949 // May not be aligned so use memcpy.
950 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
951 Src += sizeof(uint64_t);
952 }
953
954 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
955 }
956 }
957
StoreValueToMemory(const GenericValue & Val,GenericValue * Ptr,Type * Ty)958 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
959 GenericValue *Ptr, Type *Ty) {
960 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
961
962 switch (Ty->getTypeID()) {
963 default:
964 dbgs() << "Cannot store value of type " << *Ty << "!\n";
965 break;
966 case Type::IntegerTyID:
967 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
968 break;
969 case Type::FloatTyID:
970 *((float*)Ptr) = Val.FloatVal;
971 break;
972 case Type::DoubleTyID:
973 *((double*)Ptr) = Val.DoubleVal;
974 break;
975 case Type::X86_FP80TyID:
976 memcpy(Ptr, Val.IntVal.getRawData(), 10);
977 break;
978 case Type::PointerTyID:
979 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
980 if (StoreBytes != sizeof(PointerTy))
981 memset(&(Ptr->PointerVal), 0, StoreBytes);
982
983 *((PointerTy*)Ptr) = Val.PointerVal;
984 break;
985 case Type::VectorTyID:
986 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
987 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
988 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
989 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
990 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
991 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
992 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
993 StoreIntToMemory(Val.AggregateVal[i].IntVal,
994 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
995 }
996 }
997 break;
998 }
999
1000 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
1001 // Host and target are different endian - reverse the stored bytes.
1002 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1003 }
1004
1005 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1006 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
LoadIntFromMemory(APInt & IntVal,uint8_t * Src,unsigned LoadBytes)1007 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1008 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
1009 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1010 const_cast<uint64_t *>(IntVal.getRawData()));
1011
1012 if (sys::IsLittleEndianHost)
1013 // Little-endian host - the destination must be ordered from LSB to MSB.
1014 // The source is ordered from LSB to MSB: Do a straight copy.
1015 memcpy(Dst, Src, LoadBytes);
1016 else {
1017 // Big-endian - the destination is an array of 64 bit words ordered from
1018 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1019 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1020 // a word.
1021 while (LoadBytes > sizeof(uint64_t)) {
1022 LoadBytes -= sizeof(uint64_t);
1023 // May not be aligned so use memcpy.
1024 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1025 Dst += sizeof(uint64_t);
1026 }
1027
1028 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1029 }
1030 }
1031
1032 /// FIXME: document
1033 ///
LoadValueFromMemory(GenericValue & Result,GenericValue * Ptr,Type * Ty)1034 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1035 GenericValue *Ptr,
1036 Type *Ty) {
1037 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
1038
1039 switch (Ty->getTypeID()) {
1040 case Type::IntegerTyID:
1041 // An APInt with all words initially zero.
1042 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1043 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1044 break;
1045 case Type::FloatTyID:
1046 Result.FloatVal = *((float*)Ptr);
1047 break;
1048 case Type::DoubleTyID:
1049 Result.DoubleVal = *((double*)Ptr);
1050 break;
1051 case Type::PointerTyID:
1052 Result.PointerVal = *((PointerTy*)Ptr);
1053 break;
1054 case Type::X86_FP80TyID: {
1055 // This is endian dependent, but it will only work on x86 anyway.
1056 // FIXME: Will not trap if loading a signaling NaN.
1057 uint64_t y[2];
1058 memcpy(y, Ptr, 10);
1059 Result.IntVal = APInt(80, y);
1060 break;
1061 }
1062 case Type::VectorTyID: {
1063 const VectorType *VT = cast<VectorType>(Ty);
1064 const Type *ElemT = VT->getElementType();
1065 const unsigned numElems = VT->getNumElements();
1066 if (ElemT->isFloatTy()) {
1067 Result.AggregateVal.resize(numElems);
1068 for (unsigned i = 0; i < numElems; ++i)
1069 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1070 }
1071 if (ElemT->isDoubleTy()) {
1072 Result.AggregateVal.resize(numElems);
1073 for (unsigned i = 0; i < numElems; ++i)
1074 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1075 }
1076 if (ElemT->isIntegerTy()) {
1077 GenericValue intZero;
1078 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1079 intZero.IntVal = APInt(elemBitWidth, 0);
1080 Result.AggregateVal.resize(numElems, intZero);
1081 for (unsigned i = 0; i < numElems; ++i)
1082 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1083 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1084 }
1085 break;
1086 }
1087 default:
1088 SmallString<256> Msg;
1089 raw_svector_ostream OS(Msg);
1090 OS << "Cannot load value of type " << *Ty << "!";
1091 report_fatal_error(OS.str());
1092 }
1093 }
1094
InitializeMemory(const Constant * Init,void * Addr)1095 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1096 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1097 DEBUG(Init->dump());
1098 if (isa<UndefValue>(Init))
1099 return;
1100
1101 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1102 unsigned ElementSize =
1103 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
1104 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1105 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1106 return;
1107 }
1108
1109 if (isa<ConstantAggregateZero>(Init)) {
1110 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
1111 return;
1112 }
1113
1114 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1115 unsigned ElementSize =
1116 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
1117 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1118 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1119 return;
1120 }
1121
1122 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1123 const StructLayout *SL =
1124 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
1125 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1126 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1127 return;
1128 }
1129
1130 if (const ConstantDataSequential *CDS =
1131 dyn_cast<ConstantDataSequential>(Init)) {
1132 // CDS is already laid out in host memory order.
1133 StringRef Data = CDS->getRawDataValues();
1134 memcpy(Addr, Data.data(), Data.size());
1135 return;
1136 }
1137
1138 if (Init->getType()->isFirstClassType()) {
1139 GenericValue Val = getConstantValue(Init);
1140 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1141 return;
1142 }
1143
1144 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1145 llvm_unreachable("Unknown constant type to initialize memory with!");
1146 }
1147
1148 /// EmitGlobals - Emit all of the global variables to memory, storing their
1149 /// addresses into GlobalAddress. This must make sure to copy the contents of
1150 /// their initializers into the memory.
emitGlobals()1151 void ExecutionEngine::emitGlobals() {
1152 // Loop over all of the global variables in the program, allocating the memory
1153 // to hold them. If there is more than one module, do a prepass over globals
1154 // to figure out how the different modules should link together.
1155 std::map<std::pair<std::string, Type*>,
1156 const GlobalValue*> LinkedGlobalsMap;
1157
1158 if (Modules.size() != 1) {
1159 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1160 Module &M = *Modules[m];
1161 for (const auto &GV : M.globals()) {
1162 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1163 GV.hasAppendingLinkage() || !GV.hasName())
1164 continue;// Ignore external globals and globals with internal linkage.
1165
1166 const GlobalValue *&GVEntry =
1167 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
1168
1169 // If this is the first time we've seen this global, it is the canonical
1170 // version.
1171 if (!GVEntry) {
1172 GVEntry = &GV;
1173 continue;
1174 }
1175
1176 // If the existing global is strong, never replace it.
1177 if (GVEntry->hasExternalLinkage())
1178 continue;
1179
1180 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1181 // symbol. FIXME is this right for common?
1182 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1183 GVEntry = &GV;
1184 }
1185 }
1186 }
1187
1188 std::vector<const GlobalValue*> NonCanonicalGlobals;
1189 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1190 Module &M = *Modules[m];
1191 for (const auto &GV : M.globals()) {
1192 // In the multi-module case, see what this global maps to.
1193 if (!LinkedGlobalsMap.empty()) {
1194 if (const GlobalValue *GVEntry =
1195 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
1196 // If something else is the canonical global, ignore this one.
1197 if (GVEntry != &GV) {
1198 NonCanonicalGlobals.push_back(&GV);
1199 continue;
1200 }
1201 }
1202 }
1203
1204 if (!GV.isDeclaration()) {
1205 addGlobalMapping(&GV, getMemoryForGV(&GV));
1206 } else {
1207 // External variable reference. Try to use the dynamic loader to
1208 // get a pointer to it.
1209 if (void *SymAddr =
1210 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1211 addGlobalMapping(&GV, SymAddr);
1212 else {
1213 report_fatal_error("Could not resolve external global address: "
1214 +GV.getName());
1215 }
1216 }
1217 }
1218
1219 // If there are multiple modules, map the non-canonical globals to their
1220 // canonical location.
1221 if (!NonCanonicalGlobals.empty()) {
1222 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1223 const GlobalValue *GV = NonCanonicalGlobals[i];
1224 const GlobalValue *CGV =
1225 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1226 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1227 assert(Ptr && "Canonical global wasn't codegen'd!");
1228 addGlobalMapping(GV, Ptr);
1229 }
1230 }
1231
1232 // Now that all of the globals are set up in memory, loop through them all
1233 // and initialize their contents.
1234 for (const auto &GV : M.globals()) {
1235 if (!GV.isDeclaration()) {
1236 if (!LinkedGlobalsMap.empty()) {
1237 if (const GlobalValue *GVEntry =
1238 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1239 if (GVEntry != &GV) // Not the canonical variable.
1240 continue;
1241 }
1242 EmitGlobalVariable(&GV);
1243 }
1244 }
1245 }
1246 }
1247
1248 // EmitGlobalVariable - This method emits the specified global variable to the
1249 // address specified in GlobalAddresses, or allocates new memory if it's not
1250 // already in the map.
EmitGlobalVariable(const GlobalVariable * GV)1251 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1252 void *GA = getPointerToGlobalIfAvailable(GV);
1253
1254 if (!GA) {
1255 // If it's not already specified, allocate memory for the global.
1256 GA = getMemoryForGV(GV);
1257
1258 // If we failed to allocate memory for this global, return.
1259 if (!GA) return;
1260
1261 addGlobalMapping(GV, GA);
1262 }
1263
1264 // Don't initialize if it's thread local, let the client do it.
1265 if (!GV->isThreadLocal())
1266 InitializeMemory(GV->getInitializer(), GA);
1267
1268 Type *ElTy = GV->getType()->getElementType();
1269 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1270 NumInitBytes += (unsigned)GVSize;
1271 ++NumGlobals;
1272 }
1273
ExecutionEngineState(ExecutionEngine & EE)1274 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1275 : EE(EE), GlobalAddressMap(this) {
1276 }
1277
1278 sys::Mutex *
getMutex(ExecutionEngineState * EES)1279 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1280 return &EES->EE.lock;
1281 }
1282
onDelete(ExecutionEngineState * EES,const GlobalValue * Old)1283 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1284 const GlobalValue *Old) {
1285 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1286 EES->GlobalAddressReverseMap.erase(OldVal);
1287 }
1288
onRAUW(ExecutionEngineState *,const GlobalValue *,const GlobalValue *)1289 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1290 const GlobalValue *,
1291 const GlobalValue *) {
1292 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1293 " RAUW on a value it has a global mapping for.");
1294 }
1295