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