1 package org.ibex.nestedvm;
4 import java.util.Hashtable;
6 import org.ibex.nestedvm.util.*;
8 import org.apache.bcel.generic.*;
10 // FEATURE: Use BCEL to do peephole optimization
11 // FEATURE: Special mode to support single-precision only - regs are floats not ints
13 /* FEATURE: Span large binaries across several classfiles
14 * We should be able to do this with no performance penalty
15 * Every method in the inner classes is static and takes the main class as an arg
16 * This makes them look just like methods in the main class because arg1 gets loaded into
20 /* FEATURE: smarter with local regs
21 * Be even smarter with the use of local registers. We need to only load fields into
22 * local regs when they are actually used and only write to fields if the regs could have
23 * changed. This should allow us to put more regs in local vars. Right now putting all used
24 * regs local vars makes code like this slower.
26 * void work(int a, int b) {
33 * Because all the regs used in "real work" are loaded/restored even for fast path
37 public class ClassFileCompiler extends Compiler implements org.apache.bcel.Constants {
38 /** The stream to write the compiled output to */
39 private OutputStream os;
40 private PrintStream warn = System.err;
43 private ConstantPoolGen cp;
44 private InstructionList clinitExtras = new InstructionList();
45 private InstructionList initExtras = new InstructionList();
46 private InstructionFactory fac;
48 // Handy wrappers around the BCEL functions
49 private InstructionList insnList;
50 private void selectMethod(MethodGen m) { insnList = m.getInstructionList(); }
51 private void selectList(InstructionList l) { insnList = l; }
52 private InstructionHandle a(Instruction i) { return insnList.append(i); }
53 private BranchHandle a(BranchInstruction i) { return insnList.append(i); }
54 private InstructionHandle a(InstructionList l) { return insnList.append(l); }
55 private InstructionHandle a(CompoundInstruction c) { return insnList.append(c); }
57 // This works around a bug in InstructionList
58 // FEATURE: fix this in bcel, send them a patch, etc
59 private static class FixedInstructionList extends InstructionList {
60 public void move(InstructionHandle start, InstructionHandle end, InstructionHandle target) {
61 InstructionHandle extra = target != null && target == getEnd() ? append(InstructionConstants.NOP) : null;
62 super.move(start,end,target);
63 if(extra != null) try { delete(extra); } catch (TargetLostException e) { /* won't happen */ }
67 private MethodGen newMethod(int flags, Type ret, Type[] args, String name) {
68 return new MethodGen(flags,ret,args,null,name,fullClassName,new FixedInstructionList(),cp);
71 public ClassFileCompiler(String path, String className, OutputStream os) throws IOException { this(new Seekable.File(path),className,os); }
72 public ClassFileCompiler(Seekable binary, String className, OutputStream os) throws IOException {
73 super(binary,className);
77 public void setWarnWriter(PrintStream warn) { this.warn = warn; }
79 protected void _go() throws Exn, IOException {
80 if(lessConstants) throw new Exn("ClassFileCompiler doesn't support -o lessconstants");
81 if(!pruneCases) throw new Exn("-o prunecases MUST be enabled for ClassFileCompiler");
84 cl = new ClassGen(fullClassName,runtimeClass,source,ACC_SUPER|ACC_PUBLIC|ACC_FINAL,null);
85 cp = cl.getConstantPool();
86 fac = new InstructionFactory(cl,cp);
89 cl.addField(new FieldGen(ACC_PRIVATE,Type.INT,"pc",cp).getField());
91 cl.addField(new FieldGen(ACC_PRIVATE,Type.INT,"r"+i,cp).getField());
93 cl.addField(new FieldGen(ACC_PRIVATE,Type.INT,"f"+i,cp).getField());
95 cl.addField(new FieldGen(ACC_PRIVATE,Type.INT,"hi",cp).getField());
96 cl.addField(new FieldGen(ACC_PRIVATE,Type.INT,"lo",cp).getField());
97 cl.addField(new FieldGen(ACC_PRIVATE,Type.INT,"fcsr",cp).getField());
100 cl.addField(new FieldGen(ACC_PRIVATE|ACC_FINAL,new ArrayType(Type.INT,1),"page",cp).getField());
102 selectList(initExtras);
103 a(InstructionConstants.ALOAD_0);
104 a(InstructionConstants.DUP);
105 a(fac.createFieldAccess(fullClassName,"readPages",new ArrayType(Type.INT, 2), GETFIELD));
107 a(InstructionConstants.AALOAD);
108 a(fac.createFieldAccess(fullClassName,"page",new ArrayType(Type.INT,1), PUTFIELD));
112 cl.addField(new FieldGen(ACC_PRIVATE|ACC_STATIC|ACC_FINAL,Type.getType("L"+hashClass.replace('.','/')+";"),"symbols",cp).getField());
116 for(int i=0;i<elf.sheaders.length;i++) {
117 ELF.SHeader sheader = elf.sheaders[i];
118 String name = sheader.name;
119 // if this section doesn't get loaded into our address space don't worry about it
120 if(sheader.addr == 0x0) continue;
122 highestAddr = Math.max(highestAddr, sheader.addr + sheader.size);
124 if(name.equals(".text"))
125 emitText(sheader.addr, new DataInputStream(sheader.getInputStream()),sheader.size);
126 else if(name.equals(".data") || name.equals(".sdata") || name.equals(".rodata") || name.equals(".ctors") || name.equals(".dtors"))
127 emitData(sheader.addr, new DataInputStream(sheader.getInputStream()), sheader.size,name.equals(".rodata"));
128 else if(name.equals(".bss") || name.equals(".sbss"))
129 emitBSS(sheader.addr,sheader.size);
131 throw new Exn("Unknown segment: " + name);
134 ELF.SHeader text = elf.sectionWithName(".text");
137 MethodGen tramp = newMethod(ACC_PRIVATE,Type.VOID, Type.NO_ARGS, "trampoline");
138 tramp.addException("org.ibex.nestedvm.Runtime$ExecutionException");
141 InstructionHandle start = a(InstructionConstants.ALOAD_0);
142 a(fac.createFieldAccess(fullClassName,"state",Type.INT, GETFIELD));
143 pushConst(Runtime.RUNNING);
144 BranchInstruction stateCheck = InstructionFactory.createBranchInstruction(IF_ICMPNE,null);
146 a(InstructionConstants.ALOAD_0);
147 a(InstructionConstants.ALOAD_0);
148 a(fac.createFieldAccess(fullClassName,"pc",Type.INT, GETFIELD));
149 pushConst(methodShift);
150 a(InstructionConstants.IUSHR);
152 int beg = text.addr >>> methodShift;
153 int end = ((text.addr + text.size + maxBytesPerMethod - 1) >>> methodShift);
155 // This data is redundant but BCEL wants it
156 int[] matches = new int[end-beg];
157 for(int i=beg;i<end;i++) matches[i-beg] = i;
158 TABLESWITCH ts = new TABLESWITCH(matches,new InstructionHandle[matches.length],null);
160 for(int n=beg;n<end;n++){
161 InstructionHandle h = a(fac.createInvoke(fullClassName,"run_"+toHex(n<<methodShift),Type.VOID,Type.NO_ARGS,INVOKESPECIAL));
162 a(InstructionFactory.createBranchInstruction(GOTO,start));
163 ts.setTarget(n-beg,h);
166 ts.setTarget(a(InstructionConstants.POP)); // default case
167 a(fac.createNew("org.ibex.nestedvm.Runtime$ExecutionException"));
168 a(InstructionConstants.DUP);
169 a(fac.createNew("java.lang.StringBuffer"));
170 a(InstructionConstants.DUP);
171 a(new PUSH(cp,"Jumped to invalid address in trampoline (r2: "));
172 a(fac.createInvoke("java.lang.StringBuffer","<init>",Type.VOID,new Type[]{Type.STRING},INVOKESPECIAL));
173 a(InstructionConstants.ALOAD_0);
174 a(fac.createFieldAccess(fullClassName,"r2",Type.INT, GETFIELD));
175 a(fac.createInvoke("java.lang.StringBuffer","append",Type.STRINGBUFFER,new Type[]{Type.INT},INVOKEVIRTUAL));
176 a(new PUSH(cp," pc:"));
177 a(fac.createInvoke("java.lang.StringBuffer","append",Type.STRINGBUFFER,new Type[]{Type.STRING},INVOKEVIRTUAL));
178 a(InstructionConstants.ALOAD_0);
179 a(fac.createFieldAccess(fullClassName,"pc",Type.INT, GETFIELD));
180 a(fac.createInvoke("java.lang.StringBuffer","append",Type.STRINGBUFFER,new Type[]{Type.INT},INVOKEVIRTUAL));
182 a(fac.createInvoke("java.lang.StringBuffer","append",Type.STRINGBUFFER,new Type[]{Type.CHAR},INVOKEVIRTUAL));
183 a(fac.createInvoke("java.lang.StringBuffer","toString",Type.STRING,Type.NO_ARGS,INVOKEVIRTUAL));
184 a(fac.createInvoke("org.ibex.nestedvm.Runtime$ExecutionException","<init>",Type.VOID,new Type[]{Type.STRING},INVOKESPECIAL));
185 a(InstructionConstants.ATHROW);
187 stateCheck.setTarget(a(InstructionConstants.RETURN));
190 tramp.setMaxLocals();
192 cl.addMethod(tramp.getMethod());
193 } catch(ClassGenException e) {
194 e.printStackTrace(warn);
195 throw new Exn("Generation of the trampoline method failed. Try increasing maxInsnPerMethod");
198 addConstReturnMethod("gp",gp.addr);
199 addConstReturnMethod("entryPoint",elf.header.entry);
200 addConstReturnMethod("heapStart",highestAddr);
202 if(userInfo != null) {
203 addConstReturnMethod("userInfoBase",userInfo.addr);
204 addConstReturnMethod("userInfoSize",userInfo.size);
207 // FEATURE: Allow specification of memory size at runtime (numpages)
209 MethodGen init = newMethod(ACC_PUBLIC,Type.VOID, Type.NO_ARGS, "<init>");
211 a(InstructionConstants.ALOAD_0);
213 pushConst(totalPages);
214 a(fac.createInvoke(runtimeClass,"<init>",Type.VOID,new Type[]{Type.INT,Type.INT},INVOKESPECIAL));
218 a(InstructionConstants.RETURN);
222 cl.addMethod(init.getMethod());
225 MethodGen clinit = newMethod(ACC_PRIVATE|ACC_STATIC,Type.VOID, Type.NO_ARGS, "<clinit>");
226 selectMethod(clinit);
230 a(fac.createNew(hashClass));
231 a(InstructionConstants.DUP);
232 a(InstructionConstants.DUP);
233 a(fac.createInvoke(hashClass,"<init>",Type.VOID,Type.NO_ARGS,INVOKESPECIAL));
234 a(fac.createFieldAccess(fullClassName,"symbols",Type.getType("L"+hashClass.replace('.','/')+";"), PUTSTATIC));
235 ELF.Symbol[] symbols = elf.getSymtab().symbols;
236 for(int i=0;i<symbols.length;i++) {
237 ELF.Symbol s = symbols[i];
238 if(s.type == ELF.Symbol.STT_FUNC && s.binding == ELF.Symbol.STB_GLOBAL && (s.name.equals("_call_helper") || !s.name.startsWith("_"))) {
239 a(InstructionConstants.DUP);
240 a(new PUSH(cp,s.name));
241 a(fac.createNew("java.lang.Integer"));
242 a(InstructionConstants.DUP);
243 a(new PUSH(cp,s.addr));
244 a(fac.createInvoke("java.lang.Integer","<init>",Type.VOID,new Type[]{Type.INT},INVOKESPECIAL));
245 a(fac.createInvoke(hashClass,"put",Type.OBJECT,new Type[]{Type.OBJECT,Type.OBJECT},INVOKEVIRTUAL));
246 a(InstructionConstants.POP);
249 a(InstructionConstants.POP);
252 a(InstructionConstants.RETURN);
253 clinit.setMaxLocals();
254 clinit.setMaxStack();
255 cl.addMethod(clinit.getMethod());
258 MethodGen lookupSymbol = newMethod(ACC_PROTECTED,Type.INT,new Type[]{Type.STRING},"lookupSymbol");
259 selectMethod(lookupSymbol);
260 a(fac.createFieldAccess(fullClassName,"symbols",Type.getType("L"+hashClass.replace('.','/')+";"), GETSTATIC));
261 a(InstructionConstants.ALOAD_1);
262 a(fac.createInvoke(hashClass,"get",Type.OBJECT,new Type[]{Type.OBJECT},INVOKEVIRTUAL));
263 a(InstructionConstants.DUP);
264 BranchHandle bh = a(InstructionFactory.createBranchInstruction(IFNULL,null));
265 a(fac.createCheckCast(new ObjectType("java.lang.Integer")));
266 a(fac.createInvoke("java.lang.Integer","intValue",Type.INT,Type.NO_ARGS,INVOKEVIRTUAL));
267 a(InstructionConstants.IRETURN);
268 bh.setTarget(a(InstructionConstants.ICONST_M1));
269 a(InstructionConstants.IRETURN);
270 lookupSymbol.setMaxLocals();
271 lookupSymbol.setMaxStack();
272 cl.addMethod(lookupSymbol.getMethod());
275 MethodGen setCPUState = newMethod(ACC_PROTECTED,Type.VOID,new Type[]{Type.getType("Lorg/ibex/nestedvm/Runtime$CPUState;")},"setCPUState");
276 selectMethod(setCPUState);
277 a(InstructionConstants.ALOAD_1);
278 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","r",new ArrayType(Type.INT,1),GETFIELD));
279 a(InstructionConstants.ASTORE_2);
280 for(int i=1;i<32;i++) {
281 a(InstructionConstants.ALOAD_0);
282 a(InstructionConstants.ALOAD_2);
284 a(InstructionConstants.IALOAD);
285 a(fac.createFieldAccess(fullClassName,"r"+i,Type.INT, PUTFIELD));
287 a(InstructionConstants.ALOAD_1);
288 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","f",new ArrayType(Type.INT,1),GETFIELD));
289 a(InstructionConstants.ASTORE_2);
290 for(int i=0;i<32;i++) {
291 a(InstructionConstants.ALOAD_0);
292 a(InstructionConstants.ALOAD_2);
294 a(InstructionConstants.IALOAD);
295 a(fac.createFieldAccess(fullClassName,"f"+i,Type.INT, PUTFIELD));
297 a(InstructionConstants.ALOAD_0);
298 a(InstructionConstants.ALOAD_1);
299 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","hi",Type.INT,GETFIELD));
300 a(fac.createFieldAccess(fullClassName,"hi",Type.INT, PUTFIELD));
301 a(InstructionConstants.ALOAD_0);
302 a(InstructionConstants.ALOAD_1);
303 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","lo",Type.INT,GETFIELD));
304 a(fac.createFieldAccess(fullClassName,"lo",Type.INT, PUTFIELD));
305 a(InstructionConstants.ALOAD_0);
306 a(InstructionConstants.ALOAD_1);
307 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","fcsr",Type.INT,GETFIELD));
308 a(fac.createFieldAccess(fullClassName,"fcsr",Type.INT, PUTFIELD));
309 a(InstructionConstants.ALOAD_0);
310 a(InstructionConstants.ALOAD_1);
311 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","pc",Type.INT,GETFIELD));
312 a(fac.createFieldAccess(fullClassName,"pc",Type.INT, PUTFIELD));
314 a(InstructionConstants.RETURN);
315 setCPUState.setMaxLocals();
316 setCPUState.setMaxStack();
317 cl.addMethod(setCPUState.getMethod());
319 MethodGen getCPUState = newMethod(ACC_PROTECTED,Type.VOID,new Type[]{Type.getType("Lorg/ibex/nestedvm/Runtime$CPUState;")},"getCPUState");
320 selectMethod(getCPUState);
321 a(InstructionConstants.ALOAD_1);
322 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","r",new ArrayType(Type.INT,1),GETFIELD));
323 a(InstructionConstants.ASTORE_2);
324 for(int i=1;i<32;i++) {
325 a(InstructionConstants.ALOAD_2);
327 a(InstructionConstants.ALOAD_0);
328 a(fac.createFieldAccess(fullClassName,"r"+i,Type.INT, GETFIELD));
329 a(InstructionConstants.IASTORE);
332 a(InstructionConstants.ALOAD_1);
333 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","f",new ArrayType(Type.INT,1),GETFIELD));
334 a(InstructionConstants.ASTORE_2);
335 for(int i=0;i<32;i++) {
336 a(InstructionConstants.ALOAD_2);
338 a(InstructionConstants.ALOAD_0);
339 a(fac.createFieldAccess(fullClassName,"f"+i,Type.INT, GETFIELD));
340 a(InstructionConstants.IASTORE);
342 a(InstructionConstants.ALOAD_1);
343 a(InstructionConstants.ALOAD_0);
344 a(fac.createFieldAccess(fullClassName,"hi",Type.INT, GETFIELD));
345 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","hi",Type.INT,PUTFIELD));
346 a(InstructionConstants.ALOAD_1);
347 a(InstructionConstants.ALOAD_0);
348 a(fac.createFieldAccess(fullClassName,"lo",Type.INT, GETFIELD));
349 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","lo",Type.INT,PUTFIELD));
350 a(InstructionConstants.ALOAD_1);
351 a(InstructionConstants.ALOAD_0);
352 a(fac.createFieldAccess(fullClassName,"fcsr",Type.INT, GETFIELD));
353 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","fcsr",Type.INT,PUTFIELD));
354 a(InstructionConstants.ALOAD_1);
355 a(InstructionConstants.ALOAD_0);
356 a(fac.createFieldAccess(fullClassName,"pc",Type.INT, GETFIELD));
357 a(fac.createFieldAccess("org.ibex.nestedvm.Runtime$CPUState","pc",Type.INT,PUTFIELD));
359 a(InstructionConstants.RETURN);
360 getCPUState.setMaxLocals();
361 getCPUState.setMaxStack();
362 cl.addMethod(getCPUState.getMethod());
365 MethodGen execute = newMethod(ACC_PROTECTED,Type.VOID,Type.NO_ARGS,"_execute");
366 selectMethod(execute);
367 InstructionHandle tryStart = a(InstructionConstants.ALOAD_0);
368 InstructionHandle tryEnd = a(fac.createInvoke(fullClassName,"trampoline",Type.VOID,Type.NO_ARGS,INVOKESPECIAL));
369 a(InstructionConstants.RETURN);
371 InstructionHandle catchInsn = a(InstructionConstants.ASTORE_1);
372 a(fac.createNew("org.ibex.nestedvm.Runtime$FaultException"));
373 a(InstructionConstants.DUP);
374 a(InstructionConstants.ALOAD_1);
375 a(fac.createInvoke("org.ibex.nestedvm.Runtime$FaultException","<init>",Type.VOID,new Type[]{new ObjectType("java.lang.RuntimeException")},INVOKESPECIAL));
376 a(InstructionConstants.ATHROW);
378 execute.addExceptionHandler(tryStart,tryEnd,catchInsn,new ObjectType("java.lang.RuntimeException"));
379 execute.setMaxLocals();
380 execute.setMaxStack();
381 cl.addMethod(execute.getMethod());
384 MethodGen main = newMethod(ACC_STATIC|ACC_PUBLIC,Type.VOID,new Type[]{new ArrayType(Type.STRING,1)},"main");
386 a(fac.createNew(fullClassName));
387 a(InstructionConstants.DUP);
388 a(fac.createInvoke(fullClassName,"<init>",Type.VOID,Type.NO_ARGS,INVOKESPECIAL));
389 a(new PUSH(cp,fullClassName));
390 a(InstructionConstants.ALOAD_0);
392 a(fac.createInvoke("org.ibex.nestedvm.UnixRuntime","runAndExec",Type.INT,
393 new Type[]{Type.getType("Lorg/ibex/nestedvm/UnixRuntime;"),Type.STRING,new ArrayType(Type.STRING,1)},
396 a(fac.createInvoke(fullClassName,"run",Type.INT,new Type[]{Type.STRING,new ArrayType(Type.STRING,1)},INVOKEVIRTUAL));
397 a(fac.createInvoke("java.lang.System","exit",Type.VOID,new Type[]{Type.INT},INVOKESTATIC));
398 a(InstructionConstants.RETURN);
401 cl.addMethod(main.getMethod());
404 System.out.println("Constant Pool Size: " + cp.getSize());
405 cl.getJavaClass().dump(os);
408 private void addConstReturnMethod(String name, int val) {
409 MethodGen method = newMethod(ACC_PROTECTED,Type.INT, Type.NO_ARGS,name);
410 selectMethod(method);
412 a(InstructionConstants.IRETURN);
413 method.setMaxLocals();
414 method.setMaxStack();
415 cl.addMethod(method.getMethod());
418 private static int initDataCount;
419 private void emitData(int addr, DataInputStream dis, int size, boolean readOnly) throws Exn,IOException {
420 if((addr&3)!=0 || (size&3)!=0) throw new Exn("Data section on weird boundaries");
421 int last = addr + size;
423 int segSize = Math.min(size,28000); // must be a multiple of 56
424 StringBuffer sb = new StringBuffer();
425 for(int i=0;i<segSize;i+=7) {
427 for(int j=0;j<7;j++) {
429 byte b = (i+j < size) ? dis.readByte() : 1;
433 sb.append((char) ((l>>>(7*(7-j)))&0x7f));
435 String fieldname = "_data" + (++initDataCount);
436 cl.addField(new FieldGen(ACC_PRIVATE|ACC_STATIC|ACC_FINAL,new ArrayType(Type.INT,1),fieldname,cp).getField());
438 selectList(clinitExtras);
439 a(new PUSH(cp,sb.toString()));
440 a(new PUSH(cp,segSize/4));
441 a(fac.createInvoke("org.ibex.nestedvm.Runtime","decodeData",new ArrayType(Type.INT,1),new Type[]{Type.STRING,Type.INT},INVOKESTATIC));
442 a(fac.createPutStatic(fullClassName,fieldname,new ArrayType(Type.INT,1)));
444 selectList(initExtras);
445 a(InstructionConstants.ALOAD_0);
446 a(fac.createGetStatic(fullClassName,fieldname,new ArrayType(Type.INT,1)));
447 a(new PUSH(cp,addr));
448 a(new PUSH(cp,readOnly));
449 a(fac.createInvoke(fullClassName,"initPages",Type.VOID,new Type[]{new ArrayType(Type.INT,1),Type.INT,Type.BOOLEAN},INVOKEVIRTUAL));
457 private void emitBSS(int addr, int size) throws Exn {
458 if((addr&3)!=0) throw new Exn("BSS section on weird boundaries");
461 selectList(initExtras);
462 a(InstructionConstants.ALOAD_0);
463 a(new PUSH(cp,addr));
464 a(new PUSH(cp,count));
465 a(fac.createInvoke(fullClassName,"clearPages",Type.VOID,new Type[]{Type.INT,Type.INT},INVOKEVIRTUAL));
469 private boolean textDone;
470 private int startOfMethod = 0;
471 private int endOfMethod = 0;
472 private boolean unreachable = false;
473 private InstructionHandle[] jumpHandles;
474 private InstructionHandle defaultHandle;
475 private InstructionHandle returnHandle;
476 private InstructionHandle realStart;
477 private MethodGen curMethod;
479 private boolean jumpable(int addr) { return jumpableAddresses.contains(new Integer(addr)); }
481 private void emitText(int addr, DataInputStream dis, int size) throws Exn,IOException {
482 if(textDone) throw new Exn("Multiple text segments");
485 if((addr&3)!=0 || (size&3)!=0) throw new Exn("Section on weird boundaries");
487 int insn,nextInsn=-1;
488 boolean skipNext = true;
490 for(int i=0;i<count;i++,addr+=4) {
491 insn = skipNext ? dis.readInt() : nextInsn;
492 nextInsn = (i == count-1) ? -1 : dis.readInt();
493 if(addr >= endOfMethod) { endMethod(addr); startMethod(addr); }
494 if(jumpHandles[(addr-startOfMethod)/4] != null) {
495 // Move the fake jump target to the current location
496 insnList.move(jumpHandles[(addr-startOfMethod)/4],insnList.getEnd());
498 } else if(unreachable) {
502 skipNext = emitInstruction(addr,insn,nextInsn);
503 } catch(RuntimeException e) {
504 warn.println("Exception at " + toHex(addr));
507 if(skipNext) { addr+=4; i++; }
513 private void startMethod(int first) {
514 startOfMethod = first & methodMask;
515 endOfMethod = startOfMethod + maxBytesPerMethod;
516 curMethod = newMethod(ACC_PRIVATE,Type.VOID,Type.NO_ARGS,"run_" + toHex(startOfMethod));
517 selectMethod(curMethod);
519 int[] buf = new int[maxBytesPerMethod/4];
520 jumpHandles = new InstructionHandle[maxBytesPerMethod/4];
522 for(int addr=first;addr<endOfMethod;addr+=4) {
525 // append NOPs for GOTO jumps (these will be moved to the correct location later)
526 jumpHandles[(addr-startOfMethod)/4] = a(InstructionConstants.NOP);
530 // append NOP for default case (throw exn) (this will be moved later)
531 defaultHandle = a(InstructionConstants.NOP);
532 returnHandle = a(InstructionConstants.NOP);
534 int[] matches = new int[n];
535 System.arraycopy(buf,0,matches,0,n);
536 InstructionHandle[] targets = new InstructionHandle[n];
537 for(int i=0;i<matches.length;i++)
538 targets[i] = jumpHandles[(matches[i]-startOfMethod)/4];
541 // First instruction of the actual method - everything above this should be removed
542 // before we get to the end
543 realStart = a(InstructionConstants.NOP);
546 a(InstructionConstants.ALOAD_0);
547 a(fac.createFieldAccess(fullClassName,"page",new ArrayType(Type.INT,1), GETFIELD));
548 a(InstructionConstants.ASTORE_2);
550 a(InstructionConstants.ALOAD_0);
551 a(fac.createFieldAccess(fullClassName,"readPages",new ArrayType(Type.INT,2), GETFIELD));
552 a(InstructionConstants.ASTORE_2);
553 a(InstructionConstants.ALOAD_0);
554 a(fac.createFieldAccess(fullClassName,"writePages",new ArrayType(Type.INT,2), GETFIELD));
555 a(InstructionFactory.createStore(Type.OBJECT,3));
558 LOOKUPSWITCH initialSwitch = new LOOKUPSWITCH(matches,targets,defaultHandle);
559 a(InstructionConstants.ALOAD_0);
560 a(fac.createFieldAccess(fullClassName,"pc",Type.INT, GETFIELD));
564 private void endMethod(int firstAddrOfNext) {
565 if(startOfMethod == 0) return;
569 pushConst(firstAddrOfNext);
571 // mark the start of the next method as jumpable
572 jumpableAddresses.add(new Integer(firstAddrOfNext));
575 insnList.move(returnHandle,insnList.getEnd());
577 a(InstructionConstants.RETURN);
579 // move the default jump target (lookupswitch) to before the throw
580 insnList.move(defaultHandle,insnList.getEnd());
582 a(fac.createNew("org.ibex.nestedvm.Runtime$ExecutionException"));
583 a(InstructionConstants.DUP);
584 a(fac.createNew("java.lang.StringBuffer"));
585 a(InstructionConstants.DUP);
586 a(new PUSH(cp,"Jumped to invalid address: "));
587 a(fac.createInvoke("java.lang.StringBuffer","<init>",Type.VOID,new Type[]{Type.STRING},INVOKESPECIAL));
588 a(InstructionConstants.ALOAD_0);
589 a(fac.createFieldAccess(fullClassName,"pc",Type.INT, GETFIELD));
590 a(fac.createInvoke("java.lang.StringBuffer","append",Type.STRINGBUFFER,new Type[]{Type.INT},INVOKEVIRTUAL));
591 a(fac.createInvoke("java.lang.StringBuffer","toString",Type.STRING,Type.NO_ARGS,INVOKEVIRTUAL));
592 a(fac.createInvoke("org.ibex.nestedvm.Runtime$ExecutionException","<init>",Type.VOID,new Type[]{Type.STRING},INVOKESPECIAL));
593 a(InstructionConstants.ATHROW);
595 a(fac.createNew("org.ibex.nestedvm.Runtime$ExecutionException"));
596 a(InstructionConstants.DUP);
597 a(new PUSH(cp,"Jumped to invalid address"));
598 a(fac.createInvoke("org.ibex.nestedvm.Runtime$ExecutionException","<init>",Type.VOID,new Type[]{Type.STRING},INVOKESPECIAL));
599 a(InstructionConstants.ATHROW);
602 if(insnList.getStart() != realStart) {
603 System.err.println(insnList);
604 throw new Error("A jumpHandle wasn't moved into place");
607 curMethod.removeNOPs();
608 curMethod.setMaxLocals();
609 curMethod.setMaxStack();
611 cl.addMethod(curMethod.getMethod());
613 endOfMethod = startOfMethod = 0;
617 private void leaveMethod() {
618 a(InstructionFactory.createBranchInstruction(GOTO,returnHandle));
621 private void branch(int pc, int target) {
622 if((pc&methodMask) == (target&methodMask)) {
623 a(InstructionFactory.createBranchInstruction(GOTO,jumpHandles[(target-startOfMethod)/4]));
632 // This assumes everything needed by ifInsn is already on the stack
633 private boolean doIfInstruction(short op, int pc, int target, int nextInsn) throws Exn {
634 emitInstruction(-1,nextInsn,-1); // delay slot
636 IfInstruction ifInsn = (IfInstruction) InstructionFactory.createBranchInstruction(op,null);
637 if((target&methodMask) == (pc&methodMask)) {
639 h.setTarget(jumpHandles[(target-startOfMethod)/4]);
641 h = a(ifInsn.negate());
643 h.setTarget(a(InstructionConstants.NOP));
645 if(!jumpable(pc+4)) return true; // done - skip it
647 //System.err.println("Delay slot is jumpable - This code is untested + " + toHex(nextInsn));
648 if(pc+4==endOfMethod) {
649 // the delay slot is at the start of the next method
650 jumpableAddresses.add(new Integer(pc+8)); // make the 2nd insn of the next method jumpable
651 branch(pc,pc+8); // jump over it
652 //System.err.println("delay slot: " + toHex(pc+8));
654 return false; // we still need to output it
656 //System.err.println("jumped over delay slot: " + toHex(pc+4));
657 // add another copy and jump over
658 h = a(InstructionFactory.createBranchInstruction(GOTO,null));
659 insnList.move(jumpHandles[(pc+4-startOfMethod)/4],insnList.getEnd());
660 emitInstruction(-1,nextInsn,-1); // delay slot
661 h.setTarget(a(InstructionConstants.NOP));
666 private boolean emitInstruction(int pc, int insn, int nextInsn) throws Exn {
667 if(insn == -1) throw new Exn("insn is -1");
669 int op = (insn >>> 26) & 0xff; // bits 26-31
670 int rs = (insn >>> 21) & 0x1f; // bits 21-25
671 int rt = (insn >>> 16) & 0x1f; // bits 16-20
672 int ft = (insn >>> 16) & 0x1f;
673 int rd = (insn >>> 11) & 0x1f; // bits 11-15
674 int fs = (insn >>> 11) & 0x1f;
675 int shamt = (insn >>> 6) & 0x1f; // bits 6-10
676 int fd = (insn >>> 6) & 0x1f;
677 int subcode = insn & 0x3f; // bits 0-5
678 int breakCode = (insn >>> 6) & 0xfffff; // bits 6-20
680 int jumpTarget = (insn & 0x03ffffff); // bits 0-25
681 int unsignedImmediate = insn & 0xffff;
682 int signedImmediate = (insn << 16) >> 16;
683 int branchTarget = signedImmediate;
696 a(InstructionConstants.ISHL);
703 a(InstructionConstants.IUSHR);
710 a(InstructionConstants.ISHR);
717 a(InstructionConstants.ISHL);
724 a(InstructionConstants.IUSHR);
731 a(InstructionConstants.ISHR);
735 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
736 emitInstruction(-1,nextInsn,-1);
744 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
745 emitInstruction(-1,nextInsn,-1);
761 restoreChangedRegs();
764 a(InstructionConstants.ALOAD_0);
770 a(fac.createInvoke(fullClassName,"syscall",Type.INT,new Type[]{Type.INT,Type.INT,Type.INT,Type.INT,Type.INT},INVOKEVIRTUAL));
773 a(InstructionConstants.ALOAD_0);
774 a(fac.createFieldAccess(fullClassName,"state",Type.INT, GETFIELD));
775 pushConst(Runtime.RUNNING);
776 b1 = a(InstructionFactory.createBranchInstruction(IF_ICMPEQ,null));
781 b1.setTarget(a(InstructionConstants.NOP));
785 a(fac.createNew("org.ibex.nestedvm.Runtime$ExecutionException"));
786 a(InstructionConstants.DUP);
787 a(new PUSH(cp,"BREAK Code " + toHex(breakCode)));
788 a(fac.createInvoke("org.ibex.nestedvm.Runtime$ExecutionException","<init>",Type.VOID,new Type[]{Type.STRING},INVOKESPECIAL));
789 a(InstructionConstants.ATHROW);
814 a(InstructionConstants.I2L);
816 a(InstructionConstants.I2L);
817 a(InstructionConstants.LMUL);
818 a(InstructionConstants.DUP2);
820 a(InstructionConstants.L2I);
822 a(InstructionConstants.SWAP);
826 a(InstructionConstants.LUSHR);
827 a(InstructionConstants.L2I);
829 a(InstructionConstants.SWAP);
835 a(InstructionConstants.I2L);
836 pushConst(0xffffffffL);
837 a(InstructionConstants.LAND);
839 a(InstructionConstants.I2L);
840 pushConst(0xffffffffL);
841 a(InstructionConstants.LAND);
842 a(InstructionConstants.LMUL);
843 a(InstructionConstants.DUP2);
845 a(InstructionConstants.L2I);
847 a(InstructionConstants.SWAP);
851 a(InstructionConstants.LUSHR);
852 a(InstructionConstants.L2I);
854 a(InstructionConstants.SWAP);
861 a(InstructionConstants.DUP2);
863 a(InstructionConstants.IDIV);
865 a(InstructionConstants.SWAP);
868 a(InstructionConstants.IREM);
870 a(InstructionConstants.SWAP);
876 a(InstructionConstants.DUP);
878 b1 = a(InstructionFactory.createBranchInstruction(IFEQ,null));
881 a(InstructionConstants.I2L);
882 pushConst(0xffffffffL);
883 a(InstructionConstants.LAND);
884 a(InstructionConstants.DUP2);
886 a(InstructionConstants.I2L);
887 pushConst(0xffffffffL);
889 a(InstructionConstants.LAND);
890 a(InstructionConstants.DUP2_X2);
891 a(InstructionConstants.LDIV);
893 a(InstructionConstants.L2I);
895 a(InstructionConstants.SWAP);
898 a(InstructionConstants.LREM);
899 a(InstructionConstants.L2I);
901 a(InstructionConstants.SWAP);
904 b1.setTarget(a(InstructionConstants.NOP));
909 throw new Exn("ADD (add with oveflow trap) not suported");
912 if(rt != 0 && rs != 0) {
915 a(InstructionConstants.IADD);
924 throw new Exn("SUB (add with oveflow trap) not suported");
927 if(rt != 0 && rs != 0) {
930 a(InstructionConstants.ISUB);
933 a(InstructionConstants.INEG);
943 a(InstructionConstants.IAND);
950 a(InstructionConstants.IOR);
957 a(InstructionConstants.IXOR);
962 if(rs != 0 || rt != 0) {
963 if(rs != 0 && rt != 0) {
966 a(InstructionConstants.IOR);
972 a(InstructionConstants.ICONST_M1);
973 a(InstructionConstants.IXOR);
984 b1 = a(InstructionFactory.createBranchInstruction(IF_ICMPLT,null));
985 a(InstructionConstants.ICONST_0);
986 b2 = a(InstructionFactory.createBranchInstruction(GOTO,null));
987 b1.setTarget(a(InstructionConstants.ICONST_1));
988 b2.setTarget(a(InstructionConstants.NOP));
999 a(InstructionConstants.I2L);
1000 pushConst(0xffffffffL);
1001 a(InstructionConstants.LAND);
1003 a(InstructionConstants.I2L);
1004 pushConst(0xffffffffL);
1005 a(InstructionConstants.LAND);
1006 a(InstructionConstants.LCMP);
1007 b1 = a(InstructionFactory.createBranchInstruction(IFLT,null));
1010 b1 = a(InstructionFactory.createBranchInstruction(IFNE,null));
1012 a(InstructionConstants.ICONST_0);
1013 b2 = a(InstructionFactory.createBranchInstruction(GOTO,null));
1014 b1.setTarget(a(InstructionConstants.ICONST_1));
1015 b2.setTarget(a(InstructionConstants.NOP));
1022 throw new Exn("Illegal instruction 0/" + subcode);
1029 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1031 return doIfInstruction(IFLT,pc,pc+branchTarget*4+4,nextInsn);
1033 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1035 return doIfInstruction(IFGE,pc,pc+branchTarget*4+4,nextInsn);
1037 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1039 b1 = a(InstructionFactory.createBranchInstruction(IFGE,null));
1040 emitInstruction(-1,nextInsn,-1);
1044 branch(pc,pc+branchTarget*4+4);
1045 b1.setTarget(a(InstructionConstants.NOP));
1048 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1050 if(rs != 0) { // r0 is always >= 0
1052 b1 = a(InstructionFactory.createBranchInstruction(IFLT,null));
1054 emitInstruction(-1,nextInsn,-1);
1058 branch(pc,pc+branchTarget*4+4);
1059 if(b1 != null) b1.setTarget(a(InstructionConstants.NOP));
1060 if(b1 == null) unreachable = true;
1063 throw new Exn("Illegal Instruction 1/" + rt);
1068 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1069 emitInstruction(-1,nextInsn,-1);
1070 branch(pc,(pc&0xf0000000)|(jumpTarget << 2));
1075 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1076 int target = (pc&0xf0000000)|(jumpTarget << 2);
1077 emitInstruction(-1,nextInsn,-1);
1086 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1088 emitInstruction(-1,nextInsn,-1);
1089 branch(pc,pc+branchTarget*4+4);
1091 } else if(rs == 0 || rt == 0) {
1092 pushReg(rt == 0 ? R+rs : R+rt);
1093 return doIfInstruction(IFEQ,pc,pc+branchTarget*4+4,nextInsn);
1097 return doIfInstruction(IF_ICMPEQ,pc,pc+branchTarget*4+4,nextInsn);
1101 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1104 return doIfInstruction(IFNE,pc,pc+branchTarget*4+4,nextInsn);
1107 return doIfInstruction(IF_ICMPNE,pc,pc+branchTarget*4+4,nextInsn);
1110 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1112 return doIfInstruction(IFLE,pc,pc+branchTarget*4+4,nextInsn);
1114 if(pc == -1) throw new Exn("pc modifying insn in delay slot");
1116 return doIfInstruction(IFGT,pc,pc+branchTarget*4+4,nextInsn);
1118 throw new Exn("ADDI (add immediate with oveflow trap) not suported");
1121 addiu(rs,signedImmediate);
1127 pushConst(signedImmediate);
1128 b1 = a(InstructionFactory.createBranchInstruction(IF_ICMPLT,null));
1129 a(InstructionConstants.ICONST_0);
1130 b2 = a(InstructionFactory.createBranchInstruction(GOTO,null));
1131 b1.setTarget(a(InstructionConstants.ICONST_1));
1132 b2.setTarget(a(InstructionConstants.NOP));
1138 a(InstructionConstants.I2L);
1139 pushConst(0xffffffffL);
1140 a(InstructionConstants.LAND);
1141 // Yes, this is correct, you have to sign extend the immediate then do an UNSIGNED comparison
1142 pushConst(signedImmediate&0xffffffffL);
1143 a(InstructionConstants.LCMP);
1145 b1 = a(InstructionFactory.createBranchInstruction(IFLT,null));
1146 a(InstructionConstants.ICONST_0);
1147 b2 = a(InstructionFactory.createBranchInstruction(GOTO,null));
1148 b1.setTarget(a(InstructionConstants.ICONST_1));
1149 b2.setTarget(a(InstructionConstants.NOP));
1156 pushConst(unsignedImmediate);
1157 a(InstructionConstants.IAND);
1162 if(rs != 0 && unsignedImmediate != 0) {
1164 pushConst(unsignedImmediate);
1165 a(InstructionConstants.IOR);
1169 pushConst(unsignedImmediate);
1176 pushConst(unsignedImmediate);
1177 a(InstructionConstants.IXOR);
1182 pushConst(unsignedImmediate << 16);
1186 throw new Exn("TLB/Exception support not implemented");
1195 if(fs != 31) throw new Exn("FCR " + fs + " unavailable");
1209 if(fs != 31) throw new Exn("FCR " + fs + " unavailable");
1214 case 8: {// BC1F, BC1T
1216 pushConst(0x800000);
1217 a(InstructionConstants.IAND);
1218 return doIfInstruction(((insn>>>16)&1) == 0 ? IFEQ : IFNE,pc,pc+branchTarget*4+4,nextInsn);
1222 { // Single/Double math
1223 boolean d = rs == 17;
1226 preSetDouble(F+fd,d);
1229 a(d ? InstructionConstants.DADD : InstructionConstants.FADD);
1233 preSetDouble(F+fd,d);
1236 a(d ? InstructionConstants.DSUB : InstructionConstants.FSUB);
1240 preSetDouble(F+fd,d);
1243 a(d ? InstructionConstants.DMUL : InstructionConstants.FMUL);
1247 preSetDouble(F+fd,d);
1250 a(d ? InstructionConstants.DDIV : InstructionConstants.FDIV);
1254 preSetDouble(F+fd,d);
1255 // NOTE: We can't use fneg/dneg here since they'll turn +0.0 into -0.0
1258 a(d ? InstructionConstants.DUP2 : InstructionConstants.DUP);
1259 a(d ? InstructionConstants.DCONST_0 : InstructionConstants.FCONST_0);
1260 a(d ? InstructionConstants.DCMPG : InstructionConstants.FCMPG);
1262 b1 = a(InstructionFactory.createBranchInstruction(IFGT,null));
1263 a(d ? InstructionConstants.DCONST_0 : InstructionConstants.FCONST_0);
1265 a(InstructionConstants.DUP2_X2);
1266 a(InstructionConstants.POP2);
1268 a(InstructionConstants.POP);
1270 a(InstructionConstants.DSUB);
1272 b1.setTarget(setDouble(d));
1286 preSetDouble(F+fd,d);
1288 a(d ? InstructionConstants.DNEG : InstructionConstants.FNEG);
1294 if(d) a(InstructionConstants.D2F);
1300 if(!d) a(InstructionConstants.F2D);
1303 case 36: { // CVT.W.D
1304 int[] matches = new int[4];
1305 for(int i=0;i<4;i++) matches[i] = i;
1307 TABLESWITCH ts = new TABLESWITCH(matches,new InstructionHandle[4], null);
1312 a(InstructionConstants.ICONST_3);
1313 a(InstructionConstants.IAND);
1316 // Round towards plus infinity
1317 ts.setTarget(2,a(InstructionConstants.NOP));
1318 if(!d) a(InstructionConstants.F2D); // Ugh.. java.lang.Math doesn't have a float ceil/floor
1319 a(fac.createInvoke("java.lang.Math","ceil",Type.DOUBLE,new Type[]{Type.DOUBLE},INVOKESTATIC));
1320 if(!d) a(InstructionConstants.D2F);
1321 b1 = a(InstructionFactory.createBranchInstruction(GOTO,null));
1324 ts.setTarget(0,d ? pushConst(0.5d) : pushConst(0.5f));
1325 a(d ? InstructionConstants.DADD : InstructionConstants.FADD);
1328 // Round towards minus infinity
1329 ts.setTarget(3,a(InstructionConstants.NOP));
1330 if(!d) a(InstructionConstants.F2D);
1331 a(fac.createInvoke("java.lang.Math","floor",Type.DOUBLE,new Type[]{Type.DOUBLE},INVOKESTATIC));
1332 if(!d) a(InstructionConstants.D2F);
1334 InstructionHandle h = a(d ? InstructionConstants.D2I : InstructionConstants.F2I);
1348 pushConst(~0x800000);
1349 a(InstructionConstants.IAND);
1352 a(d ? InstructionConstants.DCMPG : InstructionConstants.FCMPG);
1354 case 50: b1 = a(InstructionFactory.createBranchInstruction(IFEQ,null)); break;
1355 case 60: b1 = a(InstructionFactory.createBranchInstruction(IFLT,null)); break;
1356 case 62: b1 = a(InstructionFactory.createBranchInstruction(IFLE,null)); break;
1360 pushConst(0x000000);
1361 b2 = a(InstructionFactory.createBranchInstruction(GOTO,null));
1362 b1.setTarget(pushConst(0x800000));
1363 b2.setTarget(a(InstructionConstants.IOR));
1366 default: throw new Exn("Invalid Instruction 17/" + rs + "/" + subcode);
1370 case 20: { // Integer
1375 a(InstructionConstants.I2F);
1381 a(InstructionConstants.I2D);
1384 default: throw new Exn("Invalid Instruction 17/" + rs + "/" + subcode);
1389 throw new Exn("Invalid Instruction 17/" + rs);
1394 throw new Exn("coprocessor 2 and 3 instructions not available");
1397 addiu(R+rs,signedImmediate);
1404 a(InstructionConstants.ICONST_M1);
1405 a(InstructionConstants.IXOR);
1406 a(InstructionConstants.ICONST_3);
1407 a(InstructionConstants.IAND);
1408 a(InstructionConstants.ICONST_3);
1409 a(InstructionConstants.ISHL);
1410 a(InstructionConstants.IUSHR);
1411 a(InstructionConstants.I2B);
1417 addiu(R+rs,signedImmediate);
1424 a(InstructionConstants.ICONST_M1);
1425 a(InstructionConstants.IXOR);
1426 a(InstructionConstants.ICONST_2);
1427 a(InstructionConstants.IAND);
1428 a(InstructionConstants.ICONST_3);
1429 a(InstructionConstants.ISHL);
1430 a(InstructionConstants.IUSHR);
1431 a(InstructionConstants.I2S);
1437 addiu(R+rs,signedImmediate);
1441 pushConst(0x00ffffff);
1444 a(InstructionConstants.ICONST_M1);
1445 a(InstructionConstants.IXOR);
1446 a(InstructionConstants.ICONST_3);
1447 a(InstructionConstants.IAND);
1448 a(InstructionConstants.ICONST_3);
1449 a(InstructionConstants.ISHL);
1450 a(InstructionConstants.IUSHR);
1451 a(InstructionConstants.IAND);
1458 a(InstructionConstants.ICONST_3);
1459 a(InstructionConstants.IAND);
1460 a(InstructionConstants.ICONST_3);
1461 a(InstructionConstants.ISHL);
1462 a(InstructionConstants.ISHL);
1463 a(InstructionConstants.IOR);
1472 memRead(R+rs,signedImmediate);
1477 addiu(R+rs,signedImmediate);
1484 a(InstructionConstants.ICONST_M1);
1485 a(InstructionConstants.IXOR);
1486 a(InstructionConstants.ICONST_3);
1487 a(InstructionConstants.IAND);
1488 a(InstructionConstants.ICONST_3);
1489 a(InstructionConstants.ISHL);
1490 a(InstructionConstants.IUSHR);
1492 a(InstructionConstants.IAND);
1498 addiu(R+rs,signedImmediate);
1505 a(InstructionConstants.ICONST_M1);
1506 a(InstructionConstants.IXOR);
1507 a(InstructionConstants.ICONST_2);
1508 a(InstructionConstants.IAND);
1509 a(InstructionConstants.ICONST_3);
1510 a(InstructionConstants.ISHL);
1511 a(InstructionConstants.IUSHR);
1513 // chars are unsigend so this works
1514 a(InstructionConstants.I2C);
1520 addiu(R+rs,signedImmediate);
1524 pushConst(0xffffff00);
1527 a(InstructionConstants.ICONST_3);
1528 a(InstructionConstants.IAND);
1529 a(InstructionConstants.ICONST_3);
1530 a(InstructionConstants.ISHL);
1531 a(InstructionConstants.ISHL);
1532 a(InstructionConstants.IAND);
1539 a(InstructionConstants.ICONST_M1);
1540 a(InstructionConstants.IXOR);
1541 a(InstructionConstants.ICONST_3);
1542 a(InstructionConstants.IAND);
1543 a(InstructionConstants.ICONST_3);
1544 a(InstructionConstants.ISHL);
1545 a(InstructionConstants.IUSHR);
1546 a(InstructionConstants.IOR);
1553 addiu(R+rs,signedImmediate);
1556 // FEATURE: DO the preMemRead(true) thing for the rest of the S* instructions
1561 pushConst(0xff000000);
1564 a(InstructionConstants.ICONST_3);
1565 a(InstructionConstants.IAND);
1566 a(InstructionConstants.ICONST_3);
1567 a(InstructionConstants.ISHL);
1568 a(InstructionConstants.IUSHR);
1569 a(InstructionConstants.ICONST_M1);
1570 a(InstructionConstants.IXOR);
1571 a(InstructionConstants.IAND);
1576 a(InstructionConstants.IAND);
1582 a(InstructionConstants.ICONST_M1);
1583 a(InstructionConstants.IXOR);
1584 a(InstructionConstants.ICONST_3);
1585 a(InstructionConstants.IAND);
1586 a(InstructionConstants.ICONST_3);
1587 a(InstructionConstants.ISHL);
1588 a(InstructionConstants.ISHL);
1589 a(InstructionConstants.IOR);
1598 addiu(R+rs,signedImmediate);
1600 a(InstructionConstants.DUP);
1612 a(InstructionConstants.ICONST_2);
1613 a(InstructionConstants.IAND);
1614 a(InstructionConstants.ICONST_3);
1615 a(InstructionConstants.ISHL);
1616 a(InstructionConstants.ISHL);
1617 a(InstructionConstants.IAND);
1622 a(InstructionConstants.IAND);
1628 a(InstructionConstants.ICONST_M1);
1629 a(InstructionConstants.IXOR);
1630 a(InstructionConstants.ICONST_2);
1631 a(InstructionConstants.IAND);
1632 a(InstructionConstants.ICONST_3);
1633 a(InstructionConstants.ISHL);
1634 a(InstructionConstants.ISHL);
1635 a(InstructionConstants.IOR);
1644 addiu(R+rs,signedImmediate);
1645 a(InstructionConstants.DUP);
1654 pushConst(0xffffff00);
1657 a(InstructionConstants.ICONST_M1);
1658 a(InstructionConstants.IXOR);
1659 a(InstructionConstants.ICONST_3);
1660 a(InstructionConstants.IAND);
1661 a(InstructionConstants.ICONST_3);
1662 a(InstructionConstants.ISHL);
1663 a(InstructionConstants.ISHL);
1664 a(InstructionConstants.IAND);
1669 a(InstructionConstants.ICONST_3);
1670 a(InstructionConstants.IAND);
1671 a(InstructionConstants.ICONST_3);
1672 a(InstructionConstants.ISHL);
1673 a(InstructionConstants.IUSHR);
1674 a(InstructionConstants.IOR);
1682 preMemWrite2(R+rs,signedImmediate);
1689 addiu(R+rs,signedImmediate);
1690 a(InstructionConstants.DUP);
1699 pushConst(0x00ffffff);
1702 a(InstructionConstants.ICONST_3);
1703 a(InstructionConstants.IAND);
1704 a(InstructionConstants.ICONST_3);
1705 a(InstructionConstants.ISHL);
1706 a(InstructionConstants.IUSHR);
1707 a(InstructionConstants.IAND);
1712 a(InstructionConstants.ICONST_M1);
1713 a(InstructionConstants.IXOR);
1714 a(InstructionConstants.ICONST_3);
1715 a(InstructionConstants.IAND);
1716 a(InstructionConstants.ICONST_3);
1717 a(InstructionConstants.ISHL);
1718 a(InstructionConstants.ISHL);
1719 a(InstructionConstants.IOR);
1724 // This need to be atomic if we ever support threads (see SWC0/SC)
1727 memRead(R+rs,signedImmediate);
1733 memRead(R+rs,signedImmediate);
1737 /* This needs to fail (set rt to 0) if the memory location was modified
1738 * between the LL and SC if we every support threads.
1743 preMemWrite2(R+rs,signedImmediate);
1752 preMemWrite2(R+rs,signedImmediate);
1757 throw new Exn("Invalid Instruction: " + op + " at " + toHex(pc));
1762 // Helper functions for emitText
1764 private static final int R = 0;
1765 private static final int F = 32;
1766 private static final int HI = 64;
1767 private static final int LO = 65;
1768 private static final int FCSR = 66;
1769 private static final int REG_COUNT=67;
1771 private int[] regLocalMapping = new int[REG_COUNT];
1772 private int[] regLocalReadCount = new int[REG_COUNT];
1773 private int[] regLocalWriteCount = new int[REG_COUNT];
1774 private int nextAvailLocal;
1776 private int getLocalForReg(int reg) {
1777 if(regLocalMapping[reg] != 0) return regLocalMapping[reg];
1778 if(nextAvailLocal == 0) nextAvailLocal = onePage ? 3 : 4;
1779 regLocalMapping[reg] = nextAvailLocal++;
1780 return regLocalMapping[reg];
1783 private void fixupRegs() {
1784 InstructionHandle prev = realStart;
1785 for(int i=0;i<REG_COUNT;i++) {
1786 if(regLocalMapping[i] == 0) continue;
1788 prev = insnList.append(prev,InstructionConstants.ALOAD_0);
1789 prev = insnList.append(prev,fac.createFieldAccess(fullClassName,regField(i),Type.INT, GETFIELD));
1790 prev = insnList.append(prev,InstructionFactory.createStore(Type.INT,regLocalMapping[i]));
1792 if(regLocalWriteCount[i] > 0) {
1793 a(InstructionConstants.ALOAD_0);
1794 a(InstructionFactory.createLoad(Type.INT,regLocalMapping[i]));
1795 a(fac.createFieldAccess(fullClassName,regField(i),Type.INT, PUTFIELD));
1798 regLocalMapping[i] = regLocalReadCount[i] = regLocalWriteCount[i] = 0;
1803 private void restoreChangedRegs() {
1804 for(int i=0;i<REG_COUNT;i++) {
1805 if(regLocalWriteCount[i] > 0) {
1806 a(InstructionConstants.ALOAD_0);
1807 a(InstructionFactory.createLoad(Type.INT,regLocalMapping[i]));
1808 a(fac.createFieldAccess(fullClassName,regField(i),Type.INT, PUTFIELD));
1813 private static final String[] regField = {
1814 "r0","r1","r2","r3","r4","r5","r6","r7",
1815 "r8","r9","r10","r11","r12","r13","r14","r15",
1816 "r16","r17","r18","r19","r20","r21","r22","r23",
1817 "r24","r25","r26","r27","r28","r29","r30","r31",
1819 "f0","f1","f2","f3","f4","f5","f6","f7",
1820 "f8","f9","f10","f11","f12","f13","f14","f15",
1821 "f16","f17","f18","f19","f20","f21","f22","f23",
1822 "f24","f25","f26","f27","f28","f29","f30","f31",
1827 private static String regField(int reg) {
1828 return regField[reg];
1832 case HI: field = "hi"; break;
1833 case LO: field = "lo"; break;
1834 case FCSR: field = "fcsr"; break;
1836 if(reg > R && reg < R+32) regFieldR[reg-R];
1837 else if(reg >= F && reg < F+32) return regFieldF[
1838 else throw new IllegalArgumentException(""+reg);
1843 private boolean doLocal(int reg) {
1845 return reg == R+2 || reg == R+3 || reg == R+4 || reg == R+29;
1848 private InstructionHandle pushRegWZ(int reg) {
1850 warn.println("Warning: Pushing r0!");
1851 new Exception().printStackTrace(warn);
1853 return pushRegZ(reg);
1856 private InstructionHandle pushRegZ(int reg) {
1857 if(reg == R+0) return pushConst(0);
1858 else return pushReg(reg);
1862 private InstructionHandle pushReg(int reg) {
1863 InstructionHandle h;
1865 regLocalReadCount[reg]++;
1866 h = a(InstructionFactory.createLoad(Type.INT,getLocalForReg(reg)));
1868 h = a(InstructionConstants.ALOAD_0);
1869 a(fac.createFieldAccess(fullClassName,regField(reg),Type.INT, GETFIELD));
1874 private int preSetRegStackPos;
1875 private int[] preSetRegStack = new int[8];
1877 // This can push ONE or ZERO words to the stack. If it pushed one it returns true
1878 private boolean preSetReg(int reg) {
1879 regField(reg); // just to check for validity
1880 preSetRegStack[preSetRegStackPos] = reg;
1881 preSetRegStackPos++;
1885 a(InstructionConstants.ALOAD_0);
1890 private InstructionHandle setReg() {
1891 if(preSetRegStackPos==0) throw new RuntimeException("didn't do preSetReg");
1892 preSetRegStackPos--;
1893 int reg = preSetRegStack[preSetRegStackPos];
1894 InstructionHandle h;
1896 h = a(InstructionFactory.createStore(Type.INT,getLocalForReg(reg)));
1897 regLocalWriteCount[reg]++;
1899 h = a(fac.createFieldAccess(fullClassName,regField(reg),Type.INT, PUTFIELD));
1904 private InstructionHandle preSetPC() { return a(InstructionConstants.ALOAD_0); }
1905 private InstructionHandle setPC() { return a(fac.createFieldAccess(fullClassName,"pc",Type.INT, PUTFIELD)); }
1907 //unused - private InstructionHandle pushFloat(int reg) throws CompilationException { return pushDouble(reg,false); }
1908 //unused - private InstructionHandle pushDouble(int reg) throws CompilationException { return pushDouble(reg,true); }
1909 private InstructionHandle pushDouble(int reg, boolean d) throws Exn {
1910 if(reg < F || reg >= F+32) throw new IllegalArgumentException(""+reg);
1911 InstructionHandle h;
1913 if(reg == F+31) throw new Exn("Tried to use a double in f31");
1915 a(InstructionConstants.I2L);
1917 a(InstructionConstants.LSHL);
1919 a(InstructionConstants.I2L);
1920 pushConst(0xffffffffL);
1921 a(InstructionConstants.LAND);
1922 a(InstructionConstants.LOR);
1923 //p("invokestatic java/lang/Double/longBitsToDouble(J)D");
1924 a(fac.createInvoke("java.lang.Double","longBitsToDouble",Type.DOUBLE,new Type[]{Type.LONG},INVOKESTATIC));
1927 a(fac.createInvoke("java.lang.Float","intBitsToFloat",Type.FLOAT,new Type[]{Type.INT},INVOKESTATIC));
1932 private void preSetFloat(int reg) { preSetDouble(reg,false); }
1933 private void preSetDouble(int reg) { preSetDouble(reg,true); }
1934 private void preSetDouble(int reg, boolean d) { preSetReg(reg); }
1936 private InstructionHandle setFloat() throws Exn { return setDouble(false); }
1937 private InstructionHandle setDouble() throws Exn { return setDouble(true); }
1938 private InstructionHandle setDouble(boolean d) throws Exn {
1939 int reg = preSetRegStack[preSetRegStackPos-1];
1940 if(reg < F || reg >= F+32) throw new IllegalArgumentException(""+reg);
1941 //p("invokestatic java/lang/Double/doubleToLongBits(D)J");
1942 InstructionHandle h;
1944 if(reg == F+31) throw new Exn("Tried to use a double in f31");
1945 h = a(fac.createInvoke("java.lang.Double","doubleToLongBits",Type.LONG,new Type[]{Type.DOUBLE},INVOKESTATIC));
1946 a(InstructionConstants.DUP2);
1948 a(InstructionConstants.LUSHR);
1949 a(InstructionConstants.L2I);
1950 if(preSetReg(reg+1))
1951 a(InstructionConstants.SWAP);
1953 a(InstructionConstants.L2I);
1954 setReg(); // preSetReg was already done for this by preSetDouble
1956 h = a(fac.createInvoke("java.lang.Float","floatToRawIntBits",Type.INT,new Type[]{Type.FLOAT},INVOKESTATIC));
1962 private Hashtable intCache = new Hashtable();
1964 private InstructionHandle pushConst(int n) {
1965 if(n >= -1 && n <= 5) {
1967 case -1: return a(InstructionConstants.ICONST_M1);
1968 case 0: return a(InstructionConstants.ICONST_0);
1969 case 1: return a(InstructionConstants.ICONST_1);
1970 case 2: return a(InstructionConstants.ICONST_2);
1971 case 3: return a(InstructionConstants.ICONST_3);
1972 case 4: return a(InstructionConstants.ICONST_4);
1973 case 5: return a(InstructionConstants.ICONST_5);
1974 default: return null;
1976 } else if(n >= -128 && n <= 127) {
1977 return a(new BIPUSH((byte) n));
1978 } else if(n >= -32768 && n <= 32767) {
1979 return a(new SIPUSH((short) n));
1981 return a(new PUSH(cp,n));
1985 private InstructionHandle pushConst(long l) { return a(new PUSH(cp,l)); }
1986 private InstructionHandle pushConst(float f) { return a(new PUSH(cp,f)); }
1987 private InstructionHandle pushConst(double d) { return a(new PUSH(cp,d)); }
1989 private void pushTmp() { a(InstructionConstants.ILOAD_1); }
1990 private void setTmp() { a(InstructionConstants.ISTORE_1); }
1992 private void addiu(int reg, int offset) {
1993 if(reg != R+0 && offset != 0) {
1996 a(InstructionConstants.IADD);
1997 } else if(reg != R+0) {
2003 private int memWriteStage;
2004 private void preMemWrite1() {
2005 if(memWriteStage!=0) throw new Error("pending preMemWrite1/2");
2008 a(InstructionConstants.ALOAD_2);
2010 a(InstructionFactory.createLoad(Type.OBJECT,3));
2012 a(InstructionConstants.ALOAD_0);
2015 private void preMemWrite2(int reg, int offset) {
2020 private void preMemWrite2() { preMemWrite2(false); }
2021 private void preMemWrite2(boolean addrInTmp) {
2022 if(memWriteStage!=1) throw new Error("pending preMemWrite2 or no preMemWrite1");
2025 if(nullPointerCheck) {
2026 a(InstructionConstants.DUP);
2027 a(InstructionConstants.ALOAD_0);
2028 a(InstructionConstants.SWAP);
2029 a(fac.createInvoke(fullClassName,"nullPointerCheck",Type.VOID,new Type[]{Type.INT},INVOKEVIRTUAL));
2033 a(InstructionConstants.ICONST_2);
2034 a(InstructionConstants.IUSHR);
2035 } else if(fastMem) {
2037 a(InstructionConstants.DUP_X1);
2038 pushConst(pageShift);
2039 a(InstructionConstants.IUSHR);
2040 a(InstructionConstants.AALOAD);
2044 a(InstructionConstants.SWAP);
2045 a(InstructionConstants.ICONST_2);
2046 a(InstructionConstants.IUSHR);
2047 pushConst((pageSize>>2)-1);
2048 a(InstructionConstants.IAND);
2052 // pops an address and value off the stack, sets *addr to value
2053 private void memWrite() {
2054 if(memWriteStage!=2) throw new Error("didn't do preMemWrite1 or preMemWrite2");
2058 a(InstructionConstants.IASTORE);
2059 } else if(fastMem) {
2060 a(InstructionConstants.IASTORE);
2062 a(fac.createInvoke(fullClassName,"unsafeMemWrite",Type.VOID,new Type[]{Type.INT,Type.INT},INVOKEVIRTUAL));
2067 // reads the word at r[reg]+offset
2068 private void memRead(int reg, int offset) {
2074 private boolean didPreMemRead;
2075 private boolean preMemReadDoPreWrite;
2077 private void preMemRead() { preMemRead(false); }
2078 private void preMemRead(boolean preWrite) {
2079 if(didPreMemRead) throw new Error("pending preMemRead");
2080 didPreMemRead = true;
2081 preMemReadDoPreWrite = preWrite;
2083 a(InstructionConstants.ALOAD_2);
2085 a(InstructionFactory.createLoad(Type.OBJECT,preWrite ? 3 : 2));
2087 a(InstructionConstants.ALOAD_0);
2089 // memRead pops an address off the stack, reads the value at that addr, and pushed the value
2090 // preMemRead MUST be called BEFORE the addresses is pushed
2091 private void memRead() { memRead(false); }
2093 private void memRead(boolean addrInTmp) {
2094 if(!didPreMemRead) throw new Error("didn't do preMemRead");
2095 didPreMemRead = false;
2096 if(preMemReadDoPreWrite)
2099 if(nullPointerCheck) {
2100 a(InstructionConstants.DUP);
2101 a(InstructionConstants.ALOAD_0);
2102 a(InstructionConstants.SWAP);
2103 a(fac.createInvoke(fullClassName,"nullPointerCheck",Type.VOID,new Type[]{Type.INT},INVOKEVIRTUAL));
2107 // p(target + "= page[(" + addr + ")>>>2];");
2108 a(InstructionConstants.ICONST_2);
2109 a(InstructionConstants.IUSHR);
2110 if(preMemReadDoPreWrite)
2111 a(InstructionConstants.DUP2);
2112 a(InstructionConstants.IALOAD);
2113 } else if(fastMem) {
2114 //p(target + " = readPages[("+addr+")>>>"+pageShift+"][(("+addr+")>>>2)&"+toHex((pageSize>>2)-1)+"];");
2117 a(InstructionConstants.DUP_X1);
2118 pushConst(pageShift);
2119 a(InstructionConstants.IUSHR);
2120 a(InstructionConstants.AALOAD);
2124 a(InstructionConstants.SWAP);
2125 a(InstructionConstants.ICONST_2);
2126 a(InstructionConstants.IUSHR);
2127 pushConst((pageSize>>2)-1);
2128 a(InstructionConstants.IAND);
2129 if(preMemReadDoPreWrite)
2130 a(InstructionConstants.DUP2);
2131 a(InstructionConstants.IALOAD);
2134 if(preMemReadDoPreWrite)
2135 a(InstructionConstants.DUP2);
2136 a(fac.createInvoke(fullClassName,"unsafeMemWrite",Type.INT,new Type[]{Type.INT},INVOKEVIRTUAL));
2141 // This might come in handy for something else
2142 /*private boolean touchesReg(int insn, int reg) {
2143 if((reg < R+0 || reg >= R+32) && reg != FCSR) throw new IllegalArgumentException(""+reg);
2144 if(reg == R+0) return false; // r0 is never modified
2145 int op = (insn >>> 26) & 0xff; // bits 26-31
2146 int subcode = insn & 0x3f; // bits 0-5
2147 int rd = (insn >>> 11) & 0x1f; // bits 11-15
2148 int rt = (insn >>> 16) & 0x1f; // bits 16-20
2149 int rs = (insn >>> 21) & 0x1f; // bits 21-25
2153 if(subcode >= 0 && subcode <= 7) return reg == R+rd; // Shift ops
2154 if(subcode >= 32 && subcode <= 43) return reg == R+rd; // Other math ops
2155 if(subcode >= 24 && subcode <= 27) return reg == HI || reg == LO; // MULT/DIV
2157 case 13: return false; // BREAK
2160 case 0: return reg == R+rt; // MFC.1
2161 case 2: return reg == R+rt; // CFC.1
2162 case 4: return false; // MTC.1
2163 case 6: return false; // CTC.1
2166 if(subcode == 50 || subcode == 60 || subcode == 62) return reg == FCSR;
2167 return false; // everything else just touches f0-f31
2168 case 20: return false; // Integer - just touches f0-f31
2172 if(op >= 8 && op <= 15) return reg == R+rt; // XXXI instructions
2173 if(op >= 40 && op <= 46) return false; // Memory WRITE ops
2174 if(op == 49) return reg == F+rt; // LWC1
2175 if(op == 57) return false; // SWC1
2178 warn.println("Unknown instruction in touchesReg()- assuming it modifies all regs " + op + " " + subcode);
2179 new Exception().fillInStackTrace().printStackTrace(warn);