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