add scheduling simulator
[IRC.git] / Robust / src / Main / Main.java
1 package Main;
2
3 import java.io.FileOutputStream;
4 import java.io.InputStream;
5 import java.io.PrintStream;
6 import java.io.Reader;
7 import java.io.BufferedReader;
8 import java.io.FileReader;
9 import java.io.FileInputStream;
10 import java.util.Iterator;
11 import java.util.Vector;
12
13 import IR.Tree.ParseNode;
14 import IR.Tree.BuildIR;
15 import IR.Tree.SemanticCheck;
16 import IR.Flat.BuildFlat;
17 import IR.Flat.BuildCode;
18 import IR.ClassDescriptor;
19 import IR.State;
20 import IR.TaskDescriptor;
21 import IR.TypeUtil;
22 import Analysis.Scheduling.Schedule;
23 import Analysis.Scheduling.ScheduleAnalysis;
24 import Analysis.Scheduling.ScheduleEdge;
25 import Analysis.Scheduling.ScheduleNode;
26 import Analysis.Scheduling.ScheduleSimulator;
27 import Analysis.TaskStateAnalysis.TaskAnalysis;
28 import Analysis.TaskStateAnalysis.TaskTagAnalysis;
29 import Analysis.TaskStateAnalysis.TaskGraph;
30 import Analysis.CallGraph.CallGraph;
31 import Analysis.TaskStateAnalysis.FEdge;
32 import Analysis.TaskStateAnalysis.FlagState;
33 import Analysis.TaskStateAnalysis.TagAnalysis;
34 import Analysis.TaskStateAnalysis.GarbageAnalysis;
35 import Analysis.TaskStateAnalysis.ExecutionGraph;
36 import Analysis.TaskStateAnalysis.SafetyAnalysis;
37 import Analysis.Locality.LocalityAnalysis;
38 import Analysis.Locality.GenerateConversions;
39 import Analysis.Prefetch.PrefetchAnalysis;
40 import Analysis.FlatIRGraph.FlatIRGraph;
41 import Analysis.OwnershipAnalysis.OwnershipAnalysis;
42 import Interface.*;
43
44 public class Main {
45
46     /** Main method for the compiler.  */
47
48   public static void main(String args[]) throws Exception {
49       String ClassLibraryPrefix="./ClassLibrary/";
50       State state=new State();
51
52       for(int i=0;i<args.length;i++) {
53           String option=args[i];
54           if (option.equals("-precise"))
55               IR.Flat.BuildCode.GENERATEPRECISEGC=true;
56           else if (option.equals("-prefetch"))
57               state.PREFETCH=true;
58           else if (option.equals("-dir"))
59               IR.Flat.BuildCode.PREFIX=args[++i]+"/";
60           else if (option.equals("-selfloop"))
61               state.selfloops.add(args[++i]);
62           else if (option.equals("-classlibrary"))
63               ClassLibraryPrefix=args[++i]+"/";
64           else if (option.equals("-mainclass"))
65               state.main=args[++i];
66           else if (option.equals("-struct"))
67               state.structfile=args[++i];
68           else if (option.equals("-conscheck"))
69               state.CONSCHECK=true;
70           else if (option.equals("-task"))
71               state.TASK=true;
72           else if (option.equals("-taskstate"))
73               state.TASKSTATE=true;
74           else if (option.equals("-tagstate"))
75               state.TAGSTATE=true;
76           else if (option.equals("-flatirtasks")) {
77               state.FLATIRGRAPH=true;
78               state.FLATIRGRAPHTASKS=true;
79           }
80           else if (option.equals("-flatirusermethods")) {
81               state.FLATIRGRAPH=true;
82               state.FLATIRGRAPHUSERMETHODS=true;
83           }
84           else if (option.equals("-flatirlibmethods")) {
85               state.FLATIRGRAPH=true;
86               state.FLATIRGRAPHLIBMETHODS=true;
87           }
88           else if (option.equals("-ownership"))
89               state.OWNERSHIP=true;
90           else if (option.equals("-optional"))
91               state.OPTIONAL=true;
92           else if (option.equals("-scheduling"))
93                   state.SCHEDULING=true; 
94           else if (option.equals("-thread"))
95               state.THREAD=true;
96           else if (option.equals("-dsm"))
97               state.DSM=true;
98           else if (option.equals("-webinterface"))
99               state.WEBINTERFACE=true;
100           else if (option.equals("-instructionfailures"))
101               state.INSTRUCTIONFAILURE=true;
102           else if (option.equals("-help")) {
103               System.out.println("-classlibrary classlibrarydirectory -- directory where classlibrary is located");
104               System.out.println("-selfloop task -- this task doesn't self loop its parameters forever");
105               System.out.println("-dir outputdirectory -- output code in outputdirectory");
106               System.out.println("-struct structfile -- output structure declarations for repair tool");
107               System.out.println("-mainclass -- main function to call");
108               System.out.println("-dsm -- distributed shared memory support");
109               System.out.println("-precise -- use precise garbage collection");
110               System.out.println("-conscheck -- turn on consistency checking");
111               System.out.println("-task -- compiler for tasks");
112               System.out.println("-thread -- threads");
113               System.out.println("-instructionfailures -- insert code for instruction level failures");
114               System.out.println("-taskstate -- do task state analysis");
115               System.out.println("-flatirtasks -- create dot files for flat IR graphs of tasks");
116               System.out.println("-flatirusermethods -- create dot files for flat IR graphs of user methods");
117               System.out.println("-flatirlibmethods -- create dot files for flat IR graphs of library class methods");
118               System.out.println("  note: -flatirusermethods or -flatirlibmethods currently generate all class method flat IR graphs");
119               System.out.println("-ownership -- do ownership analysis");
120               System.out.println("-optional -- enable optional arguments");
121               System.out.println("-webinterface -- enable web interface");
122               System.out.println("-help -- print out help");
123               System.exit(0);
124           } else {
125               readSourceFile(state, args[i]);
126           }
127       }
128       
129
130       readSourceFile(state, ClassLibraryPrefix+"System.java");
131       readSourceFile(state, ClassLibraryPrefix+"String.java");
132       readSourceFile(state, ClassLibraryPrefix+"HashSet.java");
133       readSourceFile(state, ClassLibraryPrefix+"HashMap.java");
134       readSourceFile(state, ClassLibraryPrefix+"HashMapIterator.java");
135       readSourceFile(state, ClassLibraryPrefix+"HashEntry.java");
136       readSourceFile(state, ClassLibraryPrefix+"Integer.java");
137       readSourceFile(state, ClassLibraryPrefix+"StringBuffer.java");
138       readSourceFile(state, ClassLibraryPrefix+"FileInputStream.java");
139       readSourceFile(state, ClassLibraryPrefix+"InputStream.java");
140       readSourceFile(state, ClassLibraryPrefix+"OutputStream.java");
141       readSourceFile(state, ClassLibraryPrefix+"FileOutputStream.java");
142       readSourceFile(state, ClassLibraryPrefix+"File.java");
143       readSourceFile(state, ClassLibraryPrefix+"Math.java");
144       readSourceFile(state, ClassLibraryPrefix+"InetAddress.java");
145       readSourceFile(state, ClassLibraryPrefix+"SocketInputStream.java");
146       readSourceFile(state, ClassLibraryPrefix+"SocketOutputStream.java");
147       readSourceFile(state, ClassLibraryPrefix+"gnu/Random.java");
148
149
150       if (state.TASK) {
151           readSourceFile(state, ClassLibraryPrefix+"Object.java");
152           readSourceFile(state, ClassLibraryPrefix+"TagDescriptor.java");
153       } else if (state.DSM) {
154           readSourceFile(state, ClassLibraryPrefix+"ThreadDSM.java");
155           readSourceFile(state, ClassLibraryPrefix+"ObjectJavaDSM.java");
156       } else {
157           if (state.THREAD) {
158               readSourceFile(state, ClassLibraryPrefix+"Thread.java");
159               readSourceFile(state, ClassLibraryPrefix+"ObjectJava.java");
160           } else
161               readSourceFile(state, ClassLibraryPrefix+"ObjectJavaNT.java");
162       }
163
164       if (state.TASK) {
165           readSourceFile(state, ClassLibraryPrefix+"StartupObject.java");
166           readSourceFile(state, ClassLibraryPrefix+"Socket.java");
167           readSourceFile(state, ClassLibraryPrefix+"ServerSocket.java");
168       } else {
169           readSourceFile(state, ClassLibraryPrefix+"SocketJava.java");
170           readSourceFile(state, ClassLibraryPrefix+"ServerSocketJava.java");
171       }
172
173       BuildIR bir=new BuildIR(state);
174       bir.buildtree();
175       
176       TypeUtil tu=new TypeUtil(state);
177       
178       SemanticCheck sc=new SemanticCheck(state,tu);
179       sc.semanticCheck();
180       tu.createFullTable();
181
182       BuildFlat bf=new BuildFlat(state,tu);
183       bf.buildFlat();
184       SafetyAnalysis sa=null;
185
186       if (state.TAGSTATE) {
187           CallGraph callgraph=new CallGraph(state);
188           TagAnalysis taganalysis=new TagAnalysis(state, callgraph);
189           TaskTagAnalysis tta=new TaskTagAnalysis(state, taganalysis);
190       }
191
192       if (state.TASKSTATE) {
193           CallGraph callgraph=new CallGraph(state);
194           TagAnalysis taganalysis=new TagAnalysis(state, callgraph);
195           TaskAnalysis ta=new TaskAnalysis(state, taganalysis);
196           ta.taskAnalysis();
197           TaskGraph tg=new TaskGraph(state, ta);
198           tg.createDOTfiles();
199           
200           if (state.OPTIONAL) {
201               ExecutionGraph et=new ExecutionGraph(state, ta);
202               et.createExecutionGraph();
203               sa = new SafetyAnalysis(et.getExecutionGraph(), state, ta);
204               sa.doAnalysis();
205               state.storeAnalysisResult(sa.getResult());
206               state.storeOptionalTaskDescriptors(sa.getOptionalTaskDescriptors());
207           }
208           
209           if (state.WEBINTERFACE) {
210               GarbageAnalysis ga=new GarbageAnalysis(state, ta);
211               WebInterface wi=new WebInterface(state, ta, tg, ga, taganalysis);
212               JhttpServer serve=new JhttpServer(8000,wi);
213               serve.run();
214           }
215           
216           if (state.SCHEDULING) {
217               // Save the current standard input, output, and error streams
218               // for later restoration.
219               PrintStream       origOut = System.out;
220
221               // Create a new output stream for the standard output.
222               PrintStream       stdout  = null;
223               try {
224                   stdout = new PrintStream (new FileOutputStream("SimulatorResult.out"));
225               } catch (Exception e) {
226                   // Sigh.  Couldn't open the file.
227                   System.out.println ("Redirect:  Unable to open output file!");
228                   System.exit (1);
229               }
230
231               // Print stuff to the original output and error streams.
232               // On most systems all of this will end up on your console when you
233               // run this application.
234               origOut.println ("\nRedirect:  Round #1");
235               System.out.println ("Test output via 'System.out'.");
236               origOut.println ("Test output via 'origOut' reference.");
237
238               // Set the System out and err streams to use our replacements.
239               System.setOut(stdout);
240
241               // Print stuff to the original output and error streams.
242               // The stuff printed through the 'origOut' and 'origErr' references
243               // should go to the console on most systems while the messages
244               // printed through the 'System.out' and 'System.err' will end up in
245               // the files we created for them.
246               origOut.println ("\nRedirect:  Round #2");
247               System.out.println ("Test output via 'SimulatorResult.out'.");
248               origOut.println ("Test output via 'origOut' reference.");
249               
250               // for test
251               // Randomly set the newRate and probability of FEdges
252               java.util.Random r=new java.util.Random();
253               int tint = 0;
254               for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator();it_classes.hasNext();) {
255                   ClassDescriptor cd=(ClassDescriptor) it_classes.next();
256                   if(cd.hasFlags()){
257                       Vector rootnodes=ta.getRootNodes(cd);
258                       if(rootnodes!=null)
259                           for(Iterator it_rootnodes=rootnodes.iterator();it_rootnodes.hasNext();){
260                               FlagState root=(FlagState)it_rootnodes.next();
261                               Vector allocatingTasks = root.getAllocatingTasks();
262                               if(allocatingTasks != null) {
263                                   for(int k = 0; k < allocatingTasks.size(); k++) {
264                                       TaskDescriptor td = (TaskDescriptor)allocatingTasks.elementAt(k);
265                                       Vector<FEdge> fev = (Vector<FEdge>)ta.getFEdgesFromTD(td);
266                                       int numEdges = fev.size();
267                                       int total = 100;
268                                       for(int j = 0; j < numEdges; j++) {
269                                           FEdge pfe = fev.elementAt(j);
270                                           if(numEdges - j == 1) {
271                                               pfe.setProbability(total);
272                                           } else {
273                                               if(total != 0) {
274                                                   do {
275                                                       tint = r.nextInt()%total;
276                                                   } while(tint <= 0);
277                                               }
278                                               pfe.setProbability(tint);
279                                               total -= tint;
280                                           }
281                                           do {
282                                               tint = r.nextInt()%10;
283                                           } while(tint <= 0);
284                                           //int newRate = tint;
285                                           int newRate = (j+1)%2+1;
286                                           /*do {
287                                               tint = r.nextInt()%100;
288                                           } while(tint <= 0);
289                                           int probability = tint;*/
290                                           int probability = 100;
291                                           pfe.addNewObjInfo(cd, newRate, probability);
292                                       }
293                                   }
294                               }
295                           }
296                       
297                       Iterator it_flags = ta.getFlagStates(cd).iterator();
298                       while(it_flags.hasNext()) {
299                           FlagState fs = (FlagState)it_flags.next();
300                           Iterator it_edges = fs.edges();
301                           while(it_edges.hasNext()) {
302                               do {
303                                   tint = r.nextInt()%10;
304                               } while(tint <= 0);
305                               ((FEdge)it_edges.next()).setExeTime(tint);
306                           }
307                       }
308                   }
309               }
310               
311               // generate multiple schedulings
312               ScheduleAnalysis scheduleAnalysis = new ScheduleAnalysis(state, ta);
313               scheduleAnalysis.preSchedule();
314               scheduleAnalysis.scheduleAnalysis();
315               scheduleAnalysis.setCoreNum(scheduleAnalysis.getSEdges4Test().size());
316               scheduleAnalysis.schedule();
317               
318               //simulate these schedulings
319               ScheduleSimulator scheduleSimulator = new ScheduleSimulator(scheduleAnalysis.getCoreNum(), state, ta);
320               Iterator it_scheduling = scheduleAnalysis.getSchedulingsIter();
321               int index = 0;
322               Vector<Integer> selectedScheduling = new Vector<Integer>();
323               int processTime = Integer.MAX_VALUE;
324               while(it_scheduling.hasNext()) {
325                   Vector<Schedule> scheduling = (Vector<Schedule>)it_scheduling.next();
326                   scheduleSimulator.setScheduling(scheduling);
327                   int tmpTime = scheduleSimulator.process();
328                   if(tmpTime < processTime) {
329                       selectedScheduling.clear();
330                       selectedScheduling.add(index);
331                       processTime = tmpTime;
332                   } else if(tmpTime == processTime) {
333                       selectedScheduling.add(index);
334                   }
335                   index++;
336               }
337               System.out.print("Selected schedulings with least exectution time " + processTime + ": \n\t");
338               for(int i = 0; i < selectedScheduling.size(); i++) {
339                   System.out.print(selectedScheduling.elementAt(i) + ", ");
340               }
341               System.out.println();
342               
343               /*ScheduleSimulator scheduleSimulator = new ScheduleSimulator(4, state, ta);
344               Vector<Schedule> scheduling = new Vector<Schedule>();
345               for(int i = 0; i < 4; i++) {
346                   Schedule schedule = new Schedule(i);
347                   scheduling.add(schedule);
348               }
349               Iterator it_tasks = state.getTaskSymbolTable().getAllDescriptorsIterator();
350               while(it_tasks.hasNext()) {
351                   TaskDescriptor td = (TaskDescriptor)it_tasks.next();
352                   if(td.getSymbol().equals("t10")) {
353                       scheduling.elementAt(1).addTask(td);
354                   } else {
355                       scheduling.elementAt(0).addTask(td);
356                   }
357               }
358               ClassDescriptor cd = (ClassDescriptor)state.getClassSymbolTable().get("E");
359               scheduling.elementAt(0).addTargetCore(cd, 1);
360               scheduleSimulator.setScheduling(scheduling);
361               scheduleSimulator.process();
362               
363               Vector<Schedule> scheduling1 = new Vector<Schedule>();
364               for(int i = 0; i < 4; i++) {
365                   Schedule schedule = new Schedule(i);
366                   scheduling1.add(schedule);
367               }
368               Iterator it_tasks1 = state.getTaskSymbolTable().getAllDescriptorsIterator();
369               while(it_tasks1.hasNext()) {
370                   TaskDescriptor td = (TaskDescriptor)it_tasks1.next();
371                   scheduling1.elementAt(0).addTask(td);
372               }
373               scheduleSimulator.setScheduling(scheduling1);
374               scheduleSimulator.process();*/
375               
376               // Close the streams.
377               try {
378                   stdout.close ();
379                   System.setOut(origOut);
380               } catch (Exception e) {
381                   origOut.println ("Redirect:  Unable to close files!");
382               }
383           }
384           
385       }
386
387       if (state.DSM) {
388           CallGraph callgraph=new CallGraph(state);
389           if (state.PREFETCH) {
390               PrefetchAnalysis pa=new PrefetchAnalysis(state, callgraph, tu);
391           }
392           LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu);
393           GenerateConversions gc=new GenerateConversions(la, state);
394           BuildCode bc=new BuildCode(state, bf.getMap(), tu, la);
395           bc.buildCode();
396       } else {
397           BuildCode bc=new BuildCode(state, bf.getMap(), tu, sa);
398           bc.buildCode();
399       }
400
401       if (state.FLATIRGRAPH) {
402           FlatIRGraph firg = new FlatIRGraph(state,
403                                              state.FLATIRGRAPHTASKS,
404                                              state.FLATIRGRAPHUSERMETHODS,
405                                              state.FLATIRGRAPHLIBMETHODS);
406       }
407
408       if (state.OWNERSHIP) {
409           //      OwnershipAnalysis oa = new OwnershipAnalysis(state);
410       }
411
412       System.exit(0);
413   }
414     
415     /** Reads in a source file and adds the parse tree to the state object. */
416     
417     private static void readSourceFile(State state, String sourcefile) throws Exception {
418         Reader fr = new BufferedReader(new FileReader(sourcefile));
419         Lex.Lexer l = new Lex.Lexer(fr);
420         java_cup.runtime.lr_parser g;
421         g = new Parse.Parser(l);
422         ParseNode p=null;
423         try {
424             p=(ParseNode) g./*debug_*/parse().value;
425         } catch (Exception e) {
426             System.err.println("Error parsing file:"+sourcefile);
427             e.printStackTrace();
428             System.exit(-1);
429         }
430         state.addParseNode(p);
431         if (l.numErrors()!=0) {
432             System.out.println("Error parsing "+sourcefile);
433             System.exit(l.numErrors());
434         }
435     }
436 }