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