optimized constant pool
[org.ibex.classgen.git] / src / org / ibex / classgen / CPGen.java
index 91b002e..c41d67d 100644 (file)
@@ -5,53 +5,61 @@ import java.io.*;
 
 import org.ibex.classgen.util.*;
 
-public class CPGen {
-    private Hashtable entries = new Hashtable();
-    private int nextIndex = 1; // 0 is reserved
-    private boolean sealed;
+class CPGen {
+    private final Hashtable entries = new Hashtable();
+    private int usedSlots = 1; // 0 is reserved
+    private int state = OPEN;
+    private static final int OPEN = 0;
+    private static final int STABLE = 1; // existing entries won't change
+    private static final int SEALED = 2; // no new entries
     
     CPGen() { }
     
     /*
      * Entries 
      */
-    abstract static class Ent implements Sort.Comparable {
-        int index;
-        public abstract int tag();
-        public void dump(DataOutput o) throws IOException { o.writeByte(tag()); }
-        public int compareTo(Object o) {
-            if(!(o instanceof Ent)) return 1;
-            int oi = ((Ent)o).index;
-            if(index < oi) return -1;
-            if(index > oi) return 1;
-            return 0;
-        }
+    abstract static class Ent {
+        int n; // this is the refcount if state == OPEN, index if >= STABLE
+        int tag;
+        
+        Ent(int tag) { this.tag = tag; }
+        
+        void dump(DataOutput o) throws IOException { o.writeByte(tag); }
+        String debugToString() { return toString(); } // so we can remove this method when not debugging
     }
     
-    abstract static class OneU2Ent extends Ent      { int i;  public void dump(DataOutput o) throws IOException { super.dump(o); o.writeShort(i);  } }
-    abstract static class OneU4Ent extends Ent      { int i;  public void dump(DataOutput o) throws IOException { super.dump(o); o.writeInt(i);    } }
-    abstract static class TwoU2Ent extends OneU2Ent { int i2; public void dump(DataOutput o) throws IOException { super.dump(o); o.writeShort(i2); } }
-    abstract static class TwoU4Ent extends OneU4Ent { int i2; public void dump(DataOutput o) throws IOException { super.dump(o); o.writeInt(i2);   } }
-    
-    static class IntEnt         extends OneU4Ent { public int tag() { return 3;  } } // word1: bytes
-    static class FloatEnt       extends OneU4Ent { public int tag() { return 4;  } } // word1: bytes
-    static class LongEnt        extends TwoU4Ent { public int tag() { return 5;  } } // word1/2: bytes
-    static class DoubleEnt      extends TwoU4Ent { public int tag() { return 6;  } } // word1/2: bytes
-    static class ClassEnt       extends OneU2Ent { public int tag() { return 7;  } } // word1: name_index
-    static class StringEnt      extends OneU2Ent { public int tag() { return 8;  } } // word1: string_index
-    static class FieldRefEnt    extends TwoU2Ent { public int tag() { return 9;  } } // word1: class_index word2: name_and_type_index
-    static class MethodRefEnt   extends TwoU2Ent { public int tag() { return 10; } } // word1: class_index word2: name_and_type_index
-    static class IMethodRefEnt  extends TwoU2Ent { public int tag() { return 11; } } // word1: class_index word2: name_and_type_index
-    static class NameAndTypeEnt extends TwoU2Ent { public int tag() { return 12; } } // word1: name_index  word2: descriptor_index
+    static class IntEnt extends Ent {
+        int i;
+        IntEnt(int tag) { super(tag); }
+        void dump(DataOutput o) throws IOException { super.dump(o); o.writeInt(i);  }
+    }
     
-    static class Utf8Ent extends Ent {
-        String s;
-        public int tag() { return 1; }
-        public void dump(DataOutput o) throws IOException {
+    static class LongEnt extends Ent {
+        long l;
+        LongEnt(int tag) { super(tag); }
+        void dump(DataOutput o) throws IOException { super.dump(o); o.writeLong(l); }
+    }
+    
+    static class CPRefEnt extends Ent {
+        Ent e1;
+        Ent e2;
+        CPRefEnt(int tag) { super(tag); }
+        
+        String debugToString() { return "[" + e1.n + ":" + e1.debugToString() + (e2 == null ? "" : " + " + e2.n + ":" + e2.debugToString()) + "]"; }
+        
+        void dump(DataOutput o) throws IOException {
             super.dump(o);
-            o.writeUTF(s);
+            if(e1.n == 6 || (e2!=null && e2.n == 6)) System.err.println(debugToString() + " refs 6");
+            o.writeShort(e1.n);
+            if(e2 != null) o.writeShort(e2.n);
         }
-        public String toString() { return "Utf8: " + s; }
+    }
+        
+    static class Utf8Ent extends Ent {
+        String s;
+        Utf8Ent() { super(1); }
+        String debugToString() { return s; }
+        void dump(DataOutput o) throws IOException { super.dump(o); o.writeUTF(s); }
     }
     
     /*
@@ -63,120 +71,165 @@ public class CPGen {
         public boolean equals(Object o) { return o instanceof Utf8Key && ((Utf8Key)o).s.equals(s); }
         public int hashCode() { return ~s.hashCode(); }
     }
-    
-    public static class NameAndType {
+        
+    static class NameAndTypeKey {
         String name;
         String type;
-        public NameAndType(String name, String type) { this.name = name; this.type = type; }
+        NameAndTypeKey(String name, String type) { this.name = name; this.type = type; }
         public boolean equals(Object o_) {
-            if(!(o_ instanceof NameAndType)) return false;
-            NameAndType o = (NameAndType) o_;
+            if(!(o_ instanceof NameAndTypeKey)) return false;
+            NameAndTypeKey o = (NameAndTypeKey) o_;
             return o.name.equals(name) && o.type.equals(type);
         }
         public int hashCode() { return name.hashCode() ^ type.hashCode(); }
     }
     
-    static abstract class FieldMethodRef {
-        Type.Object klass;
-        NameAndType nameAndType;
-        public FieldMethodRef(Type.Object klass, NameAndType nameAndType) { this.klass = klass; this.nameAndType = nameAndType; }
-        public boolean equals(Object o_) {
-            if(!(o_ instanceof FieldMethodRef)) return false;
-            FieldMethodRef o = (FieldMethodRef) o_;
-            return o.klass.equals(klass) && o.nameAndType.equals(nameAndType);
-        }
-    }
-    
-    public static class FieldRef   extends FieldMethodRef { public FieldRef  (Type.Object c, NameAndType t) { super(c,t); } }
-    public static class MethodRef  extends FieldMethodRef { public MethodRef (Type.Object c, NameAndType t) { super(c,t); } }
-    public static class IMethodRef extends FieldMethodRef { public IMethodRef(Type.Object c, NameAndType t) { super(c,t); } }
-    
     /*
      * Methods
      */
-    public void seal() { sealed = true; }
     
     public final Ent get(Object o) { return (Ent) entries.get(o); }
     public final Ent getUtf8(String s) { return get(new Utf8Key(s)); }
+    public final int getIndex(Object o) {
+        Ent e = get(o);
+        if(e == null) throw new IllegalStateException("entry not found");
+        return getIndex(e);
+    }
+    public final int getUtf8Index(String s) {
+        Ent e = getUtf8(s);
+        if(e == null) throw new IllegalStateException("entry not found");
+        return getIndex(e);
+    }
+    public final int getIndex(Ent ent) {
+        if(state < STABLE) throw new IllegalStateException("constant pool is not stable");
+        return ent.n;
+    }
     
-    public final Ent addNameAndType(String name, String descriptor) { return add(new NameAndType(name,descriptor)); }
+    public final Ent addNameAndType(String name, String descriptor) { return add(new NameAndTypeKey(name,descriptor)); }
     public final Ent addUtf8(String s) { return add(new Utf8Key(s)); }
     
     public final Ent add(Object o) {
-        if(sealed) throw new IllegalStateException("constant pool is sealed");
+        if(state == SEALED) throw new IllegalStateException("constant pool is sealed");
             
         Ent ent = get(o);
-        if(ent != null) return ent;
-        
-        if(nextIndex == 65536) throw new ClassGen.Exn("constant pool full");
+        if(ent != null) {
+            if(state == OPEN) ent.n++;
+            return ent;
+        }
         
         if(o instanceof Type.Object) {
-            ClassEnt ce = new ClassEnt();
-            ce.i = addUtf8(((Type.Object)o).internalForm()).index;
+            CPRefEnt ce = new CPRefEnt(7);
+            ce.e1 = addUtf8(((Type.Object)o).internalForm());
             ent = ce;
         } else if(o instanceof String) {
-            StringEnt se = new StringEnt();
-            se.i = addUtf8((String)o).index;
-            ent = se;
+            CPRefEnt ce = new CPRefEnt(8);
+            ce.e1 = addUtf8((String)o);
+            ent = ce;
         } else if(o instanceof Integer) {
-            IntEnt ie = new IntEnt();
-            ie.i = ((Integer)o).intValue();
-            ent = ie;
+            IntEnt ue = new IntEnt(3);
+            ue.i = ((Integer)o).intValue();
+            ent = ue;
         } else if(o instanceof Float) {
-            FloatEnt fe = new FloatEnt();
-            fe.i = Float.floatToIntBits(((Float)o).floatValue());
-            ent = fe;
+            IntEnt ue = new IntEnt(4);
+            ue.i = Float.floatToIntBits(((Float)o).floatValue());
+            ent = ue;
         } else if(o instanceof Long) {
-            LongEnt le = new LongEnt();
-            long l = ((Long)o).longValue();
-            le.i = (int)(l>>>32);
-            le.i2 = (int)l;
+            LongEnt le = new LongEnt(5);
+            le.l = ((Long)o).longValue();
             ent = le;
         } else if(o instanceof Double) {
-            DoubleEnt de = new DoubleEnt();
-            long l = Double.doubleToLongBits(((Double)o).doubleValue());
-            de.i = (int)(l>>>32);
-            de.i2 = (int)l;
-            ent = de;
+            LongEnt le = new LongEnt(6);
+            le.l = Double.doubleToLongBits(((Double)o).doubleValue());
+            ent = le;
         } else if(o instanceof Utf8Key) {
             Utf8Ent ue = new Utf8Ent();
             ue.s = ((Utf8Key)o).s;
             ent = ue;
-        } else if(o instanceof NameAndType) {
-            NameAndTypeEnt ne = new NameAndTypeEnt();
-            NameAndType key = (NameAndType) o;
-            ne.i = addUtf8(key.name).index;
-            ne.i2 = addUtf8(key.type).index;
-            ent = ne;
-        } else if(o instanceof FieldMethodRef) {
-            FieldMethodRef key = (FieldMethodRef) o;
-            TwoU2Ent fme;
-            if(o instanceof MethodRef) fme = new MethodRefEnt();
-            else if(o instanceof IMethodRef) fme = new IMethodRefEnt();
-            else if(o instanceof FieldRef) fme = new FieldRefEnt();
-            else throw new Error("should never happen");
-            fme.i = add(key.klass).index;
-            fme.i2 = add(key.nameAndType).index;
-            ent = fme;
+        } else if(o instanceof NameAndTypeKey) {
+            CPRefEnt ce = new CPRefEnt(12);
+            NameAndTypeKey key = (NameAndTypeKey) o;
+            ce.e1 = addUtf8(key.name);
+            ce.e2 = addUtf8(key.type);
+            ent = ce;
+        } else if(o instanceof ClassGen.FieldOrMethodRef) {
+            ClassGen.FieldOrMethodRef key = (ClassGen.FieldOrMethodRef) o;
+            int tag = o instanceof FieldRef ? 9 : o instanceof MethodRef ? 10 : o instanceof MethodRef.I ? 11 : 0;
+            if(tag == 0) throw new Error("should never happen");
+            CPRefEnt ce = new CPRefEnt(tag);
+            ce.e1 = add(key.klass);
+            ce.e2 = addNameAndType(key.name,key.descriptor);
+            ent = ce;
         } else {
             throw new IllegalArgumentException("Unknown type passed to add");
         }
         
-        ent.index = nextIndex++;
+        int spaces = ent instanceof LongEnt ? 2 : 1;        
+        if(usedSlots + spaces > 65536) throw new ClassGen.Exn("constant pool full");
+        
+        ent.n = state == OPEN ? 1 : usedSlots; // refcount or index
+
+        usedSlots += spaces;        
+
         entries.put(o,ent);
         return ent;
     }
     
-    public int size() { return nextIndex; }
+    public int slots() { return usedSlots; }
+
+    public void seal() { state = SEALED; }
     
-    public void dump(DataOutput o) throws IOException {
-        Ent[] ents = new Ent[nextIndex-1];
+    private Ent[] asArray() {
+        int count = entries.size();
+        Ent[] ents = new Ent[count];
         int i=0;
         Enumeration e = entries.keys();
         while(e.hasMoreElements()) ents[i++] = (Ent) entries.get(e.nextElement());
-        Sort.sort(ents);
-        for(i=0;i<ents.length;i++) {
-            //System.err.println("" + (i+1) + ": " + ents[i]);
+        if(i != count) throw new Error("should never happen");
+        return ents;
+    }
+    
+    private static void assignIndex(Ent[] ents) {
+        int index = 1;
+        for(int i=0;i<ents.length;i++) {
+            Ent ent = ents[i];
+            ent.n = index;
+            index += ent instanceof LongEnt ? 2 : 1;
+        }
+    }
+        
+    public void stable() {
+        if(state != OPEN) return;
+        state = STABLE;
+        assignIndex(asArray());
+    } 
+
+    private static final Sort.CompareFunc compareFunc = new Sort.CompareFunc() {
+        public int compare(Object a_, Object b_) {
+            return ((Ent)a_).n - ((Ent)b_).n;
+        }
+    };
+    
+    private static final Sort.CompareFunc reverseCompareFunc = new Sort.CompareFunc() {
+        public int compare(Object a_, Object b_) {
+            return ((Ent)b_).n - ((Ent)a_).n;
+        }
+    };
+    
+    public void optimize() {
+        if(state != OPEN) throw new IllegalStateException("can't optimize a stable constant pool");
+        Ent[] ents = asArray();
+        Sort.sort(ents,reverseCompareFunc);
+        for(int i=0;i<ents.length;i++)
+            System.err.println("" + i + " -> " + ents[i].debugToString() + " (" + ents[i].n + ")");
+        state = STABLE;
+        assignIndex(ents);
+    }
+    
+    public void dump(DataOutput o) throws IOException {
+        Ent[] ents = asArray();
+        Sort.sort(ents,compareFunc);
+        for(int i=0;i<ents.length;i++) {
+            System.err.println("" + ents[i].n + ": " + ents[i].debugToString());
             ents[i].dump(o);
         }
     }