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