1 //===-- ExternalMethods.cpp - Implement External Methods ------------------===//
3 // This file contains both code to deal with invoking "external" methods, but
4 // also contains code that implements "exported" external methods.
6 // External methods in LLI are implemented by dlopen'ing the lli executable and
7 // using dlsym to look op the methods that we want to invoke. If a method is
8 // found, then the arguments are mangled and passed in to the function call.
10 //===----------------------------------------------------------------------===//
12 #include "Interpreter.h"
13 #include "llvm/DerivedTypes.h"
23 typedef GenericValue (*ExFunc)(MethodType *, const vector<GenericValue> &);
24 static std::map<const Method *, ExFunc> Functions;
25 static std::map<std::string, ExFunc> FuncNames;
27 static Interpreter *TheInterpreter;
29 // getCurrentExecutablePath() - Return the directory that the lli executable
32 std::string Interpreter::getCurrentExecutablePath() const {
34 if (dladdr(&TheInterpreter, &Info) == 0) return "";
36 std::string LinkAddr(Info.dli_fname);
37 unsigned SlashPos = LinkAddr.rfind('/');
38 if (SlashPos != std::string::npos)
39 LinkAddr.resize(SlashPos); // Trim the executable name off...
45 static char getTypeID(const Type *Ty) {
46 switch (Ty->getPrimitiveID()) {
47 case Type::VoidTyID: return 'V';
48 case Type::BoolTyID: return 'o';
49 case Type::UByteTyID: return 'B';
50 case Type::SByteTyID: return 'b';
51 case Type::UShortTyID: return 'S';
52 case Type::ShortTyID: return 's';
53 case Type::UIntTyID: return 'I';
54 case Type::IntTyID: return 'i';
55 case Type::ULongTyID: return 'L';
56 case Type::LongTyID: return 'l';
57 case Type::FloatTyID: return 'F';
58 case Type::DoubleTyID: return 'D';
59 case Type::PointerTyID: return 'P';
60 case Type::MethodTyID: return 'M';
61 case Type::StructTyID: return 'T';
62 case Type::ArrayTyID: return 'A';
63 case Type::OpaqueTyID: return 'O';
68 static ExFunc lookupMethod(const Method *M) {
69 // Function not found, look it up... start by figuring out what the
70 // composite function name should be.
71 std::string ExtName = "lle_";
72 const MethodType *MT = M->getMethodType();
73 for (unsigned i = 0; const Type *Ty = MT->getContainedType(i); ++i)
74 ExtName += getTypeID(Ty);
75 ExtName += "_" + M->getName();
77 //cout << "Tried: '" << ExtName << "'\n";
78 ExFunc FnPtr = FuncNames[ExtName];
80 FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
82 FnPtr = FuncNames["lle_X_"+M->getName()];
83 if (FnPtr == 0) // Try calling a generic function... if it exists...
84 FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ("lle_X_"+M->getName()).c_str());
86 Functions.insert(std::make_pair(M, FnPtr)); // Cache for later
90 GenericValue Interpreter::callExternalMethod(Method *M,
91 const vector<GenericValue> &ArgVals) {
92 TheInterpreter = this;
94 // Do a lookup to see if the method is in our cache... this should just be a
95 // defered annotation!
96 std::map<const Method *, ExFunc>::iterator FI = Functions.find(M);
97 ExFunc Fn = (FI == Functions.end()) ? lookupMethod(M) : FI->second;
99 cout << "Tried to execute an unknown external method: "
100 << M->getType()->getDescription() << " " << M->getName() << "\n";
101 return GenericValue();
104 // TODO: FIXME when types are not const!
105 GenericValue Result = Fn(const_cast<MethodType*>(M->getMethodType()),ArgVals);
110 //===----------------------------------------------------------------------===//
111 // Methods "exported" to the running application...
113 extern "C" { // Don't add C++ manglings to llvm mangling :)
115 // Implement void printstr([ubyte {x N}] *)
116 GenericValue lle_VP_printstr(MethodType *M, const vector<GenericValue> &ArgVal){
117 assert(ArgVal.size() == 1 && "printstr only takes one argument!");
118 cout << (char*)ArgVal[0].PointerVal;
119 return GenericValue();
122 // Implement 'void print(X)' for every type...
123 GenericValue lle_X_print(MethodType *M, const vector<GenericValue> &ArgVals) {
124 assert(ArgVals.size() == 1 && "generic print only takes one argument!");
126 Interpreter::print(M->getParamTypes()[0], ArgVals[0]);
127 return GenericValue();
130 // Implement 'void printVal(X)' for every type...
131 GenericValue lle_X_printVal(MethodType *M, const vector<GenericValue> &ArgVal) {
132 assert(ArgVal.size() == 1 && "generic print only takes one argument!");
134 // Specialize print([ubyte {x N} ] *) and print(sbyte *)
135 if (PointerType *PTy = dyn_cast<PointerType>(M->getParamTypes()[0].get()))
136 if (PTy->getElementType() == Type::SByteTy ||
137 isa<ArrayType>(PTy->getElementType())) {
138 return lle_VP_printstr(M, ArgVal);
141 Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);
142 return GenericValue();
145 // Implement 'void printString(X)'
146 // Argument must be [ubyte {x N} ] * or sbyte *
147 GenericValue lle_X_printString(MethodType *M, const vector<GenericValue> &ArgVal) {
148 assert(ArgVal.size() == 1 && "generic print only takes one argument!");
149 return lle_VP_printstr(M, ArgVal);
152 // Implement 'void print<TYPE>(X)' for each primitive type or pointer type
153 #define PRINT_TYPE_FUNC(TYPENAME,TYPEID) \
154 GenericValue lle_X_print##TYPENAME(MethodType *M,\
155 const vector<GenericValue> &ArgVal) {\
156 assert(ArgVal.size() == 1 && "generic print only takes one argument!");\
157 assert(M->getParamTypes()[0].get()->getPrimitiveID() == Type::TYPEID);\
158 Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);\
159 return GenericValue();\
162 PRINT_TYPE_FUNC(SByte, SByteTyID)
163 PRINT_TYPE_FUNC(UByte, UByteTyID)
164 PRINT_TYPE_FUNC(Short, ShortTyID)
165 PRINT_TYPE_FUNC(UShort, UShortTyID)
166 PRINT_TYPE_FUNC(Int, IntTyID)
167 PRINT_TYPE_FUNC(UInt, UIntTyID)
168 PRINT_TYPE_FUNC(Long, LongTyID)
169 PRINT_TYPE_FUNC(ULong, ULongTyID)
170 PRINT_TYPE_FUNC(Float, FloatTyID)
171 PRINT_TYPE_FUNC(Double, DoubleTyID)
172 PRINT_TYPE_FUNC(Pointer, PointerTyID)
175 // void "putchar"(sbyte)
176 GenericValue lle_Vb_putchar(MethodType *M, const vector<GenericValue> &Args) {
177 cout << Args[0].SByteVal;
178 return GenericValue();
181 // int "putchar"(int)
182 GenericValue lle_ii_putchar(MethodType *M, const vector<GenericValue> &Args) {
183 cout << ((char)Args[0].IntVal) << std::flush;
187 // void "putchar"(ubyte)
188 GenericValue lle_VB_putchar(MethodType *M, const vector<GenericValue> &Args) {
189 cout << Args[0].SByteVal << std::flush;
194 GenericValue lle_V___main(MethodType *M, const vector<GenericValue> &Args) {
195 return GenericValue();
199 GenericValue lle_X_exit(MethodType *M, const vector<GenericValue> &Args) {
200 TheInterpreter->exitCalled(Args[0]);
201 return GenericValue();
204 // void *malloc(uint)
205 GenericValue lle_X_malloc(MethodType *M, const vector<GenericValue> &Args) {
206 assert(Args.size() == 1 && "Malloc expects one argument!");
208 GV.PointerVal = (PointerTy)malloc(Args[0].UIntVal);
213 GenericValue lle_X_free(MethodType *M, const vector<GenericValue> &Args) {
214 assert(Args.size() == 1);
215 free((void*)Args[0].PointerVal);
216 return GenericValue();
220 GenericValue lle_X_atoi(MethodType *M, const vector<GenericValue> &Args) {
221 assert(Args.size() == 1);
223 GV.IntVal = atoi((char*)Args[0].PointerVal);
227 // double pow(double, double)
228 GenericValue lle_X_pow(MethodType *M, const vector<GenericValue> &Args) {
229 assert(Args.size() == 2);
231 GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
235 // double sqrt(double)
236 GenericValue lle_X_sqrt(MethodType *M, const vector<GenericValue> &Args) {
237 assert(Args.size() == 1);
239 GV.DoubleVal = sqrt(Args[0].DoubleVal);
243 // double log(double)
244 GenericValue lle_X_log(MethodType *M, const vector<GenericValue> &Args) {
245 assert(Args.size() == 1);
247 GV.DoubleVal = log(Args[0].DoubleVal);
251 // double floor(double)
252 GenericValue lle_X_floor(MethodType *M, const vector<GenericValue> &Args) {
253 assert(Args.size() == 1);
255 GV.DoubleVal = floor(Args[0].DoubleVal);
260 GenericValue lle_X_drand48(MethodType *M, const vector<GenericValue> &Args) {
261 assert(Args.size() == 0);
263 GV.DoubleVal = drand48();
268 GenericValue lle_X_lrand48(MethodType *M, const vector<GenericValue> &Args) {
269 assert(Args.size() == 0);
271 GV.IntVal = lrand48();
275 // void srand48(long)
276 GenericValue lle_X_srand48(MethodType *M, const vector<GenericValue> &Args) {
277 assert(Args.size() == 1);
278 srand48(Args[0].IntVal);
279 return GenericValue();
283 GenericValue lle_X_srand(MethodType *M, const vector<GenericValue> &Args) {
284 assert(Args.size() == 1);
285 srand(Args[0].UIntVal);
286 return GenericValue();
289 // int sprintf(sbyte *, sbyte *, ...) - a very rough implementation to make
291 GenericValue lle_X_sprintf(MethodType *M, const vector<GenericValue> &Args) {
292 char *OutputBuffer = (char *)Args[0].PointerVal;
293 const char *FmtStr = (const char *)Args[1].PointerVal;
296 // printf should return # chars printed. This is completely incorrect, but
297 // close enough for now.
298 GenericValue GV; GV.IntVal = strlen(FmtStr);
301 case 0: return GV; // Null terminator...
302 default: // Normal nonspecial character
303 sprintf(OutputBuffer++, "%c", *FmtStr++);
305 case '\\': { // Handle escape codes
306 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
307 FmtStr += 2; OutputBuffer += 2;
310 case '%': { // Handle format specifiers
311 char FmtBuf[100] = "", Buffer[1000] = "";
314 char Last = *FB++ = *FmtStr++;
315 unsigned HowLong = 0;
316 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
317 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
318 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
319 Last != 'p' && Last != 's' && Last != '%') {
320 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
321 Last = *FB++ = *FmtStr++;
327 sprintf(Buffer, FmtBuf); break;
329 sprintf(Buffer, FmtBuf, Args[ArgNo++].SByteVal); break;
334 sprintf(Buffer, FmtBuf, Args[ArgNo++].ULongVal);
336 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
337 case 'e': case 'E': case 'g': case 'G': case 'f':
338 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
340 sprintf(Buffer, FmtBuf, (void*)Args[ArgNo++].PointerVal); break;
342 sprintf(Buffer, FmtBuf, (char*)Args[ArgNo++].PointerVal); break;
343 default: cout << "<unknown printf code '" << *FmtStr << "'!>";
346 strcpy(OutputBuffer, Buffer);
347 OutputBuffer += strlen(Buffer);
354 // int printf(sbyte *, ...) - a very rough implementation to make output useful.
355 GenericValue lle_X_printf(MethodType *M, const vector<GenericValue> &Args) {
357 vector<GenericValue> NewArgs;
358 GenericValue GV; GV.PointerVal = (PointerTy)Buffer;
359 NewArgs.push_back(GV);
360 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
361 GV = lle_X_sprintf(M, NewArgs);
370 void Interpreter::initializeExternalMethods() {
371 FuncNames["lle_VP_printstr"] = lle_VP_printstr;
372 FuncNames["lle_X_print"] = lle_X_print;
373 FuncNames["lle_X_printVal"] = lle_X_printVal;
374 FuncNames["lle_X_printString"] = lle_X_printString;
375 FuncNames["lle_X_printUByte"] = lle_X_printUByte;
376 FuncNames["lle_X_printSByte"] = lle_X_printSByte;
377 FuncNames["lle_X_printUShort"] = lle_X_printUShort;
378 FuncNames["lle_X_printShort"] = lle_X_printShort;
379 FuncNames["lle_X_printInt"] = lle_X_printInt;
380 FuncNames["lle_X_printUInt"] = lle_X_printUInt;
381 FuncNames["lle_X_printLong"] = lle_X_printLong;
382 FuncNames["lle_X_printULong"] = lle_X_printULong;
383 FuncNames["lle_X_printFloat"] = lle_X_printFloat;
384 FuncNames["lle_X_printDouble"] = lle_X_printDouble;
385 FuncNames["lle_X_printPointer"] = lle_X_printPointer;
386 FuncNames["lle_Vb_putchar"] = lle_Vb_putchar;
387 FuncNames["lle_ii_putchar"] = lle_ii_putchar;
388 FuncNames["lle_VB_putchar"] = lle_VB_putchar;
389 FuncNames["lle_V___main"] = lle_V___main;
390 FuncNames["lle_X_exit"] = lle_X_exit;
391 FuncNames["lle_X_malloc"] = lle_X_malloc;
392 FuncNames["lle_X_free"] = lle_X_free;
393 FuncNames["lle_X_atoi"] = lle_X_atoi;
394 FuncNames["lle_X_pow"] = lle_X_pow;
395 FuncNames["lle_X_log"] = lle_X_log;
396 FuncNames["lle_X_floor"] = lle_X_floor;
397 FuncNames["lle_X_srand"] = lle_X_srand;
398 FuncNames["lle_X_drand48"] = lle_X_drand48;
399 FuncNames["lle_X_srand48"] = lle_X_srand48;
400 FuncNames["lle_X_lrand48"] = lle_X_lrand48;
401 FuncNames["lle_X_sqrt"] = lle_X_sqrt;
402 FuncNames["lle_X_printf"] = lle_X_printf;
403 FuncNames["lle_X_sprintf"] = lle_X_sprintf;