1 //===-- ExternalFunctions.cpp - Implement External Functions --------------===//
3 // This file contains both code to deal with invoking "external" functions, but
4 // also contains code that implements "exported" external functions.
6 // External functions in LLI are implemented by dlopen'ing the lli executable
7 // and using dlsym to look op the functions that we want to invoke. If a
8 // function is found, then the arguments are mangled and passed in to the
11 //===----------------------------------------------------------------------===//
13 #include "Interpreter.h"
14 #include "llvm/DerivedTypes.h"
24 typedef GenericValue (*ExFunc)(FunctionType *, const vector<GenericValue> &);
25 static std::map<const Function *, ExFunc> Functions;
26 static std::map<std::string, ExFunc> FuncNames;
28 static Interpreter *TheInterpreter;
30 // getCurrentExecutablePath() - Return the directory that the lli executable
33 std::string Interpreter::getCurrentExecutablePath() const {
35 if (dladdr(&TheInterpreter, &Info) == 0) return "";
37 std::string LinkAddr(Info.dli_fname);
38 unsigned SlashPos = LinkAddr.rfind('/');
39 if (SlashPos != std::string::npos)
40 LinkAddr.resize(SlashPos); // Trim the executable name off...
46 static char getTypeID(const Type *Ty) {
47 switch (Ty->getPrimitiveID()) {
48 case Type::VoidTyID: return 'V';
49 case Type::BoolTyID: return 'o';
50 case Type::UByteTyID: return 'B';
51 case Type::SByteTyID: return 'b';
52 case Type::UShortTyID: return 'S';
53 case Type::ShortTyID: return 's';
54 case Type::UIntTyID: return 'I';
55 case Type::IntTyID: return 'i';
56 case Type::ULongTyID: return 'L';
57 case Type::LongTyID: return 'l';
58 case Type::FloatTyID: return 'F';
59 case Type::DoubleTyID: return 'D';
60 case Type::PointerTyID: return 'P';
61 case Type::FunctionTyID: return 'M';
62 case Type::StructTyID: return 'T';
63 case Type::ArrayTyID: return 'A';
64 case Type::OpaqueTyID: return 'O';
69 static ExFunc lookupFunction(const Function *M) {
70 // Function not found, look it up... start by figuring out what the
71 // composite function name should be.
72 std::string ExtName = "lle_";
73 const FunctionType *MT = M->getFunctionType();
74 for (unsigned i = 0; const Type *Ty = MT->getContainedType(i); ++i)
75 ExtName += getTypeID(Ty);
76 ExtName += "_" + M->getName();
78 //cout << "Tried: '" << ExtName << "'\n";
79 ExFunc FnPtr = FuncNames[ExtName];
81 FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
83 FnPtr = FuncNames["lle_X_"+M->getName()];
84 if (FnPtr == 0) // Try calling a generic function... if it exists...
85 FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ("lle_X_"+M->getName()).c_str());
87 Functions.insert(std::make_pair(M, FnPtr)); // Cache for later
91 GenericValue Interpreter::callExternalMethod(Function *M,
92 const vector<GenericValue> &ArgVals) {
93 TheInterpreter = this;
95 // Do a lookup to see if the function is in our cache... this should just be a
96 // defered annotation!
97 std::map<const Function *, ExFunc>::iterator FI = Functions.find(M);
98 ExFunc Fn = (FI == Functions.end()) ? lookupFunction(M) : FI->second;
100 cout << "Tried to execute an unknown external function: "
101 << M->getType()->getDescription() << " " << M->getName() << "\n";
102 return GenericValue();
105 // TODO: FIXME when types are not const!
106 GenericValue Result = Fn(const_cast<FunctionType*>(M->getFunctionType()),
112 //===----------------------------------------------------------------------===//
113 // Functions "exported" to the running application...
115 extern "C" { // Don't add C++ manglings to llvm mangling :)
117 // Implement void printstr([ubyte {x N}] *)
118 GenericValue lle_VP_printstr(FunctionType *M, const vector<GenericValue> &ArgVal){
119 assert(ArgVal.size() == 1 && "printstr only takes one argument!");
120 cout << (char*)ArgVal[0].PointerVal;
121 return GenericValue();
124 // Implement 'void print(X)' for every type...
125 GenericValue lle_X_print(FunctionType *M, const vector<GenericValue> &ArgVals) {
126 assert(ArgVals.size() == 1 && "generic print only takes one argument!");
128 Interpreter::print(M->getParamTypes()[0], ArgVals[0]);
129 return GenericValue();
132 // Implement 'void printVal(X)' for every type...
133 GenericValue lle_X_printVal(FunctionType *M, const vector<GenericValue> &ArgVal) {
134 assert(ArgVal.size() == 1 && "generic print only takes one argument!");
136 // Specialize print([ubyte {x N} ] *) and print(sbyte *)
137 if (const PointerType *PTy =
138 dyn_cast<PointerType>(M->getParamTypes()[0].get()))
139 if (PTy->getElementType() == Type::SByteTy ||
140 isa<ArrayType>(PTy->getElementType())) {
141 return lle_VP_printstr(M, ArgVal);
144 Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);
145 return GenericValue();
148 // Implement 'void printString(X)'
149 // Argument must be [ubyte {x N} ] * or sbyte *
150 GenericValue lle_X_printString(FunctionType *M, const vector<GenericValue> &ArgVal) {
151 assert(ArgVal.size() == 1 && "generic print only takes one argument!");
152 return lle_VP_printstr(M, ArgVal);
155 // Implement 'void print<TYPE>(X)' for each primitive type or pointer type
156 #define PRINT_TYPE_FUNC(TYPENAME,TYPEID) \
157 GenericValue lle_X_print##TYPENAME(FunctionType *M,\
158 const vector<GenericValue> &ArgVal) {\
159 assert(ArgVal.size() == 1 && "generic print only takes one argument!");\
160 assert(M->getParamTypes()[0].get()->getPrimitiveID() == Type::TYPEID);\
161 Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);\
162 return GenericValue();\
165 PRINT_TYPE_FUNC(SByte, SByteTyID)
166 PRINT_TYPE_FUNC(UByte, UByteTyID)
167 PRINT_TYPE_FUNC(Short, ShortTyID)
168 PRINT_TYPE_FUNC(UShort, UShortTyID)
169 PRINT_TYPE_FUNC(Int, IntTyID)
170 PRINT_TYPE_FUNC(UInt, UIntTyID)
171 PRINT_TYPE_FUNC(Long, LongTyID)
172 PRINT_TYPE_FUNC(ULong, ULongTyID)
173 PRINT_TYPE_FUNC(Float, FloatTyID)
174 PRINT_TYPE_FUNC(Double, DoubleTyID)
175 PRINT_TYPE_FUNC(Pointer, PointerTyID)
178 // void "putchar"(sbyte)
179 GenericValue lle_Vb_putchar(FunctionType *M, const vector<GenericValue> &Args) {
180 cout << Args[0].SByteVal;
181 return GenericValue();
184 // int "putchar"(int)
185 GenericValue lle_ii_putchar(FunctionType *M, const vector<GenericValue> &Args) {
186 cout << ((char)Args[0].IntVal) << std::flush;
190 // void "putchar"(ubyte)
191 GenericValue lle_VB_putchar(FunctionType *M, const vector<GenericValue> &Args) {
192 cout << Args[0].SByteVal << std::flush;
197 GenericValue lle_V___main(FunctionType *M, const vector<GenericValue> &Args) {
198 return GenericValue();
202 GenericValue lle_X_exit(FunctionType *M, const vector<GenericValue> &Args) {
203 TheInterpreter->exitCalled(Args[0]);
204 return GenericValue();
207 // void "abort"(void)
208 GenericValue lle_X_abort(FunctionType *M, const vector<GenericValue> &Args) {
209 std::cerr << "***PROGRAM ABORTED***!\n";
212 TheInterpreter->exitCalled(GV);
213 return GenericValue();
216 // void *malloc(uint)
217 GenericValue lle_X_malloc(FunctionType *M, const vector<GenericValue> &Args) {
218 assert(Args.size() == 1 && "Malloc expects one argument!");
220 GV.PointerVal = (PointerTy)malloc(Args[0].UIntVal);
225 GenericValue lle_X_free(FunctionType *M, const vector<GenericValue> &Args) {
226 assert(Args.size() == 1);
227 free((void*)Args[0].PointerVal);
228 return GenericValue();
232 GenericValue lle_X_atoi(FunctionType *M, const vector<GenericValue> &Args) {
233 assert(Args.size() == 1);
235 GV.IntVal = atoi((char*)Args[0].PointerVal);
239 // double pow(double, double)
240 GenericValue lle_X_pow(FunctionType *M, const vector<GenericValue> &Args) {
241 assert(Args.size() == 2);
243 GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
247 // double exp(double)
248 GenericValue lle_X_exp(FunctionType *M, const vector<GenericValue> &Args) {
249 assert(Args.size() == 1);
251 GV.DoubleVal = exp(Args[0].DoubleVal);
255 // double sqrt(double)
256 GenericValue lle_X_sqrt(FunctionType *M, const vector<GenericValue> &Args) {
257 assert(Args.size() == 1);
259 GV.DoubleVal = sqrt(Args[0].DoubleVal);
263 // double log(double)
264 GenericValue lle_X_log(FunctionType *M, const vector<GenericValue> &Args) {
265 assert(Args.size() == 1);
267 GV.DoubleVal = log(Args[0].DoubleVal);
271 // double floor(double)
272 GenericValue lle_X_floor(FunctionType *M, const vector<GenericValue> &Args) {
273 assert(Args.size() == 1);
275 GV.DoubleVal = floor(Args[0].DoubleVal);
280 GenericValue lle_X_drand48(FunctionType *M, const vector<GenericValue> &Args) {
281 assert(Args.size() == 0);
283 GV.DoubleVal = drand48();
288 GenericValue lle_X_lrand48(FunctionType *M, const vector<GenericValue> &Args) {
289 assert(Args.size() == 0);
291 GV.IntVal = lrand48();
295 // void srand48(long)
296 GenericValue lle_X_srand48(FunctionType *M, const vector<GenericValue> &Args) {
297 assert(Args.size() == 1);
298 srand48(Args[0].IntVal);
299 return GenericValue();
303 GenericValue lle_X_srand(FunctionType *M, const vector<GenericValue> &Args) {
304 assert(Args.size() == 1);
305 srand(Args[0].UIntVal);
306 return GenericValue();
309 // int sprintf(sbyte *, sbyte *, ...) - a very rough implementation to make
311 GenericValue lle_X_sprintf(FunctionType *M, const vector<GenericValue> &Args) {
312 char *OutputBuffer = (char *)Args[0].PointerVal;
313 const char *FmtStr = (const char *)Args[1].PointerVal;
316 // printf should return # chars printed. This is completely incorrect, but
317 // close enough for now.
318 GenericValue GV; GV.IntVal = strlen(FmtStr);
321 case 0: return GV; // Null terminator...
322 default: // Normal nonspecial character
323 sprintf(OutputBuffer++, "%c", *FmtStr++);
325 case '\\': { // Handle escape codes
326 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
327 FmtStr += 2; OutputBuffer += 2;
330 case '%': { // Handle format specifiers
331 char FmtBuf[100] = "", Buffer[1000] = "";
334 char Last = *FB++ = *FmtStr++;
335 unsigned HowLong = 0;
336 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
337 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
338 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
339 Last != 'p' && Last != 's' && Last != '%') {
340 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
341 Last = *FB++ = *FmtStr++;
347 sprintf(Buffer, FmtBuf); break;
349 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
355 // Make sure we use %lld with a 64 bit argument because we might be
356 // compiling LLI on a 32 bit compiler.
357 unsigned Size = strlen(FmtBuf);
358 FmtBuf[Size] = FmtBuf[Size-1];
360 FmtBuf[Size-1] = 'l';
362 sprintf(Buffer, FmtBuf, Args[ArgNo++].ULongVal);
364 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
365 case 'e': case 'E': case 'g': case 'G': case 'f':
366 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
368 sprintf(Buffer, FmtBuf, (void*)Args[ArgNo++].PointerVal); break;
370 sprintf(Buffer, FmtBuf, (char*)Args[ArgNo++].PointerVal); break;
371 default: cout << "<unknown printf code '" << *FmtStr << "'!>";
374 strcpy(OutputBuffer, Buffer);
375 OutputBuffer += strlen(Buffer);
382 // int printf(sbyte *, ...) - a very rough implementation to make output useful.
383 GenericValue lle_X_printf(FunctionType *M, const vector<GenericValue> &Args) {
385 vector<GenericValue> NewArgs;
386 GenericValue GV; GV.PointerVal = (PointerTy)Buffer;
387 NewArgs.push_back(GV);
388 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
389 GV = lle_X_sprintf(M, NewArgs);
394 // int sscanf(const char *format, ...);
395 GenericValue lle_X_sscanf(FunctionType *M, const vector<GenericValue> &args) {
396 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
398 const char *Args[10];
399 for (unsigned i = 0; i < args.size(); ++i)
400 Args[i] = (const char*)args[i].PointerVal;
403 GV.IntVal = sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
404 Args[5], Args[6], Args[7], Args[8], Args[9]);
409 // int clock(void) - Profiling implementation
410 GenericValue lle_i_clock(FunctionType *M, const vector<GenericValue> &Args) {
411 extern int clock(void);
412 GenericValue GV; GV.IntVal = clock();
416 //===----------------------------------------------------------------------===//
418 //===----------------------------------------------------------------------===//
420 // FILE *fopen(const char *filename, const char *mode);
421 GenericValue lle_X_fopen(FunctionType *M, const vector<GenericValue> &Args) {
422 assert(Args.size() == 2);
425 GV.PointerVal = (PointerTy)fopen((const char *)Args[0].PointerVal,
426 (const char *)Args[1].PointerVal);
430 // int fclose(FILE *F);
431 GenericValue lle_X_fclose(FunctionType *M, const vector<GenericValue> &Args) {
432 assert(Args.size() == 1);
435 GV.IntVal = fclose((FILE *)Args[0].PointerVal);
439 // size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);
440 GenericValue lle_X_fread(FunctionType *M, const vector<GenericValue> &Args) {
441 assert(Args.size() == 4);
444 GV.UIntVal = fread((void*)Args[0].PointerVal, Args[1].UIntVal,
445 Args[2].UIntVal, (FILE*)Args[3].PointerVal);
449 // size_t fwrite(const void *ptr, size_t size, size_t nitems, FILE *stream);
450 GenericValue lle_X_fwrite(FunctionType *M, const vector<GenericValue> &Args) {
451 assert(Args.size() == 4);
454 GV.UIntVal = fwrite((void*)Args[0].PointerVal, Args[1].UIntVal,
455 Args[2].UIntVal, (FILE*)Args[3].PointerVal);
459 // char *fgets(char *s, int n, FILE *stream);
460 GenericValue lle_X_fgets(FunctionType *M, const vector<GenericValue> &Args) {
461 assert(Args.size() == 3);
464 GV.PointerVal = (PointerTy)fgets((char*)Args[0].PointerVal, Args[1].IntVal,
465 (FILE*)Args[2].PointerVal);
469 // int fflush(FILE *stream);
470 GenericValue lle_X_fflush(FunctionType *M, const vector<GenericValue> &Args) {
471 assert(Args.size() == 1);
474 GV.IntVal = fflush((FILE*)Args[0].PointerVal);
481 void Interpreter::initializeExternalMethods() {
482 FuncNames["lle_VP_printstr"] = lle_VP_printstr;
483 FuncNames["lle_X_print"] = lle_X_print;
484 FuncNames["lle_X_printVal"] = lle_X_printVal;
485 FuncNames["lle_X_printString"] = lle_X_printString;
486 FuncNames["lle_X_printUByte"] = lle_X_printUByte;
487 FuncNames["lle_X_printSByte"] = lle_X_printSByte;
488 FuncNames["lle_X_printUShort"] = lle_X_printUShort;
489 FuncNames["lle_X_printShort"] = lle_X_printShort;
490 FuncNames["lle_X_printInt"] = lle_X_printInt;
491 FuncNames["lle_X_printUInt"] = lle_X_printUInt;
492 FuncNames["lle_X_printLong"] = lle_X_printLong;
493 FuncNames["lle_X_printULong"] = lle_X_printULong;
494 FuncNames["lle_X_printFloat"] = lle_X_printFloat;
495 FuncNames["lle_X_printDouble"] = lle_X_printDouble;
496 FuncNames["lle_X_printPointer"] = lle_X_printPointer;
497 FuncNames["lle_Vb_putchar"] = lle_Vb_putchar;
498 FuncNames["lle_ii_putchar"] = lle_ii_putchar;
499 FuncNames["lle_VB_putchar"] = lle_VB_putchar;
500 FuncNames["lle_V___main"] = lle_V___main;
501 FuncNames["lle_X_exit"] = lle_X_exit;
502 FuncNames["lle_X_abort"] = lle_X_abort;
503 FuncNames["lle_X_malloc"] = lle_X_malloc;
504 FuncNames["lle_X_free"] = lle_X_free;
505 FuncNames["lle_X_atoi"] = lle_X_atoi;
506 FuncNames["lle_X_pow"] = lle_X_pow;
507 FuncNames["lle_X_exp"] = lle_X_exp;
508 FuncNames["lle_X_log"] = lle_X_log;
509 FuncNames["lle_X_floor"] = lle_X_floor;
510 FuncNames["lle_X_srand"] = lle_X_srand;
511 FuncNames["lle_X_drand48"] = lle_X_drand48;
512 FuncNames["lle_X_srand48"] = lle_X_srand48;
513 FuncNames["lle_X_lrand48"] = lle_X_lrand48;
514 FuncNames["lle_X_sqrt"] = lle_X_sqrt;
515 FuncNames["lle_X_printf"] = lle_X_printf;
516 FuncNames["lle_X_sprintf"] = lle_X_sprintf;
517 FuncNames["lle_X_sscanf"] = lle_X_sscanf;
518 FuncNames["lle_i_clock"] = lle_i_clock;
519 FuncNames["lle_X_fopen"] = lle_X_fopen;
520 FuncNames["lle_X_fclose"] = lle_X_fclose;
521 FuncNames["lle_X_fread"] = lle_X_fread;
522 FuncNames["lle_X_fwrite"] = lle_X_fwrite;
523 FuncNames["lle_X_fgets"] = lle_X_fgets;
524 FuncNames["lle_X_fflush"] = lle_X_fflush;