blob: b7e45942e34bbe440c2c0ae4315866c2d80d4eb8 [file] [log] [blame]
Jack Palevichae54f1f2009-05-08 14:54:15 -07001/*
Jack Paleviche7b59062009-05-19 17:12:17 -07002 * Android "Almost" C Compiler.
3 * This is a compiler for a small subset of the C language, intended for use
4 * in scripting environments where speed and memory footprint are important.
5 *
6 * This code is based upon the "unobfuscated" version of the
Jack Palevich1cdef202009-05-22 12:06:27 -07007 * Obfuscated Tiny C compiler, see the file LICENSE for details.
Jack Paleviche7b59062009-05-19 17:12:17 -07008 *
9 */
10
Jack Palevich77ae76e2009-05-10 19:59:24 -070011#include <ctype.h>
12#include <dlfcn.h>
Jack Paleviche27bf3e2009-05-10 14:09:03 -070013#include <stdarg.h>
Jack Palevich8b0624c2009-05-20 12:12:06 -070014#include <stdint.h>
Jack Palevichae54f1f2009-05-08 14:54:15 -070015#include <stdio.h>
Jack Palevichf6b5a532009-05-10 19:16:42 -070016#include <stdlib.h>
17#include <string.h>
Jack Palevichae54f1f2009-05-08 14:54:15 -070018
Jack Palevich546b2242009-05-13 15:10:04 -070019#if defined(__arm__)
20#include <unistd.h>
21#endif
22
Jack Paleviche7b59062009-05-19 17:12:17 -070023#if defined(__arm__)
24#define DEFAULT_ARM_CODEGEN
Jack Palevich8b0624c2009-05-20 12:12:06 -070025#define PROVIDE_ARM_CODEGEN
Jack Paleviche7b59062009-05-19 17:12:17 -070026#elif defined(__i386__)
27#define DEFAULT_X86_CODEGEN
Jack Palevich8b0624c2009-05-20 12:12:06 -070028#define PROVIDE_X86_CODEGEN
Jack Paleviche7b59062009-05-19 17:12:17 -070029#elif defined(__x86_64__)
30#define DEFAULT_X64_CODEGEN
Jack Palevich8b0624c2009-05-20 12:12:06 -070031#define PROVIDE_X64_CODEGEN
Jack Paleviche7b59062009-05-19 17:12:17 -070032#endif
33
Jack Paleviche7b59062009-05-19 17:12:17 -070034
35#ifdef PROVIDE_ARM_CODEGEN
Jack Palevicha6535612009-05-13 16:24:17 -070036#include "disassem.h"
Jack Paleviche7b59062009-05-19 17:12:17 -070037#endif
Jack Palevicha6535612009-05-13 16:24:17 -070038
Jack Palevich1cdef202009-05-22 12:06:27 -070039#include <acc/acc.h>
40
Jack Palevich09555c72009-05-27 12:25:55 -070041#define LOG_API(...) do {} while(0)
42// #define LOG_API(...) fprintf (stderr, __VA_ARGS__)
43
44// #define ENABLE_ARM_DISASSEMBLY
45
Jack Palevichbbf8ab52009-05-11 11:54:30 -070046namespace acc {
47
Jack Paleviche7b59062009-05-19 17:12:17 -070048class Compiler {
Jack Palevich21a15a22009-05-11 14:49:29 -070049 class CodeBuf {
50 char* ind;
51 char* pProgramBase;
Jack Palevichf0cbc922009-05-08 16:35:13 -070052
Jack Palevich21a15a22009-05-11 14:49:29 -070053 void release() {
54 if (pProgramBase != 0) {
55 free(pProgramBase);
56 pProgramBase = 0;
Jack Palevichae54f1f2009-05-08 14:54:15 -070057 }
Jack Palevich21a15a22009-05-11 14:49:29 -070058 }
59
60 public:
61 CodeBuf() {
62 pProgramBase = 0;
63 ind = 0;
64 }
65
66 ~CodeBuf() {
67 release();
68 }
69
70 void init(int size) {
71 release();
72 pProgramBase = (char*) calloc(1, size);
73 ind = pProgramBase;
74 }
75
Jack Palevich546b2242009-05-13 15:10:04 -070076 int o4(int n) {
Jack Palevich8b0624c2009-05-20 12:12:06 -070077 intptr_t result = (intptr_t) ind;
Jack Palevich546b2242009-05-13 15:10:04 -070078 * (int*) ind = n;
79 ind += 4;
80 return result;
81 }
82
Jack Palevich21a15a22009-05-11 14:49:29 -070083 /*
84 * Output a byte. Handles all values, 0..ff.
85 */
86 void ob(int n) {
87 *ind++ = n;
88 }
89
Jack Palevich21a15a22009-05-11 14:49:29 -070090 inline void* getBase() {
91 return (void*) pProgramBase;
92 }
93
Jack Palevich8b0624c2009-05-20 12:12:06 -070094 intptr_t getSize() {
Jack Palevich21a15a22009-05-11 14:49:29 -070095 return ind - pProgramBase;
96 }
97
Jack Palevich8b0624c2009-05-20 12:12:06 -070098 intptr_t getPC() {
99 return (intptr_t) ind;
Jack Palevich21a15a22009-05-11 14:49:29 -0700100 }
101 };
102
Jack Palevich1cdef202009-05-22 12:06:27 -0700103 /**
104 * A code generator creates an in-memory program, generating the code on
105 * the fly. There is one code generator implementation for each supported
106 * architecture.
107 *
108 * The code generator implements the following abstract machine:
109 * R0 - the main accumulator.
110 * R1 - the secondary accumulator.
111 * FP - a frame pointer for accessing function arguments and local
112 * variables.
113 * SP - a stack pointer for storing intermediate results while evaluating
114 * expressions. The stack pointer grows downwards.
115 *
116 * The function calling convention is that all arguments are placed on the
117 * stack such that the first argument has the lowest address.
118 * After the call, the result is in R0. The caller is responsible for
119 * removing the arguments from the stack.
120 * The R0 and R1 registers are not saved across function calls. The
121 * FP and SP registers are saved.
122 */
123
Jack Palevich21a15a22009-05-11 14:49:29 -0700124 class CodeGenerator {
125 public:
126 CodeGenerator() {}
127 virtual ~CodeGenerator() {}
128
Jack Palevich22305132009-05-13 10:58:45 -0700129 virtual void init(CodeBuf* pCodeBuf) {
Jack Palevich21a15a22009-05-11 14:49:29 -0700130 this->pCodeBuf = pCodeBuf;
131 }
132
Jack Palevich1cdef202009-05-22 12:06:27 -0700133 /* Emit a function prolog.
134 * argCount is the number of arguments.
135 * Save the old value of the FP.
136 * Set the new value of the FP.
137 * Convert from the native platform calling convention to
138 * our stack-based calling convention. This may require
139 * pushing arguments from registers to the stack.
140 * Allocate "N" bytes of stack space. N isn't known yet, so
141 * just emit the instructions for adjusting the stack, and return
142 * the address to patch up. The patching will be done in
143 * functionExit().
144 * returns address to patch with local variable size.
Jack Palevich22305132009-05-13 10:58:45 -0700145 */
Jack Palevich546b2242009-05-13 15:10:04 -0700146 virtual int functionEntry(int argCount) = 0;
Jack Palevich22305132009-05-13 10:58:45 -0700147
Jack Palevich1cdef202009-05-22 12:06:27 -0700148 /* Emit a function epilog.
149 * Restore the old SP and FP register values.
150 * Return to the calling function.
151 * argCount - the number of arguments to the function.
152 * localVariableAddress - returned from functionEntry()
153 * localVariableSize - the size in bytes of the local variables.
154 */
155 virtual void functionExit(int argCount, int localVariableAddress,
156 int localVariableSize) = 0;
Jack Palevich22305132009-05-13 10:58:45 -0700157
Jack Palevich1cdef202009-05-22 12:06:27 -0700158 /* load immediate value to R0 */
Jack Palevich546b2242009-05-13 15:10:04 -0700159 virtual void li(int t) = 0;
Jack Palevich22305132009-05-13 10:58:45 -0700160
Jack Palevich1cdef202009-05-22 12:06:27 -0700161 /* Jump to a target, and return the address of the word that
162 * holds the target data, in case it needs to be fixed up later.
163 */
Jack Palevich22305132009-05-13 10:58:45 -0700164 virtual int gjmp(int t) = 0;
165
Jack Palevich1cdef202009-05-22 12:06:27 -0700166 /* Test R0 and jump to a target if the test succeeds.
167 * l = 0: je, l == 1: jne
168 * Return the address of the word that holds the targed data, in
169 * case it needs to be fixed up later.
170 */
Jack Palevich22305132009-05-13 10:58:45 -0700171 virtual int gtst(bool l, int t) = 0;
172
Jack Palevich1cdef202009-05-22 12:06:27 -0700173 /* Compare R1 against R0, and store the boolean result in R0.
174 * op specifies the comparison.
175 */
Jack Palevich22305132009-05-13 10:58:45 -0700176 virtual void gcmp(int op) = 0;
177
Jack Palevich1cdef202009-05-22 12:06:27 -0700178 /* Perform the arithmetic op specified by op. R1 is the
179 * left argument, R0 is the right argument.
180 */
Jack Palevich546b2242009-05-13 15:10:04 -0700181 virtual void genOp(int op) = 0;
Jack Palevich22305132009-05-13 10:58:45 -0700182
Jack Palevich1cdef202009-05-22 12:06:27 -0700183 /* Set R1 to 0.
184 */
185 virtual void clearR1() = 0;
Jack Palevich22305132009-05-13 10:58:45 -0700186
Jack Palevich1cdef202009-05-22 12:06:27 -0700187 /* Push R0 onto the stack.
188 */
189 virtual void pushR0() = 0;
Jack Palevich22305132009-05-13 10:58:45 -0700190
Jack Palevich1cdef202009-05-22 12:06:27 -0700191 /* Pop R1 off of the stack.
192 */
193 virtual void popR1() = 0;
Jack Palevich22305132009-05-13 10:58:45 -0700194
Jack Palevich1cdef202009-05-22 12:06:27 -0700195 /* Store R0 to the address stored in R1.
196 * isInt is true if a whole 4-byte integer value
197 * should be stored, otherwise a 1-byte character
198 * value should be stored.
199 */
200 virtual void storeR0ToR1(bool isInt) = 0;
Jack Palevich22305132009-05-13 10:58:45 -0700201
Jack Palevich1cdef202009-05-22 12:06:27 -0700202 /* Load R0 from the address stored in R0.
203 * isInt is true if a whole 4-byte integer value
204 * should be loaded, otherwise a 1-byte character
205 * value should be loaded.
206 */
207 virtual void loadR0FromR0(bool isInt) = 0;
Jack Palevich22305132009-05-13 10:58:45 -0700208
Jack Palevich1cdef202009-05-22 12:06:27 -0700209 /* Load the absolute address of a variable to R0.
210 * If ea <= LOCAL, then this is a local variable, or an
211 * argument, addressed relative to FP.
212 * else it is an absolute global address.
213 */
214 virtual void leaR0(int ea) = 0;
Jack Palevich22305132009-05-13 10:58:45 -0700215
Jack Palevich1cdef202009-05-22 12:06:27 -0700216 /* Store R0 to a variable.
217 * If ea <= LOCAL, then this is a local variable, or an
218 * argument, addressed relative to FP.
219 * else it is an absolute global address.
220 */
221 virtual void storeR0(int ea) = 0;
Jack Palevich22305132009-05-13 10:58:45 -0700222
Jack Palevich1cdef202009-05-22 12:06:27 -0700223 /* load R0 from a variable.
224 * If ea <= LOCAL, then this is a local variable, or an
225 * argument, addressed relative to FP.
226 * else it is an absolute global address.
227 * If isIncDec is true, then the stored variable's value
228 * should be post-incremented or post-decremented, based
229 * on the value of op.
230 */
231 virtual void loadR0(int ea, bool isIncDec, int op) = 0;
Jack Palevich22305132009-05-13 10:58:45 -0700232
Jack Palevich1cdef202009-05-22 12:06:27 -0700233 /* Emit code to adjust the stack for a function call. Return the
234 * label for the address of the instruction that adjusts the
235 * stack size. This will be passed as argument "a" to
236 * endFunctionCallArguments.
237 */
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700238 virtual int beginFunctionCallArguments() = 0;
239
Jack Palevich1cdef202009-05-22 12:06:27 -0700240 /* Emit code to store R0 to the stack at byte offset l.
241 */
242 virtual void storeR0ToArg(int l) = 0;
Jack Palevich7810bc92009-05-15 14:31:47 -0700243
Jack Palevich1cdef202009-05-22 12:06:27 -0700244 /* Patch the function call preamble.
245 * a is the address returned from beginFunctionCallArguments
246 * l is the number of bytes the arguments took on the stack.
247 * Typically you would also emit code to convert the argument
248 * list into whatever the native function calling convention is.
249 * On ARM for example you would pop the first 5 arguments into
250 * R0..R4
251 */
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700252 virtual void endFunctionCallArguments(int a, int l) = 0;
Jack Palevich22305132009-05-13 10:58:45 -0700253
Jack Palevich1cdef202009-05-22 12:06:27 -0700254 /* Emit a call to an unknown function. The argument "symbol" needs to
255 * be stored in the location where the address should go. It forms
256 * a chain. The address will be patched later.
257 * Return the address of the word that has to be patched.
258 */
Jack Palevich22305132009-05-13 10:58:45 -0700259 virtual int callForward(int symbol) = 0;
260
Jack Palevich1cdef202009-05-22 12:06:27 -0700261 /* Call a function using PC-relative addressing. t is the PC-relative
262 * address of the function. It has already been adjusted for the
263 * architectural jump offset, so just store it as-is.
264 */
Jack Palevich22305132009-05-13 10:58:45 -0700265 virtual void callRelative(int t) = 0;
266
Jack Palevich1cdef202009-05-22 12:06:27 -0700267 /* Call a function pointer. L is the number of bytes the arguments
268 * take on the stack. The address of the function is stored at
269 * location SP + l.
270 */
Jack Palevich22305132009-05-13 10:58:45 -0700271 virtual void callIndirect(int l) = 0;
272
Jack Palevich1cdef202009-05-22 12:06:27 -0700273 /* Adjust SP after returning from a function call. l is the
274 * number of bytes of arguments stored on the stack. isIndirect
275 * is true if this was an indirect call. (In which case the
276 * address of the function is stored at location SP + l.)
277 */
Jack Palevich7810bc92009-05-15 14:31:47 -0700278 virtual void adjustStackAfterCall(int l, bool isIndirect) = 0;
Jack Palevich22305132009-05-13 10:58:45 -0700279
Jack Palevich1cdef202009-05-22 12:06:27 -0700280 /* Print a disassembly of the assembled code to out. Return
281 * non-zero if there is an error.
282 */
Jack Palevicha6535612009-05-13 16:24:17 -0700283 virtual int disassemble(FILE* out) = 0;
284
Jack Palevich1cdef202009-05-22 12:06:27 -0700285 /* Generate a symbol at the current PC. t is the head of a
286 * linked list of addresses to patch.
287 */
Jack Paleviche7b59062009-05-19 17:12:17 -0700288 virtual void gsym(int t) = 0;
Jack Palevich21a15a22009-05-11 14:49:29 -0700289
Jack Palevich1cdef202009-05-22 12:06:27 -0700290 /*
291 * Do any cleanup work required at the end of a compile.
292 * For example, an instruction cache might need to be
293 * invalidated.
294 * Return non-zero if there is an error.
295 */
296 virtual int finishCompile() = 0;
Jack Palevich546b2242009-05-13 15:10:04 -0700297
Jack Palevicha6535612009-05-13 16:24:17 -0700298 /**
299 * Adjust relative branches by this amount.
300 */
301 virtual int jumpOffset() = 0;
302
Jack Palevich21a15a22009-05-11 14:49:29 -0700303 protected:
Jack Palevich21a15a22009-05-11 14:49:29 -0700304 /*
305 * Output a byte. Handles all values, 0..ff.
306 */
307 void ob(int n) {
308 pCodeBuf->ob(n);
309 }
310
Jack Palevich8b0624c2009-05-20 12:12:06 -0700311 intptr_t o4(int data) {
Jack Paleviche7b59062009-05-19 17:12:17 -0700312 return pCodeBuf->o4(data);
Jack Palevich21a15a22009-05-11 14:49:29 -0700313 }
314
Jack Palevich8b0624c2009-05-20 12:12:06 -0700315 intptr_t getBase() {
316 return (intptr_t) pCodeBuf->getBase();
Jack Palevicha6535612009-05-13 16:24:17 -0700317 }
318
Jack Palevich8b0624c2009-05-20 12:12:06 -0700319 intptr_t getPC() {
Jack Palevich21a15a22009-05-11 14:49:29 -0700320 return pCodeBuf->getPC();
321 }
Jack Palevich1cdef202009-05-22 12:06:27 -0700322
323 intptr_t getSize() {
324 return pCodeBuf->getSize();
325 }
Jack Palevich21a15a22009-05-11 14:49:29 -0700326 private:
327 CodeBuf* pCodeBuf;
328 };
329
Jack Paleviche7b59062009-05-19 17:12:17 -0700330#ifdef PROVIDE_ARM_CODEGEN
331
Jack Palevich22305132009-05-13 10:58:45 -0700332 class ARMCodeGenerator : public CodeGenerator {
333 public:
334 ARMCodeGenerator() {}
335 virtual ~ARMCodeGenerator() {}
336
337 /* returns address to patch with local variable size
338 */
Jack Palevich546b2242009-05-13 15:10:04 -0700339 virtual int functionEntry(int argCount) {
Jack Palevich09555c72009-05-27 12:25:55 -0700340 LOG_API(stderr, "functionEntry(%d);\n", argCount);
Jack Palevich69796b62009-05-14 15:42:26 -0700341 // sp -> arg4 arg5 ...
342 // Push our register-based arguments back on the stack
343 if (argCount > 0) {
344 int regArgCount = argCount <= 4 ? argCount : 4;
345 o4(0xE92D0000 | ((1 << argCount) - 1)); // stmfd sp!, {}
346 }
347 // sp -> arg0 arg1 ...
348 o4(0xE92D4800); // stmfd sp!, {fp, lr}
349 // sp, fp -> oldfp, retadr, arg0 arg1 ....
350 o4(0xE1A0B00D); // mov fp, sp
351 return o4(0xE24DD000); // sub sp, sp, # <local variables>
Jack Palevich22305132009-05-13 10:58:45 -0700352 }
353
Jack Palevich546b2242009-05-13 15:10:04 -0700354 virtual void functionExit(int argCount, int localVariableAddress, int localVariableSize) {
Jack Palevich09555c72009-05-27 12:25:55 -0700355 LOG_API("functionExit(%d, %d, %d);\n", argCount, localVariableAddress, localVariableSize);
Jack Palevich69796b62009-05-14 15:42:26 -0700356 // Patch local variable allocation code:
357 if (localVariableSize < 0 || localVariableSize > 255) {
Jack Palevich8de461d2009-05-14 17:21:45 -0700358 error("localVariables out of range: %d", localVariableSize);
Jack Palevich546b2242009-05-13 15:10:04 -0700359 }
Jack Palevich69796b62009-05-14 15:42:26 -0700360 *(char*) (localVariableAddress) = localVariableSize;
361
362 // sp -> locals .... fp -> oldfp, retadr, arg0, arg1, ...
363 o4(0xE1A0E00B); // mov lr, fp
364 o4(0xE59BB000); // ldr fp, [fp]
365 o4(0xE28ED004); // add sp, lr, #4
366 // sp -> retadr, arg0, ...
367 o4(0xE8BD4000); // ldmfd sp!, {lr}
368 // sp -> arg0 ....
369 if (argCount > 0) {
370 // We store the PC into the lr so we can adjust the sp before
Jack Palevich8de461d2009-05-14 17:21:45 -0700371 // returning. We need to pull off the registers we pushed
Jack Palevich69796b62009-05-14 15:42:26 -0700372 // earlier. We don't need to actually store them anywhere,
373 // just adjust the stack.
374 int regArgCount = argCount <= 4 ? argCount : 4;
375 o4(0xE28DD000 | (regArgCount << 2)); // add sp, sp, #argCount << 2
376 }
377 o4(0xE12FFF1E); // bx lr
Jack Palevich22305132009-05-13 10:58:45 -0700378 }
379
380 /* load immediate value */
Jack Palevich546b2242009-05-13 15:10:04 -0700381 virtual void li(int t) {
Jack Palevich09555c72009-05-27 12:25:55 -0700382 LOG_API("li(%d);\n", t);
Jack Palevicha6535612009-05-13 16:24:17 -0700383 if (t >= 0 && t < 255) {
Jack Palevich69796b62009-05-14 15:42:26 -0700384 o4(0xE3A00000 + t); // mov r0, #0
Jack Palevicha6535612009-05-13 16:24:17 -0700385 } else if (t >= -256 && t < 0) {
386 // mvn means move constant ^ ~0
Jack Palevich69796b62009-05-14 15:42:26 -0700387 o4(0xE3E00001 - t); // mvn r0, #0
Jack Palevicha6535612009-05-13 16:24:17 -0700388 } else {
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700389 o4(0xE51F0000); // ldr r0, .L3
390 o4(0xEA000000); // b .L99
391 o4(t); // .L3: .word 0
392 // .L99:
Jack Palevicha6535612009-05-13 16:24:17 -0700393 }
Jack Palevich22305132009-05-13 10:58:45 -0700394 }
395
396 virtual int gjmp(int t) {
Jack Palevich09555c72009-05-27 12:25:55 -0700397 LOG_API("gjmp(%d);\n", t);
Jack Palevich8de461d2009-05-14 17:21:45 -0700398 return o4(0xEA000000 | encodeAddress(t)); // b .L33
Jack Palevich22305132009-05-13 10:58:45 -0700399 }
400
401 /* l = 0: je, l == 1: jne */
402 virtual int gtst(bool l, int t) {
Jack Palevich09555c72009-05-27 12:25:55 -0700403 LOG_API("gtst(%d, %d);\n", l, t);
Jack Palevich8de461d2009-05-14 17:21:45 -0700404 o4(0xE3500000); // cmp r0,#0
405 int branch = l ? 0x1A000000 : 0x0A000000; // bne : beq
406 return o4(branch | encodeAddress(t));
Jack Palevich22305132009-05-13 10:58:45 -0700407 }
408
409 virtual void gcmp(int op) {
Jack Palevich09555c72009-05-27 12:25:55 -0700410 LOG_API("gcmp(%d);\n", op);
Jack Palevich8de461d2009-05-14 17:21:45 -0700411 o4(0xE1510000); // cmp r1, r1
412 switch(op) {
413 case OP_EQUALS:
414 o4(0x03A00001); // moveq r0,#1
415 o4(0x13A00000); // movne r0,#0
416 break;
417 case OP_NOT_EQUALS:
418 o4(0x03A00000); // moveq r0,#0
419 o4(0x13A00001); // movne r0,#1
420 break;
421 case OP_LESS_EQUAL:
422 o4(0xD3A00001); // movle r0,#1
423 o4(0xC3A00000); // movgt r0,#0
424 break;
425 case OP_GREATER:
426 o4(0xD3A00000); // movle r0,#0
427 o4(0xC3A00001); // movgt r0,#1
428 break;
429 case OP_GREATER_EQUAL:
430 o4(0xA3A00001); // movge r0,#1
431 o4(0xB3A00000); // movlt r0,#0
432 break;
433 case OP_LESS:
434 o4(0xA3A00000); // movge r0,#0
435 o4(0xB3A00001); // movlt r0,#1
436 break;
437 default:
438 error("Unknown comparison op %d", op);
439 break;
440 }
Jack Palevich22305132009-05-13 10:58:45 -0700441 }
442
Jack Palevich546b2242009-05-13 15:10:04 -0700443 virtual void genOp(int op) {
Jack Palevich09555c72009-05-27 12:25:55 -0700444 LOG_API("genOp(%d);\n", op);
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700445 switch(op) {
446 case OP_MUL:
447 o4(0x0E0000091); // mul r0,r1,r0
448 break;
Jack Palevich3d474a72009-05-15 15:12:38 -0700449 case OP_DIV:
450 callRuntime(runtime_DIV);
451 break;
452 case OP_MOD:
453 callRuntime(runtime_MOD);
454 break;
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700455 case OP_PLUS:
456 o4(0xE0810000); // add r0,r1,r0
457 break;
458 case OP_MINUS:
459 o4(0xE0410000); // sub r0,r1,r0
460 break;
461 case OP_SHIFT_LEFT:
462 o4(0xE1A00011); // lsl r0,r1,r0
463 break;
464 case OP_SHIFT_RIGHT:
465 o4(0xE1A00051); // asr r0,r1,r0
466 break;
467 case OP_BIT_AND:
468 o4(0xE0010000); // and r0,r1,r0
469 break;
470 case OP_BIT_XOR:
471 o4(0xE0210000); // eor r0,r1,r0
472 break;
473 case OP_BIT_OR:
474 o4(0xE1810000); // orr r0,r1,r0
475 break;
476 case OP_BIT_NOT:
477 o4(0xE1E00000); // mvn r0, r0
478 break;
479 default:
Jack Palevich69796b62009-05-14 15:42:26 -0700480 error("Unimplemented op %d\n", op);
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700481 break;
482 }
Jack Palevich22305132009-05-13 10:58:45 -0700483#if 0
484 o(decodeOp(op));
485 if (op == OP_MOD)
486 o(0x92); /* xchg %edx, %eax */
487#endif
488 }
489
Jack Palevich1cdef202009-05-22 12:06:27 -0700490 virtual void clearR1() {
Jack Palevich09555c72009-05-27 12:25:55 -0700491 LOG_API("clearR1();\n");
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700492 o4(0xE3A01000); // mov r1, #0
Jack Palevich22305132009-05-13 10:58:45 -0700493 }
494
Jack Palevich1cdef202009-05-22 12:06:27 -0700495 virtual void pushR0() {
Jack Palevich09555c72009-05-27 12:25:55 -0700496 LOG_API("pushR0();\n");
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700497 o4(0xE92D0001); // stmfd sp!,{r0}
Jack Palevich22305132009-05-13 10:58:45 -0700498 }
499
Jack Palevich1cdef202009-05-22 12:06:27 -0700500 virtual void popR1() {
Jack Palevich09555c72009-05-27 12:25:55 -0700501 LOG_API("popR1();\n");
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700502 o4(0xE8BD0002); // ldmfd sp!,{r1}
Jack Palevich22305132009-05-13 10:58:45 -0700503 }
504
Jack Palevich1cdef202009-05-22 12:06:27 -0700505 virtual void storeR0ToR1(bool isInt) {
Jack Palevich09555c72009-05-27 12:25:55 -0700506 LOG_API("storeR0ToR1(%d);\n", isInt);
Jack Palevichbd894902009-05-14 19:35:31 -0700507 if (isInt) {
508 o4(0xE5810000); // str r0, [r1]
509 } else {
510 o4(0xE5C10000); // strb r0, [r1]
511 }
Jack Palevich22305132009-05-13 10:58:45 -0700512 }
513
Jack Palevich1cdef202009-05-22 12:06:27 -0700514 virtual void loadR0FromR0(bool isInt) {
Jack Palevich09555c72009-05-27 12:25:55 -0700515 LOG_API("loadR0FromR0(%d);\n", isInt);
Jack Palevich22305132009-05-13 10:58:45 -0700516 if (isInt)
Jack Palevich69796b62009-05-14 15:42:26 -0700517 o4(0xE5900000); // ldr r0, [r0]
Jack Palevich22305132009-05-13 10:58:45 -0700518 else
Jack Palevich69796b62009-05-14 15:42:26 -0700519 o4(0xE5D00000); // ldrb r0, [r0]
Jack Palevich22305132009-05-13 10:58:45 -0700520 }
521
Jack Palevich1cdef202009-05-22 12:06:27 -0700522 virtual void leaR0(int ea) {
Jack Palevich09555c72009-05-27 12:25:55 -0700523 LOG_API("leaR0(%d);\n", ea);
Jack Palevich4d93f302009-05-15 13:30:00 -0700524 if (ea < LOCAL) {
525 // Local, fp relative
526 if (ea < -1023 || ea > 1023 || ((ea & 3) != 0)) {
527 error("Offset out of range: %08x", ea);
528 }
529 if (ea < 0) {
530 o4(0xE24B0F00 | (0xff & ((-ea) >> 2))); // sub r0, fp, #ea
531 } else {
532 o4(0xE28B0F00 | (0xff & (ea >> 2))); // add r0, fp, #ea
533 }
Jack Palevichbd894902009-05-14 19:35:31 -0700534 } else {
Jack Palevich4d93f302009-05-15 13:30:00 -0700535 // Global, absolute.
536 o4(0xE59F0000); // ldr r0, .L1
537 o4(0xEA000000); // b .L99
538 o4(ea); // .L1: .word 0
539 // .L99:
Jack Palevichbd894902009-05-14 19:35:31 -0700540 }
Jack Palevich22305132009-05-13 10:58:45 -0700541 }
542
Jack Palevich1cdef202009-05-22 12:06:27 -0700543 virtual void storeR0(int ea) {
Jack Palevich09555c72009-05-27 12:25:55 -0700544 LOG_API("storeR0(%d);\n", ea);
Jack Palevich4d93f302009-05-15 13:30:00 -0700545 if (ea < LOCAL) {
546 // Local, fp relative
547 if (ea < -4095 || ea > 4095) {
548 error("Offset out of range: %08x", ea);
549 }
550 if (ea < 0) {
551 o4(0xE50B0000 | (0xfff & (-ea))); // str r0, [fp,#-ea]
552 } else {
553 o4(0xE58B0000 | (0xfff & ea)); // str r0, [fp,#ea]
554 }
555 } else{
556 // Global, absolute
557 o4(0xE59F1000); // ldr r1, .L1
558 o4(0xEA000000); // b .L99
559 o4(ea); // .L1: .word 0
560 o4(0xE5810000); // .L99: str r0, [r1]
Jack Palevich69796b62009-05-14 15:42:26 -0700561 }
Jack Palevich22305132009-05-13 10:58:45 -0700562 }
563
Jack Palevich1cdef202009-05-22 12:06:27 -0700564 virtual void loadR0(int ea, bool isIncDec, int op) {
Jack Palevich09555c72009-05-27 12:25:55 -0700565 LOG_API("loadR0(%d, %d, %d);\n", ea, isIncDec, op);
Jack Palevich4d93f302009-05-15 13:30:00 -0700566 if (ea < LOCAL) {
567 // Local, fp relative
568 if (ea < -4095 || ea > 4095) {
569 error("Offset out of range: %08x", ea);
570 }
571 if (ea < 0) {
572 o4(0xE51B0000 | (0xfff & (-ea))); // ldr r0, [fp,#-ea]
573 } else {
574 o4(0xE59B0000 | (0xfff & ea)); // ldr r0, [fp,#ea]
575 }
Jack Palevich69796b62009-05-14 15:42:26 -0700576 } else {
Jack Palevich4d93f302009-05-15 13:30:00 -0700577 // Global, absolute
578 o4(0xE59F2000); // ldr r2, .L1
579 o4(0xEA000000); // b .L99
580 o4(ea); // .L1: .word ea
581 o4(0xE5920000); // .L99: ldr r0, [r2]
Jack Palevich69796b62009-05-14 15:42:26 -0700582 }
Jack Palevich22305132009-05-13 10:58:45 -0700583
Jack Palevich4d93f302009-05-15 13:30:00 -0700584 if (isIncDec) {
585 switch (op) {
586 case OP_INCREMENT:
587 o4(0xE2801001); // add r1, r0, #1
588 break;
589 case OP_DECREMENT:
590 o4(0xE2401001); // sub r1, r0, #1
591 break;
592 default:
593 error("unknown opcode: %d", op);
594 }
595 if (ea < LOCAL) {
596 // Local, fp relative
597 // Don't need range check, was already checked above
598 if (ea < 0) {
599 o4(0xE50B1000 | (0xfff & (-ea))); // str r1, [fp,#-ea]
600 } else {
601 o4(0xE58B1000 | (0xfff & ea)); // str r1, [fp,#ea]
602 }
603 } else{
604 // Global, absolute
605 // r2 is already set up from before.
606 o4(0xE5821000); // str r1, [r2]
607 }
Jack Palevichbd894902009-05-14 19:35:31 -0700608 }
Jack Palevich22305132009-05-13 10:58:45 -0700609 }
610
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700611 virtual int beginFunctionCallArguments() {
Jack Palevich09555c72009-05-27 12:25:55 -0700612 LOG_API("beginFunctionCallArguments();\n");
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700613 return o4(0xE24DDF00); // Placeholder
614 }
615
Jack Palevich1cdef202009-05-22 12:06:27 -0700616 virtual void storeR0ToArg(int l) {
Jack Palevich09555c72009-05-27 12:25:55 -0700617 LOG_API("storeR0ToArg(%d);\n", l);
Jack Palevich7810bc92009-05-15 14:31:47 -0700618 if (l < 0 || l > 4096-4) {
619 error("l out of range for stack offset: 0x%08x", l);
620 }
621 o4(0xE58D0000 + l); // str r0, [sp, #4]
622 }
623
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700624 virtual void endFunctionCallArguments(int a, int l) {
Jack Palevich09555c72009-05-27 12:25:55 -0700625 LOG_API("endFunctionCallArguments(0x%08x, %d);\n", a, l);
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700626 if (l < 0 || l > 0x3FC) {
627 error("L out of range for stack adjustment: 0x%08x", l);
628 }
629 * (int*) a = 0xE24DDF00 | (l >> 2); // sub sp, sp, #0 << 2
630 int argCount = l >> 2;
631 if (argCount > 0) {
632 int regArgCount = argCount > 4 ? 4 : argCount;
633 o4(0xE8BD0000 | ((1 << regArgCount) - 1)); // ldmfd sp!,{}
634 }
Jack Palevich22305132009-05-13 10:58:45 -0700635 }
636
Jack Palevich22305132009-05-13 10:58:45 -0700637 virtual int callForward(int symbol) {
Jack Palevich09555c72009-05-27 12:25:55 -0700638 LOG_API("callForward(%d);\n", symbol);
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700639 // Forward calls are always short (local)
640 return o4(0xEB000000 | encodeAddress(symbol));
Jack Palevich22305132009-05-13 10:58:45 -0700641 }
642
643 virtual void callRelative(int t) {
Jack Palevich09555c72009-05-27 12:25:55 -0700644 LOG_API("callRelative(%d);\n", t);
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700645 int abs = t + getPC() + jumpOffset();
Jack Palevichbd894902009-05-14 19:35:31 -0700646 fprintf(stderr, "abs=%d (0x%08x)\n", abs, abs);
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700647 if (t >= - (1 << 25) && t < (1 << 25)) {
648 o4(0xEB000000 | encodeAddress(t));
649 } else {
650 // Long call.
651 o4(0xE59FC000); // ldr r12, .L1
652 o4(0xEA000000); // b .L99
Jack Palevichbd894902009-05-14 19:35:31 -0700653 o4(t - 12); // .L1: .word 0
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700654 o4(0xE08CC00F); // .L99: add r12,pc
655 o4(0xE12FFF3C); // blx r12
656 }
Jack Palevich22305132009-05-13 10:58:45 -0700657 }
658
659 virtual void callIndirect(int l) {
Jack Palevich09555c72009-05-27 12:25:55 -0700660 LOG_API("callIndirect(%d);\n", l);
Jack Palevich7810bc92009-05-15 14:31:47 -0700661 int argCount = l >> 2;
662 int poppedArgs = argCount > 4 ? 4 : argCount;
663 int adjustedL = l - (poppedArgs << 2);
664 if (adjustedL < 0 || adjustedL > 4096-4) {
665 error("l out of range for stack offset: 0x%08x", l);
666 }
667 o4(0xE59DC000 | (0xfff & adjustedL)); // ldr r12, [sp,#adjustedL]
668 o4(0xE12FFF3C); // blx r12
Jack Palevich22305132009-05-13 10:58:45 -0700669 }
670
Jack Palevich7810bc92009-05-15 14:31:47 -0700671 virtual void adjustStackAfterCall(int l, bool isIndirect) {
Jack Palevich09555c72009-05-27 12:25:55 -0700672 LOG_API("adjustStackAfterCall(%d, %d);\n", l, isIndirect);
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700673 int argCount = l >> 2;
Jack Palevich7810bc92009-05-15 14:31:47 -0700674 int stackArgs = argCount > 4 ? argCount - 4 : 0;
675 int stackUse = stackArgs + (isIndirect ? 1 : 0);
676 if (stackUse) {
677 if (stackUse < 0 || stackUse > 255) {
678 error("L out of range for stack adjustment: 0x%08x", l);
679 }
680 o4(0xE28DDF00 | stackUse); // add sp, sp, #stackUse << 2
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700681 }
Jack Palevich22305132009-05-13 10:58:45 -0700682 }
683
Jack Palevicha6535612009-05-13 16:24:17 -0700684 virtual int jumpOffset() {
Jack Palevichbd894902009-05-14 19:35:31 -0700685 return 8;
Jack Palevicha6535612009-05-13 16:24:17 -0700686 }
687
688 /* output a symbol and patch all calls to it */
689 virtual void gsym(int t) {
Jack Palevich09555c72009-05-27 12:25:55 -0700690 LOG_API("gsym(0x%x)\n", t);
Jack Palevicha6535612009-05-13 16:24:17 -0700691 int n;
692 int base = getBase();
693 int pc = getPC();
Jack Palevich09555c72009-05-27 12:25:55 -0700694 LOG_API("pc = 0x%x\n", pc);
Jack Palevicha6535612009-05-13 16:24:17 -0700695 while (t) {
696 int data = * (int*) t;
697 int decodedOffset = ((BRANCH_REL_ADDRESS_MASK & data) << 2);
698 if (decodedOffset == 0) {
699 n = 0;
700 } else {
701 n = base + decodedOffset; /* next value */
702 }
703 *(int *) t = (data & ~BRANCH_REL_ADDRESS_MASK)
704 | encodeRelAddress(pc - t - 8);
705 t = n;
706 }
707 }
708
Jack Palevich1cdef202009-05-22 12:06:27 -0700709 virtual int finishCompile() {
710#if defined(__arm__)
711 const long base = long(getBase());
712 const long curr = long(getPC());
713 int err = cacheflush(base, curr, 0);
714 return err;
715#else
716 return 0;
717#endif
718 }
719
Jack Palevicha6535612009-05-13 16:24:17 -0700720 virtual int disassemble(FILE* out) {
Jack Palevich09555c72009-05-27 12:25:55 -0700721#ifdef ENABLE_ARM_DISASSEMBLY
722 disasmOut = out;
Jack Palevicha6535612009-05-13 16:24:17 -0700723 disasm_interface_t di;
724 di.di_readword = disassemble_readword;
725 di.di_printaddr = disassemble_printaddr;
726 di.di_printf = disassemble_printf;
727
728 int base = getBase();
729 int pc = getPC();
730 for(int i = base; i < pc; i += 4) {
731 fprintf(out, "%08x: %08x ", i, *(int*) i);
732 ::disasm(&di, i, 0);
733 }
Jack Palevich09555c72009-05-27 12:25:55 -0700734#endif
Jack Palevicha6535612009-05-13 16:24:17 -0700735 return 0;
736 }
Jack Palevich7810bc92009-05-15 14:31:47 -0700737
Jack Palevich22305132009-05-13 10:58:45 -0700738 private:
Jack Palevicha6535612009-05-13 16:24:17 -0700739 static FILE* disasmOut;
740
741 static u_int
742 disassemble_readword(u_int address)
743 {
744 return(*((u_int *)address));
745 }
746
747 static void
748 disassemble_printaddr(u_int address)
749 {
750 fprintf(disasmOut, "0x%08x", address);
751 }
752
753 static void
754 disassemble_printf(const char *fmt, ...) {
755 va_list ap;
756 va_start(ap, fmt);
757 vfprintf(disasmOut, fmt, ap);
758 va_end(ap);
759 }
760
761 static const int BRANCH_REL_ADDRESS_MASK = 0x00ffffff;
762
763 /** Encode a relative address that might also be
764 * a label.
765 */
766 int encodeAddress(int value) {
767 int base = getBase();
768 if (value >= base && value <= getPC() ) {
769 // This is a label, encode it relative to the base.
770 value = value - base;
771 }
772 return encodeRelAddress(value);
773 }
774
775 int encodeRelAddress(int value) {
776 return BRANCH_REL_ADDRESS_MASK & (value >> 2);
777 }
Jack Palevich22305132009-05-13 10:58:45 -0700778
Jack Palevich3d474a72009-05-15 15:12:38 -0700779 typedef int (*int2FnPtr)(int a, int b);
780 void callRuntime(int2FnPtr fn) {
781 o4(0xE59F2000); // ldr r2, .L1
782 o4(0xEA000000); // b .L99
783 o4((int) fn); //.L1: .word fn
784 o4(0xE12FFF32); //.L99: blx r2
785 }
786
787 static int runtime_DIV(int a, int b) {
788 return b / a;
789 }
790
791 static int runtime_MOD(int a, int b) {
792 return b % a;
793 }
794
Jack Palevich546b2242009-05-13 15:10:04 -0700795 void error(const char* fmt,...) {
796 va_list ap;
797 va_start(ap, fmt);
798 vfprintf(stderr, fmt, ap);
799 va_end(ap);
800 exit(12);
801 }
Jack Palevich22305132009-05-13 10:58:45 -0700802 };
803
Jack Palevich09555c72009-05-27 12:25:55 -0700804#endif // PROVIDE_ARM_CODEGEN
Jack Paleviche7b59062009-05-19 17:12:17 -0700805
806#ifdef PROVIDE_X86_CODEGEN
807
Jack Palevich21a15a22009-05-11 14:49:29 -0700808 class X86CodeGenerator : public CodeGenerator {
809 public:
810 X86CodeGenerator() {}
811 virtual ~X86CodeGenerator() {}
812
Jack Palevichbf42c9c2009-05-12 12:48:35 -0700813 /* returns address to patch with local variable size
814 */
Jack Palevich546b2242009-05-13 15:10:04 -0700815 virtual int functionEntry(int argCount) {
Jack Palevichbf42c9c2009-05-12 12:48:35 -0700816 o(0xe58955); /* push %ebp, mov %esp, %ebp */
817 return oad(0xec81, 0); /* sub $xxx, %esp */
818 }
819
Jack Palevich546b2242009-05-13 15:10:04 -0700820 virtual void functionExit(int argCount, int localVariableAddress, int localVariableSize) {
Jack Palevichbf42c9c2009-05-12 12:48:35 -0700821 o(0xc3c9); /* leave, ret */
Jack Palevich546b2242009-05-13 15:10:04 -0700822 *(int *) localVariableAddress = localVariableSize; /* save local variables */
Jack Palevichbf42c9c2009-05-12 12:48:35 -0700823 }
824
Jack Palevich21a15a22009-05-11 14:49:29 -0700825 /* load immediate value */
Jack Palevich546b2242009-05-13 15:10:04 -0700826 virtual void li(int t) {
Jack Palevich21a15a22009-05-11 14:49:29 -0700827 oad(0xb8, t); /* mov $xx, %eax */
828 }
829
Jack Palevich22305132009-05-13 10:58:45 -0700830 virtual int gjmp(int t) {
Jack Palevich21a15a22009-05-11 14:49:29 -0700831 return psym(0xe9, t);
832 }
833
834 /* l = 0: je, l == 1: jne */
Jack Palevich22305132009-05-13 10:58:45 -0700835 virtual int gtst(bool l, int t) {
Jack Palevich21a15a22009-05-11 14:49:29 -0700836 o(0x0fc085); /* test %eax, %eax, je/jne xxx */
837 return psym(0x84 + l, t);
838 }
839
Jack Palevich22305132009-05-13 10:58:45 -0700840 virtual void gcmp(int op) {
Jack Palevichbf42c9c2009-05-12 12:48:35 -0700841 int t = decodeOp(op);
Jack Palevich21a15a22009-05-11 14:49:29 -0700842 o(0xc139); /* cmp %eax,%ecx */
843 li(0);
844 o(0x0f); /* setxx %al */
845 o(t + 0x90);
846 o(0xc0);
847 }
848
Jack Palevich546b2242009-05-13 15:10:04 -0700849 virtual void genOp(int op) {
Jack Palevichbf42c9c2009-05-12 12:48:35 -0700850 o(decodeOp(op));
851 if (op == OP_MOD)
852 o(0x92); /* xchg %edx, %eax */
853 }
854
Jack Palevich1cdef202009-05-22 12:06:27 -0700855 virtual void clearR1() {
Jack Palevich21a15a22009-05-11 14:49:29 -0700856 oad(0xb9, 0); /* movl $0, %ecx */
857 }
858
Jack Palevich1cdef202009-05-22 12:06:27 -0700859 virtual void pushR0() {
Jack Palevich21a15a22009-05-11 14:49:29 -0700860 o(0x50); /* push %eax */
861 }
862
Jack Palevich1cdef202009-05-22 12:06:27 -0700863 virtual void popR1() {
Jack Palevich21a15a22009-05-11 14:49:29 -0700864 o(0x59); /* pop %ecx */
Jack Palevichbf42c9c2009-05-12 12:48:35 -0700865 }
866
Jack Palevich1cdef202009-05-22 12:06:27 -0700867 virtual void storeR0ToR1(bool isInt) {
Jack Palevich21a15a22009-05-11 14:49:29 -0700868 o(0x0188 + isInt); /* movl %eax/%al, (%ecx) */
869 }
870
Jack Palevich1cdef202009-05-22 12:06:27 -0700871 virtual void loadR0FromR0(bool isInt) {
Jack Palevich21a15a22009-05-11 14:49:29 -0700872 if (isInt)
873 o(0x8b); /* mov (%eax), %eax */
874 else
875 o(0xbe0f); /* movsbl (%eax), %eax */
876 ob(0); /* add zero in code */
877 }
878
Jack Palevich1cdef202009-05-22 12:06:27 -0700879 virtual void leaR0(int ea) {
Jack Palevich21a15a22009-05-11 14:49:29 -0700880 gmov(10, ea); /* leal EA, %eax */
881 }
882
Jack Palevich1cdef202009-05-22 12:06:27 -0700883 virtual void storeR0(int ea) {
Jack Palevich21a15a22009-05-11 14:49:29 -0700884 gmov(6, ea); /* mov %eax, EA */
885 }
886
Jack Palevich1cdef202009-05-22 12:06:27 -0700887 virtual void loadR0(int ea, bool isIncDec, int op) {
Jack Palevich21a15a22009-05-11 14:49:29 -0700888 gmov(8, ea); /* mov EA, %eax */
Jack Palevich4d93f302009-05-15 13:30:00 -0700889 if (isIncDec) {
890 /* Implement post-increment or post decrement.
891 */
892 gmov(0, ea); /* 83 ADD */
893 o(decodeOp(op));
894 }
Jack Palevich21a15a22009-05-11 14:49:29 -0700895 }
896
Jack Palevichcb1c9ef2009-05-14 11:38:49 -0700897 virtual int beginFunctionCallArguments() {
Jack Palevich21a15a22009-05-11 14:49:29 -0700898 return oad(0xec81, 0); /* sub $xxx, %esp */
899 }
900
Jack Palevich1cdef202009-05-22 12:06:27 -0700901 virtual void storeR0ToArg(int l) {
Jack Palevich21a15a22009-05-11 14:49:29 -0700902 oad(0x248489, l); /* movl %eax, xxx(%esp) */
903 }
904
Jack Palevich7810bc92009-05-15 14:31:47 -0700905 virtual void endFunctionCallArguments(int a, int l) {
906 * (int*) a = l;
907 }
908
Jack Palevich22305132009-05-13 10:58:45 -0700909 virtual int callForward(int symbol) {
Jack Palevich21a15a22009-05-11 14:49:29 -0700910 return psym(0xe8, symbol); /* call xxx */
911 }
912
Jack Palevich22305132009-05-13 10:58:45 -0700913 virtual void callRelative(int t) {
Jack Palevich21a15a22009-05-11 14:49:29 -0700914 psym(0xe8, t); /* call xxx */
915 }
916
Jack Palevich22305132009-05-13 10:58:45 -0700917 virtual void callIndirect(int l) {
Jack Palevich21a15a22009-05-11 14:49:29 -0700918 oad(0x2494ff, l); /* call *xxx(%esp) */
919 }
920
Jack Palevich7810bc92009-05-15 14:31:47 -0700921 virtual void adjustStackAfterCall(int l, bool isIndirect) {
922 if (isIndirect) {
923 l += 4;
924 }
Jack Palevich21a15a22009-05-11 14:49:29 -0700925 oad(0xc481, l); /* add $xxx, %esp */
926 }
927
Jack Palevicha6535612009-05-13 16:24:17 -0700928 virtual int jumpOffset() {
929 return 5;
930 }
931
932 virtual int disassemble(FILE* out) {
Jack Palevich1cdef202009-05-22 12:06:27 -0700933 return 0;
Jack Palevicha6535612009-05-13 16:24:17 -0700934 }
935
Jack Paleviche7b59062009-05-19 17:12:17 -0700936 /* output a symbol and patch all calls to it */
937 virtual void gsym(int t) {
938 int n;
939 int pc = getPC();
940 while (t) {
941 n = *(int *) t; /* next value */
942 *(int *) t = pc - t - 4;
943 t = n;
944 }
945 }
946
Jack Palevich1cdef202009-05-22 12:06:27 -0700947 virtual int finishCompile() {
948 return 0;
949 }
950
Jack Palevich21a15a22009-05-11 14:49:29 -0700951 private:
Jack Paleviche7b59062009-05-19 17:12:17 -0700952
953 /** Output 1 to 4 bytes.
954 *
955 */
956 void o(int n) {
957 /* cannot use unsigned, so we must do a hack */
958 while (n && n != -1) {
959 ob(n & 0xff);
960 n = n >> 8;
961 }
962 }
963
964 /* psym is used to put an instruction with a data field which is a
965 reference to a symbol. It is in fact the same as oad ! */
966 int psym(int n, int t) {
967 return oad(n, t);
968 }
969
970 /* instruction + address */
971 int oad(int n, int t) {
972 o(n);
973 int result = getPC();
974 o4(t);
975 return result;
976 }
977
978
Jack Palevichbf42c9c2009-05-12 12:48:35 -0700979 static const int operatorHelper[];
980
981 int decodeOp(int op) {
982 if (op < 0 || op > OP_COUNT) {
983 fprintf(stderr, "Out-of-range operator: %d\n", op);
984 exit(1);
985 }
986 return operatorHelper[op];
987 }
Jack Palevich21a15a22009-05-11 14:49:29 -0700988
Jack Palevich546b2242009-05-13 15:10:04 -0700989 void gmov(int l, int t) {
Jack Palevich21a15a22009-05-11 14:49:29 -0700990 o(l + 0x83);
991 oad((t < LOCAL) << 7 | 5, t);
992 }
993 };
994
Jack Paleviche7b59062009-05-19 17:12:17 -0700995#endif // PROVIDE_X86_CODEGEN
996
Jack Palevich1cdef202009-05-22 12:06:27 -0700997 class InputStream {
998 public:
999 virtual int get() = 0;
1000 virtual long tell() = 0;
1001 };
1002
1003 class FileInputStream : public InputStream {
1004 public:
1005 FileInputStream(FILE* in) : f(in) {}
1006 virtual int get() { return fgetc(f); }
1007 virtual long tell() { return ftell(f); }
1008 private:
1009 FILE* f;
1010 };
1011
1012 class TextInputStream : public InputStream {
1013 public:
1014 TextInputStream(const char* text, size_t textLength)
1015 : pText(text), mTextLength(textLength), mPosition(0) {
1016 }
1017 virtual int get() {
1018 return mPosition < mTextLength ? pText[mPosition++] : EOF;
1019 }
1020 virtual long tell() {
1021 return mPosition;
1022 }
1023
1024 private:
1025 const char* pText;
1026 size_t mTextLength;
1027 size_t mPosition;
1028 };
1029
Jack Palevich21a15a22009-05-11 14:49:29 -07001030 /* vars: value of variables
1031 loc : local variable index
1032 glo : global variable index
1033 ind : output code ptr
1034 rsym: return symbol
1035 prog: output code
1036 dstk: define stack
1037 dptr, dch: macro state
1038 */
Jack Palevich8b0624c2009-05-20 12:12:06 -07001039 intptr_t tok, tokc, tokl, ch, vars, rsym, loc, glo, sym_stk, dstk,
Jack Palevich21a15a22009-05-11 14:49:29 -07001040 dptr, dch, last_id;
1041 void* pSymbolBase;
1042 void* pGlobalBase;
1043 void* pVarsBase;
Jack Palevich1cdef202009-05-22 12:06:27 -07001044
1045 InputStream* file;
Jack Palevich21a15a22009-05-11 14:49:29 -07001046
1047 CodeBuf codeBuf;
Jack Palevich22305132009-05-13 10:58:45 -07001048 CodeGenerator* pGen;
Jack Palevich21a15a22009-05-11 14:49:29 -07001049
1050 static const int ALLOC_SIZE = 99999;
1051
1052 /* depends on the init string */
1053 static const int TOK_STR_SIZE = 48;
1054 static const int TOK_IDENT = 0x100;
1055 static const int TOK_INT = 0x100;
1056 static const int TOK_IF = 0x120;
1057 static const int TOK_ELSE = 0x138;
1058 static const int TOK_WHILE = 0x160;
1059 static const int TOK_BREAK = 0x190;
1060 static const int TOK_RETURN = 0x1c0;
1061 static const int TOK_FOR = 0x1f8;
1062 static const int TOK_DEFINE = 0x218;
1063 static const int TOK_MAIN = 0x250;
1064
1065 static const int TOK_DUMMY = 1;
1066 static const int TOK_NUM = 2;
1067
1068 static const int LOCAL = 0x200;
1069
1070 static const int SYM_FORWARD = 0;
1071 static const int SYM_DEFINE = 1;
1072
1073 /* tokens in string heap */
1074 static const int TAG_TOK = ' ';
1075 static const int TAG_MACRO = 2;
1076
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001077 static const int OP_INCREMENT = 0;
1078 static const int OP_DECREMENT = 1;
1079 static const int OP_MUL = 2;
1080 static const int OP_DIV = 3;
1081 static const int OP_MOD = 4;
1082 static const int OP_PLUS = 5;
1083 static const int OP_MINUS = 6;
1084 static const int OP_SHIFT_LEFT = 7;
1085 static const int OP_SHIFT_RIGHT = 8;
1086 static const int OP_LESS_EQUAL = 9;
1087 static const int OP_GREATER_EQUAL = 10;
1088 static const int OP_LESS = 11;
1089 static const int OP_GREATER = 12;
1090 static const int OP_EQUALS = 13;
1091 static const int OP_NOT_EQUALS = 14;
1092 static const int OP_LOGICAL_AND = 15;
1093 static const int OP_LOGICAL_OR = 16;
1094 static const int OP_BIT_AND = 17;
1095 static const int OP_BIT_XOR = 18;
1096 static const int OP_BIT_OR = 19;
1097 static const int OP_BIT_NOT = 20;
1098 static const int OP_LOGICAL_NOT = 21;
1099 static const int OP_COUNT = 22;
1100
1101 /* Operators are searched from front, the two-character operators appear
1102 * before the single-character operators with the same first character.
1103 * @ is used to pad out single-character operators.
1104 */
1105 static const char* operatorChars;
1106 static const char operatorLevel[];
1107
Jack Palevich21a15a22009-05-11 14:49:29 -07001108 void pdef(int t) {
1109 *(char *) dstk++ = t;
1110 }
1111
1112 void inp() {
1113 if (dptr) {
1114 ch = *(char *) dptr++;
1115 if (ch == TAG_MACRO) {
1116 dptr = 0;
1117 ch = dch;
1118 }
1119 } else
Jack Palevich1cdef202009-05-22 12:06:27 -07001120 ch = file->get();
Jack Palevich21a15a22009-05-11 14:49:29 -07001121 /* printf("ch=%c 0x%x\n", ch, ch); */
1122 }
1123
1124 int isid() {
Jack Palevich546b2242009-05-13 15:10:04 -07001125 return isalnum(ch) | (ch == '_');
Jack Palevich21a15a22009-05-11 14:49:29 -07001126 }
1127
1128 /* read a character constant */
1129 void getq() {
1130 if (ch == '\\') {
1131 inp();
1132 if (ch == 'n')
1133 ch = '\n';
1134 }
1135 }
1136
1137 void next() {
1138 int l, a;
1139
Jack Palevich546b2242009-05-13 15:10:04 -07001140 while (isspace(ch) | (ch == '#')) {
Jack Palevich21a15a22009-05-11 14:49:29 -07001141 if (ch == '#') {
1142 inp();
1143 next();
1144 if (tok == TOK_DEFINE) {
1145 next();
1146 pdef(TAG_TOK); /* fill last ident tag */
1147 *(int *) tok = SYM_DEFINE;
1148 *(int *) (tok + 4) = dstk; /* define stack */
1149 }
1150 /* well we always save the values ! */
1151 while (ch != '\n') {
1152 pdef(ch);
1153 inp();
1154 }
1155 pdef(ch);
1156 pdef(TAG_MACRO);
1157 }
1158 inp();
1159 }
1160 tokl = 0;
1161 tok = ch;
1162 /* encode identifiers & numbers */
1163 if (isid()) {
1164 pdef(TAG_TOK);
1165 last_id = dstk;
1166 while (isid()) {
Jack Paleviche27bf3e2009-05-10 14:09:03 -07001167 pdef(ch);
1168 inp();
Jack Palevichae54f1f2009-05-08 14:54:15 -07001169 }
Jack Palevich21a15a22009-05-11 14:49:29 -07001170 if (isdigit(tok)) {
1171 tokc = strtol((char*) last_id, 0, 0);
1172 tok = TOK_NUM;
Jack Paleviche27bf3e2009-05-10 14:09:03 -07001173 } else {
Jack Palevich21a15a22009-05-11 14:49:29 -07001174 *(char *) dstk = TAG_TOK; /* no need to mark end of string (we
1175 suppose data is initialized to zero by calloc) */
Jack Palevich8b0624c2009-05-20 12:12:06 -07001176 tok = (intptr_t) (strstr((char*) sym_stk, (char*) (last_id - 1))
Jack Palevich21a15a22009-05-11 14:49:29 -07001177 - sym_stk);
1178 *(char *) dstk = 0; /* mark real end of ident for dlsym() */
1179 tok = tok * 8 + TOK_IDENT;
1180 if (tok > TOK_DEFINE) {
1181 tok = vars + tok;
1182 /* printf("tok=%s %x\n", last_id, tok); */
1183 /* define handling */
1184 if (*(int *) tok == SYM_DEFINE) {
1185 dptr = *(int *) (tok + 4);
1186 dch = ch;
1187 inp();
1188 next();
1189 }
Jack Paleviche27bf3e2009-05-10 14:09:03 -07001190 }
1191 }
Jack Paleviche27bf3e2009-05-10 14:09:03 -07001192 } else {
Jack Palevich21a15a22009-05-11 14:49:29 -07001193 inp();
1194 if (tok == '\'') {
1195 tok = TOK_NUM;
1196 getq();
1197 tokc = ch;
1198 inp();
1199 inp();
Jack Palevich546b2242009-05-13 15:10:04 -07001200 } else if ((tok == '/') & (ch == '*')) {
Jack Palevich21a15a22009-05-11 14:49:29 -07001201 inp();
1202 while (ch) {
1203 while (ch != '*')
1204 inp();
1205 inp();
1206 if (ch == '/')
1207 ch = 0;
Jack Paleviche27bf3e2009-05-10 14:09:03 -07001208 }
Jack Palevich21a15a22009-05-11 14:49:29 -07001209 inp();
Jack Paleviche27bf3e2009-05-10 14:09:03 -07001210 next();
Jack Palevichbd894902009-05-14 19:35:31 -07001211 } else if ((tok == '/') & (ch == '/')) {
1212 inp();
1213 while (ch && (ch != '\n')) {
1214 inp();
1215 }
1216 inp();
1217 next();
Jack Palevich21a15a22009-05-11 14:49:29 -07001218 } else {
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001219 const char* t = operatorChars;
1220 int opIndex = 0;
Jack Palevich546b2242009-05-13 15:10:04 -07001221 while ((l = *t++) != 0) {
Jack Palevich21a15a22009-05-11 14:49:29 -07001222 a = *t++;
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001223 tokl = operatorLevel[opIndex];
1224 tokc = opIndex;
Jack Palevich546b2242009-05-13 15:10:04 -07001225 if ((l == tok) & ((a == ch) | (a == '@'))) {
Jack Palevich21a15a22009-05-11 14:49:29 -07001226#if 0
1227 printf("%c%c -> tokl=%d tokc=0x%x\n",
1228 l, a, tokl, tokc);
1229#endif
1230 if (a == ch) {
1231 inp();
1232 tok = TOK_DUMMY; /* dummy token for double tokens */
1233 }
1234 break;
1235 }
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001236 opIndex++;
1237 }
1238 if (l == 0) {
1239 tokl = 0;
1240 tokc = 0;
Jack Palevich21a15a22009-05-11 14:49:29 -07001241 }
1242 }
1243 }
1244#if 0
1245 {
1246 int p;
1247
1248 printf("tok=0x%x ", tok);
1249 if (tok >= TOK_IDENT) {
1250 printf("'");
1251 if (tok> TOK_DEFINE)
1252 p = sym_stk + 1 + (tok - vars - TOK_IDENT) / 8;
1253 else
1254 p = sym_stk + 1 + (tok - TOK_IDENT) / 8;
1255 while (*(char *)p != TAG_TOK && *(char *)p)
1256 printf("%c", *(char *)p++);
1257 printf("'\n");
1258 } else if (tok == TOK_NUM) {
1259 printf("%d\n", tokc);
1260 } else {
1261 printf("'%c'\n", tok);
1262 }
1263 }
1264#endif
1265 }
1266
1267 void error(const char *fmt, ...) {
1268 va_list ap;
1269
1270 va_start(ap, fmt);
Jack Palevich1cdef202009-05-22 12:06:27 -07001271 fprintf(stderr, "%ld: ", file->tell());
Jack Palevich21a15a22009-05-11 14:49:29 -07001272 vfprintf(stderr, fmt, ap);
1273 fprintf(stderr, "\n");
1274 va_end(ap);
1275 exit(1);
1276 }
1277
Jack Palevich8b0624c2009-05-20 12:12:06 -07001278 void skip(intptr_t c) {
Jack Palevich21a15a22009-05-11 14:49:29 -07001279 if (tok != c) {
1280 error("'%c' expected", c);
1281 }
1282 next();
1283 }
1284
Jack Palevich21a15a22009-05-11 14:49:29 -07001285 /* l is one if '=' parsing wanted (quick hack) */
Jack Palevich8b0624c2009-05-20 12:12:06 -07001286 void unary(intptr_t l) {
1287 intptr_t n, t, a, c;
Jack Palevich546b2242009-05-13 15:10:04 -07001288 t = 0;
Jack Palevich21a15a22009-05-11 14:49:29 -07001289 n = 1; /* type of expression 0 = forward, 1 = value, other =
1290 lvalue */
1291 if (tok == '\"') {
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001292 pGen->li(glo);
Jack Palevich21a15a22009-05-11 14:49:29 -07001293 while (ch != '\"') {
1294 getq();
1295 *(char *) glo++ = ch;
1296 inp();
1297 }
1298 *(char *) glo = 0;
Jack Palevich546b2242009-05-13 15:10:04 -07001299 glo = (glo + 4) & -4; /* align heap */
Jack Palevich21a15a22009-05-11 14:49:29 -07001300 inp();
1301 next();
1302 } else {
1303 c = tokl;
1304 a = tokc;
1305 t = tok;
1306 next();
1307 if (t == TOK_NUM) {
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001308 pGen->li(a);
Jack Palevich21a15a22009-05-11 14:49:29 -07001309 } else if (c == 2) {
1310 /* -, +, !, ~ */
1311 unary(0);
Jack Palevich1cdef202009-05-22 12:06:27 -07001312 pGen->clearR1();
Jack Palevich21a15a22009-05-11 14:49:29 -07001313 if (t == '!')
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001314 pGen->gcmp(a);
Jack Palevich21a15a22009-05-11 14:49:29 -07001315 else
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001316 pGen->genOp(a);
Jack Palevich21a15a22009-05-11 14:49:29 -07001317 } else if (t == '(') {
1318 expr();
1319 skip(')');
1320 } else if (t == '*') {
1321 /* parse cast */
1322 skip('(');
1323 t = tok; /* get type */
1324 next(); /* skip int/char/void */
1325 next(); /* skip '*' or '(' */
1326 if (tok == '*') {
1327 /* function type */
1328 skip('*');
1329 skip(')');
1330 skip('(');
1331 skip(')');
1332 t = 0;
1333 }
1334 skip(')');
1335 unary(0);
1336 if (tok == '=') {
1337 next();
Jack Palevich1cdef202009-05-22 12:06:27 -07001338 pGen->pushR0();
Jack Palevich21a15a22009-05-11 14:49:29 -07001339 expr();
Jack Palevich1cdef202009-05-22 12:06:27 -07001340 pGen->popR1();
1341 pGen->storeR0ToR1(t == TOK_INT);
Jack Palevich21a15a22009-05-11 14:49:29 -07001342 } else if (t) {
Jack Palevich1cdef202009-05-22 12:06:27 -07001343 pGen->loadR0FromR0(t == TOK_INT);
Jack Palevich21a15a22009-05-11 14:49:29 -07001344 }
1345 } else if (t == '&') {
Jack Palevich1cdef202009-05-22 12:06:27 -07001346 pGen->leaR0(*(int *) tok);
Jack Palevich21a15a22009-05-11 14:49:29 -07001347 next();
1348 } else {
1349 n = *(int *) t;
1350 /* forward reference: try dlsym */
Jack Palevichcb1c9ef2009-05-14 11:38:49 -07001351 if (!n) {
Jack Palevich8b0624c2009-05-20 12:12:06 -07001352 n = (intptr_t) dlsym(RTLD_DEFAULT, (char*) last_id);
Jack Palevichcb1c9ef2009-05-14 11:38:49 -07001353 }
Jack Palevich546b2242009-05-13 15:10:04 -07001354 if ((tok == '=') & l) {
Jack Palevich21a15a22009-05-11 14:49:29 -07001355 /* assignment */
1356 next();
1357 expr();
Jack Palevich1cdef202009-05-22 12:06:27 -07001358 pGen->storeR0(n);
Jack Palevich21a15a22009-05-11 14:49:29 -07001359 } else if (tok != '(') {
1360 /* variable */
Jack Palevich1cdef202009-05-22 12:06:27 -07001361 pGen->loadR0(n, tokl == 11, tokc);
Jack Palevich21a15a22009-05-11 14:49:29 -07001362 if (tokl == 11) {
Jack Palevich21a15a22009-05-11 14:49:29 -07001363 next();
1364 }
1365 }
1366 }
1367 }
1368
1369 /* function call */
1370 if (tok == '(') {
1371 if (n == 1)
Jack Palevich1cdef202009-05-22 12:06:27 -07001372 pGen->pushR0();
Jack Palevich21a15a22009-05-11 14:49:29 -07001373
1374 /* push args and invert order */
Jack Palevichcb1c9ef2009-05-14 11:38:49 -07001375 a = pGen->beginFunctionCallArguments();
Jack Palevich21a15a22009-05-11 14:49:29 -07001376 next();
1377 l = 0;
1378 while (tok != ')') {
1379 expr();
Jack Palevich1cdef202009-05-22 12:06:27 -07001380 pGen->storeR0ToArg(l);
Jack Palevichbbf8ab52009-05-11 11:54:30 -07001381 if (tok == ',')
Jack Paleviche27bf3e2009-05-10 14:09:03 -07001382 next();
Jack Palevich21a15a22009-05-11 14:49:29 -07001383 l = l + 4;
Jack Paleviche27bf3e2009-05-10 14:09:03 -07001384 }
Jack Palevichcb1c9ef2009-05-14 11:38:49 -07001385 pGen->endFunctionCallArguments(a, l);
Jack Palevich21a15a22009-05-11 14:49:29 -07001386 next();
1387 if (!n) {
1388 /* forward reference */
1389 t = t + 4;
1390 *(int *) t = pGen->callForward(*(int *) t);
1391 } else if (n == 1) {
1392 pGen->callIndirect(l);
Jack Palevich21a15a22009-05-11 14:49:29 -07001393 } else {
Jack Palevich7810bc92009-05-15 14:31:47 -07001394 pGen->callRelative(n - codeBuf.getPC() - pGen->jumpOffset());
Jack Palevich21a15a22009-05-11 14:49:29 -07001395 }
Jack Palevich3d474a72009-05-15 15:12:38 -07001396 if (l | (n == 1))
Jack Palevich7810bc92009-05-15 14:31:47 -07001397 pGen->adjustStackAfterCall(l, n == 1);
Jack Palevich21a15a22009-05-11 14:49:29 -07001398 }
1399 }
1400
Jack Palevich8b0624c2009-05-20 12:12:06 -07001401 void sum(intptr_t l) {
1402 intptr_t t, n, a;
Jack Palevich546b2242009-05-13 15:10:04 -07001403 t = 0;
Jack Palevich21a15a22009-05-11 14:49:29 -07001404 if (l-- == 1)
1405 unary(1);
1406 else {
1407 sum(l);
1408 a = 0;
1409 while (l == tokl) {
1410 n = tok;
1411 t = tokc;
1412 next();
1413
1414 if (l > 8) {
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001415 a = pGen->gtst(t == OP_LOGICAL_OR, a); /* && and || output code generation */
Jack Palevich21a15a22009-05-11 14:49:29 -07001416 sum(l);
1417 } else {
Jack Palevich1cdef202009-05-22 12:06:27 -07001418 pGen->pushR0();
Jack Palevich21a15a22009-05-11 14:49:29 -07001419 sum(l);
Jack Palevich1cdef202009-05-22 12:06:27 -07001420 pGen->popR1();
Jack Palevich21a15a22009-05-11 14:49:29 -07001421
Jack Palevich546b2242009-05-13 15:10:04 -07001422 if ((l == 4) | (l == 5)) {
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001423 pGen->gcmp(t);
Jack Palevich21a15a22009-05-11 14:49:29 -07001424 } else {
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001425 pGen->genOp(t);
Jack Palevich21a15a22009-05-11 14:49:29 -07001426 }
1427 }
1428 }
1429 /* && and || output code generation */
1430 if (a && l > 8) {
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001431 a = pGen->gtst(t == OP_LOGICAL_OR, a);
1432 pGen->li(t != OP_LOGICAL_OR);
Jack Palevicha6535612009-05-13 16:24:17 -07001433 pGen->gjmp(5); /* jmp $ + 5 (sizeof li, FIXME for ARM) */
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001434 pGen->gsym(a);
1435 pGen->li(t == OP_LOGICAL_OR);
Jack Palevich21a15a22009-05-11 14:49:29 -07001436 }
1437 }
1438 }
1439
1440 void expr() {
1441 sum(11);
1442 }
1443
1444 int test_expr() {
1445 expr();
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001446 return pGen->gtst(0, 0);
Jack Palevich21a15a22009-05-11 14:49:29 -07001447 }
1448
Jack Palevich8b0624c2009-05-20 12:12:06 -07001449 void block(intptr_t l) {
1450 intptr_t a, n, t;
Jack Palevich21a15a22009-05-11 14:49:29 -07001451
1452 if (tok == TOK_IF) {
Jack Paleviche27bf3e2009-05-10 14:09:03 -07001453 next();
1454 skip('(');
Jack Palevich21a15a22009-05-11 14:49:29 -07001455 a = test_expr();
1456 skip(')');
1457 block(l);
1458 if (tok == TOK_ELSE) {
Jack Paleviche27bf3e2009-05-10 14:09:03 -07001459 next();
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001460 n = pGen->gjmp(0); /* jmp */
1461 pGen->gsym(a);
Jack Palevich21a15a22009-05-11 14:49:29 -07001462 block(l);
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001463 pGen->gsym(n); /* patch else jmp */
Jack Palevich21a15a22009-05-11 14:49:29 -07001464 } else {
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001465 pGen->gsym(a); /* patch if test */
Jack Paleviche27bf3e2009-05-10 14:09:03 -07001466 }
Jack Palevich546b2242009-05-13 15:10:04 -07001467 } else if ((tok == TOK_WHILE) | (tok == TOK_FOR)) {
Jack Palevich21a15a22009-05-11 14:49:29 -07001468 t = tok;
1469 next();
1470 skip('(');
1471 if (t == TOK_WHILE) {
Jack Palevicha6535612009-05-13 16:24:17 -07001472 n = codeBuf.getPC(); // top of loop, target of "next" iteration
Jack Palevich21a15a22009-05-11 14:49:29 -07001473 a = test_expr();
1474 } else {
1475 if (tok != ';')
1476 expr();
1477 skip(';');
1478 n = codeBuf.getPC();
1479 a = 0;
1480 if (tok != ';')
1481 a = test_expr();
1482 skip(';');
1483 if (tok != ')') {
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001484 t = pGen->gjmp(0);
Jack Palevich21a15a22009-05-11 14:49:29 -07001485 expr();
Jack Palevicha6535612009-05-13 16:24:17 -07001486 pGen->gjmp(n - codeBuf.getPC() - pGen->jumpOffset());
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001487 pGen->gsym(t);
Jack Palevich21a15a22009-05-11 14:49:29 -07001488 n = t + 4;
1489 }
1490 }
1491 skip(')');
Jack Palevich8b0624c2009-05-20 12:12:06 -07001492 block((intptr_t) &a);
Jack Palevicha6535612009-05-13 16:24:17 -07001493 pGen->gjmp(n - codeBuf.getPC() - pGen->jumpOffset()); /* jmp */
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001494 pGen->gsym(a);
Jack Palevich21a15a22009-05-11 14:49:29 -07001495 } else if (tok == '{') {
1496 next();
1497 /* declarations */
1498 decl(1);
1499 while (tok != '}')
1500 block(l);
1501 next();
1502 } else {
1503 if (tok == TOK_RETURN) {
1504 next();
1505 if (tok != ';')
1506 expr();
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001507 rsym = pGen->gjmp(rsym); /* jmp */
Jack Palevich21a15a22009-05-11 14:49:29 -07001508 } else if (tok == TOK_BREAK) {
1509 next();
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001510 *(int *) l = pGen->gjmp(*(int *) l);
Jack Palevich21a15a22009-05-11 14:49:29 -07001511 } else if (tok != ';')
1512 expr();
1513 skip(';');
Jack Paleviche27bf3e2009-05-10 14:09:03 -07001514 }
1515 }
Jack Palevich21a15a22009-05-11 14:49:29 -07001516
1517 /* 'l' is true if local declarations */
Jack Palevich8b0624c2009-05-20 12:12:06 -07001518 void decl(bool l) {
1519 intptr_t a;
Jack Palevich21a15a22009-05-11 14:49:29 -07001520
Jack Palevich546b2242009-05-13 15:10:04 -07001521 while ((tok == TOK_INT) | ((tok != -1) & (!l))) {
Jack Palevich21a15a22009-05-11 14:49:29 -07001522 if (tok == TOK_INT) {
1523 next();
1524 while (tok != ';') {
1525 if (l) {
1526 loc = loc + 4;
1527 *(int *) tok = -loc;
1528 } else {
1529 *(int *) tok = glo;
1530 glo = glo + 4;
1531 }
1532 next();
1533 if (tok == ',')
1534 next();
1535 }
1536 skip(';');
1537 } else {
1538 /* patch forward references (XXX: do not work for function
1539 pointers) */
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001540 pGen->gsym(*(int *) (tok + 4));
Jack Palevich21a15a22009-05-11 14:49:29 -07001541 /* put function address */
1542 *(int *) tok = codeBuf.getPC();
1543 next();
1544 skip('(');
1545 a = 8;
Jack Palevich546b2242009-05-13 15:10:04 -07001546 int argCount = 0;
Jack Palevich21a15a22009-05-11 14:49:29 -07001547 while (tok != ')') {
1548 /* read param name and compute offset */
1549 *(int *) tok = a;
1550 a = a + 4;
1551 next();
1552 if (tok == ',')
1553 next();
Jack Palevich546b2242009-05-13 15:10:04 -07001554 argCount++;
Jack Palevich21a15a22009-05-11 14:49:29 -07001555 }
1556 next(); /* skip ')' */
1557 rsym = loc = 0;
Jack Palevich546b2242009-05-13 15:10:04 -07001558 a = pGen->functionEntry(argCount);
Jack Palevich21a15a22009-05-11 14:49:29 -07001559 block(0);
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001560 pGen->gsym(rsym);
Jack Palevich546b2242009-05-13 15:10:04 -07001561 pGen->functionExit(argCount, a, loc);
Jack Palevich21a15a22009-05-11 14:49:29 -07001562 }
1563 }
1564 }
1565
1566 void cleanup() {
1567 if (sym_stk != 0) {
1568 free((void*) sym_stk);
1569 sym_stk = 0;
1570 }
1571 if (pGlobalBase != 0) {
1572 free((void*) pGlobalBase);
1573 pGlobalBase = 0;
1574 }
1575 if (pVarsBase != 0) {
1576 free(pVarsBase);
1577 pVarsBase = 0;
1578 }
1579 if (pGen) {
1580 delete pGen;
1581 pGen = 0;
1582 }
Jack Palevich1cdef202009-05-22 12:06:27 -07001583 if (file) {
1584 delete file;
1585 file = 0;
1586 }
Jack Palevich21a15a22009-05-11 14:49:29 -07001587 }
1588
1589 void clear() {
1590 tok = 0;
1591 tokc = 0;
1592 tokl = 0;
1593 ch = 0;
1594 vars = 0;
1595 rsym = 0;
1596 loc = 0;
1597 glo = 0;
1598 sym_stk = 0;
1599 dstk = 0;
1600 dptr = 0;
1601 dch = 0;
1602 last_id = 0;
1603 file = 0;
1604 pGlobalBase = 0;
1605 pVarsBase = 0;
1606 pGen = 0;
1607 }
Jack Paleviche27bf3e2009-05-10 14:09:03 -07001608
Jack Palevich22305132009-05-13 10:58:45 -07001609 void setArchitecture(const char* architecture) {
1610 delete pGen;
1611 pGen = 0;
1612
1613 if (architecture != NULL) {
Jack Paleviche7b59062009-05-19 17:12:17 -07001614#ifdef PROVIDE_ARM_CODEGEN
Jack Palevich8b0624c2009-05-20 12:12:06 -07001615 if (! pGen && strcmp(architecture, "arm") == 0) {
Jack Palevich22305132009-05-13 10:58:45 -07001616 pGen = new ARMCodeGenerator();
Jack Palevich8b0624c2009-05-20 12:12:06 -07001617 }
Jack Paleviche7b59062009-05-19 17:12:17 -07001618#endif
Jack Paleviche7b59062009-05-19 17:12:17 -07001619#ifdef PROVIDE_X86_CODEGEN
Jack Palevich8b0624c2009-05-20 12:12:06 -07001620 if (! pGen && strcmp(architecture, "x86") == 0) {
Jack Palevich22305132009-05-13 10:58:45 -07001621 pGen = new X86CodeGenerator();
Jack Palevich8b0624c2009-05-20 12:12:06 -07001622 }
Jack Paleviche7b59062009-05-19 17:12:17 -07001623#endif
Jack Palevich8b0624c2009-05-20 12:12:06 -07001624 if (!pGen ) {
1625 fprintf(stderr, "Unknown architecture %s\n", architecture);
Jack Palevich22305132009-05-13 10:58:45 -07001626 }
1627 }
1628
1629 if (pGen == NULL) {
Jack Paleviche7b59062009-05-19 17:12:17 -07001630#if defined(DEFAULT_ARM_CODEGEN)
Jack Palevich22305132009-05-13 10:58:45 -07001631 pGen = new ARMCodeGenerator();
Jack Paleviche7b59062009-05-19 17:12:17 -07001632#elif defined(DEFAULT_X86_CODEGEN)
1633 pGen = new X86CodeGenerator();
1634#endif
1635 }
1636 if (pGen == NULL) {
Jack Palevich1cdef202009-05-22 12:06:27 -07001637 fprintf(stderr, "No code generator defined.\n");
Jack Palevich22305132009-05-13 10:58:45 -07001638 }
1639 }
1640
Jack Palevich77ae76e2009-05-10 19:59:24 -07001641public:
Jack Palevich22305132009-05-13 10:58:45 -07001642 struct args {
1643 args() {
1644 architecture = 0;
1645 }
1646 const char* architecture;
1647 };
1648
Jack Paleviche7b59062009-05-19 17:12:17 -07001649 Compiler() {
Jack Palevich21a15a22009-05-11 14:49:29 -07001650 clear();
Jack Paleviche27bf3e2009-05-10 14:09:03 -07001651 }
Jack Palevichbbf8ab52009-05-11 11:54:30 -07001652
Jack Paleviche7b59062009-05-19 17:12:17 -07001653 ~Compiler() {
Jack Palevich21a15a22009-05-11 14:49:29 -07001654 cleanup();
1655 }
1656
Jack Palevich1cdef202009-05-22 12:06:27 -07001657 int compile(const char* text, size_t textLength) {
Jack Palevich21a15a22009-05-11 14:49:29 -07001658 cleanup();
1659 clear();
1660 codeBuf.init(ALLOC_SIZE);
Jack Palevich1cdef202009-05-22 12:06:27 -07001661 setArchitecture(NULL);
Jack Palevich8b0624c2009-05-20 12:12:06 -07001662 if (!pGen) {
1663 return -1;
1664 }
Jack Palevich21a15a22009-05-11 14:49:29 -07001665 pGen->init(&codeBuf);
Jack Palevich1cdef202009-05-22 12:06:27 -07001666 file = new TextInputStream(text, textLength);
Jack Palevich8b0624c2009-05-20 12:12:06 -07001667 sym_stk = (intptr_t) calloc(1, ALLOC_SIZE);
1668 dstk = (intptr_t) strcpy((char*) sym_stk,
Jack Palevich21a15a22009-05-11 14:49:29 -07001669 " int if else while break return for define main ")
1670 + TOK_STR_SIZE;
1671 pGlobalBase = calloc(1, ALLOC_SIZE);
Jack Palevich8b0624c2009-05-20 12:12:06 -07001672 glo = (intptr_t) pGlobalBase;
Jack Palevich21a15a22009-05-11 14:49:29 -07001673 pVarsBase = calloc(1, ALLOC_SIZE);
Jack Palevich8b0624c2009-05-20 12:12:06 -07001674 vars = (intptr_t) pVarsBase;
Jack Palevich21a15a22009-05-11 14:49:29 -07001675 inp();
1676 next();
1677 decl(0);
Jack Palevich546b2242009-05-13 15:10:04 -07001678 pGen->finishCompile();
Jack Palevich21a15a22009-05-11 14:49:29 -07001679 return 0;
1680 }
1681
1682 int run(int argc, char** argv) {
1683 typedef int (*mainPtr)(int argc, char** argv);
1684 mainPtr aMain = (mainPtr) *(int*) (vars + TOK_MAIN);
1685 if (!aMain) {
1686 fprintf(stderr, "Could not find function \"main\".\n");
1687 return -1;
1688 }
1689 return aMain(argc, argv);
1690 }
1691
1692 int dump(FILE* out) {
1693 fwrite(codeBuf.getBase(), 1, codeBuf.getSize(), out);
1694 return 0;
1695 }
Jack Palevich77ae76e2009-05-10 19:59:24 -07001696
Jack Palevicha6535612009-05-13 16:24:17 -07001697 int disassemble(FILE* out) {
1698 return pGen->disassemble(out);
1699 }
1700
Jack Palevich1cdef202009-05-22 12:06:27 -07001701 /* Look through the symbol table to find a symbol.
1702 * If found, return its value.
1703 */
1704 void* lookup(const char* name) {
1705 if (!sym_stk) {
1706 return NULL;
1707 }
1708 size_t nameLen = strlen(name);
1709 char* pSym = (char*) sym_stk;
1710 char c;
1711 for(;;) {
1712 c = *pSym++;
1713 if (c == 0) {
1714 break;
1715 }
1716 if (c == TAG_TOK) {
1717 if (memcmp(pSym, name, nameLen) == 0
1718 && pSym[nameLen] == TAG_TOK) {
1719 int tok = pSym - 1 - (char*) sym_stk;
1720 tok = tok * 8 + TOK_IDENT;
1721 if (tok <= TOK_DEFINE) {
1722 return 0;
1723 } else {
1724 tok = vars + tok;
1725 return * (void**) tok;
1726 }
1727 }
1728 }
1729 }
1730 return NULL;
1731 }
1732
Jack Palevich77ae76e2009-05-10 19:59:24 -07001733};
1734
Jack Paleviche7b59062009-05-19 17:12:17 -07001735const char* Compiler::operatorChars =
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001736 "++--*@/@%@+@-@<<>><=>=<@>@==!=&&||&@^@|@~@!@";
1737
Jack Paleviche7b59062009-05-19 17:12:17 -07001738const char Compiler::operatorLevel[] =
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001739 {11, 11, 1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4,
1740 5, 5, /* ==, != */
1741 9, 10, /* &&, || */
1742 6, 7, 8, /* & ^ | */
1743 2, 2 /* ~ ! */
1744 };
1745
Jack Palevich8b0624c2009-05-20 12:12:06 -07001746#ifdef PROVIDE_ARM_CODEGEN
Jack Paleviche7b59062009-05-19 17:12:17 -07001747FILE* Compiler::ARMCodeGenerator::disasmOut;
Jack Palevich8b0624c2009-05-20 12:12:06 -07001748#endif
Jack Palevicha6535612009-05-13 16:24:17 -07001749
Jack Palevich8b0624c2009-05-20 12:12:06 -07001750#ifdef PROVIDE_X86_CODEGEN
Jack Paleviche7b59062009-05-19 17:12:17 -07001751const int Compiler::X86CodeGenerator::operatorHelper[] = {
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001752 0x1, // ++
1753 0xff, // --
1754 0xc1af0f, // *
1755 0xf9f79991, // /
1756 0xf9f79991, // % (With manual assist to swap results)
1757 0xc801, // +
1758 0xd8f7c829, // -
1759 0xe0d391, // <<
1760 0xf8d391, // >>
1761 0xe, // <=
1762 0xd, // >=
1763 0xc, // <
1764 0xf, // >
1765 0x4, // ==
1766 0x5, // !=
1767 0x0, // &&
1768 0x1, // ||
1769 0xc821, // &
1770 0xc831, // ^
1771 0xc809, // |
1772 0xd0f7, // ~
1773 0x4 // !
1774};
Jack Palevich8b0624c2009-05-20 12:12:06 -07001775#endif
Jack Palevichbf42c9c2009-05-12 12:48:35 -07001776
Jack Palevich1cdef202009-05-22 12:06:27 -07001777struct ACCscript {
1778 ACCscript() {
1779 text = 0;
1780 textLength = 0;
1781 accError = ACC_NO_ERROR;
1782 }
Jack Palevichbbf8ab52009-05-11 11:54:30 -07001783
Jack Palevich1cdef202009-05-22 12:06:27 -07001784 ~ACCscript() {
1785 delete text;
1786 }
Jack Palevich546b2242009-05-13 15:10:04 -07001787
Jack Palevich1cdef202009-05-22 12:06:27 -07001788 void setError(ACCenum error) {
1789 if (accError == ACC_NO_ERROR && error != ACC_NO_ERROR) {
1790 accError = error;
Jack Palevichbbf8ab52009-05-11 11:54:30 -07001791 }
1792 }
1793
Jack Palevich1cdef202009-05-22 12:06:27 -07001794 ACCenum getError() {
1795 ACCenum result = accError;
1796 accError = ACC_NO_ERROR;
Jack Palevich22305132009-05-13 10:58:45 -07001797 return result;
Jack Palevichbbf8ab52009-05-11 11:54:30 -07001798 }
1799
Jack Palevich1cdef202009-05-22 12:06:27 -07001800 Compiler compiler;
1801 char* text;
1802 int textLength;
1803 ACCenum accError;
1804};
1805
1806
1807extern "C"
1808ACCscript* accCreateScript() {
1809 return new ACCscript();
Jack Palevichbbf8ab52009-05-11 11:54:30 -07001810}
Jack Palevich1cdef202009-05-22 12:06:27 -07001811
1812extern "C"
1813ACCenum accGetError( ACCscript* script ) {
1814 return script->getError();
1815}
1816
1817extern "C"
1818void accDeleteScript(ACCscript* script) {
1819 delete script;
1820}
1821
1822extern "C"
1823void accScriptSource(ACCscript* script,
1824 ACCsizei count,
1825 const ACCchar ** string,
1826 const ACCint * length) {
1827 int totalLength = 0;
1828 for(int i = 0; i < count; i++) {
1829 int len = -1;
1830 const ACCchar* s = string[i];
1831 if (length) {
1832 len = length[i];
1833 }
1834 if (len < 0) {
1835 len = strlen(s);
1836 }
1837 totalLength += len;
1838 }
1839 delete script->text;
1840 char* text = new char[totalLength + 1];
1841 script->text = text;
1842 script->textLength = totalLength;
Jack Palevich09555c72009-05-27 12:25:55 -07001843 char* dest = text;
Jack Palevich1cdef202009-05-22 12:06:27 -07001844 for(int i = 0; i < count; i++) {
1845 int len = -1;
1846 const ACCchar* s = string[i];
1847 if (length) {
1848 len = length[i];
1849 }
1850 if (len < 0) {
1851 len = strlen(s);
1852 }
Jack Palevich09555c72009-05-27 12:25:55 -07001853 memcpy(dest, s, len);
1854 dest += len;
Jack Palevich1cdef202009-05-22 12:06:27 -07001855 }
1856 text[totalLength] = '\0';
1857}
1858
1859extern "C"
1860void accCompileScript(ACCscript* script) {
1861 int result = script->compiler.compile(script->text, script->textLength);
1862 if (result) {
1863 script->setError(ACC_INVALID_OPERATION);
1864 }
1865}
1866
1867extern "C"
1868void accGetScriptiv(ACCscript* script,
1869 ACCenum pname,
1870 ACCint * params) {
1871 switch (pname) {
1872 case ACC_INFO_LOG_LENGTH:
1873 *params = 0;
1874 break;
1875 }
1876}
1877
1878extern "C"
1879void accGetScriptInfoLog(ACCscript* script,
1880 ACCsizei maxLength,
1881 ACCsizei * length,
1882 ACCchar * infoLog) {
1883 if (length) {
1884 *length = 0;
1885 }
1886 if (maxLength > 0 && infoLog) {
1887 *infoLog = 0;
1888 }
1889}
1890
1891extern "C"
1892void accGetScriptLabel(ACCscript* script, const ACCchar * name,
1893 ACCvoid ** address) {
1894 void* value = script->compiler.lookup(name);
1895 if (value) {
1896 *address = value;
1897 } else {
1898 script->setError(ACC_INVALID_VALUE);
1899 }
1900}
1901
1902} // namespace acc
1903