add FleetProcess.sendWord() that takes a signal
[fleet.git] / src / edu / berkeley / fleet / interpreter / Interpreter.java
1 package edu.berkeley.fleet.interpreter;
2 import java.io.*;
3 import java.util.*;
4 import java.util.concurrent.*;
5 import java.lang.reflect.*;
6 import edu.berkeley.sbp.util.ANSI;
7 import edu.berkeley.fleet.api.*;
8 import edu.berkeley.fleet.two.*;
9 import edu.berkeley.fleet.assembler.*;
10 import edu.berkeley.fleet.util.*;
11
12 public class Interpreter extends FleetTwoFleet {
13
14     /** used to allocate serial numbers; see InterpreterDestination for further detail */
15     int maxAllocatedDestinationSerialNumber = 0;
16
17     private InterpreterShip debugShip = null;
18     private BlockingQueue<BitVector> debugStream = new LinkedBlockingQueue<BitVector>();
19     private LinkedHashMap<String,InterpreterShip> ships = new LinkedHashMap<String,InterpreterShip>();
20     public Iterator<Ship> iterator() { return (Iterator<Ship>)(Object)ships.values().iterator(); }
21     public Ship getShip(String type, int ordinal) {
22         for(Ship s : this)
23             if (s.getType().equals(type))
24                 if (ordinal-- <= 0)
25                     return s;
26         return null;
27     }
28
29     /** do not use this; it is going to go away */
30     public Interpreter() { this(true); }
31     public Interpreter(boolean logging) {
32         this(new String[] {
33                 "Debug",
34                 "Memory",
35                 "Memory",
36                 "Memory",
37                 "Alu",
38                 "Alu",
39                 "Alu",
40                 "Alu",
41                 "Alu",
42                 "Alu",
43                 "Alu",
44                 "Fifo",
45                 "Fifo",
46                 "Counter",
47                 "Counter",
48                 "Counter",
49                 "Counter",
50                 "Counter",
51                 "Counter",
52                 "Counter",
53                 "Counter",
54                 "Counter",
55                 "Counter",
56                 "Counter",
57                 "Counter",
58                 "Counter",
59                 "Counter",
60                 "Lut3",
61                 "CarrySaveAdder",
62                 "Rotator",
63             }, logging);
64     }
65
66     public Interpreter(String[] ships, boolean logging) {
67         int i=0;
68         Log.quiet = !logging;
69         for(String s : ships) {
70             createShip(ships[i], ships[i]+"_"+i);
71             i++;
72         }
73     }
74
75     private Ship createShip(String shipType, String shipname) {
76         try {
77             if (ships.get(shipname)!=null) return ships.get(shipname);
78             Class c = Class.forName("edu.berkeley.fleet.interpreter."+shipType);
79             Constructor con = c.getConstructor(new Class[] { Interpreter.class, String.class, ShipDescription.class });
80             String src = "/ships/" + shipType + ".ship";
81             InputStream is = getClass().getResourceAsStream(src);
82             BufferedReader br = new BufferedReader(new InputStreamReader(is));
83             ShipDescription sd = new ShipDescription(this, shipType, br);
84             InterpreterShip ret = (InterpreterShip)con.newInstance(new Object[] { this, shipname, sd });
85             ships.put(shipname, ret);
86             if (shipType.equals("Debug") && debugShip == null)
87                 debugShip = ret;
88             return ret;
89         } catch (Exception e) {
90             e.printStackTrace();
91             return null;
92         }
93     }
94
95     void debug(long d) { debug(new BitVector(getWordWidth()).set(d)); }
96     void debug(BitVector data) {
97         try {
98             if (debugStream != null) debugStream.put(data);
99             else Log.println(ANSI.invert("   DEBUG: got a datum: " +  data+ANSI.clreol()));
100         } catch (Exception e) {
101             throw new RuntimeException(e);
102         }
103     }
104
105     // Instruction Encoding /////////////////////////////////////////////////////////////////////////
106
107     public BitVector getDestAddr(Path path) {
108         long ret = ((InterpreterDestination)path.getDestination()).getSerialNumber();
109         BitVector sig = path.getSignal();
110         BitVector bv = new BitVector(DISPATCH_PATH.valmaskwidth+1);
111         bv.set(ret);
112         if (sig != null) {
113             if (sig.length() > 1) throw new RuntimeException("signal was " + sig.length() + " bits long!");
114             if (sig.length() > 0 && sig.get(0)) bv.set(bv.length()-1,true);
115         }
116         return bv;
117     }
118
119
120     // ShipDescription //////////////////////////////////////////////////////////////////////////////
121
122     public void expand(ShipDescription sd) {
123         try {
124             String filename = sd.getName();
125             //String filename = (sd.getName().charAt(0)+"").toUpperCase() + sd.getName().substring(1).toLowerCase();
126             File outf = new File("build/java/edu/berkeley/fleet/interpreter/"+filename+".java");
127             new File(outf.getParent()).mkdirs();
128             System.err.println("writing to " + outf);
129             FileOutputStream out = new FileOutputStream(outf);
130             PrintWriter pw = new PrintWriter(out);
131
132             pw.println("package edu.berkeley.fleet.interpreter;");
133             pw.println("import edu.berkeley.sbp.util.ANSI;");
134             pw.println("import edu.berkeley.fleet.api.*;");
135             pw.println("import edu.berkeley.fleet.two.*;");
136             pw.println("import edu.berkeley.fleet.*;");
137             pw.println("import java.util.*;");
138             pw.println("import java.io.*;");
139             pw.println("");
140             pw.println("public class "+filename+" extends InterpreterShip {");
141             pw.println("");
142             pw.println("    public "+filename+"(Interpreter fleet, String name, ShipDescription sd) {");
143             pw.println("       super(fleet, sd);");
144             pw.println("    }");
145             pw.println("");
146             for(DockDescription b : sd) {
147                 String name = b.getName();
148                 pw.print("    InterpreterDock box_");
149                 pw.print(name);
150                 pw.print(" = new InterpreterDock(this, shipDescription.getDockDescription(\""+name+"\"));");
151             }
152             pw.println("");
153             pw.println(sd.getSection("fleeterpreter"));
154             pw.println("}");
155             pw.flush();
156             pw.close();
157         } catch (Exception e) { throw new RuntimeException(e); }
158     }
159
160     // Run //////////////////////////////////////////////////////////////////////////////
161
162     public FleetProcess run(final Instruction[] instructions) {
163         InterpreterProcess ip = initialize(instructions);
164         new Thread(ip).start();
165         return ip;
166     }
167
168     public InterpreterProcess initialize(Instruction[] instr) {
169         return new InterpreterProcess(instr);
170     }
171
172     public class InterpreterProcess extends FleetProcess implements Runnable {
173         private Instruction[] instructions;
174         public synchronized void sendWord(Destination d, BitVector word) { sendWord(d, word, null); }
175         public synchronized void sendWord(Destination d, BitVector word, BitVector signal) {
176             InterpreterPath path = (InterpreterPath)debugShip.getDock("in").getPath(d, signal==null?new BitVector(1):signal);
177             ((InterpreterDestination)d).
178                 addDataFromFabric(new Packet(path, word, false));
179         }
180         public synchronized void sendToken(Destination d) {
181             InterpreterPath path = (InterpreterPath)debugShip.getDock("in").getPath(d, new BitVector(1));
182             ((InterpreterDestination)d).
183                 addDataFromFabric(new Packet(path, new BitVector(getWordWidth()), true));
184         }
185         public InterpreterProcess(Instruction[] instructions) {
186             this.instructions = instructions;
187             for(Instruction i : instructions)
188                 sendInstruction(i);
189         }
190         public Fleet getFleet() { return Interpreter.this; }
191         public synchronized void sendInstruction(Instruction i) {
192             Log.dispatch(i);
193             long il = writeInstruction(i, debugShip.getDock("in"));
194             Path path = debugShip.getDock("in").getPath(i.dock.getInstructionDestination(), null);
195             new Packet((InterpreterPath)path, new BitVector(getWordWidth()).set(il), false).send();
196         }
197         public Dock getDebugInputDock() { return debugShip.getDock("in"); }
198         public BitVector recvWord() {
199             try {
200                 return debugStream.take();
201             } catch (Exception e) { throw new RuntimeException(e); }
202         }
203         protected void _terminate() { }
204         public void run() {
205             try {
206                 while(!isTerminated()) {
207                     flush();
208                 }
209                 for(InterpreterShip ship : ships.values())
210                     ship.reset();
211                 debugStream.clear();
212             } catch (Exception e) {
213                 if (isTerminated()) return;
214                 throw new RuntimeException(e);
215             }
216         }
217
218         public void flush() {
219             // FIXME: should this run until we detect some sort of "quiescence"?  OTOH that might never happen.
220             for(InterpreterShip ship : ships.values())
221                 for(int j=0; j<10; j++)
222                     if (!isTerminated())
223                         synchronized(this) {
224                             ship._service();
225                         }
226         }
227
228         public synchronized void step(Dock d) {
229             ((InterpreterDock)d).service();
230         }
231         
232         public synchronized void step(Ship s) {
233             ((InterpreterShip)s).service();
234         }
235
236     }
237 }