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