bcff5e579541ac8654ea1b04bc99a9947c6dea16
[oota-llvm.git] / lib / ExecutionEngine / Interpreter / ExternalFunctions.cpp
1 //===-- ExternalMethods.cpp - Implement External Methods ------------------===//
2 // 
3 //  This file contains both code to deal with invoking "external" methods, but
4 //  also contains code that implements "exported" external methods. 
5 //
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.
9 //
10 //===----------------------------------------------------------------------===//
11
12 #include "Interpreter.h"
13 #include "llvm/DerivedTypes.h"
14 #include <map>
15 #include <dlfcn.h>
16 #include <iostream>
17 #include <link.h>
18 #include <math.h>
19 #include <stdio.h>
20 using std::vector;
21 using std::cout;
22
23 typedef GenericValue (*ExFunc)(MethodType *, const vector<GenericValue> &);
24 static std::map<const Method *, ExFunc> Functions;
25 static std::map<std::string, ExFunc> FuncNames;
26
27 static Interpreter *TheInterpreter;
28
29 // getCurrentExecutablePath() - Return the directory that the lli executable
30 // lives in.
31 //
32 std::string Interpreter::getCurrentExecutablePath() const {
33   Dl_info Info;
34   if (dladdr(&TheInterpreter, &Info) == 0) return "";
35   
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...
40
41   return LinkAddr;
42 }
43
44
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';
64   default: return 'U';
65   }
66 }
67
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();
76
77   //cout << "Tried: '" << ExtName << "'\n";
78   ExFunc FnPtr = FuncNames[ExtName];
79   if (FnPtr == 0)
80     FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
81   if (FnPtr == 0)
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());
85   if (FnPtr != 0)
86     Functions.insert(std::make_pair(M, FnPtr));  // Cache for later
87   return FnPtr;
88 }
89
90 GenericValue Interpreter::callExternalMethod(Method *M,
91                                          const vector<GenericValue> &ArgVals) {
92   TheInterpreter = this;
93
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;
98   if (Fn == 0) {
99     cout << "Tried to execute an unknown external method: "
100          << M->getType()->getDescription() << " " << M->getName() << "\n";
101     return GenericValue();
102   }
103
104   // TODO: FIXME when types are not const!
105   GenericValue Result = Fn(const_cast<MethodType*>(M->getMethodType()),ArgVals);
106   return Result;
107 }
108
109
110 //===----------------------------------------------------------------------===//
111 //  Methods "exported" to the running application...
112 //
113 extern "C" {  // Don't add C++ manglings to llvm mangling :)
114
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();
120 }
121
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!");
125
126   Interpreter::print(M->getParamTypes()[0], ArgVals[0]);
127   return GenericValue();
128 }
129
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!");
133
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);
139     }
140
141   Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);
142   return GenericValue();
143 }
144
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);
150 }
151
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();\
160   }
161
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)
173
174
175 // void "putchar"(sbyte)
176 GenericValue lle_Vb_putchar(MethodType *M, const vector<GenericValue> &Args) {
177   cout << Args[0].SByteVal;
178   return GenericValue();
179 }
180
181 // int "putchar"(int)
182 GenericValue lle_ii_putchar(MethodType *M, const vector<GenericValue> &Args) {
183   cout << ((char)Args[0].IntVal) << std::flush;
184   return Args[0];
185 }
186
187 // void "putchar"(ubyte)
188 GenericValue lle_VB_putchar(MethodType *M, const vector<GenericValue> &Args) {
189   cout << Args[0].SByteVal << std::flush;
190   return Args[0];
191 }
192
193 // void "__main"()
194 GenericValue lle_V___main(MethodType *M, const vector<GenericValue> &Args) {
195   return GenericValue();
196 }
197
198 // void "exit"(int)
199 GenericValue lle_X_exit(MethodType *M, const vector<GenericValue> &Args) {
200   TheInterpreter->exitCalled(Args[0]);
201   return GenericValue();
202 }
203
204 // void *malloc(uint)
205 GenericValue lle_X_malloc(MethodType *M, const vector<GenericValue> &Args) {
206   assert(Args.size() == 1 && "Malloc expects one argument!");
207   GenericValue GV;
208   GV.PointerVal = (PointerTy)malloc(Args[0].UIntVal);
209   return GV;
210 }
211
212 // void free(void *)
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();
217 }
218
219 // int atoi(char *)
220 GenericValue lle_X_atoi(MethodType *M, const vector<GenericValue> &Args) {
221   assert(Args.size() == 1);
222   GenericValue GV;
223   GV.IntVal = atoi((char*)Args[0].PointerVal);
224   return GV;
225 }
226
227 // double pow(double, double)
228 GenericValue lle_X_pow(MethodType *M, const vector<GenericValue> &Args) {
229   assert(Args.size() == 2);
230   GenericValue GV;
231   GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
232   return GV;
233 }
234
235 // double sqrt(double)
236 GenericValue lle_X_sqrt(MethodType *M, const vector<GenericValue> &Args) {
237   assert(Args.size() == 1);
238   GenericValue GV;
239   GV.DoubleVal = sqrt(Args[0].DoubleVal);
240   return GV;
241 }
242
243 // double log(double)
244 GenericValue lle_X_log(MethodType *M, const vector<GenericValue> &Args) {
245   assert(Args.size() == 1);
246   GenericValue GV;
247   GV.DoubleVal = log(Args[0].DoubleVal);
248   return GV;
249 }
250
251 // double floor(double)
252 GenericValue lle_X_floor(MethodType *M, const vector<GenericValue> &Args) {
253   assert(Args.size() == 1);
254   GenericValue GV;
255   GV.DoubleVal = floor(Args[0].DoubleVal);
256   return GV;
257 }
258
259 // double drand48()
260 GenericValue lle_X_drand48(MethodType *M, const vector<GenericValue> &Args) {
261   assert(Args.size() == 0);
262   GenericValue GV;
263   GV.DoubleVal = drand48();
264   return GV;
265 }
266
267 // long lrand48()
268 GenericValue lle_X_lrand48(MethodType *M, const vector<GenericValue> &Args) {
269   assert(Args.size() == 0);
270   GenericValue GV;
271   GV.IntVal = lrand48();
272   return GV;
273 }
274
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();
280 }
281
282 // void srand(uint)
283 GenericValue lle_X_srand(MethodType *M, const vector<GenericValue> &Args) {
284   assert(Args.size() == 1);
285   srand(Args[0].UIntVal);
286   return GenericValue();
287 }
288
289 // int sprintf(sbyte *, sbyte *, ...) - a very rough implementation to make
290 // output useful.
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;
294   unsigned ArgNo = 2;
295
296   // printf should return # chars printed.  This is completely incorrect, but
297   // close enough for now.
298   GenericValue GV; GV.IntVal = strlen(FmtStr);
299   while (1) {
300     switch (*FmtStr) {
301     case 0: return GV;             // Null terminator...
302     default:                       // Normal nonspecial character
303       sprintf(OutputBuffer++, "%c", *FmtStr++);
304       break;
305     case '\\': {                   // Handle escape codes
306       sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
307       FmtStr += 2; OutputBuffer += 2;
308       break;
309     }
310     case '%': {                    // Handle format specifiers
311       char FmtBuf[100] = "", Buffer[1000] = "";
312       char *FB = FmtBuf;
313       *FB++ = *FmtStr++;
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++;
322       }
323       *FB = 0;
324       
325       switch (Last) {
326       case '%':
327         sprintf(Buffer, FmtBuf); break;
328       case 'c':
329         sprintf(Buffer, FmtBuf, Args[ArgNo++].SByteVal); break;
330       case 'd': case 'i':
331       case 'u': case 'o':
332       case 'x': case 'X':
333         if (HowLong == 2)
334           sprintf(Buffer, FmtBuf, Args[ArgNo++].ULongVal);
335         else
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;
339       case 'p':
340         sprintf(Buffer, FmtBuf, (void*)Args[ArgNo++].PointerVal); break;
341       case 's': 
342         sprintf(Buffer, FmtBuf, (char*)Args[ArgNo++].PointerVal); break;
343       default:  cout << "<unknown printf code '" << *FmtStr << "'!>";
344         ArgNo++; break;
345       }
346       strcpy(OutputBuffer, Buffer);
347       OutputBuffer += strlen(Buffer);
348       }
349       break;
350     }
351   }
352 }
353
354 // int printf(sbyte *, ...) - a very rough implementation to make output useful.
355 GenericValue lle_X_printf(MethodType *M, const vector<GenericValue> &Args) {
356   char Buffer[10000];
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);
362   cout << Buffer;
363   return GV;
364 }
365
366
367 } // End extern "C"
368
369
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;
404 }