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