1//===-- ExternalFunctions.cpp - Implement External Functions --------------===// 3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4// See https://llvm.org/LICENSE.txt for license information. 5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 7//===----------------------------------------------------------------------===// 9// This file contains both code to deal with invoking "external" functions, but 10// also contains code that implements "exported" external functions. 12// There are currently two mechanisms for handling external functions in the 13// Interpreter. The first is to implement lle_* wrapper functions that are 14// specific to well-known library functions which manually translate the 15// arguments from GenericValues and make the call. If such a wrapper does 16// not exist, and libffi is available, then the Interpreter will attempt to 17// invoke the function using libffi, after finding its address. 19//===----------------------------------------------------------------------===// 24#include "llvm/Config/config.h"// Detect libffi 62typedef void (*RawFunc)();
66 std::map<const Function *, ExFunc> ExportedFunctions;
67 std::map<std::string, ExFunc> FuncNames;
69 std::map<const Function *, RawFunc> RawFunctions;
73Functions &getFunctions() {
78}
// anonymous namespace 104// Try to find address of external function given a Function object. 105// Please note, that interpreter doesn't know how to assemble a 106// real call in general case (this is JIT job), that's why it assumes, 107// that all external functions has the same (and pretty "general") signature. 108// The typical example of such functions are "lle_X_" ones. 110// Function not found, look it up... start by figuring out what the 111// composite function name should be. 112 std::string ExtName =
"lle_";
114 ExtName +=
getTypeID(FT->getReturnType());
115for (
Type *
T : FT->params())
117 ExtName += (
"_" +
F->getName()).str();
119auto &Fns = getFunctions();
121 ExFunc FnPtr = Fns.FuncNames[ExtName];
123 FnPtr = Fns.FuncNames[(
"lle_X_" +
F->getName()).str()];
124if (!FnPtr)
// Try calling a generic function... if it exists... 126 (
"lle_X_" +
F->getName()).str());
128 Fns.ExportedFunctions.insert(std::make_pair(
F, FnPtr));
// Cache for later 133static ffi_type *ffiTypeFor(
Type *Ty) {
138case 8:
return &ffi_type_sint8;
139case 16:
return &ffi_type_sint16;
140case 32:
return &ffi_type_sint32;
141case 64:
return &ffi_type_sint64;
149// TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc. 160 int8_t *I8Ptr = (int8_t *) ArgDataPtr;
165 int16_t *I16Ptr = (int16_t *) ArgDataPtr;
170 int32_t *I32Ptr = (int32_t *) ArgDataPtr;
175 int64_t *I64Ptr = (int64_t *) ArgDataPtr;
182float *FloatPtr = (
float *) ArgDataPtr;
187double *DoublePtr = (
double *) ArgDataPtr;
192void **PtrPtr = (
void **) ArgDataPtr;
198// TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc. 207constunsigned NumArgs =
F->arg_size();
209// TODO: We don't have type information about the remaining arguments, because 210// this information is never passed into ExecutionEngine::runFunction(). 211if (ArgVals.
size() > NumArgs &&
F->isVarArg()) {
213 +
"' is not supported by the Interpreter.");
216unsigned ArgBytes = 0;
218 std::vector<ffi_type*>
args(NumArgs);
221constunsigned ArgNo =
A->getArgNo();
222Type *ArgTy = FTy->getParamType(ArgNo);
223args[ArgNo] = ffiTypeFor(ArgTy);
233constunsigned ArgNo =
A->getArgNo();
234Type *ArgTy = FTy->getParamType(ArgNo);
235values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);
240 ffi_type *rtype = ffiTypeFor(
RetTy);
242if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype,
args.data()) ==
248switch (
RetTy->getTypeID()) {
273auto &Fns = getFunctions();
274 std::unique_lock<sys::Mutex> Guard(Fns.Lock);
276// Do a lookup to see if the function is in our cache... this should just be a 277// deferred annotation! 278 std::map<const Function *, ExFunc>::iterator FI =
279 Fns.ExportedFunctions.find(
F);
283return Fn(
F->getFunctionType(), ArgVals);
287 std::map<const Function *, RawFunc>::iterator RF = Fns.RawFunctions.find(
F);
289if (RF == Fns.RawFunctions.end()) {
290 RawFn = (RawFunc)(intptr_t)
295 Fns.RawFunctions.insert(std::make_pair(
F, RawFn));
// Cache for later 303if (RawFn != 0 && ffiInvoke(RawFn,
F, ArgVals,
getDataLayout(), Result))
307if (
F->getName() ==
"__main")
308errs() <<
"Tried to execute an unknown external function: " 309 << *
F->getType() <<
" __main\n";
314errs() <<
"Recompiling LLVM with --enable-libffi might help.\n";
319//===----------------------------------------------------------------------===// 320// Functions "exported" to the running application... 323// void atexit(Function*) 341//FIXME: should we report or raise here? 342//report_fatal_error("Interpreted program raised SIGABRT"); 347// Silence warnings about sprintf. (See also 348// https://github.com/llvm/llvm-project/issues/58086) 349#if defined(__clang__) 350#pragma clang diagnostic push 351#pragma clang diagnostic ignored "-Wdeprecated-declarations" 353// int sprintf(char *, const char *, ...) - a very rough implementation to make 358constchar *FmtStr = (
constchar *)
GVTOP(Args[1]);
361// printf should return # chars printed. This is completely incorrect, but 362// close enough for now. 367case 0:
return GV;
// Null terminator... 368default:
// Normal nonspecial character 371case'\\': {
// Handle escape codes 376case'%': {
// Handle format specifiers 377char FmtBuf[100] =
"", Buffer[1000] =
"";
380charLast = *FB++ = *FmtStr++;
386if (
Last ==
'l' ||
Last ==
'L') HowLong++;
// Keep track of l's 387Last = *FB++ = *FmtStr++;
393 memcpy(Buffer,
"%", 2);
break;
395 sprintf(Buffer, FmtBuf,
uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
403sizeof(
long) <
sizeof(int64_t)) {
404// Make sure we use %lld with a 64 bit argument because we might be 405// compiling LLI on a 32 bit compiler. 406unsignedSize = strlen(FmtBuf);
411 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());
413 sprintf(Buffer, FmtBuf,
uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
415case'e':
case'E':
case'g':
case'G':
case'f':
416 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal);
break;
418 sprintf(Buffer, FmtBuf, (
void*)
GVTOP(Args[ArgNo++]));
break;
420 sprintf(Buffer, FmtBuf, (
char*)
GVTOP(Args[ArgNo++]));
break;
422errs() <<
"<unknown printf code '" << *FmtStr <<
"'!>";
425size_t Len = strlen(Buffer);
434#if defined(__clang__) 435#pragma clang diagnostic pop 438// int printf(const char *, ...) - a very rough implementation to make output 443 std::vector<GenericValue> NewArgs;
444 NewArgs.push_back(
PTOGV((
void*)&Buffer[0]));
451// int sscanf(const char *format, ...); 454assert(
args.size() < 10 &&
"Only handle up to 10 args to sscanf right now!");
457for (
unsigned i = 0; i <
args.size(); ++i)
461 GV.
IntVal =
APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
462 Args[5], Args[6], Args[7], Args[8], Args[9]));
466// int scanf(const char *format, ...); 468assert(
args.size() < 10 &&
"Only handle up to 10 args to scanf right now!");
471for (
unsigned i = 0; i <
args.size(); ++i)
475 GV.
IntVal =
APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],
476 Args[5], Args[6], Args[7], Args[8], Args[9]));
480// int fprintf(FILE *, const char *, ...) - a very rough implementation to make 486 std::vector<GenericValue> NewArgs;
487 NewArgs.push_back(
PTOGV(Buffer));
488 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
491 fputs(Buffer, (FILE *)
GVTOP(Args[0]));
497int val = (int)Args[1].IntVal.getSExtValue();
498size_t len = (size_t)Args[2].IntVal.getZExtValue();
499 memset((
void *)
GVTOP(Args[0]), val, len);
500// llvm.memset.* returns void, lle_X_* returns GenericValue, 501// so here we return GenericValue with IntVal set to zero 510 (
size_t)(Args[2].IntVal.getLimitedValue()));
512// llvm.memcpy* returns void, lle_X_* returns GenericValue, 513// so here we return GenericValue with IntVal set to zero 519void Interpreter::initializeExternalFunctions() {
520auto &Fns = getFunctions();
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Mark the given Function as meaning that it cannot be changed in any way mark any values that are used as this function s parameters or by its return values(according to Uses) live as well. void DeadArgumentEliminationPass
static ExFunc lookupFunction(const Function *F)
static Interpreter * TheInterpreter
static GenericValue lle_X_memset(FunctionType *FT, ArrayRef< GenericValue > Args)
static char getTypeID(Type *Ty)
static GenericValue lle_X_fprintf(FunctionType *FT, ArrayRef< GenericValue > Args)
static GenericValue lle_X_scanf(FunctionType *FT, ArrayRef< GenericValue > args)
static GenericValue lle_X_printf(FunctionType *FT, ArrayRef< GenericValue > Args)
static GenericValue lle_X_memcpy(FunctionType *FT, ArrayRef< GenericValue > Args)
static GenericValue lle_X_atexit(FunctionType *FT, ArrayRef< GenericValue > Args)
static GenericValue lle_X_sscanf(FunctionType *FT, ArrayRef< GenericValue > args)
static GenericValue lle_X_abort(FunctionType *FT, ArrayRef< GenericValue > Args)
static GenericValue lle_X_exit(FunctionType *FT, ArrayRef< GenericValue > Args)
static GenericValue lle_X_sprintf(FunctionType *FT, ArrayRef< GenericValue > Args)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Class for arbitrary precision integers.
uint64_t getZExtValue() const
Get zero extended value.
This class represents an incoming formal argument to a Function.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
A parsed version of the target data layout string in and methods for querying it.
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
const DataLayout & getDataLayout() const
void * getPointerToGlobalIfAvailable(StringRef S)
getPointerToGlobalIfAvailable - This returns the address of the specified global value if it is has a...
void addAtExitHandler(Function *F)
void exitCalled(GenericValue GV)
GenericValue callExternalFunction(Function *F, ArrayRef< GenericValue > ArgVals)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
@ VoidTyID
type with no size
@ FloatTyID
32-bit floating point type
@ IntegerTyID
Arbitrary bit width integers.
@ DoubleTyID
64-bit floating point type
TypeID getTypeID() const
Return the type id for the type.
static void * SearchForAddressOfSymbol(const char *symbolName)
This function will search through all previously loaded dynamic libraries for the symbol symbolName.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
SmartScopedLock< false > ScopedLock
This is an optimization pass for GlobalISel generic memory operations.
raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
GenericValue PTOGV(void *P)
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void * GVTOP(const GenericValue &GV)