ab5dab5839b94319b9194b437732ac4f38a79263
[oota-llvm.git] / lib / ExecutionEngine / Interpreter / ExternalFunctions.cpp
1 //===-- ExternalFunctions.cpp - Implement External Functions --------------===//
2 // 
3 //  This file contains both code to deal with invoking "external" functions, but
4 //  also contains code that implements "exported" external functions.
5 //
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
9 //  function call.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "Interpreter.h"
14 #include "ExecutionAnnotations.h"
15 #include "llvm/Module.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/SymbolTable.h"
18 #include "llvm/Target/TargetData.h"
19 #include <map>
20 #include <dlfcn.h>
21 #include <link.h>
22 #include <math.h>
23 #include <stdio.h>
24 using std::vector;
25
26 typedef GenericValue (*ExFunc)(FunctionType *, const vector<GenericValue> &);
27 static std::map<const Function *, ExFunc> Functions;
28 static std::map<std::string, ExFunc> FuncNames;
29
30 static Interpreter *TheInterpreter;
31
32 // getCurrentExecutablePath() - Return the directory that the lli executable
33 // lives in.
34 //
35 std::string Interpreter::getCurrentExecutablePath() const {
36   Dl_info Info;
37   if (dladdr(&TheInterpreter, &Info) == 0) return "";
38   
39   std::string LinkAddr(Info.dli_fname);
40   unsigned SlashPos = LinkAddr.rfind('/');
41   if (SlashPos != std::string::npos)
42     LinkAddr.resize(SlashPos);    // Trim the executable name off...
43
44   return LinkAddr;
45 }
46
47
48 static char getTypeID(const Type *Ty) {
49   switch (Ty->getPrimitiveID()) {
50   case Type::VoidTyID:    return 'V';
51   case Type::BoolTyID:    return 'o';
52   case Type::UByteTyID:   return 'B';
53   case Type::SByteTyID:   return 'b';
54   case Type::UShortTyID:  return 'S';
55   case Type::ShortTyID:   return 's';
56   case Type::UIntTyID:    return 'I';
57   case Type::IntTyID:     return 'i';
58   case Type::ULongTyID:   return 'L';
59   case Type::LongTyID:    return 'l';
60   case Type::FloatTyID:   return 'F';
61   case Type::DoubleTyID:  return 'D';
62   case Type::PointerTyID: return 'P';
63   case Type::FunctionTyID:  return 'M';
64   case Type::StructTyID:  return 'T';
65   case Type::ArrayTyID:   return 'A';
66   case Type::OpaqueTyID:  return 'O';
67   default: return 'U';
68   }
69 }
70
71 static ExFunc lookupFunction(const Function *M) {
72   // Function not found, look it up... start by figuring out what the
73   // composite function name should be.
74   std::string ExtName = "lle_";
75   const FunctionType *MT = M->getFunctionType();
76   for (unsigned i = 0; const Type *Ty = MT->getContainedType(i); ++i)
77     ExtName += getTypeID(Ty);
78   ExtName += "_" + M->getName();
79
80   //std::cout << "Tried: '" << ExtName << "'\n";
81   ExFunc FnPtr = FuncNames[ExtName];
82   if (FnPtr == 0)
83     FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
84   if (FnPtr == 0)
85     FnPtr = FuncNames["lle_X_"+M->getName()];
86   if (FnPtr == 0)  // Try calling a generic function... if it exists...
87     FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ("lle_X_"+M->getName()).c_str());
88   if (FnPtr != 0)
89     Functions.insert(std::make_pair(M, FnPtr));  // Cache for later
90   return FnPtr;
91 }
92
93 GenericValue Interpreter::callExternalFunction(Function *M,
94                                      const std::vector<GenericValue> &ArgVals) {
95   TheInterpreter = this;
96
97   // Do a lookup to see if the function is in our cache... this should just be a
98   // defered annotation!
99   std::map<const Function *, ExFunc>::iterator FI = Functions.find(M);
100   ExFunc Fn = (FI == Functions.end()) ? lookupFunction(M) : FI->second;
101   if (Fn == 0) {
102     std::cout << "Tried to execute an unknown external function: "
103               << M->getType()->getDescription() << " " << M->getName() << "\n";
104     return GenericValue();
105   }
106
107   // TODO: FIXME when types are not const!
108   GenericValue Result = Fn(const_cast<FunctionType*>(M->getFunctionType()),
109                            ArgVals);
110   return Result;
111 }
112
113
114 //===----------------------------------------------------------------------===//
115 //  Functions "exported" to the running application...
116 //
117 extern "C" {  // Don't add C++ manglings to llvm mangling :)
118
119 // void putchar(sbyte)
120 GenericValue lle_Vb_putchar(FunctionType *M, const vector<GenericValue> &Args) {
121   std::cout << Args[0].SByteVal;
122   return GenericValue();
123 }
124
125 // int putchar(int)
126 GenericValue lle_ii_putchar(FunctionType *M, const vector<GenericValue> &Args) {
127   std::cout << ((char)Args[0].IntVal) << std::flush;
128   return Args[0];
129 }
130
131 // void putchar(ubyte)
132 GenericValue lle_VB_putchar(FunctionType *M, const vector<GenericValue> &Args) {
133   std::cout << Args[0].SByteVal << std::flush;
134   return Args[0];
135 }
136
137 // void atexit(Function*)
138 GenericValue lle_X_atexit(FunctionType *M, const vector<GenericValue> &Args) {
139   assert(Args.size() == 1);
140   TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
141   GenericValue GV;
142   GV.IntVal = 0;
143   return GV;
144 }
145
146 // void exit(int)
147 GenericValue lle_X_exit(FunctionType *M, const vector<GenericValue> &Args) {
148   TheInterpreter->exitCalled(Args[0]);
149   return GenericValue();
150 }
151
152 // void abort(void)
153 GenericValue lle_X_abort(FunctionType *M, const vector<GenericValue> &Args) {
154   std::cerr << "***PROGRAM ABORTED***!\n";
155   GenericValue GV;
156   GV.IntVal = 1;
157   TheInterpreter->exitCalled(GV);
158   return GenericValue();
159 }
160
161 // void *malloc(uint)
162 GenericValue lle_X_malloc(FunctionType *M, const vector<GenericValue> &Args) {
163   assert(Args.size() == 1 && "Malloc expects one argument!");
164   return PTOGV(malloc(Args[0].UIntVal));
165 }
166
167 // void *calloc(uint, uint)
168 GenericValue lle_X_calloc(FunctionType *M, const vector<GenericValue> &Args) {
169   assert(Args.size() == 2 && "calloc expects two arguments!");
170   return PTOGV(calloc(Args[0].UIntVal, Args[1].UIntVal));
171 }
172
173 // void free(void *)
174 GenericValue lle_X_free(FunctionType *M, const vector<GenericValue> &Args) {
175   assert(Args.size() == 1);
176   free(GVTOP(Args[0]));
177   return GenericValue();
178 }
179
180 // int atoi(char *)
181 GenericValue lle_X_atoi(FunctionType *M, const vector<GenericValue> &Args) {
182   assert(Args.size() == 1);
183   GenericValue GV;
184   GV.IntVal = atoi((char*)GVTOP(Args[0]));
185   return GV;
186 }
187
188 // double pow(double, double)
189 GenericValue lle_X_pow(FunctionType *M, const vector<GenericValue> &Args) {
190   assert(Args.size() == 2);
191   GenericValue GV;
192   GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
193   return GV;
194 }
195
196 // double exp(double)
197 GenericValue lle_X_exp(FunctionType *M, const vector<GenericValue> &Args) {
198   assert(Args.size() == 1);
199   GenericValue GV;
200   GV.DoubleVal = exp(Args[0].DoubleVal);
201   return GV;
202 }
203
204 // double sqrt(double)
205 GenericValue lle_X_sqrt(FunctionType *M, const vector<GenericValue> &Args) {
206   assert(Args.size() == 1);
207   GenericValue GV;
208   GV.DoubleVal = sqrt(Args[0].DoubleVal);
209   return GV;
210 }
211
212 // double log(double)
213 GenericValue lle_X_log(FunctionType *M, const vector<GenericValue> &Args) {
214   assert(Args.size() == 1);
215   GenericValue GV;
216   GV.DoubleVal = log(Args[0].DoubleVal);
217   return GV;
218 }
219
220 // int isnan(double value);
221 GenericValue lle_X_isnan(FunctionType *F, const vector<GenericValue> &Args) {
222   assert(Args.size() == 1);
223   GenericValue GV;
224   GV.IntVal = std::isnan(Args[0].DoubleVal);
225   return GV;
226 }
227
228 // double floor(double)
229 GenericValue lle_X_floor(FunctionType *M, const vector<GenericValue> &Args) {
230   assert(Args.size() == 1);
231   GenericValue GV;
232   GV.DoubleVal = floor(Args[0].DoubleVal);
233   return GV;
234 }
235
236 // double drand48()
237 GenericValue lle_X_drand48(FunctionType *M, const vector<GenericValue> &Args) {
238   assert(Args.size() == 0);
239   GenericValue GV;
240   GV.DoubleVal = drand48();
241   return GV;
242 }
243
244 // long lrand48()
245 GenericValue lle_X_lrand48(FunctionType *M, const vector<GenericValue> &Args) {
246   assert(Args.size() == 0);
247   GenericValue GV;
248   GV.IntVal = lrand48();
249   return GV;
250 }
251
252 // void srand48(long)
253 GenericValue lle_X_srand48(FunctionType *M, const vector<GenericValue> &Args) {
254   assert(Args.size() == 1);
255   srand48(Args[0].IntVal);
256   return GenericValue();
257 }
258
259 // void srand(uint)
260 GenericValue lle_X_srand(FunctionType *M, const vector<GenericValue> &Args) {
261   assert(Args.size() == 1);
262   srand(Args[0].UIntVal);
263   return GenericValue();
264 }
265
266 // int puts(const char*)
267 GenericValue lle_X_puts(FunctionType *M, const vector<GenericValue> &Args) {
268   assert(Args.size() == 1);
269   GenericValue GV;
270   GV.IntVal = puts((char*)GVTOP(Args[0]));
271   return GV;
272 }
273
274 // int sprintf(sbyte *, sbyte *, ...) - a very rough implementation to make
275 // output useful.
276 GenericValue lle_X_sprintf(FunctionType *M, const vector<GenericValue> &Args) {
277   char *OutputBuffer = (char *)GVTOP(Args[0]);
278   const char *FmtStr = (const char *)GVTOP(Args[1]);
279   unsigned ArgNo = 2;
280
281   // printf should return # chars printed.  This is completely incorrect, but
282   // close enough for now.
283   GenericValue GV; GV.IntVal = strlen(FmtStr);
284   while (1) {
285     switch (*FmtStr) {
286     case 0: return GV;             // Null terminator...
287     default:                       // Normal nonspecial character
288       sprintf(OutputBuffer++, "%c", *FmtStr++);
289       break;
290     case '\\': {                   // Handle escape codes
291       sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
292       FmtStr += 2; OutputBuffer += 2;
293       break;
294     }
295     case '%': {                    // Handle format specifiers
296       char FmtBuf[100] = "", Buffer[1000] = "";
297       char *FB = FmtBuf;
298       *FB++ = *FmtStr++;
299       char Last = *FB++ = *FmtStr++;
300       unsigned HowLong = 0;
301       while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
302              Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
303              Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
304              Last != 'p' && Last != 's' && Last != '%') {
305         if (Last == 'l' || Last == 'L') HowLong++;  // Keep track of l's
306         Last = *FB++ = *FmtStr++;
307       }
308       *FB = 0;
309       
310       switch (Last) {
311       case '%':
312         sprintf(Buffer, FmtBuf); break;
313       case 'c':
314         sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
315       case 'd': case 'i':
316       case 'u': case 'o':
317       case 'x': case 'X':
318         if (HowLong >= 1) {
319           if (HowLong == 1 && TheInterpreter->getModule().has64BitPointers() &&
320               sizeof(long) < sizeof(long long)) {
321             // Make sure we use %lld with a 64 bit argument because we might be
322             // compiling LLI on a 32 bit compiler.
323             unsigned Size = strlen(FmtBuf);
324             FmtBuf[Size] = FmtBuf[Size-1];
325             FmtBuf[Size+1] = 0;
326             FmtBuf[Size-1] = 'l';
327           }
328           sprintf(Buffer, FmtBuf, Args[ArgNo++].ULongVal);
329         } else
330           sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal); break;
331       case 'e': case 'E': case 'g': case 'G': case 'f':
332         sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
333       case 'p':
334         sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
335       case 's': 
336         sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
337       default:  std::cout << "<unknown printf code '" << *FmtStr << "'!>";
338         ArgNo++; break;
339       }
340       strcpy(OutputBuffer, Buffer);
341       OutputBuffer += strlen(Buffer);
342       }
343       break;
344     }
345   }
346 }
347
348 // int printf(sbyte *, ...) - a very rough implementation to make output useful.
349 GenericValue lle_X_printf(FunctionType *M, const vector<GenericValue> &Args) {
350   char Buffer[10000];
351   vector<GenericValue> NewArgs;
352   NewArgs.push_back(PTOGV(Buffer));
353   NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
354   GenericValue GV = lle_X_sprintf(M, NewArgs);
355   std::cout << Buffer;
356   return GV;
357 }
358
359 static void ByteswapSCANFResults(const char *Fmt, void *Arg0, void *Arg1,
360                                  void *Arg2, void *Arg3, void *Arg4, void *Arg5,
361                                  void *Arg6, void *Arg7, void *Arg8) {
362   void *Args[] = { Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, 0 };
363
364   // Loop over the format string, munging read values as appropriate (performs
365   // byteswaps as neccesary).
366   unsigned ArgNo = 0;
367   while (*Fmt) {
368     if (*Fmt++ == '%') {
369       // Read any flag characters that may be present...
370       bool Suppress = false;
371       bool Half = false;
372       bool Long = false;
373       bool LongLong = false;  // long long or long double
374
375       while (1) {
376         switch (*Fmt++) {
377         case '*': Suppress = true; break;
378         case 'a': /*Allocate = true;*/ break;  // We don't need to track this
379         case 'h': Half = true; break;
380         case 'l': Long = true; break;
381         case 'q':
382         case 'L': LongLong = true; break;
383         default:
384           if (Fmt[-1] > '9' || Fmt[-1] < '0')   // Ignore field width specs
385             goto Out;
386         }
387       }
388     Out:
389
390       // Read the conversion character
391       if (!Suppress && Fmt[-1] != '%') { // Nothing to do?
392         unsigned Size = 0;
393         const Type *Ty = 0;
394
395         switch (Fmt[-1]) {
396         case 'i': case 'o': case 'u': case 'x': case 'X': case 'n': case 'p':
397         case 'd':
398           if (Long || LongLong) {
399             Size = 8; Ty = Type::ULongTy;
400           } else if (Half) {
401             Size = 4; Ty = Type::UShortTy;
402           } else {
403             Size = 4; Ty = Type::UIntTy;
404           }
405           break;
406
407         case 'e': case 'g': case 'E':
408         case 'f':
409           if (Long || LongLong) {
410             Size = 8; Ty = Type::DoubleTy;
411           } else {
412             Size = 4; Ty = Type::FloatTy;
413           }
414           break;
415
416         case 's': case 'c': case '[':  // No byteswap needed
417           Size = 1;
418           Ty = Type::SByteTy;
419           break;
420
421         default: break;
422         }
423
424         if (Size) {
425           GenericValue GV;
426           void *Arg = Args[ArgNo++];
427           memcpy(&GV, Arg, Size);
428           TheInterpreter->StoreValueToMemory(GV, (GenericValue*)Arg, Ty);
429         }
430       }
431     }
432   }
433 }
434
435 // int sscanf(const char *format, ...);
436 GenericValue lle_X_sscanf(FunctionType *M, const vector<GenericValue> &args) {
437   assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
438
439   char *Args[10];
440   for (unsigned i = 0; i < args.size(); ++i)
441     Args[i] = (char*)GVTOP(args[i]);
442
443   GenericValue GV;
444   GV.IntVal = sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
445                      Args[5], Args[6], Args[7], Args[8], Args[9]);
446   ByteswapSCANFResults(Args[1], Args[2], Args[3], Args[4],
447                        Args[5], Args[6], Args[7], Args[8], Args[9], 0);
448   return GV;
449 }
450
451 // int scanf(const char *format, ...);
452 GenericValue lle_X_scanf(FunctionType *M, const vector<GenericValue> &args) {
453   assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
454
455   char *Args[10];
456   for (unsigned i = 0; i < args.size(); ++i)
457     Args[i] = (char*)GVTOP(args[i]);
458
459   GenericValue GV;
460   GV.IntVal = scanf(Args[0], Args[1], Args[2], Args[3], Args[4],
461                     Args[5], Args[6], Args[7], Args[8], Args[9]);
462   ByteswapSCANFResults(Args[0], Args[1], Args[2], Args[3], Args[4],
463                        Args[5], Args[6], Args[7], Args[8], Args[9]);
464   return GV;
465 }
466
467
468 // int clock(void) - Profiling implementation
469 GenericValue lle_i_clock(FunctionType *M, const vector<GenericValue> &Args) {
470   extern int clock(void);
471   GenericValue GV; GV.IntVal = clock();
472   return GV;
473 }
474
475
476 //===----------------------------------------------------------------------===//
477 // String Functions...
478 //===----------------------------------------------------------------------===//
479
480 // int strcmp(const char *S1, const char *S2);
481 GenericValue lle_X_strcmp(FunctionType *M, const vector<GenericValue> &Args) {
482   assert(Args.size() == 2);
483   GenericValue Ret;
484   Ret.IntVal = strcmp((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1]));
485   return Ret;
486 }
487
488 // char *strcat(char *Dest, const char *src);
489 GenericValue lle_X_strcat(FunctionType *M, const vector<GenericValue> &Args) {
490   assert(Args.size() == 2);
491   return PTOGV(strcat((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1])));
492 }
493
494 // char *strcpy(char *Dest, const char *src);
495 GenericValue lle_X_strcpy(FunctionType *M, const vector<GenericValue> &Args) {
496   assert(Args.size() == 2);
497   return PTOGV(strcpy((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1])));
498 }
499
500 // long strlen(const char *src);
501 GenericValue lle_X_strlen(FunctionType *M, const vector<GenericValue> &Args) {
502   assert(Args.size() == 1);
503   GenericValue Ret;
504   Ret.LongVal = strlen((char*)GVTOP(Args[0]));
505   return Ret;
506 }
507
508 // char *__strdup(const char *src);
509 GenericValue lle_X___strdup(FunctionType *M, const vector<GenericValue> &Args) {
510   assert(Args.size() == 1);
511   return PTOGV(strdup((char*)GVTOP(Args[0])));
512 }
513
514 // void *memset(void *S, int C, size_t N)
515 GenericValue lle_X_memset(FunctionType *M, const vector<GenericValue> &Args) {
516   assert(Args.size() == 3);
517   return PTOGV(memset(GVTOP(Args[0]), Args[1].IntVal, Args[2].UIntVal));
518 }
519
520 // void *memcpy(void *Dest, void *src, size_t Size);
521 GenericValue lle_X_memcpy(FunctionType *M, const vector<GenericValue> &Args) {
522   assert(Args.size() == 3);
523   return PTOGV(memcpy((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1]),
524                       Args[2].UIntVal));
525 }
526
527 //===----------------------------------------------------------------------===//
528 // IO Functions...
529 //===----------------------------------------------------------------------===//
530
531 // getFILE - Turn a pointer in the host address space into a legit pointer in
532 // the interpreter address space.  For the most part, this is an identity
533 // transformation, but if the program refers to stdio, stderr, stdin then they
534 // have pointers that are relative to the __iob array.  If this is the case,
535 // change the FILE into the REAL stdio stream.
536 // 
537 static FILE *getFILE(void *Ptr) {
538   static Module *LastMod = 0;
539   static PointerTy IOBBase = 0;
540   static unsigned FILESize;
541
542   if (LastMod != &TheInterpreter->getModule()) { // Module change or initialize?
543     Module *M = LastMod = &TheInterpreter->getModule();
544
545     // Check to see if the currently loaded module contains an __iob symbol...
546     GlobalVariable *IOB = 0;
547     SymbolTable &ST = M->getSymbolTable();
548     for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I) {
549       SymbolTable::VarMap &M = I->second;
550       for (SymbolTable::VarMap::iterator J = M.begin(), E = M.end();
551            J != E; ++J)
552         if (J->first == "__iob")
553           if ((IOB = dyn_cast<GlobalVariable>(J->second)))
554             break;
555       if (IOB) break;
556     }
557
558 #if 0   /// FIXME!  __iob support for LLI
559     // If we found an __iob symbol now, find out what the actual address it's
560     // held in is...
561     if (IOB) {
562       // Get the address the array lives in...
563       GlobalAddress *Address = 
564         (GlobalAddress*)IOB->getOrCreateAnnotation(GlobalAddressAID);
565       IOBBase = (PointerTy)(GenericValue*)Address->Ptr;
566
567       // Figure out how big each element of the array is...
568       const ArrayType *AT =
569         dyn_cast<ArrayType>(IOB->getType()->getElementType());
570       if (AT)
571         FILESize = TD.getTypeSize(AT->getElementType());
572       else
573         FILESize = 16*8;  // Default size
574     }
575 #endif
576   }
577
578   // Check to see if this is a reference to __iob...
579   if (IOBBase) {
580     unsigned FDNum = ((unsigned long)Ptr-IOBBase)/FILESize;
581     if (FDNum == 0)
582       return stdin;
583     else if (FDNum == 1)
584       return stdout;
585     else if (FDNum == 2)
586       return stderr;
587   }
588
589   return (FILE*)Ptr;
590 }
591
592
593 // FILE *fopen(const char *filename, const char *mode);
594 GenericValue lle_X_fopen(FunctionType *M, const vector<GenericValue> &Args) {
595   assert(Args.size() == 2);
596   return PTOGV(fopen((const char *)GVTOP(Args[0]),
597                      (const char *)GVTOP(Args[1])));
598 }
599
600 // int fclose(FILE *F);
601 GenericValue lle_X_fclose(FunctionType *M, const vector<GenericValue> &Args) {
602   assert(Args.size() == 1);
603   GenericValue GV;
604   GV.IntVal = fclose(getFILE(GVTOP(Args[0])));
605   return GV;
606 }
607
608 // int feof(FILE *stream);
609 GenericValue lle_X_feof(FunctionType *M, const vector<GenericValue> &Args) {
610   assert(Args.size() == 1);
611   GenericValue GV;
612
613   GV.IntVal = feof(getFILE(GVTOP(Args[0])));
614   return GV;
615 }
616
617 // size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);
618 GenericValue lle_X_fread(FunctionType *M, const vector<GenericValue> &Args) {
619   assert(Args.size() == 4);
620   GenericValue GV;
621
622   GV.UIntVal = fread((void*)GVTOP(Args[0]), Args[1].UIntVal,
623                      Args[2].UIntVal, getFILE(GVTOP(Args[3])));
624   return GV;
625 }
626
627 // size_t fwrite(const void *ptr, size_t size, size_t nitems, FILE *stream);
628 GenericValue lle_X_fwrite(FunctionType *M, const vector<GenericValue> &Args) {
629   assert(Args.size() == 4);
630   GenericValue GV;
631
632   GV.UIntVal = fwrite((void*)GVTOP(Args[0]), Args[1].UIntVal,
633                       Args[2].UIntVal, getFILE(GVTOP(Args[3])));
634   return GV;
635 }
636
637 // char *fgets(char *s, int n, FILE *stream);
638 GenericValue lle_X_fgets(FunctionType *M, const vector<GenericValue> &Args) {
639   assert(Args.size() == 3);
640   return GVTOP(fgets((char*)GVTOP(Args[0]), Args[1].IntVal,
641                      getFILE(GVTOP(Args[2]))));
642 }
643
644 // FILE *freopen(const char *path, const char *mode, FILE *stream);
645 GenericValue lle_X_freopen(FunctionType *M, const vector<GenericValue> &Args) {
646   assert(Args.size() == 3);
647   return PTOGV(freopen((char*)GVTOP(Args[0]), (char*)GVTOP(Args[1]),
648                        getFILE(GVTOP(Args[2]))));
649 }
650
651 // int fflush(FILE *stream);
652 GenericValue lle_X_fflush(FunctionType *M, const vector<GenericValue> &Args) {
653   assert(Args.size() == 1);
654   GenericValue GV;
655   GV.IntVal = fflush(getFILE(GVTOP(Args[0])));
656   return GV;
657 }
658
659 // int getc(FILE *stream);
660 GenericValue lle_X_getc(FunctionType *M, const vector<GenericValue> &Args) {
661   assert(Args.size() == 1);
662   GenericValue GV;
663   GV.IntVal = getc(getFILE(GVTOP(Args[0])));
664   return GV;
665 }
666
667 // int _IO_getc(FILE *stream);
668 GenericValue lle_X__IO_getc(FunctionType *F, const vector<GenericValue> &Args) {
669   return lle_X_getc(F, Args);
670 }
671
672 // int fputc(int C, FILE *stream);
673 GenericValue lle_X_fputc(FunctionType *M, const vector<GenericValue> &Args) {
674   assert(Args.size() == 2);
675   GenericValue GV;
676   GV.IntVal = fputc(Args[0].IntVal, getFILE(GVTOP(Args[1])));
677   return GV;
678 }
679
680 // int ungetc(int C, FILE *stream);
681 GenericValue lle_X_ungetc(FunctionType *M, const vector<GenericValue> &Args) {
682   assert(Args.size() == 2);
683   GenericValue GV;
684   GV.IntVal = ungetc(Args[0].IntVal, getFILE(GVTOP(Args[1])));
685   return GV;
686 }
687
688 // int fprintf(FILE *,sbyte *, ...) - a very rough implementation to make output
689 // useful.
690 GenericValue lle_X_fprintf(FunctionType *M, const vector<GenericValue> &Args) {
691   assert(Args.size() >= 2);
692   char Buffer[10000];
693   vector<GenericValue> NewArgs;
694   NewArgs.push_back(PTOGV(Buffer));
695   NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
696   GenericValue GV = lle_X_sprintf(M, NewArgs);
697
698   fputs(Buffer, getFILE(GVTOP(Args[0])));
699   return GV;
700 }
701
702 //===----------------------------------------------------------------------===//
703 // LLVM Intrinsic Functions...
704 //===----------------------------------------------------------------------===//
705
706 // void llvm.va_start(<va_list> *) - Implement the va_start operation...
707 GenericValue llvm_va_start(FunctionType *F, const vector<GenericValue> &Args) {
708   assert(Args.size() == 1);
709   GenericValue *VAListP = (GenericValue *)GVTOP(Args[0]);
710   GenericValue Val;
711   Val.UIntVal = 0;   // Start at the first '...' argument...
712   TheInterpreter->StoreValueToMemory(Val, VAListP, Type::UIntTy);
713   return GenericValue();
714 }
715
716 // void llvm.va_end(<va_list> *) - Implement the va_end operation...
717 GenericValue llvm_va_end(FunctionType *F, const vector<GenericValue> &Args) {
718   assert(Args.size() == 1);
719   return GenericValue();    // Noop!
720 }
721
722 // void llvm.va_copy(<va_list> *, <va_list>) - Implement the va_copy
723 // operation...
724 GenericValue llvm_va_copy(FunctionType *F, const vector<GenericValue> &Args) {
725   assert(Args.size() == 2);
726   GenericValue *DestVAList = (GenericValue*)GVTOP(Args[0]);
727   TheInterpreter->StoreValueToMemory(Args[1], DestVAList, Type::UIntTy);
728   return GenericValue();
729 }
730
731 } // End extern "C"
732
733
734 void Interpreter::initializeExternalFunctions() {
735   FuncNames["lle_Vb_putchar"]     = lle_Vb_putchar;
736   FuncNames["lle_ii_putchar"]     = lle_ii_putchar;
737   FuncNames["lle_VB_putchar"]     = lle_VB_putchar;
738   FuncNames["lle_X_exit"]         = lle_X_exit;
739   FuncNames["lle_X_abort"]        = lle_X_abort;
740   FuncNames["lle_X_malloc"]       = lle_X_malloc;
741   FuncNames["lle_X_calloc"]       = lle_X_calloc;
742   FuncNames["lle_X_free"]         = lle_X_free;
743   FuncNames["lle_X_atoi"]         = lle_X_atoi;
744   FuncNames["lle_X_pow"]          = lle_X_pow;
745   FuncNames["lle_X_exp"]          = lle_X_exp;
746   FuncNames["lle_X_log"]          = lle_X_log;
747   FuncNames["lle_X_isnan"]        = lle_X_isnan;
748   FuncNames["lle_X_floor"]        = lle_X_floor;
749   FuncNames["lle_X_srand"]        = lle_X_srand;
750   FuncNames["lle_X_drand48"]      = lle_X_drand48;
751   FuncNames["lle_X_srand48"]      = lle_X_srand48;
752   FuncNames["lle_X_lrand48"]      = lle_X_lrand48;
753   FuncNames["lle_X_sqrt"]         = lle_X_sqrt;
754   FuncNames["lle_X_puts"]         = lle_X_puts;
755   FuncNames["lle_X_printf"]       = lle_X_printf;
756   FuncNames["lle_X_sprintf"]      = lle_X_sprintf;
757   FuncNames["lle_X_sscanf"]       = lle_X_sscanf;
758   FuncNames["lle_X_scanf"]        = lle_X_scanf;
759   FuncNames["lle_i_clock"]        = lle_i_clock;
760
761   FuncNames["lle_X_strcmp"]       = lle_X_strcmp;
762   FuncNames["lle_X_strcat"]       = lle_X_strcat;
763   FuncNames["lle_X_strcpy"]       = lle_X_strcpy;
764   FuncNames["lle_X_strlen"]       = lle_X_strlen;
765   FuncNames["lle_X___strdup"]     = lle_X___strdup;
766   FuncNames["lle_X_memset"]       = lle_X_memset;
767   FuncNames["lle_X_memcpy"]       = lle_X_memcpy;
768
769   FuncNames["lle_X_fopen"]        = lle_X_fopen;
770   FuncNames["lle_X_fclose"]       = lle_X_fclose;
771   FuncNames["lle_X_feof"]         = lle_X_feof;
772   FuncNames["lle_X_fread"]        = lle_X_fread;
773   FuncNames["lle_X_fwrite"]       = lle_X_fwrite;
774   FuncNames["lle_X_fgets"]        = lle_X_fgets;
775   FuncNames["lle_X_fflush"]       = lle_X_fflush;
776   FuncNames["lle_X_fgetc"]        = lle_X_getc;
777   FuncNames["lle_X_getc"]         = lle_X_getc;
778   FuncNames["lle_X__IO_getc"]     = lle_X__IO_getc;
779   FuncNames["lle_X_fputc"]        = lle_X_fputc;
780   FuncNames["lle_X_ungetc"]       = lle_X_ungetc;
781   FuncNames["lle_X_fprintf"]      = lle_X_fprintf;
782   FuncNames["lle_X_freopen"]      = lle_X_freopen;
783
784   FuncNames["lle_X_llvm.va_start"]= llvm_va_start;
785   FuncNames["lle_X_llvm.va_end"]  = llvm_va_end;
786   FuncNames["lle_X_llvm.va_copy"] = llvm_va_copy;
787 }