<commit_before>//===-- ExternalFunctions.cpp - Implement External Functions --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file contains both code to deal with invoking "external" functions, but
//  also contains code that implements "exported" external functions.
//
//  There are currently two mechanisms for handling external functions in the
//  Interpreter.  The first is to implement lle_* wrapper functions that are
//  specific to well-known library functions which manually translate the
//  arguments from GenericValues and make the call.  If such a wrapper does
//  not exist, and libffi is available, then the Interpreter will attempt to
//  invoke the function using libffi, after finding its address.
//
//  OCCAM: we only support lle_* wrapper functions
//===----------------------------------------------------------------------===//

#include "Interpreter.h"

#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
//#include "llvm/Config/config.h" // Detect libffi
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cmath>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <map>
#include <string>
#include <utility>
#include <vector>

/// HAVE_FFI_CALL, HAVE_FFI_H, and HAVE_HAVE_FFI_FFI_H are defined if
/// LLVM is compiled with --enable-libffi.
//
// #ifdef HAVE_FFI_CALL
// #ifdef HAVE_FFI_H
// #include <ffi.h>
// #define USE_LIBFFI
// #elif HAVE_FFI_FFI_H
// #include <ffi/ffi.h>
// #define USE_LIBFFI
// #endif
// #endif

#ifdef HAVE_FFI_H
#include <ffi.h>
#define USE_LIBFFI
#elif HAVE_FFI_FFI_H
#include <ffi/ffi.h>
#define USE_LIBFFI
#endif

using namespace llvm;

static ManagedStatic<sys::Mutex> FunctionsLock;

typedef GenericValue (*ExFunc)(FunctionType *, ArrayRef<GenericValue>);
static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions;
static ManagedStatic<std::map<std::string, ExFunc> > FuncNames;

#ifdef USE_LIBFFI
typedef void (*RawFunc)();
static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions;
#endif

static previrt::Interpreter *TheInterpreter;

static char getTypeID(Type *Ty) {
  switch (Ty->getTypeID()) {
  case Type::VoidTyID:    return 'V';
  case Type::IntegerTyID:
    switch (cast<IntegerType>(Ty)->getBitWidth()) {
      case 1:  return 'o';
      case 8:  return 'B';
      case 16: return 'S';
      case 32: return 'I';
      case 64: return 'L';
      default: return 'N';
    }
  case Type::FloatTyID:   return 'F';
  case Type::DoubleTyID:  return 'D';
  case Type::PointerTyID: return 'P';
  case Type::FunctionTyID:return 'M';
  case Type::StructTyID:  return 'T';
  case Type::ArrayTyID:   return 'A';
  default: return 'U';
  }
}

// Try to find address of external function given a Function object.
// Please note, that interpreter doesn't know how to assemble a
// real call in general case (this is JIT job), that's why it assumes,
// that all external functions has the same (and pretty "general") signature.
// The typical example of such functions are "lle_X_" ones.
static ExFunc lookupFunction(const Function *F) {  
  // Function not found, look it up... start by figuring out what the
  // composite function name should be.
  std::string ExtName = "lle_";
  FunctionType *FT = F->getFunctionType();
  for (unsigned i = 0, e = FT->getNumContainedTypes(); i != e; ++i)
    ExtName += getTypeID(FT->getContainedType(i));
  ExtName += ("_" + F->getName()).str();

  sys::ScopedLock Writer(*FunctionsLock);
  ExFunc FnPtr = (*FuncNames)[ExtName];
  
  // HACK: for finding functions such as malloc
  if (!FnPtr) {
    FnPtr = (*FuncNames)[F->getName()];
  }
  if (!FnPtr) {
    FnPtr = (*FuncNames)[("lle_X_" + F->getName()).str()];
  }
  if (!FnPtr) { // Try calling a generic function... if it exists...
    FnPtr = (ExFunc)(intptr_t)sys::DynamicLibrary::SearchForAddressOfSymbol(
        ("lle_X_" + F->getName()).str());
  }

  if (FnPtr) {
    errs() << "ConfigPrime: recognized external call: " << F->getName() << "\n";    
    ExportedFunctions->insert(std::make_pair(F, FnPtr));  // Cache for later
  } else {
    errs() << "ConfigPrime: not recognized external call: " << F->getName() << "\n";
  }
  
  return FnPtr;
}

static bool hasFunctionPtrParameter(const Function &F) {
  const FunctionType *FTy = F.getFunctionType();
  for (unsigned i=0, num_params = FTy->getNumParams(); i<num_params; ++i) {
    const Type *ArgTy = FTy->getParamType(i);
    if (const PointerType *ArgPtrTy = dyn_cast<PointerType>(ArgTy)) {
      if (isa<FunctionType>(ArgPtrTy->getElementType())) {
	return true;
      }
    }
  }
  return false;
}

#ifdef USE_LIBFFI
static ffi_type *ffiTypeFor(Type *Ty) {
  switch (Ty->getTypeID()) {
    case Type::VoidTyID: return &ffi_type_void;
    case Type::IntegerTyID:
      switch (cast<IntegerType>(Ty)->getBitWidth()) {
        case 8:  return &ffi_type_sint8;
        case 16: return &ffi_type_sint16;
        case 32: return &ffi_type_sint32;
        case 64: return &ffi_type_sint64;
      }
    case Type::FloatTyID:   return &ffi_type_float;
    case Type::DoubleTyID:  return &ffi_type_double;
    case Type::PointerTyID: return &ffi_type_pointer;
    default: break;
  }
  // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
  report_fatal_error("Type could not be mapped for use with libffi.");
  return NULL;
}

static void *ffiValueFor(Type *Ty, const GenericValue &AV,
                         void *ArgDataPtr) {
  switch (Ty->getTypeID()) {
    case Type::IntegerTyID:
      switch (cast<IntegerType>(Ty)->getBitWidth()) {
        case 8: {
          int8_t *I8Ptr = (int8_t *) ArgDataPtr;
          *I8Ptr = (int8_t) AV.IntVal.getZExtValue();
          return ArgDataPtr;
        }
        case 16: {
          int16_t *I16Ptr = (int16_t *) ArgDataPtr;
          *I16Ptr = (int16_t) AV.IntVal.getZExtValue();
          return ArgDataPtr;
        }
        case 32: {
          int32_t *I32Ptr = (int32_t *) ArgDataPtr;
          *I32Ptr = (int32_t) AV.IntVal.getZExtValue();
          return ArgDataPtr;
        }
        case 64: {
          int64_t *I64Ptr = (int64_t *) ArgDataPtr;
          *I64Ptr = (int64_t) AV.IntVal.getZExtValue();
          return ArgDataPtr;
        }
      }
      break;
    case Type::FloatTyID: {
      float *FloatPtr = (float *) ArgDataPtr;
      *FloatPtr = AV.FloatVal;
      return ArgDataPtr;
    }
    case Type::DoubleTyID: {
      double *DoublePtr = (double *) ArgDataPtr;
      *DoublePtr = AV.DoubleVal;
      return ArgDataPtr;
    }
    case Type::PointerTyID: {
      void **PtrPtr = (void **) ArgDataPtr;
      *PtrPtr = GVTOP(AV);
      return ArgDataPtr;
    }
    default: break;
  }
  // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
  report_fatal_error("Type value could not be mapped for use with libffi.");
  return NULL;
}

static bool ffiInvoke(Instruction *I, RawFunc Fn, Function *F, ArrayRef<GenericValue> ArgVals,
                      const DataLayout &TD, GenericValue &Result) {


  ffi_cif cif;
  FunctionType *FTy = F->getFunctionType();
  std::vector<Type*> ArgTypes;
  if (ArgVals.size() > F->arg_size() && F->isVarArg()) {
    // Variadic function: get types from the callsite
    if (!I) {
      errs() << "Calling ffiInvoke without a callsite. "
             << "This should not happen\n";
      return false;
    }
    const unsigned NumArgs = ArgVals.size();
    CallSite CS(I);
    if (NumArgs != CS.arg_size()) {
      errs() << "Mismatch of number of parameters at callsite. "
             << "This should not happen\n";
      return false;
    }
    ArgTypes.reserve(NumArgs);
    for (unsigned i=0; i<NumArgs;++i) {
      Value* A = CS.getArgument(i)->stripPointerCasts();
      Type *ArgTy = A->getType();
      ArgTypes.push_back(ArgTy);
    }
  } else {
    // Non-variadic function: get types from the function declaration
    ArgTypes.reserve(F->arg_size());
    for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
         A != E; ++A) {
      const unsigned ArgNo = A->getArgNo();
      Type *ArgTy = FTy->getParamType(ArgNo);
      ArgTypes.push_back(ArgTy);
    }
  }

  unsigned ArgBytes = 0;
  const unsigned NumArgs = ArgTypes.size();

  std::vector<ffi_type*> args(NumArgs);
  for (unsigned i=0;i<NumArgs;++i) {
    Type *ArgTy = ArgTypes[i];
    args[i] = ffiTypeFor(ArgTy);
    ArgBytes += TD.getTypeStoreSize(ArgTy);
  }

  SmallVector<uint8_t, 128> ArgData;
  ArgData.resize(ArgBytes);
  uint8_t *ArgDataPtr = ArgData.data();
  SmallVector<void*, 16> values(NumArgs);
  for (unsigned i=0;i<NumArgs;++i) {
    Type *ArgTy = ArgTypes[i];
    values[i] = ffiValueFor(ArgTy, ArgVals[i], ArgDataPtr);
    ArgDataPtr += TD.getTypeStoreSize(ArgTy);

  }
  
  
  Type *RetTy = FTy->getReturnType();
  ffi_type *rtype = ffiTypeFor(RetTy);

  if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, &args[0]) == FFI_OK) {
    SmallVector<uint8_t, 128> ret;
    if (RetTy->getTypeID() != Type::VoidTyID)
      ret.resize(TD.getTypeStoreSize(RetTy));
    ffi_call(&cif, Fn, ret.data(), values.data());
    switch (RetTy->getTypeID()) {
      case Type::IntegerTyID:
        switch (cast<IntegerType>(RetTy)->getBitWidth()) {
          case 8:  Result.IntVal = APInt(8 , *(int8_t *) ret.data()); break;
          case 16: Result.IntVal = APInt(16, *(int16_t*) ret.data()); break;
          case 32: Result.IntVal = APInt(32, *(int32_t*) ret.data()); break;
          case 64: Result.IntVal = APInt(64, *(int64_t*) ret.data()); break;
        }
        break;
      case Type::FloatTyID:   Result.FloatVal   = *(float *) ret.data(); break;
      case Type::DoubleTyID:  Result.DoubleVal  = *(double*) ret.data(); break;
      case Type::PointerTyID: Result.PointerVal = *(void **) ret.data(); break;
      default: break;
    }
    return true;
  }

  return false;
}
#endif // USE_LIBFFI

previrt::AbsGenericValue previrt::Interpreter::
callExternalFunction(Instruction *CI, Function *F, ArrayRef<AbsGenericValue> AArgVals) {
  using namespace PatternMatch;

  // We don't want to call exit from the interpreter because it will
  // abort also OCCAM
  if (F->getName().equals("exit")) {
    errs() << "*** ConfigPrime: ignoring \"" << F->getName() << "\"\n";
    ExitExecuted = true;
    return llvm::None;
  }

  // We don't want to close standard output or error 
  if (F->getName().equals("fclose")) {
    CallSite CS(CI);
    if (CS.arg_size() == 1) {
      Value* Arg = CS.getArgument(0);
      Value* LoadAddr;
      if (match(Arg, m_Load(m_Value(LoadAddr)))) {
	if (GlobalVariable *GV= dyn_cast<GlobalVariable>(LoadAddr)) {
	  if (GV->getName() == "stderr" || GV->getName() == "stdout") {
	    errs() << "*** ConfigPrime: ignoring \"" << F->getName() << "\" on stderr or stdout.\n";
	    StopExecution = true;
	    return llvm::None;
	  }
	}
      }
    }
  }

  // REVISIT: do not remember why the interpreter crashed with
  // vfprintf
  if (F->getName().startswith("vfprintf")) {
    errs() << "*** ConfigPrime: execution ignores a call to \""
	   << F->getName() << "\" \n";
    return llvm::None;
  }
  
  TheInterpreter = this;

  std::vector<GenericValue> ArgVals;
  ArgVals.reserve(AArgVals.size());
  for(AbsGenericValue Arg: AArgVals) {
    if (Arg.hasValue()) {
      ArgVals.push_back(Arg.getValue());
    } else {
      errs() << "*** ConfigPrime: execution cannot call to \""
	     << F->getName() << "\" because some argument is unknown.\n";
      StopExecution = true;      
      return llvm::None;
    }
  }
  
  std::unique_lock<sys::Mutex> Guard(*FunctionsLock);

  // Do a lookup to see if the function is in our cache... this should just be a
  // deferred annotation!
  std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F);
  if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F)
                                                   : FI->second) {
    Guard.unlock();
    return Fn(F->getFunctionType(), ArgVals);
  }

  if (hasFunctionPtrParameter(*F)) {
    // The intepreter cannot use FFI to make callbacks
    errs() << "ConfigPrime: cannot execute call to \""
	   << F->getName() << "\" "
	   << "because FFI cannot execute callbacks.\n";
    StopExecution = true;
    return llvm::None;
  }
  
#ifdef USE_LIBFFI
  std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F);
  RawFunc RawFn;
  if (RF == RawFunctions->end()) {
    RawFn = (RawFunc)(intptr_t)
      sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName());
    if (!RawFn)
      RawFn = (RawFunc)(intptr_t)getPointerToGlobalIfAvailable(F);
    if (RawFn != 0)
      RawFunctions->insert(std::make_pair(F, RawFn));  // Cache for later
  } else {
    RawFn = RF->second;
  }

  Guard.unlock();

  GenericValue Result;
  errs() << "Invoking FFI on " << F->getName() << "\n";  
  if (RawFn != 0 && ffiInvoke(CI, RawFn, F, ArgVals, getDataLayout(), Result)) {
    return Result;
  }
#endif // USE_LIBFFI

#ifndef USE_LIBFFI
  errs() << "Recompiling LLVM with --enable-libffi might help.\n";
  errs() << "The execution continues on your own risk: callee side-effects are ignored.\n";
#else
  // If we use FFI then we don't ignore side-effects so we stop the
  // execution.
  StopExecution = true;
#endif
  return llvm::None;
}

//===----------------------------------------------------------------------===//
//  Functions "exported" to the running application...
//

// void atexit(Function*)
static GenericValue lle_X_atexit(FunctionType *FT,
                                 ArrayRef<GenericValue> Args) {<commit_msg>refactor(config-prime): use readonly/speculatable attributes<commit_after>//===-- ExternalFunctions.cpp - Implement External Functions --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file contains both code to deal with invoking "external" functions, but
//  also contains code that implements "exported" external functions.
//
//  There are currently two mechanisms for handling external functions in the
//  Interpreter.  The first is to implement lle_* wrapper functions that are
//  specific to well-known library functions which manually translate the
//  arguments from GenericValues and make the call.  If such a wrapper does
//  not exist, and libffi is available, then the Interpreter will attempt to
//  invoke the function using libffi, after finding its address.
//
//  OCCAM: we only support lle_* wrapper functions
//===----------------------------------------------------------------------===//

#include "Interpreter.h"

#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
//#include "llvm/Config/config.h" // Detect libffi
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cmath>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <map>
#include <string>
#include <utility>
#include <vector>

/// HAVE_FFI_CALL, HAVE_FFI_H, and HAVE_HAVE_FFI_FFI_H are defined if
/// LLVM is compiled with --enable-libffi.
//
// #ifdef HAVE_FFI_CALL
// #ifdef HAVE_FFI_H
// #include <ffi.h>
// #define USE_LIBFFI
// #elif HAVE_FFI_FFI_H
// #include <ffi/ffi.h>
// #define USE_LIBFFI
// #endif
// #endif

#ifdef HAVE_FFI_H
#include <ffi.h>
#define USE_LIBFFI
#elif HAVE_FFI_FFI_H
#include <ffi/ffi.h>
#define USE_LIBFFI
#endif

using namespace llvm;

static ManagedStatic<sys::Mutex> FunctionsLock;

typedef GenericValue (*ExFunc)(FunctionType *, ArrayRef<GenericValue>);
static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions;
static ManagedStatic<std::map<std::string, ExFunc> > FuncNames;

#ifdef USE_LIBFFI
typedef void (*RawFunc)();
static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions;
#endif

static previrt::Interpreter *TheInterpreter;

static char getTypeID(Type *Ty) {
  switch (Ty->getTypeID()) {
  case Type::VoidTyID:    return 'V';
  case Type::IntegerTyID:
    switch (cast<IntegerType>(Ty)->getBitWidth()) {
      case 1:  return 'o';
      case 8:  return 'B';
      case 16: return 'S';
      case 32: return 'I';
      case 64: return 'L';
      default: return 'N';
    }
  case Type::FloatTyID:   return 'F';
  case Type::DoubleTyID:  return 'D';
  case Type::PointerTyID: return 'P';
  case Type::FunctionTyID:return 'M';
  case Type::StructTyID:  return 'T';
  case Type::ArrayTyID:   return 'A';
  default: return 'U';
  }
}

// Try to find address of external function given a Function object.
// Please note, that interpreter doesn't know how to assemble a
// real call in general case (this is JIT job), that's why it assumes,
// that all external functions has the same (and pretty "general") signature.
// The typical example of such functions are "lle_X_" ones.
static ExFunc lookupFunction(const Function *F) {  
  // Function not found, look it up... start by figuring out what the
  // composite function name should be.
  std::string ExtName = "lle_";
  FunctionType *FT = F->getFunctionType();
  for (unsigned i = 0, e = FT->getNumContainedTypes(); i != e; ++i)
    ExtName += getTypeID(FT->getContainedType(i));
  ExtName += ("_" + F->getName()).str();

  sys::ScopedLock Writer(*FunctionsLock);
  ExFunc FnPtr = (*FuncNames)[ExtName];
  
  // HACK: for finding functions such as malloc
  if (!FnPtr) {
    FnPtr = (*FuncNames)[F->getName()];
  }
  if (!FnPtr) {
    FnPtr = (*FuncNames)[("lle_X_" + F->getName()).str()];
  }
  if (!FnPtr) { // Try calling a generic function... if it exists...
    FnPtr = (ExFunc)(intptr_t)sys::DynamicLibrary::SearchForAddressOfSymbol(
        ("lle_X_" + F->getName()).str());
  }

  if (FnPtr) {
    errs() << "ConfigPrime: recognized external call: " << F->getName() << "\n";    
    ExportedFunctions->insert(std::make_pair(F, FnPtr));  // Cache for later
  } else {
    errs() << "ConfigPrime: not recognized external call: " << F->getName() << "\n";
  }
  
  return FnPtr;
}

static bool hasFunctionPtrParameter(const Function &F) {
  const FunctionType *FTy = F.getFunctionType();
  for (unsigned i=0, num_params = FTy->getNumParams(); i<num_params; ++i) {
    const Type *ArgTy = FTy->getParamType(i);
    if (const PointerType *ArgPtrTy = dyn_cast<PointerType>(ArgTy)) {
      if (isa<FunctionType>(ArgPtrTy->getElementType())) {
	return true;
      }
    }
  }
  return false;
}

#ifdef USE_LIBFFI
static ffi_type *ffiTypeFor(Type *Ty) {
  switch (Ty->getTypeID()) {
    case Type::VoidTyID: return &ffi_type_void;
    case Type::IntegerTyID:
      switch (cast<IntegerType>(Ty)->getBitWidth()) {
        case 8:  return &ffi_type_sint8;
        case 16: return &ffi_type_sint16;
        case 32: return &ffi_type_sint32;
        case 64: return &ffi_type_sint64;
      }
    case Type::FloatTyID:   return &ffi_type_float;
    case Type::DoubleTyID:  return &ffi_type_double;
    case Type::PointerTyID: return &ffi_type_pointer;
    default: break;
  }
  // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
  report_fatal_error("Type could not be mapped for use with libffi.");
  return NULL;
}

static void *ffiValueFor(Type *Ty, const GenericValue &AV,
                         void *ArgDataPtr) {
  switch (Ty->getTypeID()) {
    case Type::IntegerTyID:
      switch (cast<IntegerType>(Ty)->getBitWidth()) {
        case 8: {
          int8_t *I8Ptr = (int8_t *) ArgDataPtr;
          *I8Ptr = (int8_t) AV.IntVal.getZExtValue();
          return ArgDataPtr;
        }
        case 16: {
          int16_t *I16Ptr = (int16_t *) ArgDataPtr;
          *I16Ptr = (int16_t) AV.IntVal.getZExtValue();
          return ArgDataPtr;
        }
        case 32: {
          int32_t *I32Ptr = (int32_t *) ArgDataPtr;
          *I32Ptr = (int32_t) AV.IntVal.getZExtValue();
          return ArgDataPtr;
        }
        case 64: {
          int64_t *I64Ptr = (int64_t *) ArgDataPtr;
          *I64Ptr = (int64_t) AV.IntVal.getZExtValue();
          return ArgDataPtr;
        }
      }
      break;
    case Type::FloatTyID: {
      float *FloatPtr = (float *) ArgDataPtr;
      *FloatPtr = AV.FloatVal;
      return ArgDataPtr;
    }
    case Type::DoubleTyID: {
      double *DoublePtr = (double *) ArgDataPtr;
      *DoublePtr = AV.DoubleVal;
      return ArgDataPtr;
    }
    case Type::PointerTyID: {
      void **PtrPtr = (void **) ArgDataPtr;
      *PtrPtr = GVTOP(AV);
      return ArgDataPtr;
    }
    default: break;
  }
  // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
  report_fatal_error("Type value could not be mapped for use with libffi.");
  return NULL;
}

static bool ffiInvoke(Instruction *I, RawFunc Fn, Function *F, ArrayRef<GenericValue> ArgVals,
                      const DataLayout &TD, GenericValue &Result) {


  ffi_cif cif;
  FunctionType *FTy = F->getFunctionType();
  std::vector<Type*> ArgTypes;
  if (ArgVals.size() > F->arg_size() && F->isVarArg()) {
    // Variadic function: get types from the callsite
    if (!I) {
      errs() << "Calling ffiInvoke without a callsite. "
             << "This should not happen\n";
      return false;
    }
    const unsigned NumArgs = ArgVals.size();
    CallSite CS(I);
    if (NumArgs != CS.arg_size()) {
      errs() << "Mismatch of number of parameters at callsite. "
             << "This should not happen\n";
      return false;
    }
    ArgTypes.reserve(NumArgs);
    for (unsigned i=0; i<NumArgs;++i) {
      Value* A = CS.getArgument(i)->stripPointerCasts();
      Type *ArgTy = A->getType();
      ArgTypes.push_back(ArgTy);
    }
  } else {
    // Non-variadic function: get types from the function declaration
    ArgTypes.reserve(F->arg_size());
    for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
         A != E; ++A) {
      const unsigned ArgNo = A->getArgNo();
      Type *ArgTy = FTy->getParamType(ArgNo);
      ArgTypes.push_back(ArgTy);
    }
  }

  unsigned ArgBytes = 0;
  const unsigned NumArgs = ArgTypes.size();

  std::vector<ffi_type*> args(NumArgs);
  for (unsigned i=0;i<NumArgs;++i) {
    Type *ArgTy = ArgTypes[i];
    args[i] = ffiTypeFor(ArgTy);
    ArgBytes += TD.getTypeStoreSize(ArgTy);
  }

  SmallVector<uint8_t, 128> ArgData;
  ArgData.resize(ArgBytes);
  uint8_t *ArgDataPtr = ArgData.data();
  SmallVector<void*, 16> values(NumArgs);
  for (unsigned i=0;i<NumArgs;++i) {
    Type *ArgTy = ArgTypes[i];
    values[i] = ffiValueFor(ArgTy, ArgVals[i], ArgDataPtr);
    ArgDataPtr += TD.getTypeStoreSize(ArgTy);

  }
  
  
  Type *RetTy = FTy->getReturnType();
  ffi_type *rtype = ffiTypeFor(RetTy);

  if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, &args[0]) == FFI_OK) {
    SmallVector<uint8_t, 128> ret;
    if (RetTy->getTypeID() != Type::VoidTyID)
      ret.resize(TD.getTypeStoreSize(RetTy));
    ffi_call(&cif, Fn, ret.data(), values.data());
    switch (RetTy->getTypeID()) {
      case Type::IntegerTyID:
        switch (cast<IntegerType>(RetTy)->getBitWidth()) {
          case 8:  Result.IntVal = APInt(8 , *(int8_t *) ret.data()); break;
          case 16: Result.IntVal = APInt(16, *(int16_t*) ret.data()); break;
          case 32: Result.IntVal = APInt(32, *(int32_t*) ret.data()); break;
          case 64: Result.IntVal = APInt(64, *(int64_t*) ret.data()); break;
        }
        break;
      case Type::FloatTyID:   Result.FloatVal   = *(float *) ret.data(); break;
      case Type::DoubleTyID:  Result.DoubleVal  = *(double*) ret.data(); break;
      case Type::PointerTyID: Result.PointerVal = *(void **) ret.data(); break;
      default: break;
    }
    return true;
  }

  return false;
}
#endif // USE_LIBFFI

previrt::AbsGenericValue previrt::Interpreter::
callExternalFunction(Instruction *CI, Function *F, ArrayRef<AbsGenericValue> AArgVals) {
  using namespace PatternMatch;

  // We don't want to call exit from the interpreter because it will
  // abort also OCCAM
  if (F->getName().equals("exit")) {
    errs() << "*** ConfigPrime: ignoring \"" << F->getName() << "\"\n";
    ExitExecuted = true;
    return llvm::None;
  }

  // We don't want to close standard output or error 
  if (F->getName().equals("fclose")) {
    CallSite CS(CI);
    if (CS.arg_size() == 1) {
      Value* Arg = CS.getArgument(0);
      Value* LoadAddr;
      if (match(Arg, m_Load(m_Value(LoadAddr)))) {
	if (GlobalVariable *GV= dyn_cast<GlobalVariable>(LoadAddr)) {
	  if (GV->getName() == "stderr" || GV->getName() == "stdout") {
	    errs() << "*** ConfigPrime: ignoring \""
		   << F->getName() << "\" on stderr or stdout.\n";
	    //StopExecution = true;
	    return llvm::None;
	  }
	}
      }
    }
  }

  // REVISIT: do not remember why the interpreter crashed with
  // vfprintf
  if (F->getName().startswith("vfprintf")) {
    errs() << "*** ConfigPrime: execution ignores a call to \""
	   << F->getName() << "\" \n";
    return llvm::None;
  }
  
  TheInterpreter = this;

  std::vector<GenericValue> ArgVals;
  ArgVals.reserve(AArgVals.size());
  for(AbsGenericValue Arg: AArgVals) {
    if (Arg.hasValue()) {
      ArgVals.push_back(Arg.getValue());
    } else {
      errs() << "INTERPRETER STOPPED: execution cannot call to \""
	     << F->getName() << "\" because some argument is unknown.\n";
      StopExecution = true;      
      return llvm::None;
    }
  }
  
  std::unique_lock<sys::Mutex> Guard(*FunctionsLock);

  // Do a lookup to see if the function is in our cache... this should just be a
  // deferred annotation!
  std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F);
  if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F)
                                                   : FI->second) {
    Guard.unlock();
    return Fn(F->getFunctionType(), ArgVals);
  }

  if (hasFunctionPtrParameter(*F)) {
    // The intepreter cannot use FFI to make callbacks
    errs() << "INTERPRETER STOPPED: cannot execute call to \""
	   << F->getName() << "\" "
	   << "because FFI cannot execute callbacks.\n";
    StopExecution = true;
    return llvm::None;
  }
  
#ifdef USE_LIBFFI
  std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F);
  RawFunc RawFn;
  if (RF == RawFunctions->end()) {
    RawFn = (RawFunc)(intptr_t)
      sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName());
    if (!RawFn)
      RawFn = (RawFunc)(intptr_t)getPointerToGlobalIfAvailable(F);
    if (RawFn != 0)
      RawFunctions->insert(std::make_pair(F, RawFn));  // Cache for later
  } else {
    RawFn = RF->second;
  }

  Guard.unlock();

  GenericValue Result;
  errs() << "Invoking FFI on " << F->getName() << "\n";  
  if (RawFn != 0 && ffiInvoke(CI, RawFn, F, ArgVals, getDataLayout(), Result)) {
    return Result;
  }
#endif // USE_LIBFFI

#ifndef USE_LIBFFI
  errs() << "Recompiling LLVM with --enable-libffi might help.\n";
  errs() << "The execution continues on your own risk: callee side-effects are ignored.\n";
#else
  errs() << "FFI could not execute " << F->getName() << "\n";
  
  if (F->onlyReadsMemory()) {
    errs() << "But the function does not access memory "
	   << "so that we do not stop execution.\n";
  } else if (F->onlyAccessesInaccessibleMemory()) {
    errs() << "But the function does not access memory accessible by the program "
	   << " so that we do not stop execution.\n";
  } else if (!F->isSpeculatable()) {
    errs() << "But the function does not have sideeffects "
	   << "so that we do not stop execution.\n";
  } // else if (ArgVals.empty()) {
  //   errs() << "But the function does not have arguments "
  // 	   << "so we speculatively assume that it does not modify any global variable, "
  // 	   << "and therefore, we do not stop execution\n";
  // } 
  else {
    errs() << "INTERPRETER STOPPED because function might have side effects.\n";
    StopExecution = true;
  }
  
#endif
  return llvm::None;
}

//===----------------------------------------------------------------------===//
//  Functions "exported" to the running application...
//

// void atexit(Function*)
static GenericValue lle_X_atexit(FunctionType *FT,
                                 ArrayRef<GenericValue> Args) {
{'fraction_non_alphanumeric': 0.16045619562983765, 'fraction_numerical': 0.007329269128022467, 'mean_word_length': 2.960260409602604, 'pattern_counts': {'":': 0, '<': 243, '<?xml version=': 0, '>': 197, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '234040', 'n_tokens_mistral': 9869, 'n_tokens_neox': 9609, 'n_words': 2527}