blob: c931081ff684a95264f8d91f2896ebea0f45c4bd [file] [log] [blame]
Chris Lattner2fbfdcf2002-04-07 20:49:59 +00001//===-- ExternalFunctions.cpp - Implement External Functions --------------===//
Misha Brukmand1c881a2005-04-21 22:43:08 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmand1c881a2005-04-21 22:43:08 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukmand1c881a2005-04-21 22:43:08 +00009//
Chris Lattner2fbfdcf2002-04-07 20:49:59 +000010// This file contains both code to deal with invoking "external" functions, but
11// also contains code that implements "exported" external functions.
Chris Lattner7720c8e2001-09-10 04:50:17 +000012//
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000013// There are currently two mechanisms for handling external functions in the
14// Interpreter. The first is to implement lle_* wrapper functions that are
15// specific to well-known library functions which manually translate the
16// arguments from GenericValues and make the call. If such a wrapper does
17// not exist, and libffi is available, then the Interpreter will attempt to
18// invoke the function using libffi, after finding its address.
Chris Lattner7720c8e2001-09-10 04:50:17 +000019//
20//===----------------------------------------------------------------------===//
21
22#include "Interpreter.h"
23#include "llvm/DerivedTypes.h"
Misha Brukmanb8d15b22003-10-14 21:42:11 +000024#include "llvm/Module.h"
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000025#include "llvm/Config/config.h" // Detect libffi
Torok Edwin7d696d82009-07-11 13:10:19 +000026#include "llvm/Support/ErrorHandling.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000027#include "llvm/System/DynamicLibrary.h"
Chris Lattner005cbce2002-10-02 21:12:13 +000028#include "llvm/Target/TargetData.h"
Chuck Rose III936baaa2007-07-27 18:26:35 +000029#include "llvm/Support/ManagedStatic.h"
Owen Andersonc2265702009-06-22 22:30:56 +000030#include "llvm/System/Mutex.h"
Brian Gaekeb56a6bc2003-11-05 01:18:49 +000031#include <csignal>
Duncan Sands4520dd22008-10-08 07:23:46 +000032#include <cstdio>
Misha Brukmanb8d15b22003-10-14 21:42:11 +000033#include <map>
Jeff Cohen97af7512006-12-02 02:22:01 +000034#include <cmath>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000035#include <cstring>
Daniel Dunbare4a57432009-09-17 00:14:44 +000036// Some platforms may need malloc.h for alloca.
37#ifdef HAVE_MALLOC_H
38#include <malloc.h>
39#endif
Zhou Sheng621dead2007-12-12 06:16:47 +000040
Nick Lewycky93f70fc2009-04-13 04:26:06 +000041#ifdef HAVE_FFI_CALL
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000042#ifdef HAVE_FFI_H
43#include <ffi.h>
Nick Lewycky93f70fc2009-04-13 04:26:06 +000044#define USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000045#elif HAVE_FFI_FFI_H
46#include <ffi/ffi.h>
Nick Lewycky93f70fc2009-04-13 04:26:06 +000047#define USE_LIBFFI
Zhou Sheng621dead2007-12-12 06:16:47 +000048#endif
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000049#endif
Tanya Lattner32aaee62009-01-22 20:09:20 +000050
Chris Lattnerf7a743d2003-12-14 23:25:48 +000051using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000052
Owen Andersonc2265702009-06-22 22:30:56 +000053static ManagedStatic<sys::Mutex> FunctionsLock;
54
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000055typedef GenericValue (*ExFunc)(const FunctionType *,
56 const std::vector<GenericValue> &);
57static ManagedStatic<std::map<const Function *, ExFunc> > ExportedFunctions;
Chris Lattner697954c2002-01-20 22:54:45 +000058static std::map<std::string, ExFunc> FuncNames;
Chris Lattner7720c8e2001-09-10 04:50:17 +000059
Nick Lewycky93f70fc2009-04-13 04:26:06 +000060#ifdef USE_LIBFFI
Dan Gohmana9ad0412009-08-12 22:10:57 +000061typedef void (*RawFunc)();
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +000062static ManagedStatic<std::map<const Function *, RawFunc> > RawFunctions;
63#endif
64
Chris Lattnere43db882001-10-27 04:15:57 +000065static Interpreter *TheInterpreter;
66
Chris Lattner7720c8e2001-09-10 04:50:17 +000067static char getTypeID(const Type *Ty) {
Chris Lattnerf70c22b2004-06-17 18:19:28 +000068 switch (Ty->getTypeID()) {
Chris Lattner7720c8e2001-09-10 04:50:17 +000069 case Type::VoidTyID: return 'V';
Reid Spencera54b7cb2007-01-12 07:05:14 +000070 case Type::IntegerTyID:
71 switch (cast<IntegerType>(Ty)->getBitWidth()) {
72 case 1: return 'o';
73 case 8: return 'B';
74 case 16: return 'S';
75 case 32: return 'I';
76 case 64: return 'L';
77 default: return 'N';
78 }
Chris Lattner7720c8e2001-09-10 04:50:17 +000079 case Type::FloatTyID: return 'F';
80 case Type::DoubleTyID: return 'D';
81 case Type::PointerTyID: return 'P';
Reid Spencere49661b2006-12-31 05:51:36 +000082 case Type::FunctionTyID:return 'M';
Chris Lattner7720c8e2001-09-10 04:50:17 +000083 case Type::StructTyID: return 'T';
84 case Type::ArrayTyID: return 'A';
85 case Type::OpaqueTyID: return 'O';
86 default: return 'U';
87 }
88}
89
Anton Korobeynikov42346f52007-07-30 23:03:25 +000090// Try to find address of external function given a Function object.
91// Please note, that interpreter doesn't know how to assemble a
92// real call in general case (this is JIT job), that's why it assumes,
93// that all external functions has the same (and pretty "general") signature.
94// The typical example of such functions are "lle_X_" ones.
Brian Gaeke58a6faa2003-10-10 17:03:10 +000095static ExFunc lookupFunction(const Function *F) {
Chris Lattner7720c8e2001-09-10 04:50:17 +000096 // Function not found, look it up... start by figuring out what the
97 // composite function name should be.
Chris Lattner697954c2002-01-20 22:54:45 +000098 std::string ExtName = "lle_";
Brian Gaeke58a6faa2003-10-10 17:03:10 +000099 const FunctionType *FT = F->getFunctionType();
100 for (unsigned i = 0, e = FT->getNumContainedTypes(); i != e; ++i)
101 ExtName += getTypeID(FT->getContainedType(i));
Daniel Dunbarf6ccee52009-07-24 08:24:36 +0000102 ExtName + "_" + F->getNameStr();
Chris Lattner7720c8e2001-09-10 04:50:17 +0000103
Owen Andersona9d1f2c2009-07-07 18:33:04 +0000104 sys::ScopedLock Writer(*FunctionsLock);
Chris Lattner4721f132001-10-30 20:28:00 +0000105 ExFunc FnPtr = FuncNames[ExtName];
106 if (FnPtr == 0)
Daniel Dunbarf6ccee52009-07-24 08:24:36 +0000107 FnPtr = FuncNames["lle_X_" + F->getNameStr()];
Chris Lattner7720c8e2001-09-10 04:50:17 +0000108 if (FnPtr == 0) // Try calling a generic function... if it exists...
Daniel Dunbar8f603022009-07-22 21:10:12 +0000109 FnPtr = (ExFunc)(intptr_t)
Daniel Dunbarf6ccee52009-07-24 08:24:36 +0000110 sys::DynamicLibrary::SearchForAddressOfSymbol("lle_X_"+F->getNameStr());
Chris Lattner7720c8e2001-09-10 04:50:17 +0000111 if (FnPtr != 0)
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000112 ExportedFunctions->insert(std::make_pair(F, FnPtr)); // Cache for later
Chris Lattner7720c8e2001-09-10 04:50:17 +0000113 return FnPtr;
114}
115
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000116#ifdef USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000117static ffi_type *ffiTypeFor(const Type *Ty) {
118 switch (Ty->getTypeID()) {
119 case Type::VoidTyID: return &ffi_type_void;
120 case Type::IntegerTyID:
121 switch (cast<IntegerType>(Ty)->getBitWidth()) {
122 case 8: return &ffi_type_sint8;
123 case 16: return &ffi_type_sint16;
124 case 32: return &ffi_type_sint32;
125 case 64: return &ffi_type_sint64;
126 }
127 case Type::FloatTyID: return &ffi_type_float;
128 case Type::DoubleTyID: return &ffi_type_double;
129 case Type::PointerTyID: return &ffi_type_pointer;
130 default: break;
131 }
132 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
Torok Edwin7d696d82009-07-11 13:10:19 +0000133 llvm_report_error("Type could not be mapped for use with libffi.");
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000134 return NULL;
135}
136
137static void *ffiValueFor(const Type *Ty, const GenericValue &AV,
138 void *ArgDataPtr) {
139 switch (Ty->getTypeID()) {
140 case Type::IntegerTyID:
141 switch (cast<IntegerType>(Ty)->getBitWidth()) {
142 case 8: {
143 int8_t *I8Ptr = (int8_t *) ArgDataPtr;
144 *I8Ptr = (int8_t) AV.IntVal.getZExtValue();
145 return ArgDataPtr;
146 }
147 case 16: {
148 int16_t *I16Ptr = (int16_t *) ArgDataPtr;
149 *I16Ptr = (int16_t) AV.IntVal.getZExtValue();
150 return ArgDataPtr;
151 }
152 case 32: {
153 int32_t *I32Ptr = (int32_t *) ArgDataPtr;
154 *I32Ptr = (int32_t) AV.IntVal.getZExtValue();
155 return ArgDataPtr;
156 }
157 case 64: {
158 int64_t *I64Ptr = (int64_t *) ArgDataPtr;
159 *I64Ptr = (int64_t) AV.IntVal.getZExtValue();
160 return ArgDataPtr;
161 }
162 }
163 case Type::FloatTyID: {
164 float *FloatPtr = (float *) ArgDataPtr;
165 *FloatPtr = AV.DoubleVal;
166 return ArgDataPtr;
167 }
168 case Type::DoubleTyID: {
169 double *DoublePtr = (double *) ArgDataPtr;
170 *DoublePtr = AV.DoubleVal;
171 return ArgDataPtr;
172 }
173 case Type::PointerTyID: {
174 void **PtrPtr = (void **) ArgDataPtr;
175 *PtrPtr = GVTOP(AV);
176 return ArgDataPtr;
177 }
178 default: break;
179 }
180 // TODO: Support other types such as StructTyID, ArrayTyID, OpaqueTyID, etc.
Torok Edwin7d696d82009-07-11 13:10:19 +0000181 llvm_report_error("Type value could not be mapped for use with libffi.");
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000182 return NULL;
183}
184
185static bool ffiInvoke(RawFunc Fn, Function *F,
186 const std::vector<GenericValue> &ArgVals,
187 const TargetData *TD, GenericValue &Result) {
188 ffi_cif cif;
189 const FunctionType *FTy = F->getFunctionType();
190 const unsigned NumArgs = F->arg_size();
191
192 // TODO: We don't have type information about the remaining arguments, because
193 // this information is never passed into ExecutionEngine::runFunction().
194 if (ArgVals.size() > NumArgs && F->isVarArg()) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000195 llvm_report_error("Calling external var arg function '" + F->getName()
196 + "' is not supported by the Interpreter.");
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000197 }
198
199 unsigned ArgBytes = 0;
200
201 std::vector<ffi_type*> args(NumArgs);
202 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
203 A != E; ++A) {
204 const unsigned ArgNo = A->getArgNo();
205 const Type *ArgTy = FTy->getParamType(ArgNo);
206 args[ArgNo] = ffiTypeFor(ArgTy);
207 ArgBytes += TD->getTypeStoreSize(ArgTy);
208 }
209
210 uint8_t *ArgData = (uint8_t*) alloca(ArgBytes);
211 uint8_t *ArgDataPtr = ArgData;
212 std::vector<void*> values(NumArgs);
213 for (Function::const_arg_iterator A = F->arg_begin(), E = F->arg_end();
214 A != E; ++A) {
215 const unsigned ArgNo = A->getArgNo();
216 const Type *ArgTy = FTy->getParamType(ArgNo);
217 values[ArgNo] = ffiValueFor(ArgTy, ArgVals[ArgNo], ArgDataPtr);
218 ArgDataPtr += TD->getTypeStoreSize(ArgTy);
219 }
220
221 const Type *RetTy = FTy->getReturnType();
222 ffi_type *rtype = ffiTypeFor(RetTy);
223
224 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, NumArgs, rtype, &args[0]) == FFI_OK) {
225 void *ret = NULL;
226 if (RetTy->getTypeID() != Type::VoidTyID)
227 ret = alloca(TD->getTypeStoreSize(RetTy));
228 ffi_call(&cif, Fn, ret, &values[0]);
229 switch (RetTy->getTypeID()) {
230 case Type::IntegerTyID:
231 switch (cast<IntegerType>(RetTy)->getBitWidth()) {
232 case 8: Result.IntVal = APInt(8 , *(int8_t *) ret); break;
233 case 16: Result.IntVal = APInt(16, *(int16_t*) ret); break;
234 case 32: Result.IntVal = APInt(32, *(int32_t*) ret); break;
235 case 64: Result.IntVal = APInt(64, *(int64_t*) ret); break;
236 }
237 break;
238 case Type::FloatTyID: Result.FloatVal = *(float *) ret; break;
239 case Type::DoubleTyID: Result.DoubleVal = *(double*) ret; break;
240 case Type::PointerTyID: Result.PointerVal = *(void **) ret; break;
241 default: break;
242 }
243 return true;
244 }
245
246 return false;
247}
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000248#endif // USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000249
Chris Lattner4e7dd8f2005-01-21 19:59:37 +0000250GenericValue Interpreter::callExternalFunction(Function *F,
Chris Lattner44edb6b2003-05-14 14:21:30 +0000251 const std::vector<GenericValue> &ArgVals) {
Chris Lattnere43db882001-10-27 04:15:57 +0000252 TheInterpreter = this;
253
Owen Andersonc2265702009-06-22 22:30:56 +0000254 FunctionsLock->acquire();
255
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000256 // Do a lookup to see if the function is in our cache... this should just be a
Misha Brukmand5d96b92003-10-10 17:42:19 +0000257 // deferred annotation!
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000258 std::map<const Function *, ExFunc>::iterator FI = ExportedFunctions->find(F);
259 if (ExFunc Fn = (FI == ExportedFunctions->end()) ? lookupFunction(F)
Owen Andersonc2265702009-06-22 22:30:56 +0000260 : FI->second) {
261 FunctionsLock->release();
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000262 return Fn(F->getFunctionType(), ArgVals);
Owen Andersonc2265702009-06-22 22:30:56 +0000263 }
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000264
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000265#ifdef USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000266 std::map<const Function *, RawFunc>::iterator RF = RawFunctions->find(F);
267 RawFunc RawFn;
268 if (RF == RawFunctions->end()) {
269 RawFn = (RawFunc)(intptr_t)
270 sys::DynamicLibrary::SearchForAddressOfSymbol(F->getName());
271 if (RawFn != 0)
272 RawFunctions->insert(std::make_pair(F, RawFn)); // Cache for later
273 } else {
274 RawFn = RF->second;
Chris Lattner7720c8e2001-09-10 04:50:17 +0000275 }
Daniel Dunbare4a57432009-09-17 00:14:44 +0000276
Owen Andersonc2265702009-06-22 22:30:56 +0000277 FunctionsLock->release();
Chris Lattner7720c8e2001-09-10 04:50:17 +0000278
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000279 GenericValue Result;
280 if (RawFn != 0 && ffiInvoke(RawFn, F, ArgVals, getTargetData(), Result))
281 return Result;
Nick Lewycky93f70fc2009-04-13 04:26:06 +0000282#endif // USE_LIBFFI
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000283
Torok Edwin7d696d82009-07-11 13:10:19 +0000284 if (F->getName() == "__main")
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000285 errs() << "Tried to execute an unknown external function: "
Torok Edwin7d696d82009-07-11 13:10:19 +0000286 << F->getType()->getDescription() << " __main\n";
287 else
288 llvm_report_error("Tried to execute an unknown external function: " +
289 F->getType()->getDescription() + " " +F->getName());
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000290 return GenericValue();
Chris Lattner7720c8e2001-09-10 04:50:17 +0000291}
292
293
294//===----------------------------------------------------------------------===//
Chris Lattnerb408b122002-03-29 03:57:15 +0000295// Functions "exported" to the running application...
Chris Lattner7720c8e2001-09-10 04:50:17 +0000296//
Daniel Dunbar482cccd2009-08-07 20:50:09 +0000297
298// Visual Studio warns about returning GenericValue in extern "C" linkage
299#ifdef _MSC_VER
300 #pragma warning(disable : 4190)
301#endif
302
Chris Lattner7720c8e2001-09-10 04:50:17 +0000303extern "C" { // Don't add C++ manglings to llvm mangling :)
304
Chris Lattner44edb6b2003-05-14 14:21:30 +0000305// void atexit(Function*)
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000306GenericValue lle_X_atexit(const FunctionType *FT,
307 const std::vector<GenericValue> &Args) {
Chris Lattner44edb6b2003-05-14 14:21:30 +0000308 assert(Args.size() == 1);
309 TheInterpreter->addAtExitHandler((Function*)GVTOP(Args[0]));
310 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000311 GV.IntVal = 0;
Chris Lattner44edb6b2003-05-14 14:21:30 +0000312 return GV;
Chris Lattnerf8f2afb2001-10-18 21:55:32 +0000313}
314
Chris Lattner005cbce2002-10-02 21:12:13 +0000315// void exit(int)
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000316GenericValue lle_X_exit(const FunctionType *FT,
317 const std::vector<GenericValue> &Args) {
Chris Lattnere43db882001-10-27 04:15:57 +0000318 TheInterpreter->exitCalled(Args[0]);
319 return GenericValue();
320}
321
Chris Lattner005cbce2002-10-02 21:12:13 +0000322// void abort(void)
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000323GenericValue lle_X_abort(const FunctionType *FT,
324 const std::vector<GenericValue> &Args) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000325 //FIXME: should we report or raise here?
326 //llvm_report_error("Interpreted program raised SIGABRT");
Brian Gaekeb56a6bc2003-11-05 01:18:49 +0000327 raise (SIGABRT);
Chris Lattner1ee34a52002-05-20 21:17:16 +0000328 return GenericValue();
329}
330
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000331// int sprintf(char *, const char *, ...) - a very rough implementation to make
Chris Lattnere7c6f722001-12-13 00:43:47 +0000332// output useful.
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000333GenericValue lle_X_sprintf(const FunctionType *FT,
334 const std::vector<GenericValue> &Args) {
Chris Lattnerb1118742003-01-13 00:59:47 +0000335 char *OutputBuffer = (char *)GVTOP(Args[0]);
336 const char *FmtStr = (const char *)GVTOP(Args[1]);
Chris Lattnere7c6f722001-12-13 00:43:47 +0000337 unsigned ArgNo = 2;
Chris Lattner08845a22001-10-29 20:27:45 +0000338
339 // printf should return # chars printed. This is completely incorrect, but
340 // close enough for now.
Daniel Dunbare4a57432009-09-17 00:14:44 +0000341 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000342 GV.IntVal = APInt(32, strlen(FmtStr));
Chris Lattner08845a22001-10-29 20:27:45 +0000343 while (1) {
344 switch (*FmtStr) {
345 case 0: return GV; // Null terminator...
346 default: // Normal nonspecial character
Chris Lattnere7c6f722001-12-13 00:43:47 +0000347 sprintf(OutputBuffer++, "%c", *FmtStr++);
Chris Lattner08845a22001-10-29 20:27:45 +0000348 break;
349 case '\\': { // Handle escape codes
Chris Lattnere7c6f722001-12-13 00:43:47 +0000350 sprintf(OutputBuffer, "%c%c", *FmtStr, *(FmtStr+1));
351 FmtStr += 2; OutputBuffer += 2;
Chris Lattner08845a22001-10-29 20:27:45 +0000352 break;
353 }
354 case '%': { // Handle format specifiers
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000355 char FmtBuf[100] = "", Buffer[1000] = "";
356 char *FB = FmtBuf;
357 *FB++ = *FmtStr++;
358 char Last = *FB++ = *FmtStr++;
359 unsigned HowLong = 0;
360 while (Last != 'c' && Last != 'd' && Last != 'i' && Last != 'u' &&
361 Last != 'o' && Last != 'x' && Last != 'X' && Last != 'e' &&
362 Last != 'E' && Last != 'g' && Last != 'G' && Last != 'f' &&
363 Last != 'p' && Last != 's' && Last != '%') {
364 if (Last == 'l' || Last == 'L') HowLong++; // Keep track of l's
365 Last = *FB++ = *FmtStr++;
Chris Lattner08845a22001-10-29 20:27:45 +0000366 }
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000367 *FB = 0;
Misha Brukmand1c881a2005-04-21 22:43:08 +0000368
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000369 switch (Last) {
370 case '%':
Dan Gohman1eac4e02008-08-05 23:36:35 +0000371 strcpy(Buffer, "%"); break;
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000372 case 'c':
Reid Spencerbfcd5992007-03-06 03:08:12 +0000373 sprintf(Buffer, FmtBuf, uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
374 break;
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000375 case 'd': case 'i':
376 case 'u': case 'o':
377 case 'x': case 'X':
Chris Lattner69ab7a82002-08-02 23:08:32 +0000378 if (HowLong >= 1) {
Chris Lattner1543e402003-08-24 14:02:47 +0000379 if (HowLong == 1 &&
Chris Lattnerfe854032006-08-16 01:24:12 +0000380 TheInterpreter->getTargetData()->getPointerSizeInBits() == 64 &&
Reid Spencer19b7e0e2006-05-24 19:21:13 +0000381 sizeof(long) < sizeof(int64_t)) {
Chris Lattner69ab7a82002-08-02 23:08:32 +0000382 // Make sure we use %lld with a 64 bit argument because we might be
383 // compiling LLI on a 32 bit compiler.
384 unsigned Size = strlen(FmtBuf);
385 FmtBuf[Size] = FmtBuf[Size-1];
386 FmtBuf[Size+1] = 0;
387 FmtBuf[Size-1] = 'l';
388 }
Reid Spencerbfcd5992007-03-06 03:08:12 +0000389 sprintf(Buffer, FmtBuf, Args[ArgNo++].IntVal.getZExtValue());
Chris Lattner69ab7a82002-08-02 23:08:32 +0000390 } else
Reid Spencerbfcd5992007-03-06 03:08:12 +0000391 sprintf(Buffer, FmtBuf,uint32_t(Args[ArgNo++].IntVal.getZExtValue()));
392 break;
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000393 case 'e': case 'E': case 'g': case 'G': case 'f':
394 sprintf(Buffer, FmtBuf, Args[ArgNo++].DoubleVal); break;
395 case 'p':
Chris Lattnerb1118742003-01-13 00:59:47 +0000396 sprintf(Buffer, FmtBuf, (void*)GVTOP(Args[ArgNo++])); break;
Misha Brukmand1c881a2005-04-21 22:43:08 +0000397 case 's':
Chris Lattnerb1118742003-01-13 00:59:47 +0000398 sprintf(Buffer, FmtBuf, (char*)GVTOP(Args[ArgNo++])); break;
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000399 default:
400 errs() << "<unknown printf code '" << *FmtStr << "'!>";
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000401 ArgNo++; break;
Chris Lattner08845a22001-10-29 20:27:45 +0000402 }
Chris Lattnere7c6f722001-12-13 00:43:47 +0000403 strcpy(OutputBuffer, Buffer);
404 OutputBuffer += strlen(Buffer);
Chris Lattnerea38c0e2001-11-07 19:46:27 +0000405 }
Chris Lattner08845a22001-10-29 20:27:45 +0000406 break;
407 }
Chris Lattner08845a22001-10-29 20:27:45 +0000408 }
Reid Spencerb3b07272007-04-21 17:11:45 +0000409 return GV;
Chris Lattner08845a22001-10-29 20:27:45 +0000410}
411
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000412// int printf(const char *, ...) - a very rough implementation to make output
413// useful.
414GenericValue lle_X_printf(const FunctionType *FT,
415 const std::vector<GenericValue> &Args) {
Chris Lattnere7c6f722001-12-13 00:43:47 +0000416 char Buffer[10000];
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000417 std::vector<GenericValue> NewArgs;
Reid Spencerb3b07272007-04-21 17:11:45 +0000418 NewArgs.push_back(PTOGV((void*)&Buffer[0]));
Chris Lattnere7c6f722001-12-13 00:43:47 +0000419 NewArgs.insert(NewArgs.end(), Args.begin(), Args.end());
Reid Spencer97e0c222007-03-30 16:41:50 +0000420 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Chris Lattnerd9ea85a2009-08-23 08:43:55 +0000421 outs() << Buffer;
Chris Lattnere7c6f722001-12-13 00:43:47 +0000422 return GV;
423}
424
Owen Anderson1d0be152009-08-13 21:58:54 +0000425static void ByteswapSCANFResults(LLVMContext &C,
426 const char *Fmt, void *Arg0, void *Arg1,
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000427 void *Arg2, void *Arg3, void *Arg4, void *Arg5,
428 void *Arg6, void *Arg7, void *Arg8) {
429 void *Args[] = { Arg0, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, 0 };
430
431 // Loop over the format string, munging read values as appropriate (performs
Misha Brukman5560c9d2003-08-18 14:43:39 +0000432 // byteswaps as necessary).
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000433 unsigned ArgNo = 0;
434 while (*Fmt) {
435 if (*Fmt++ == '%') {
436 // Read any flag characters that may be present...
437 bool Suppress = false;
438 bool Half = false;
439 bool Long = false;
440 bool LongLong = false; // long long or long double
441
442 while (1) {
443 switch (*Fmt++) {
444 case '*': Suppress = true; break;
445 case 'a': /*Allocate = true;*/ break; // We don't need to track this
446 case 'h': Half = true; break;
447 case 'l': Long = true; break;
448 case 'q':
449 case 'L': LongLong = true; break;
450 default:
451 if (Fmt[-1] > '9' || Fmt[-1] < '0') // Ignore field width specs
452 goto Out;
453 }
454 }
455 Out:
456
457 // Read the conversion character
458 if (!Suppress && Fmt[-1] != '%') { // Nothing to do?
459 unsigned Size = 0;
460 const Type *Ty = 0;
461
462 switch (Fmt[-1]) {
463 case 'i': case 'o': case 'u': case 'x': case 'X': case 'n': case 'p':
464 case 'd':
465 if (Long || LongLong) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000466 Size = 8; Ty = Type::getInt64Ty(C);
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000467 } else if (Half) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000468 Size = 4; Ty = Type::getInt16Ty(C);
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000469 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +0000470 Size = 4; Ty = Type::getInt32Ty(C);
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000471 }
472 break;
473
474 case 'e': case 'g': case 'E':
475 case 'f':
476 if (Long || LongLong) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000477 Size = 8; Ty = Type::getDoubleTy(C);
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000478 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +0000479 Size = 4; Ty = Type::getFloatTy(C);
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000480 }
481 break;
482
483 case 's': case 'c': case '[': // No byteswap needed
484 Size = 1;
Owen Anderson1d0be152009-08-13 21:58:54 +0000485 Ty = Type::getInt8Ty(C);
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000486 break;
487
488 default: break;
489 }
490
491 if (Size) {
492 GenericValue GV;
493 void *Arg = Args[ArgNo++];
494 memcpy(&GV, Arg, Size);
495 TheInterpreter->StoreValueToMemory(GV, (GenericValue*)Arg, Ty);
496 }
497 }
498 }
499 }
500}
501
Chris Lattner665ee882002-03-08 22:51:07 +0000502// int sscanf(const char *format, ...);
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000503GenericValue lle_X_sscanf(const FunctionType *FT,
504 const std::vector<GenericValue> &args) {
Chris Lattner665ee882002-03-08 22:51:07 +0000505 assert(args.size() < 10 && "Only handle up to 10 args to sscanf right now!");
506
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000507 char *Args[10];
Chris Lattner665ee882002-03-08 22:51:07 +0000508 for (unsigned i = 0; i < args.size(); ++i)
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000509 Args[i] = (char*)GVTOP(args[i]);
Chris Lattner665ee882002-03-08 22:51:07 +0000510
511 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000512 GV.IntVal = APInt(32, sscanf(Args[0], Args[1], Args[2], Args[3], Args[4],
513 Args[5], Args[6], Args[7], Args[8], Args[9]));
Owen Anderson1d0be152009-08-13 21:58:54 +0000514 ByteswapSCANFResults(FT->getContext(),
515 Args[1], Args[2], Args[3], Args[4],
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000516 Args[5], Args[6], Args[7], Args[8], Args[9], 0);
517 return GV;
518}
519
520// int scanf(const char *format, ...);
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000521GenericValue lle_X_scanf(const FunctionType *FT,
522 const std::vector<GenericValue> &args) {
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000523 assert(args.size() < 10 && "Only handle up to 10 args to scanf right now!");
524
525 char *Args[10];
526 for (unsigned i = 0; i < args.size(); ++i)
527 Args[i] = (char*)GVTOP(args[i]);
528
529 GenericValue GV;
Reid Spencerbfcd5992007-03-06 03:08:12 +0000530 GV.IntVal = APInt(32, scanf( Args[0], Args[1], Args[2], Args[3], Args[4],
531 Args[5], Args[6], Args[7], Args[8], Args[9]));
Owen Anderson1d0be152009-08-13 21:58:54 +0000532 ByteswapSCANFResults(FT->getContext(),
533 Args[0], Args[1], Args[2], Args[3], Args[4],
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000534 Args[5], Args[6], Args[7], Args[8], Args[9]);
Chris Lattner665ee882002-03-08 22:51:07 +0000535 return GV;
536}
537
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000538// int fprintf(FILE *, const char *, ...) - a very rough implementation to make
539// output useful.
540GenericValue lle_X_fprintf(const FunctionType *FT,
541 const std::vector<GenericValue> &Args) {
Chris Lattner9dbf6dd2003-04-21 22:43:20 +0000542 assert(Args.size() >= 2);
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000543 char Buffer[10000];
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000544 std::vector<GenericValue> NewArgs;
Chris Lattnerb1118742003-01-13 00:59:47 +0000545 NewArgs.push_back(PTOGV(Buffer));
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000546 NewArgs.insert(NewArgs.end(), Args.begin()+1, Args.end());
Reid Spencer97e0c222007-03-30 16:41:50 +0000547 GenericValue GV = lle_X_sprintf(FT, NewArgs);
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000548
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000549 fputs(Buffer, (FILE *) GVTOP(Args[0]));
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000550 return GV;
551}
552
Chris Lattner7720c8e2001-09-10 04:50:17 +0000553} // End extern "C"
Chris Lattner4721f132001-10-30 20:28:00 +0000554
Daniel Dunbar482cccd2009-08-07 20:50:09 +0000555// Done with externals; turn the warning back on
556#ifdef _MSC_VER
557 #pragma warning(default: 4190)
558#endif
559
Chris Lattner4721f132001-10-30 20:28:00 +0000560
Chris Lattnerda82ed52003-05-08 16:18:31 +0000561void Interpreter::initializeExternalFunctions() {
Owen Andersona9d1f2c2009-07-07 18:33:04 +0000562 sys::ScopedLock Writer(*FunctionsLock);
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000563 FuncNames["lle_X_atexit"] = lle_X_atexit;
Chris Lattner0f279b22001-11-03 10:15:32 +0000564 FuncNames["lle_X_exit"] = lle_X_exit;
Chris Lattner1ee34a52002-05-20 21:17:16 +0000565 FuncNames["lle_X_abort"] = lle_X_abort;
Nick Lewyckyf9c5c5c2009-02-04 06:26:47 +0000566
Chris Lattner0f279b22001-11-03 10:15:32 +0000567 FuncNames["lle_X_printf"] = lle_X_printf;
Chris Lattnere7c6f722001-12-13 00:43:47 +0000568 FuncNames["lle_X_sprintf"] = lle_X_sprintf;
Chris Lattner665ee882002-03-08 22:51:07 +0000569 FuncNames["lle_X_sscanf"] = lle_X_sscanf;
Chris Lattnerf9a88b62003-03-31 22:12:37 +0000570 FuncNames["lle_X_scanf"] = lle_X_scanf;
Chris Lattnercf9b4f02002-11-06 23:05:03 +0000571 FuncNames["lle_X_fprintf"] = lle_X_fprintf;
Chris Lattner4721f132001-10-30 20:28:00 +0000572}