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 "ExecutionAnnotations.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Target/TargetData.h"
28 typedef GenericValue (*ExFunc)(FunctionType *, const vector<GenericValue> &);
29 static std::map<const Function *, ExFunc> Functions;
30 static std::map<std::string, ExFunc> FuncNames;
32 static Interpreter *TheInterpreter;
34 // getCurrentExecutablePath() - Return the directory that the lli executable
37 std::string Interpreter::getCurrentExecutablePath() const {
39 if (dladdr(&TheInterpreter, &Info) == 0) return "";
41 std::string LinkAddr(Info.dli_fname);
42 unsigned SlashPos = LinkAddr.rfind('/');
43 if (SlashPos != std::string::npos)
44 LinkAddr.resize(SlashPos); // Trim the executable name off...
50 static char getTypeID(const Type *Ty) {
51 switch (Ty->getPrimitiveID()) {
52 case Type::VoidTyID: return 'V';
53 case Type::BoolTyID: return 'o';
54 case Type::UByteTyID: return 'B';
55 case Type::SByteTyID: return 'b';
56 case Type::UShortTyID: return 'S';
57 case Type::ShortTyID: return 's';
58 case Type::UIntTyID: return 'I';
59 case Type::IntTyID: return 'i';
60 case Type::ULongTyID: return 'L';
61 case Type::LongTyID: return 'l';
62 case Type::FloatTyID: return 'F';
63 case Type::DoubleTyID: return 'D';
64 case Type::PointerTyID: return 'P';
65 case Type::FunctionTyID: return 'M';
66 case Type::StructTyID: return 'T';
67 case Type::ArrayTyID: return 'A';
68 case Type::OpaqueTyID: return 'O';
73 static ExFunc lookupFunction(const Function *M) {
74 // Function not found, look it up... start by figuring out what the
75 // composite function name should be.
76 std::string ExtName = "lle_";
77 const FunctionType *MT = M->getFunctionType();
78 for (unsigned i = 0; const Type *Ty = MT->getContainedType(i); ++i)
79 ExtName += getTypeID(Ty);
80 ExtName += "_" + M->getName();
82 //cout << "Tried: '" << ExtName << "'\n";
83 ExFunc FnPtr = FuncNames[ExtName];
85 FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
87 FnPtr = FuncNames["lle_X_"+M->getName()];
88 if (FnPtr == 0) // Try calling a generic function... if it exists...
89 FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ("lle_X_"+M->getName()).c_str());
91 Functions.insert(std::make_pair(M, FnPtr)); // Cache for later
95 GenericValue Interpreter::callExternalMethod(Function *M,
96 const vector<GenericValue> &ArgVals) {
97 TheInterpreter = this;
99 // Do a lookup to see if the function is in our cache... this should just be a
100 // defered annotation!
101 std::map<const Function *, ExFunc>::iterator FI = Functions.find(M);
102 ExFunc Fn = (FI == Functions.end()) ? lookupFunction(M) : FI->second;
104 cout << "Tried to execute an unknown external function: "
105 << M->getType()->getDescription() << " " << M->getName() << "\n";
106 return GenericValue();
109 // TODO: FIXME when types are not const!
110 GenericValue Result = Fn(const_cast<FunctionType*>(M->getFunctionType()),
116 //===----------------------------------------------------------------------===//
117 // Functions "exported" to the running application...
119 extern "C" { // Don't add C++ manglings to llvm mangling :)
121 // Implement void printstr([ubyte {x N}] *)
122 GenericValue lle_VP_printstr(FunctionType *M, const vector<GenericValue> &ArgVal){
123 assert(ArgVal.size() == 1 && "printstr only takes one argument!");
124 cout << (char*)ArgVal[0].PointerVal;
125 return GenericValue();
128 // Implement 'void print(X)' for every type...
129 GenericValue lle_X_print(FunctionType *M, const vector<GenericValue> &ArgVals) {
130 assert(ArgVals.size() == 1 && "generic print only takes one argument!");
132 Interpreter::print(M->getParamTypes()[0], ArgVals[0]);
133 return GenericValue();
136 // Implement 'void printVal(X)' for every type...
137 GenericValue lle_X_printVal(FunctionType *M, const vector<GenericValue> &ArgVal) {
138 assert(ArgVal.size() == 1 && "generic print only takes one argument!");
140 // Specialize print([ubyte {x N} ] *) and print(sbyte *)
141 if (const PointerType *PTy =
142 dyn_cast<PointerType>(M->getParamTypes()[0].get()))
143 if (PTy->getElementType() == Type::SByteTy ||
144 isa<ArrayType>(PTy->getElementType())) {
145 return lle_VP_printstr(M, ArgVal);
148 Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);
149 return GenericValue();
152 // Implement 'void printString(X)'
153 // Argument must be [ubyte {x N} ] * or sbyte *
154 GenericValue lle_X_printString(FunctionType *M, const vector<GenericValue> &ArgVal) {
155 assert(ArgVal.size() == 1 && "generic print only takes one argument!");
156 return lle_VP_printstr(M, ArgVal);
159 // Implement 'void print<TYPE>(X)' for each primitive type or pointer type
160 #define PRINT_TYPE_FUNC(TYPENAME,TYPEID) \
161 GenericValue lle_X_print##TYPENAME(FunctionType *M,\
162 const vector<GenericValue> &ArgVal) {\
163 assert(ArgVal.size() == 1 && "generic print only takes one argument!");\
164 assert(M->getParamTypes()[0].get()->getPrimitiveID() == Type::TYPEID);\
165 Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);\
166 return GenericValue();\
169 PRINT_TYPE_FUNC(SByte, SByteTyID)
170 PRINT_TYPE_FUNC(UByte, UByteTyID)
171 PRINT_TYPE_FUNC(Short, ShortTyID)
172 PRINT_TYPE_FUNC(UShort, UShortTyID)
173 PRINT_TYPE_FUNC(Int, IntTyID)
174 PRINT_TYPE_FUNC(UInt, UIntTyID)
175 PRINT_TYPE_FUNC(Long, LongTyID)
176 PRINT_TYPE_FUNC(ULong, ULongTyID)
177 PRINT_TYPE_FUNC(Float, FloatTyID)
178 PRINT_TYPE_FUNC(Double, DoubleTyID)
179 PRINT_TYPE_FUNC(Pointer, PointerTyID)
182 // void putchar(sbyte)
183 GenericValue lle_Vb_putchar(FunctionType *M, const vector<GenericValue> &Args) {
184 cout << Args[0].SByteVal;
185 return GenericValue();
189 GenericValue lle_ii_putchar(FunctionType *M, const vector<GenericValue> &Args) {
190 cout << ((char)Args[0].IntVal) << std::flush;
194 // void putchar(ubyte)
195 GenericValue lle_VB_putchar(FunctionType *M, const vector<GenericValue> &Args) {
196 cout << Args[0].SByteVal << std::flush;
201 GenericValue lle_V___main(FunctionType *M, const vector<GenericValue> &Args) {
202 return GenericValue();
206 GenericValue lle_X_exit(FunctionType *M, const vector<GenericValue> &Args) {
207 TheInterpreter->exitCalled(Args[0]);
208 return GenericValue();
212 GenericValue lle_X_abort(FunctionType *M, const vector<GenericValue> &Args) {
213 std::cerr << "***PROGRAM ABORTED***!\n";
216 TheInterpreter->exitCalled(GV);
217 return GenericValue();
220 // void *malloc(uint)
221 GenericValue lle_X_malloc(FunctionType *M, const vector<GenericValue> &Args) {
222 assert(Args.size() == 1 && "Malloc expects one argument!");
224 GV.PointerVal = (PointerTy)malloc(Args[0].UIntVal);
229 GenericValue lle_X_free(FunctionType *M, const vector<GenericValue> &Args) {
230 assert(Args.size() == 1);
231 free((void*)Args[0].PointerVal);
232 return GenericValue();
236 GenericValue lle_X_atoi(FunctionType *M, const vector<GenericValue> &Args) {
237 assert(Args.size() == 1);
239 GV.IntVal = atoi((char*)Args[0].PointerVal);
243 // double pow(double, double)
244 GenericValue lle_X_pow(FunctionType *M, const vector<GenericValue> &Args) {
245 assert(Args.size() == 2);
247 GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
251 // double exp(double)
252 GenericValue lle_X_exp(FunctionType *M, const vector<GenericValue> &Args) {
253 assert(Args.size() == 1);
255 GV.DoubleVal = exp(Args[0].DoubleVal);
259 // double sqrt(double)
260 GenericValue lle_X_sqrt(FunctionType *M, const vector<GenericValue> &Args) {
261 assert(Args.size() == 1);
263 GV.DoubleVal = sqrt(Args[0].DoubleVal);
267 // double log(double)
268 GenericValue lle_X_log(FunctionType *M, const vector<GenericValue> &Args) {
269 assert(Args.size() == 1);
271 GV.DoubleVal = log(Args[0].DoubleVal);
275 // int isnan(double value);
276 GenericValue lle_X_isnan(FunctionType *F, const vector<GenericValue> &Args) {
277 assert(Args.size() == 1);
279 GV.IntVal = isnan(Args[0].DoubleVal);
283 // double floor(double)
284 GenericValue lle_X_floor(FunctionType *M, const vector<GenericValue> &Args) {
285 assert(Args.size() == 1);
287 GV.DoubleVal = floor(Args[0].DoubleVal);
292 GenericValue lle_X_drand48(FunctionType *M, const vector<GenericValue> &Args) {
293 assert(Args.size() == 0);
295 GV.DoubleVal = drand48();
300 GenericValue lle_X_lrand48(FunctionType *M, const vector<GenericValue> &Args) {
301 assert(Args.size() == 0);
303 GV.IntVal = lrand48();
307 // void srand48(long)
308 GenericValue lle_X_srand48(FunctionType *M, const vector<GenericValue> &Args) {
309 assert(Args.size() == 1);
310 srand48(Args[0].IntVal);
311 return GenericValue();
315 GenericValue lle_X_srand(FunctionType *M, const vector<GenericValue> &Args) {
316 assert(Args.size() == 1);
317 srand(Args[0].UIntVal);
318 return GenericValue();
321 // int sprintf(sbyte *, sbyte *, ...) - a very rough implementation to make
323 GenericValue lle_X_sprintf(FunctionType *M, const vector<GenericValue> &Args) {
324 char *OutputBuffer = (char *)Args[0].PointerVal;
325 const char *FmtStr = (const char *)Args[1].PointerVal;
328 // printf should return # chars printed. This is completely incorrect, but
329 // close enough for now.
330 GenericValue GV; GV.IntVal = strlen(FmtStr);
333 case 0: return GV; // Null terminator...
334 default: // Normal nonspecial character
335 sprintf(OutputBuffer++, "%c", *FmtStr++);
337 case '\\': { // Handle escape codes
338 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
339 FmtStr += 2; OutputBuffer += 2;
342 case '%': { // Handle format specifiers
343 char FmtBuf[100] = "", Buffer[1000] = "";
346 char Last = *FB++ = *FmtStr++;
347 unsigned HowLong = 0;
348 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
349 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
350 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
351 Last != 'p' && Last != 's' && Last != '%') {
352 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
353 Last = *FB++ = *FmtStr++;
359 sprintf(Buffer, FmtBuf); break;
361 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
367 // Make sure we use %lld with a 64 bit argument because we might be
368 // compiling LLI on a 32 bit compiler.
369 unsigned Size = strlen(FmtBuf);
370 FmtBuf[Size] = FmtBuf[Size-1];
372 FmtBuf[Size-1] = 'l';
374 sprintf(Buffer, FmtBuf, Args[ArgNo++].ULongVal);
376 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
377 case 'e': case 'E': case 'g': case 'G': case 'f':
378 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
380 sprintf(Buffer, FmtBuf, (void*)Args[ArgNo++].PointerVal); break;
382 sprintf(Buffer, FmtBuf, (char*)Args[ArgNo++].PointerVal); break;
383 default: cout << "<unknown printf code '" << *FmtStr << "'!>";
386 strcpy(OutputBuffer, Buffer);
387 OutputBuffer += strlen(Buffer);
394 // int printf(sbyte *, ...) - a very rough implementation to make output useful.
395 GenericValue lle_X_printf(FunctionType *M, const vector<GenericValue> &Args) {
397 vector<GenericValue> NewArgs;
398 GenericValue GV; GV.PointerVal = (PointerTy)Buffer;
399 NewArgs.push_back(GV);
400 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
401 GV = lle_X_sprintf(M, NewArgs);
406 // int sscanf(const char *format, ...);
407 GenericValue lle_X_sscanf(FunctionType *M, const vector<GenericValue> &args) {
408 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
410 const char *Args[10];
411 for (unsigned i = 0; i < args.size(); ++i)
412 Args[i] = (const char*)args[i].PointerVal;
415 GV.IntVal = sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
416 Args[5], Args[6], Args[7], Args[8], Args[9]);
421 // int clock(void) - Profiling implementation
422 GenericValue lle_i_clock(FunctionType *M, const vector<GenericValue> &Args) {
423 extern int clock(void);
424 GenericValue GV; GV.IntVal = clock();
428 //===----------------------------------------------------------------------===//
430 //===----------------------------------------------------------------------===//
432 // getFILE - Turn a pointer in the host address space into a legit pointer in
433 // the interpreter address space. For the most part, this is an identity
434 // transformation, but if the program refers to stdio, stderr, stdin then they
435 // have pointers that are relative to the __iob array. If this is the case,
436 // change the FILE into the REAL stdio stream.
438 static FILE *getFILE(PointerTy Ptr) {
439 static Module *LastMod = 0;
440 static PointerTy IOBBase = 0;
441 static unsigned FILESize;
443 if (LastMod != TheInterpreter->getModule()) { // Module change or initialize?
444 Module *M = LastMod = TheInterpreter->getModule();
446 // Check to see if the currently loaded module contains an __iob symbol...
447 GlobalVariable *IOB = 0;
448 SymbolTable &ST = M->getSymbolTable();
449 for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I) {
450 SymbolTable::VarMap &M = I->second;
451 for (SymbolTable::VarMap::iterator J = M.begin(), E = M.end();
453 if (J->first == "__iob")
454 if ((IOB = dyn_cast<GlobalVariable>(J->second)))
459 // If we found an __iob symbol now, find out what the actual address it's
462 // Get the address the array lives in...
463 GlobalAddress *Address =
464 (GlobalAddress*)IOB->getOrCreateAnnotation(GlobalAddressAID);
465 IOBBase = (PointerTy)(GenericValue*)Address->Ptr;
467 // Figure out how big each element of the array is...
468 const ArrayType *AT =
469 dyn_cast<ArrayType>(IOB->getType()->getElementType());
471 FILESize = TD.getTypeSize(AT->getElementType());
473 FILESize = 16*8; // Default size
477 // Check to see if this is a reference to __iob...
479 unsigned FDNum = (Ptr-IOBBase)/FILESize;
492 // FILE *fopen(const char *filename, const char *mode);
493 GenericValue lle_X_fopen(FunctionType *M, const vector<GenericValue> &Args) {
494 assert(Args.size() == 2);
497 GV.PointerVal = (PointerTy)fopen((const char *)Args[0].PointerVal,
498 (const char *)Args[1].PointerVal);
502 // int fclose(FILE *F);
503 GenericValue lle_X_fclose(FunctionType *M, const vector<GenericValue> &Args) {
504 assert(Args.size() == 1);
507 GV.IntVal = fclose(getFILE(Args[0].PointerVal));
511 // int feof(FILE *stream);
512 GenericValue lle_X_feof(FunctionType *M, const vector<GenericValue> &Args) {
513 assert(Args.size() == 1);
516 GV.IntVal = feof(getFILE(Args[0].PointerVal));
520 // size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);
521 GenericValue lle_X_fread(FunctionType *M, const vector<GenericValue> &Args) {
522 assert(Args.size() == 4);
525 GV.UIntVal = fread((void*)Args[0].PointerVal, Args[1].UIntVal,
526 Args[2].UIntVal, getFILE(Args[3].PointerVal));
530 // size_t fwrite(const void *ptr, size_t size, size_t nitems, FILE *stream);
531 GenericValue lle_X_fwrite(FunctionType *M, const vector<GenericValue> &Args) {
532 assert(Args.size() == 4);
535 GV.UIntVal = fwrite((void*)Args[0].PointerVal, Args[1].UIntVal,
536 Args[2].UIntVal, getFILE(Args[3].PointerVal));
540 // char *fgets(char *s, int n, FILE *stream);
541 GenericValue lle_X_fgets(FunctionType *M, const vector<GenericValue> &Args) {
542 assert(Args.size() == 3);
545 GV.PointerVal = (PointerTy)fgets((char*)Args[0].PointerVal, Args[1].IntVal,
546 getFILE(Args[2].PointerVal));
550 // FILE *freopen(const char *path, const char *mode, FILE *stream);
551 GenericValue lle_X_freopen(FunctionType *M, const vector<GenericValue> &Args) {
552 assert(Args.size() == 3);
554 GV.PointerVal = (PointerTy)freopen((char*)Args[0].PointerVal,
555 (char*)Args[1].PointerVal,
556 getFILE(Args[2].PointerVal));
560 // int fflush(FILE *stream);
561 GenericValue lle_X_fflush(FunctionType *M, const vector<GenericValue> &Args) {
562 assert(Args.size() == 1);
564 GV.IntVal = fflush(getFILE(Args[0].PointerVal));
568 // int getc(FILE *stream);
569 GenericValue lle_X_getc(FunctionType *M, const vector<GenericValue> &Args) {
570 assert(Args.size() == 1);
572 GV.IntVal = getc(getFILE(Args[0].PointerVal));
576 // int fputc(int C, FILE *stream);
577 GenericValue lle_X_fputc(FunctionType *M, const vector<GenericValue> &Args) {
578 assert(Args.size() == 2);
580 GV.IntVal = fputc(Args[0].IntVal, getFILE(Args[1].PointerVal));
584 // int ungetc(int C, FILE *stream);
585 GenericValue lle_X_ungetc(FunctionType *M, const vector<GenericValue> &Args) {
586 assert(Args.size() == 2);
588 GV.IntVal = ungetc(Args[0].IntVal, getFILE(Args[1].PointerVal));
592 // int fprintf(FILE *,sbyte *, ...) - a very rough implementation to make output
594 GenericValue lle_X_fprintf(FunctionType *M, const vector<GenericValue> &Args) {
595 assert(Args.size() > 2);
597 vector<GenericValue> NewArgs;
598 GenericValue GV; GV.PointerVal = (PointerTy)Buffer;
599 NewArgs.push_back(GV);
600 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
601 GV = lle_X_sprintf(M, NewArgs);
603 fputs(Buffer, getFILE(Args[0].PointerVal));
610 void Interpreter::initializeExternalMethods() {
611 FuncNames["lle_VP_printstr"] = lle_VP_printstr;
612 FuncNames["lle_X_print"] = lle_X_print;
613 FuncNames["lle_X_printVal"] = lle_X_printVal;
614 FuncNames["lle_X_printString"] = lle_X_printString;
615 FuncNames["lle_X_printUByte"] = lle_X_printUByte;
616 FuncNames["lle_X_printSByte"] = lle_X_printSByte;
617 FuncNames["lle_X_printUShort"] = lle_X_printUShort;
618 FuncNames["lle_X_printShort"] = lle_X_printShort;
619 FuncNames["lle_X_printInt"] = lle_X_printInt;
620 FuncNames["lle_X_printUInt"] = lle_X_printUInt;
621 FuncNames["lle_X_printLong"] = lle_X_printLong;
622 FuncNames["lle_X_printULong"] = lle_X_printULong;
623 FuncNames["lle_X_printFloat"] = lle_X_printFloat;
624 FuncNames["lle_X_printDouble"] = lle_X_printDouble;
625 FuncNames["lle_X_printPointer"] = lle_X_printPointer;
626 FuncNames["lle_Vb_putchar"] = lle_Vb_putchar;
627 FuncNames["lle_ii_putchar"] = lle_ii_putchar;
628 FuncNames["lle_VB_putchar"] = lle_VB_putchar;
629 FuncNames["lle_V___main"] = lle_V___main;
630 FuncNames["lle_X_exit"] = lle_X_exit;
631 FuncNames["lle_X_abort"] = lle_X_abort;
632 FuncNames["lle_X_malloc"] = lle_X_malloc;
633 FuncNames["lle_X_free"] = lle_X_free;
634 FuncNames["lle_X_atoi"] = lle_X_atoi;
635 FuncNames["lle_X_pow"] = lle_X_pow;
636 FuncNames["lle_X_exp"] = lle_X_exp;
637 FuncNames["lle_X_log"] = lle_X_log;
638 FuncNames["lle_X_isnan"] = lle_X_isnan;
639 FuncNames["lle_X_floor"] = lle_X_floor;
640 FuncNames["lle_X_srand"] = lle_X_srand;
641 FuncNames["lle_X_drand48"] = lle_X_drand48;
642 FuncNames["lle_X_srand48"] = lle_X_srand48;
643 FuncNames["lle_X_lrand48"] = lle_X_lrand48;
644 FuncNames["lle_X_sqrt"] = lle_X_sqrt;
645 FuncNames["lle_X_printf"] = lle_X_printf;
646 FuncNames["lle_X_sprintf"] = lle_X_sprintf;
647 FuncNames["lle_X_sscanf"] = lle_X_sscanf;
648 FuncNames["lle_i_clock"] = lle_i_clock;
649 FuncNames["lle_X_fopen"] = lle_X_fopen;
650 FuncNames["lle_X_fclose"] = lle_X_fclose;
651 FuncNames["lle_X_feof"] = lle_X_feof;
652 FuncNames["lle_X_fread"] = lle_X_fread;
653 FuncNames["lle_X_fwrite"] = lle_X_fwrite;
654 FuncNames["lle_X_fgets"] = lle_X_fgets;
655 FuncNames["lle_X_fflush"] = lle_X_fflush;
656 FuncNames["lle_X_fgetc"] = lle_X_getc;
657 FuncNames["lle_X_getc"] = lle_X_getc;
658 FuncNames["lle_X_fputc"] = lle_X_fputc;
659 FuncNames["lle_X_ungetc"] = lle_X_ungetc;
660 FuncNames["lle_X_fprintf"] = lle_X_fprintf;
661 FuncNames["lle_X_freopen"] = lle_X_freopen;