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