~ubuntu-branches/ubuntu/feisty/clamav/feisty

« back to all changes in this revision

Viewing changes to libclamav/c++/llvm/lib/ExecutionEngine/ExecutionEngine.cpp

  • Committer: Bazaar Package Importer
  • Author(s): Kees Cook
  • Date: 2007-02-20 10:33:44 UTC
  • mto: This revision was merged to the branch mainline in revision 16.
  • Revision ID: james.westby@ubuntu.com-20070220103344-zgcu2psnx9d98fpa
Tags: upstream-0.90
ImportĀ upstreamĀ versionĀ 0.90

Show diffs side-by-side

added added

removed removed

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