1 package org.ibex.classgen.opt;
4 import org.ibex.classgen.*;
7 import java.util.zip.*;
9 public class Arena implements CGConst {
11 public static interface Gladiator { }
13 Context cx = new Context();
15 public static final int initialSize = 1000;
18 // Initializers //////////////////////////////////////////////////////////////////////////////
20 public static Type.Class System_class = Type.Class.instance("java.lang.System");
21 public static Type.Class.Method System_arraycopy = System_class.method("arraycopy","(Ljava/lang/Object;ILjava/lang/Object;II)V");
22 public static Type.Class Gladiator_class = Type.Class.instance("org.ibex.classgen.opt.Arena$Gladiator");
24 boolean implementsGladiator(Type t) { return t instanceof Type.Class && implementsGladiator((Type.Class)t);}
25 boolean implementsGladiator(Type.Class c) { return c.extendsOrImplements(Gladiator_class, cx); }
27 String getArenaName(Type.Class c) { return c.getName().substring(0, c.getName().lastIndexOf('$')); }
28 String getGladiatorName(Type.Class c) { return c.getName().substring(c.getName().lastIndexOf('$')+1); }
29 Type.Class getArenaForGladiator(Type.Class c) { return Type.Class.instance(getArenaName(c)); }
31 Type getSliceElementType(Type t) { return implementsGladiator(t) ? Type.INT : t; }
32 Type.Class.Field getSliceForField(Type.Class.Field f) {
33 Type.Class c = f.getDeclaringClass();
34 return getArenaForGladiator(c).field(getGladiatorName(c)+"$$"+f.getName(),
35 getSliceElementType(f.getType()).makeArray());
39 // Operations performed on the Gladiator class //////////////////////////////////////////////////////////////////////////
41 public Type.Class.Method.Body getSoleConstructor(Type.Class c) {
42 Type.Class.Method.Body ret = null;
43 Type.Class.Method.Body[] bodies = c.getBody(cx).methods();
44 for(int i=0; i<bodies.length; i++) {
45 if (!bodies[i].getMethod().isConstructor()) continue;
46 if (ret != null) throw new Error("class " + c.getName() + " has two constructors");
52 public void processGladiatorClass(Type.Class c) {
54 System.out.println("**** " + c.getName() + " is a gladiator!");
56 Type.Class arena = getArenaForGladiator(c);
57 Type.Class.Body arenaBody = arena.getBody(cx);
58 Type.Class.Method.Body arenaInitBody = getSoleConstructor(c);
59 Type.Class.Method arenaInit = arenaInitBody.getMethod();
61 Type.Class.Field maxField = arena.field(getGladiatorName(c) + "$$max", Type.INT);
62 arenaBody.addField(maxField, PRIVATE);
64 assign(arenaInitBody, newIFR(arenaInitBody, maxField.makeRef()), IntConstant.v(initialSize),
65 arenaInitBody.getFirstNonIdentityStmt());
68 Type.Class.Field sizeField = arena.field(getGladiatorName(c) + "$$size", Type.INT);
69 arenaBody.addField(sizeField, PRIVATE);
71 assign(arenaInitBody, newIFR(arenaInitBody, sfr.makeRef()), IntConstant.v(0),
72 arenaInitBody.getFirstNonIdentityStmt());
75 Type.Class.Method incMethod = c.method(getGladiatorName(c) + "$$inc()I");
76 Type.Class.Method.Body incBody = incMethod.getBody(cx);
79 // Now build the $$inc method
81 Local l = newLocal(incBody, IntType.v());
82 Local l2 = newLocal(incBody, IntType.v());
83 Local l3 = newLocal(incBody, IntType.v());
84 Local l4 = newLocal(incBody, IntType.v());
86 assign(incBody, l, newIFR(incBody, sfr.makeRef()));
87 assign(incBody, l2, Jimple.v().newAddExpr(l, IntConstant.v(1)));
88 assign(incBody, newIFR(incBody, sfr.makeRef()), l2);
89 assign(incBody, l3, newIFR(incBody, maxField.makeRef()));
91 Stmt returnStmt = Jimple.v().newReturnStmt(l2);
92 incBody.getUnits().add(Jimple.v().newIfStmt(Jimple.v().newLtExpr(l2, l3), returnStmt));
94 assign(incBody, l4, Jimple.v().newShlExpr(l3, IntConstant.v(1)));
95 assign(incBody, newIFR(incBody, maxField.makeRef()), l4);
98 // Finally, iterate over the Gladiator's fields, updating the $$inc method and Arena's zero-arg constructor as we go
100 for(Iterator it = sc.getFields().iterator(); it.hasNext();) {
101 Type.Class.Field f = (Type.Class.Field)it.next();
102 Type t = getSliceElementType(f.getType());
103 f = arena.field(getGladiatorName(sc) + "$$" + f.getName(), t.makeArray());
106 Expr newArr = Jimple.v().newNewArrayExpr(t, IntConstant.v(initialSize));
107 Local newArrLocal = newLocal(arenaInitBody, f.getType());
108 arenaInitBody.getUnits().addFirst(Jimple.v().newAssignStmt(newIFR(arenaInitBody, f.makeRef()), newArrLocal));
109 arenaInitBody.getUnits().addFirst(Jimple.v().newAssignStmt(newArrLocal, newArr));
111 Local ll0 = newLocal(incBody, f.getType());
112 Local ll = newLocal(incBody, f.getType());
113 assign(incBody, ll0, newIFR(incBody, f.makeRef()));
114 assign(incBody, ll, Jimple.v().newNewArrayExpr(t, l4));
116 List args = new LinkedList();
118 args.add(IntConstant.v(0));
120 args.add(IntConstant.v(0));
122 incBody.getUnits().add(Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(System_arraycopy, args)));
123 assign(incBody, newIFR(incBody, f.makeRef()), ll);
126 for(Iterator it = c.getBody(cx).getMethods().iterator(); it.hasNext();) {
127 Type.Class.Method m = (Type.Class.Method)it.next();
128 if (!m.isConcrete()) continue;
129 boolean doremove = true;
130 Type.Class.Method.Body mincBody = m.getBody(cx);
131 if (implementsGladiator(m.getDeclaringClass()) && m.isConstructor()) {
132 System.out.println("processing ctor " + c.getName() + "." + m.getSignature());
134 Type.Class c = m.getDeclaringClass();
135 String name = "$init";
136 Type[] at = m.getArgTypes();
138 Type.Class.Method nm = c.method(name, implementsGladiator(m.getReturnType()) ? Type.INT : m.getReturnType(), at);
139 Type.Class.Method.Body bod = nm.getBody(cx);
140 bod.importBodyContentsFrom(m.getActiveBody());
144 for(Iterator it2 = mincBody.getUnits().snapshotIterator(); it2.hasNext(); ) {
145 Unit u = (Unit)it2.next();
146 if (u instanceof DefinitionStmt) {
147 DefinitionStmt ds = (DefinitionStmt)u;
148 if (ds.getLeftOp() instanceof ThisRef)
149 mincBody.getUnits().remove(u);
150 else if (ds.getLeftOp() instanceof FieldRef) {
151 if (((FieldRef)ds.getLeftOp()).getFieldRef().name().endsWith("this$0"))
152 mincBody.getUnits().remove(u);
154 } else if (u instanceof InvokeStmt) {
155 InvokeExpr ie = ((InvokeStmt)u).getInvokeExpr();
156 Type.Class.MethodRef meth = ie.getMethodRef();
157 if (meth.getDeclaringClass().getName().equals("java.lang.Object") && meth.name().equals("<init>"))
158 mincBody.getUnits().remove(u);
162 if (m.isStatic()) continue;
164 String name = c.getShortName().substring(c.getShortName().lastIndexOf('$')+1) + "$$" + m.getName();
165 Type[] list = new Type[m.getNumArgs() + 1];
166 for(int i=0; i<m.getNumArgs(); i++) list[i] = m.getArgType(i);
167 list[list.length-1] = Type.INT;
168 Type.Class.Method m2 = c.method(name, m.getReturnType(), list);
169 getArenaForGladiator(c).addMethod(m2);
170 Type.Class.Method.Body ab = m2.getBody(cx);
171 ab.importBodyContentsFrom(mincBody);
173 Local loc = Jimple.v().newLocal("tmpRef" + (tfr++), getArenaForGladiator(sc).getType());
174 ab.getLocals().add(loc);
175 // FIXME: insert assignment to this
176 for(Iterator z = ab.getLocals().iterator(); z.hasNext();) {
177 Local loc2 = (Local)z.next();
178 if (implementsGladiator(loc2.getType())) {
179 loc2.setType(IntType.v());
182 Chain units = ab.getUnits();
183 boolean touched = false;
184 Local loc0 = Jimple.v().newLocal("tmpRef" + (tfr++), getArenaForGladiator(sc).getType());
185 ab.getLocals().add(loc0);
186 for(Iterator stmtIt = units.snapshotIterator(); stmtIt.hasNext();) {
187 Stmt s = (Stmt) stmtIt.next();
188 if (s instanceof IdentityStmt) {
189 IdentityStmt is = (IdentityStmt)s;
190 Local left = (Local)is.getLeftOp();
191 if (is.getRightOp() instanceof ThisRef) {
192 left.setType(IntType.v());
193 is.getRightOpBox().setValue(Jimple.v().newParameterRef(IntType.v(), m.getParameterCount()));
195 units.addFirst(Jimple.v().newIdentityStmt(loc0, Jimple.v().newThisRef(getArenaForGladiator(sc).getType())));
201 for(Iterator i = s.getUseAndDefBoxes().iterator(); i.hasNext();) {
203 if (o instanceof ValueBox) {
204 ValueBox vb = (ValueBox)o;
206 //if (o instanceof Local && implementsGladiator(((Local)o).getType())) {
207 //System.out.println("thunking");
210 if (vb.getValue() instanceof ThisRef) {
218 if (doremove) sc.removeMethod(m);
221 incBody.getUnits().add(returnStmt);
225 // Operations performed on all classes ////////////////////////////////////////////////////////////////////////////
227 public Type processType(Type t) {
228 if (t instanceof Type.Array) return processType(((Type.Array)t).getElementType()).makeArray();
229 if (implementsGladiator(t)) return Type.INT;
233 public void processField(Type.Class.Field.Body fb) {
235 f.setType(processType(f.getType()));
239 public void processMethod(Type.Class.Method.Body mb) {
241 if (m.getName().endsWith("$$inc")) continue;
242 //if (m.isConcrete()) b = processBody(m.getBody(cx), c, m);
243 m.setReturnType(processType(m.getReturnType()));
244 Type[] argTypes = m.getArgTypes();
245 for(int i=0; i<argTypes.length; i++) argTypes[i] = processType(argTypes[i]);
246 m.setArgTypes(argTypes);
248 if (implementsGladiator(t)) {
250 if (m.hasActiveBody()) {
251 Body bod = m.getActiveBody();
252 for(Iterator stmtIt = bod.getUnits().snapshotIterator(); stmtIt.hasNext();) {
253 Stmt s = (Stmt) stmtIt.next();
254 if (s instanceof ReturnStmt) {
255 if (((ReturnStmt)s).getOp().getType() instanceof NullType) {
256 ((ReturnStmt)s).getOpBox().setValue(IntConstant.v(-1));
267 public void processClassFile(ClassFile cf) {
268 boolean verdict = implementsGladiator(cf.getType());
269 //System.out.println("checking " + cf.getType().getName() + " => " + verdict);
270 if (verdict) processGladiatorClass(cf.getType());
271 Type.Class.Field.Body[] fields = cf.fields();
272 for(int i=0; i<fields.length; i++) processField(fields[i]);
273 Type.Class.Method.Body[] methods = cf.methods();
274 for(int i=0; i<methods.length; i++) processMethod(methods[i]);
278 protected Body processBody(Body body, Type.Class ownerClass, Type.Class.Method smeth) {
279 Chain units = body.getUnits();
280 for(Iterator it = body.getLocals().snapshotIterator(); it.hasNext();) {
281 Local l = (Local)it.next();
282 if (implementsGladiator(l.getType())) l.setType(IntType.v());
284 if (!smeth.isStatic())
285 body.getThisLocal().setType(ownerClass.getType());
286 for(int qq=0; qq<2; qq++) for(Iterator stmtIt = units.snapshotIterator(); stmtIt.hasNext();) {
287 Stmt s = (Stmt) stmtIt.next();
288 if (s instanceof DefinitionStmt) {
289 DefinitionStmt ds = (DefinitionStmt)s;
290 if (ds.getLeftOp().getType() instanceof PrimType && ds.getRightOp().getType() instanceof NullType)
291 ds.getRightOpBox().setValue(IntConstant.v(-1));
293 if (implementsGladiator(smeth.getReturnType()) && s instanceof ReturnStmt)
294 if (((ReturnStmt)s).getOp().getType() instanceof NullType)
295 ((ReturnStmt)s).getOpBox().setValue(IntConstant.v(-1));
296 List l = s.getUseAndDefBoxes();
297 List l2l = new LinkedList();
299 for(Iterator it = l2l.iterator(); it.hasNext();) {
300 Object o = it.next();
301 if (o instanceof ValueBox) {
302 ValueBox vb = (ValueBox)o;
303 Value v = vb.getValue();
305 if (v instanceof BinopExpr) {
306 BinopExpr boe = (BinopExpr)v;
307 Type t1 = boe.getOp1().getType();
308 Type t2 = boe.getOp2().getType();
309 if (t1 instanceof PrimType && t2 instanceof NullType) boe.setOp2(IntConstant.v(-1));
310 if (t2 instanceof PrimType && t1 instanceof NullType) boe.setOp1(IntConstant.v(-1));
313 if (v instanceof NewExpr) {
314 NewExpr ne = (NewExpr)v;
315 if (implementsGladiator(ne.getBaseType())) {
316 Type.Class sc = ((Type.Ref)ne.getBaseType()).Type.Class.instance();
317 Type.Class arena = getArenaForGladiator(sc);
318 String incFuncName = sc.getShortName().substring(sc.getShortName().lastIndexOf('$')+1) + "$$inc";
319 Type.Class.MethodRef smr = Scene.v().makeMethodRef(arena, incFuncName, new LinkedList(), IntType.v(), false);
320 Expr invokeExpr = Jimple.v().newSpecialInvokeExpr(body.getThisLocal(), smr);
321 Local ll = viaLocal(invokeExpr, body, s);
329 if (v instanceof InvokeExpr) {
330 InvokeExpr ie = (InvokeExpr)v;
331 Type.Class.MethodRef mr = ie.getMethodRef();
332 String name = mr.name();
333 if (v instanceof InstanceInvokeExpr && implementsGladiator(mr.getDeclaringClass())) {
334 InstanceInvokeExpr iie = (InstanceInvokeExpr)v;
335 List li = new LinkedList();
336 li.addAll(iie.getArgs());
337 LinkedList pl = new LinkedList();
338 for(Iterator it2 = mr.parameterTypes().iterator(); it2.hasNext();) {
339 Type t = (Type)it2.next();
340 pl.add(implementsGladiator(t) ? IntType.v() : t);
342 if (mr.name().equals("<init>") && implementsGladiator(mr.getDeclaringClass())) {
348 //li.add(iie.getBase());
349 Type.Class sc = mr.getDeclaringClass();
350 name = sc.getShortName().substring(sc.getShortName().lastIndexOf('$')+1) + "$$" + name;
351 mr = Scene.v().makeMethodRef(getArenaForGladiator(sc),
354 implementsGladiator(mr.returnType()) ? IntType.v() : mr.returnType(),
356 ie = Jimple.v().newVirtualInvokeExpr(body.getThisLocal(), mr, li);
359 } else if (!(v instanceof StaticInvokeExpr)) {
360 List l0 = mr.parameterTypes();
361 List l2 = new LinkedList();
362 for(Iterator it2 = l0.iterator(); it2.hasNext();) {
363 Type t = (Type)it2.next();
364 l2.add(implementsGladiator(t) ? IntType.v() : t);
366 mr = Scene.v().makeMethodRef(mr.getDeclaringClass(),
369 implementsGladiator(mr.returnType()) ? IntType.v() : mr.returnType(),
375 for(int i=0; i<ie.getArgCount(); i++) {
376 ValueBox b = ie.getArgBox(i);
377 Value val = b.getValue();
378 if (mr.parameterType(i) instanceof Type.Ref && val.getType() instanceof PrimType) {
379 Type.Class intClass = Scene.v().Type.Class.instance("java.lang.Integer");
380 List typelist = new LinkedList();
381 typelist.add(IntType.v());
382 Type.Class.Method intMethod = intClass.getMethod("<init>", typelist);
383 Local loc = viaLocal(Jimple.v().newNewExpr(Type.Ref.v(intClass)), body, s);
384 List list = new LinkedList();
386 units.insertBefore(Jimple.v().newInvokeStmt(Jimple.v().newSpecialInvokeExpr(loc,
392 if (val != null && val.getType() instanceof NullType && mr.parameterType(i) instanceof IntType) {
393 b.setValue(IntConstant.v(-1));
398 } else if (v instanceof CastExpr) {
399 CastExpr ce = (CastExpr)v;
400 if (implementsGladiator(ce.getCastType())) {
401 Type.Class arena = getArenaForGladiator(((Type.Ref)ce.getCastType()).Type.Class.instance());
402 Type.Class ic = Scene.v().Type.Class.instance("java.lang.Integer");
403 ce.setCastType(ic.getType());
405 Local l1 = Jimple.v().newLocal("tmpRef" + (tfr++), ic.getType()); body.getLocals().add(l1);
406 Local l2 = Jimple.v().newLocal("tmpRef" + (tfr++), IntType.v()); body.getLocals().add(l2);
408 Stmt s2 = Jimple.v().newAssignStmt(l1, Jimple.v().newCastExpr(ce.getOp(), ic.getType()));
409 body.getUnits().insertBefore(s2, s);
411 Stmt isNull = Jimple.v().newAssignStmt(l2, IntConstant.v(-1));
412 body.getUnits().insertAfter(isNull, s2);
414 Stmt ifStmt = Jimple.v().newIfStmt(Jimple.v().newEqExpr(l1, NullConstant.v()), s);
415 body.getUnits().insertAfter(ifStmt, isNull);
417 Type.Class.MethodRef mr = Scene.v().makeMethodRef(ic, "intValue", new LinkedList(), IntType.v(), false);
419 Jimple.v().newAssignStmt(l2, Jimple.v().newVirtualInvokeExpr(l1, mr, new LinkedList()));
420 body.getUnits().insertAfter(isNotNull, ifStmt);
427 } else if (v instanceof FieldRef) {
428 FieldRef ifr = (FieldRef)v;
429 Type.Class.Field fr = ifr.getFieldRef();
431 if (implementsGladiator(fr.getDeclaringClass()) && fr.name().equals("this$0")) {
432 vb.setValue(body.getThisLocal());
433 } else if (implementsGladiator(fr.getDeclaringClass())) {
434 Type.Class arena = getArenaForGladiator(fr.getDeclaringClass());
436 vb.setValue(newIFR(body, getSliceForField(fr)));
438 InstanceFieldRef sfr = newIFR(body, getSliceForField(fr));
439 vb.setValue(Jimple.v().newArrayRef(viaLocal(sfr, body, s), ((InstanceFieldRef)ifr).getBase()));
442 if ((t instanceof Type.Ref) && implementsGladiator(((Type.Ref)t).Type.Class.instance())) {
443 Type.Class tc = ((Type.Ref)t).Type.Class.instance();
444 Type.Class arena = getArenaForGladiator(tc);
445 ifr.setFieldRef(Scene.v().makeFieldRef(arena, fr.name(), IntType.v(), fr.isStatic()));
446 } else if (t instanceof Type.Array) {
447 Type.Array at = (Type.Array)t;
448 Type et = at.getElementType();
449 if (et instanceof Type.Ref && implementsGladiator(((Type.Ref)et).Type.Class.instance()))
450 ifr.setFieldRef(Scene.v().makeFieldRef(fr.getDeclaringClass(),
452 IntType.v().makeType.Array(),
464 public static void main(String[] s) throws Exception { new Arena().process(s); }
465 public void process(String[] s) throws Exception {
466 File outf = new File(s[0] + "-");
467 File inf = new File(s[0]);
468 ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outf));
469 ZipInputStream zis = new ZipInputStream(new FileInputStream(inf));
471 ZipEntry ze = zis.getNextEntry();
473 String name = ze.getName();
474 if (!name.endsWith(".class")) {
475 out.putNextEntry(ze);
476 byte b[] = new byte[1024];
478 int numread = zis.read(b, 0, b.length);
479 if (numread==-1) break;
480 out.write(b, 0, numread);
484 System.out.println("updating " + name.substring(0, name.length()-6).replace('$','.').replace('/','.'));
485 ClassFile cf = new ClassFile(new DataInputStream(zis));
488 for(Iterator it = cx.enumerateClassFiles().iterator(); it.hasNext();) {
489 ClassFile cf = (ClassFile)it.next();
490 processClassFile(cf);
492 for(Iterator it = cx.enumerateClassFiles().iterator(); it.hasNext();) {
493 ClassFile cf = (ClassFile)it.next();
494 out.putNextEntry(new ZipEntry(cf.getType().getName().replace('.', '/') + ".class"));