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