3 import java.io.FileOutputStream;
4 import java.io.InputStream;
5 import java.io.PrintStream;
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;
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;
21 import IR.TaskDescriptor;
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;
47 /** Main method for the compiler. */
49 public static void main(String args[]) throws Exception {
50 String ClassLibraryPrefix="./ClassLibrary/";
51 State state=new State();
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"))
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")) {
69 state.CORENUM = Integer.parseInt(args[i]);
70 } else if (option.equals("-mainclass"))
72 else if (option.equals("-trueprob")) {
73 state.TRUEPROB=Double.parseDouble(args[++i]);
74 } else if (option.equals("-printflat"))
76 else if (option.equals("-struct"))
77 state.structfile=args[++i];
78 else if (option.equals("-conscheck"))
80 else if (option.equals("-task"))
82 else if (option.equals("-taskstate"))
84 else if (option.equals("-tagstate"))
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"))
97 else if (option.equals("-ownership"))
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;
106 } else if (option.equals("-ownaliasfile"))
107 state.OWNERSHIPALIASFILE=args[++i];
108 else if (option.equals("-optional"))
110 else if (option.equals("-raw"))
112 else if (option.equals("-scheduling"))
113 state.SCHEDULING=true;
114 else if (option.equals("-useprofile"))
115 state.USEPROFILE=true;
116 else if (option.equals("-thread"))
118 else if (option.equals("-dsm"))
120 else if (option.equals("-webinterface"))
121 state.WEBINTERFACE=true;
122 else if (option.equals("-instructionfailures"))
123 state.INSTRUCTIONFAILURE=true;
124 else if (option.equals("-help")) {
125 System.out.println("-classlibrary classlibrarydirectory -- directory where classlibrary is located");
126 System.out.println("-selfloop task -- this task doesn't self loop its parameters forever");
127 System.out.println("-dir outputdirectory -- output code in outputdirectory");
128 System.out.println("-struct structfile -- output structure declarations for repair tool");
129 System.out.println("-mainclass -- main function to call");
130 System.out.println("-dsm -- distributed shared memory support");
131 System.out.println("-precise -- use precise garbage collection");
132 System.out.println("-conscheck -- turn on consistency checking");
133 System.out.println("-task -- compiler for tasks");
134 System.out.println("-thread -- threads");
135 System.out.println("-trueprob <d> -- probability of true branch");
136 System.out.println("-printflat -- print out flat representation");
137 System.out.println("-instructionfailures -- insert code for instruction level failures");
138 System.out.println("-taskstate -- do task state analysis");
139 System.out.println("-flatirtasks -- create dot files for flat IR graphs of tasks");
140 System.out.println("-flatirusermethods -- create dot files for flat IR graphs of user methods");
141 System.out.println("-flatirlibmethods -- create dot files for flat IR graphs of library class methods");
142 System.out.println(" note: -flatirusermethods or -flatirlibmethods currently generate all class method flat IR graphs");
143 System.out.println("-ownership -- do ownership analysis");
144 System.out.println("-ownallocdepth <d> -- set allocation depth for ownership analysis");
145 System.out.println("-ownwritedots <all/final> -- write ownership graphs; can be all results or just final results");
146 System.out.println("-ownaliasfile <filename> -- write a text file showing all detected aliases in program tasks");
147 System.out.println("-optional -- enable optional arguments");
148 System.out.println("-webinterface -- enable web interface");
149 System.out.println("-help -- print out help");
152 readSourceFile(state, args[i]);
157 readSourceFile(state, ClassLibraryPrefix+"System.java");
158 readSourceFile(state, ClassLibraryPrefix+"String.java");
159 readSourceFile(state, ClassLibraryPrefix+"HashSet.java");
160 readSourceFile(state, ClassLibraryPrefix+"HashMap.java");
161 readSourceFile(state, ClassLibraryPrefix+"HashMapIterator.java");
162 readSourceFile(state, ClassLibraryPrefix+"HashEntry.java");
163 readSourceFile(state, ClassLibraryPrefix+"Integer.java");
164 readSourceFile(state, ClassLibraryPrefix+"StringBuffer.java");
166 readSourceFile(state, ClassLibraryPrefix+"FileInputStream.java");
167 readSourceFile(state, ClassLibraryPrefix+"InputStream.java");
168 readSourceFile(state, ClassLibraryPrefix+"OutputStream.java");
169 readSourceFile(state, ClassLibraryPrefix+"FileOutputStream.java");
170 readSourceFile(state, ClassLibraryPrefix+"File.java");
171 readSourceFile(state, ClassLibraryPrefix+"InetAddress.java");
172 readSourceFile(state, ClassLibraryPrefix+"SocketInputStream.java");
173 readSourceFile(state, ClassLibraryPrefix+"SocketOutputStream.java");
175 readSourceFile(state, ClassLibraryPrefix+"Math.java");
176 readSourceFile(state, ClassLibraryPrefix+"gnu/Random.java");
177 readSourceFile(state, ClassLibraryPrefix+"Vector.java");
178 readSourceFile(state, ClassLibraryPrefix+"Enumeration.java");
179 readSourceFile(state, ClassLibraryPrefix+"Dictionary.java");
180 readSourceFile(state, ClassLibraryPrefix+"Writer.java");
181 readSourceFile(state, ClassLibraryPrefix+"BufferedWriter.java");
182 readSourceFile(state, ClassLibraryPrefix+"OutputStreamWriter.java");
183 readSourceFile(state, ClassLibraryPrefix+"FileWriter.java");
184 readSourceFile(state, ClassLibraryPrefix+"Date.java");
187 readSourceFile(state, ClassLibraryPrefix+"Object.java");
188 readSourceFile(state, ClassLibraryPrefix+"TagDescriptor.java");
189 } else if (state.DSM) {
190 readSourceFile(state, ClassLibraryPrefix+"ThreadDSM.java");
191 readSourceFile(state, ClassLibraryPrefix+"ObjectJavaDSM.java");
192 readSourceFile(state, ClassLibraryPrefix+"Barrier.java");
195 readSourceFile(state, ClassLibraryPrefix+"Thread.java");
196 readSourceFile(state, ClassLibraryPrefix+"ObjectJava.java");
198 readSourceFile(state, ClassLibraryPrefix+"ObjectJavaNT.java");
202 readSourceFile(state, ClassLibraryPrefix+"StartupObject.java");
203 readSourceFile(state, ClassLibraryPrefix+"Socket.java");
204 readSourceFile(state, ClassLibraryPrefix+"ServerSocket.java");
206 readSourceFile(state, ClassLibraryPrefix+"SocketJava.java");
207 readSourceFile(state, ClassLibraryPrefix+"ServerSocketJava.java");
210 BuildIR bir=new BuildIR(state);
213 TypeUtil tu=new TypeUtil(state);
215 SemanticCheck sc=new SemanticCheck(state,tu);
217 tu.createFullTable();
219 BuildFlat bf=new BuildFlat(state,tu);
221 SafetyAnalysis sa=null;
222 PrefetchAnalysis pa=null;
224 if (state.TAGSTATE) {
225 CallGraph callgraph=new CallGraph(state);
226 TagAnalysis taganalysis=new TagAnalysis(state, callgraph);
227 TaskTagAnalysis tta=new TaskTagAnalysis(state, taganalysis);
230 if (state.TASKSTATE) {
231 CallGraph callgraph=new CallGraph(state);
232 TagAnalysis taganalysis=new TagAnalysis(state, callgraph);
233 TaskAnalysis ta=new TaskAnalysis(state, taganalysis);
235 TaskGraph tg=new TaskGraph(state, ta);
238 if (state.OPTIONAL) {
239 ExecutionGraph et=new ExecutionGraph(state, ta);
240 et.createExecutionGraph();
241 sa = new SafetyAnalysis(et.getExecutionGraph(), state, ta);
243 state.storeAnalysisResult(sa.getResult());
244 state.storeOptionalTaskDescriptors(sa.getOptionalTaskDescriptors());
247 if (state.WEBINTERFACE) {
248 GarbageAnalysis ga=new GarbageAnalysis(state, ta);
249 WebInterface wi=new WebInterface(state, ta, tg, ga, taganalysis);
250 JhttpServer serve=new JhttpServer(8000,wi);
254 if (state.SCHEDULING) {
255 // Save the current standard input, output, and error streams
256 // for later restoration.
257 PrintStream origOut = System.out;
259 // Create a new output stream for the standard output.
260 PrintStream stdout = null;
262 stdout = new PrintStream(new FileOutputStream("SimulatorResult.out"));
263 } catch (Exception e) {
264 // Sigh. Couldn't open the file.
265 System.out.println("Redirect: Unable to open output file!");
269 // Print stuff to the original output and error streams.
270 // On most systems all of this will end up on your console when you
271 // run this application.
272 //origOut.println ("\nRedirect: Round #1");
273 //System.out.println ("Test output via 'System.out'.");
274 //origOut.println ("Test output via 'origOut' reference.");
276 // Set the System out and err streams to use our replacements.
277 System.setOut(stdout);
279 // Print stuff to the original output and error streams.
280 // The stuff printed through the 'origOut' and 'origErr' references
281 // should go to the console on most systems while the messages
282 // printed through the 'System.out' and 'System.err' will end up in
283 // the files we created for them.
284 //origOut.println ("\nRedirect: Round #2");
285 //System.out.println ("Test output via 'SimulatorResult.out'.");
286 //origOut.println ("Test output via 'origOut' reference.");
288 if(state.USEPROFILE) {
289 // read in profile data and set
290 FileInputStream inStream = new FileInputStream("/scratch/profile.rst");
291 byte[] b = new byte[1024 * 100];
292 int length = inStream.read(b);
294 System.out.print("No content in input file: /scratch/profile.rst\n");
297 String profiledata = new String(b, 0, length);
298 java.util.Hashtable<String, Integer> taskinfo = new java.util.Hashtable<String, Integer>();
300 int inindex = profiledata.indexOf('\n');
301 while((inindex != -1) ) {
302 String inline = profiledata.substring(0, inindex);
303 profiledata = profiledata.substring(inindex + 1);
304 //System.printString(inline + "\n");
305 int tmpinindex = inline.indexOf(',');
306 if(tmpinindex == -1) {
309 String inname = inline.substring(0, tmpinindex);
310 String inint = inline.substring(tmpinindex + 1);
311 while(inint.startsWith(" ")) {
312 inint = inint.substring(1);
314 int duration = Integer.parseInt(inint);
315 taskinfo.put(inname, duration);
316 inindex = profiledata.indexOf('\n');
319 java.util.Random r=new java.util.Random();
321 for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext();) {
322 ClassDescriptor cd=(ClassDescriptor) it_classes.next();
324 Vector rootnodes=ta.getRootNodes(cd);
325 if(rootnodes!=null) {
326 for(Iterator it_rootnodes=rootnodes.iterator(); it_rootnodes.hasNext();) {
327 FlagState root=(FlagState)it_rootnodes.next();
328 Vector allocatingTasks = root.getAllocatingTasks();
329 if(allocatingTasks != null) {
330 for(int k = 0; k < allocatingTasks.size(); k++) {
331 TaskDescriptor td = (TaskDescriptor)allocatingTasks.elementAt(k);
332 Vector<FEdge> fev = (Vector<FEdge>)ta.getFEdgesFromTD(td);
333 int numEdges = fev.size();
335 for(int j = 0; j < numEdges; j++) {
336 FEdge pfe = fev.elementAt(j);
337 if(numEdges - j == 1) {
338 pfe.setProbability(total);
340 if((total != 0) && (total != 1)) {
342 tint = r.nextInt()%total;
345 pfe.setProbability(tint);
349 // tint = r.nextInt()%10;
350 // } while(tint <= 0);
351 //int newRate = tint;
352 //int newRate = (j+1)%2+1;
354 String cdname = cd.getSymbol();
355 if((cdname.equals("SeriesRunner")) ||
356 (cdname.equals("MDRunner")) ||
357 (cdname.equals("Stage")) ||
358 (cdname.equals("AppDemoRunner")) ||
359 (cdname.equals("FilterBankAtom"))) {
361 } else if(cdname.equals("SentenceParser")) {
365 // tint = r.nextInt()%100;
366 // } while(tint <= 0);
367 // int probability = tint;
368 int probability = 100;
369 pfe.addNewObjInfo(cd, newRate, probability);
375 Iterator it_flags = ta.getFlagStates(cd).iterator();
376 while(it_flags.hasNext()) {
377 FlagState fs = (FlagState)it_flags.next();
378 Iterator it_edges = fs.edges();
380 while(it_edges.hasNext()) {
382 // tint = r.nextInt()%10;
383 // } while(tint <= 0);
384 FEdge edge = (FEdge)it_edges.next();
385 tint = taskinfo.get(edge.getTask().getSymbol()).intValue();
386 edge.setExeTime(tint);
387 if(!it_edges.hasNext()) {
388 edge.setProbability(total);
390 if((total != 0) && (total != 1)) {
392 tint = r.nextInt()%total;
395 edge.setProbability(tint);
404 // Randomly set the newRate and probability of FEdges
405 java.util.Random r=new java.util.Random();
407 for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext();) {
408 ClassDescriptor cd=(ClassDescriptor) it_classes.next();
410 Vector rootnodes=ta.getRootNodes(cd);
411 if(rootnodes!=null) {
412 for(Iterator it_rootnodes=rootnodes.iterator(); it_rootnodes.hasNext();) {
413 FlagState root=(FlagState)it_rootnodes.next();
414 Vector allocatingTasks = root.getAllocatingTasks();
415 if(allocatingTasks != null) {
416 for(int k = 0; k < allocatingTasks.size(); k++) {
417 TaskDescriptor td = (TaskDescriptor)allocatingTasks.elementAt(k);
418 Vector<FEdge> fev = (Vector<FEdge>)ta.getFEdgesFromTD(td);
419 int numEdges = fev.size();
421 for(int j = 0; j < numEdges; j++) {
422 FEdge pfe = fev.elementAt(j);
423 if(numEdges - j == 1) {
424 pfe.setProbability(total);
426 if((total != 0) && (total != 1)) {
428 tint = r.nextInt()%total;
431 pfe.setProbability(tint);
435 // tint = r.nextInt()%10;
436 // } while(tint <= 0);
437 //int newRate = tint;
438 //int newRate = (j+1)%2+1;
440 String cdname = cd.getSymbol();
441 if((cdname.equals("SeriesRunner")) ||
442 (cdname.equals("MDRunner")) ||
443 (cdname.equals("Stage")) ||
444 (cdname.equals("AppDemoRunner")) ||
445 (cdname.equals("FilterBankAtom"))) {
447 } else if(cdname.equals("SentenceParser")) {
451 // tint = r.nextInt()%100;
452 // } while(tint <= 0);
453 // int probability = tint;
454 int probability = 100;
455 pfe.addNewObjInfo(cd, newRate, probability);
462 Iterator it_flags = ta.getFlagStates(cd).iterator();
463 while(it_flags.hasNext()) {
464 FlagState fs = (FlagState)it_flags.next();
465 Iterator it_edges = fs.edges();
467 while(it_edges.hasNext()) {
469 // tint = r.nextInt()%10;
470 // } while(tint <= 0);
472 FEdge edge = (FEdge)it_edges.next();
473 edge.setExeTime(tint);
474 if(!it_edges.hasNext()) {
475 edge.setProbability(total);
477 if((total != 0) && (total != 1)) {
479 tint = r.nextInt()%total;
482 edge.setProbability(tint);
491 // generate multiple schedulings
492 ScheduleAnalysis scheduleAnalysis = new ScheduleAnalysis(state, ta);
493 scheduleAnalysis.preSchedule();
494 scheduleAnalysis.scheduleAnalysis();
495 //scheduleAnalysis.setCoreNum(scheduleAnalysis.getSEdges4Test().size());
496 scheduleAnalysis.setCoreNum(state.CORENUM);
497 scheduleAnalysis.schedule();
499 //simulate these schedulings
500 ScheduleSimulator scheduleSimulator = new ScheduleSimulator(scheduleAnalysis.getCoreNum(), state, ta);
501 Iterator it_scheduling = scheduleAnalysis.getSchedulingsIter();
503 Vector<Integer> selectedScheduling = new Vector<Integer>();
504 int processTime = Integer.MAX_VALUE;
505 while(it_scheduling.hasNext()) {
506 Vector<Schedule> scheduling = (Vector<Schedule>)it_scheduling.next();
507 scheduleSimulator.setScheduling(scheduling);
508 int tmpTime = scheduleSimulator.process();
509 if(tmpTime < processTime) {
510 selectedScheduling.clear();
511 selectedScheduling.add(index);
512 processTime = tmpTime;
513 } else if(tmpTime == processTime) {
514 selectedScheduling.add(index);
518 System.out.print("Selected schedulings with least exectution time " + processTime + ": \n\t");
519 for(int i = 0; i < selectedScheduling.size(); i++) {
520 System.out.print((selectedScheduling.elementAt(i) + 1) + ", ");
522 System.out.println();
524 /*ScheduleSimulator scheduleSimulator = new ScheduleSimulator(4, state, ta);
525 Vector<Schedule> scheduling = new Vector<Schedule>();
526 for(int i = 0; i < 4; i++) {
527 Schedule schedule = new Schedule(i);
528 scheduling.add(schedule);
530 Iterator it_tasks = state.getTaskSymbolTable().getAllDescriptorsIterator();
531 while(it_tasks.hasNext()) {
532 TaskDescriptor td = (TaskDescriptor)it_tasks.next();
533 if(td.getSymbol().equals("t10")) {
534 scheduling.elementAt(1).addTask(td);
536 scheduling.elementAt(0).addTask(td);
539 ClassDescriptor cd = (ClassDescriptor)state.getClassSymbolTable().get("E");
540 scheduling.elementAt(0).addTargetCore(cd, 1);
541 scheduleSimulator.setScheduling(scheduling);
542 scheduleSimulator.process();
544 Vector<Schedule> scheduling1 = new Vector<Schedule>();
545 for(int i = 0; i < 4; i++) {
546 Schedule schedule = new Schedule(i);
547 scheduling1.add(schedule);
549 Iterator it_tasks1 = state.getTaskSymbolTable().getAllDescriptorsIterator();
550 while(it_tasks1.hasNext()) {
551 TaskDescriptor td = (TaskDescriptor)it_tasks1.next();
552 scheduling1.elementAt(0).addTask(td);
554 scheduleSimulator.setScheduling(scheduling1);
555 scheduleSimulator.process();*/
557 // Close the streams.
560 System.setOut(origOut);
561 } catch (Exception e) {
562 origOut.println("Redirect: Unable to close files!");
565 if(state.MULTICORE) {
566 //it_scheduling = scheduleAnalysis.getSchedulingsIter();
567 //Vector<Schedule> scheduling = (Vector<Schedule>)it_scheduling.next();
568 Vector<Schedule> scheduling = scheduleAnalysis.getSchedulings().elementAt(selectedScheduling.lastElement());
569 BuildCodeMultiCore bcm=new BuildCodeMultiCore(state, bf.getMap(), tu, sa, scheduling, scheduleAnalysis.getCoreNum(), pa);
576 if(!state.MULTICORE) {
578 CallGraph callgraph=new CallGraph(state);
579 if (state.PREFETCH) {
580 //speed up prefetch generation using locality analysis results
581 LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu);
582 pa=new PrefetchAnalysis(state, callgraph, tu, la);
585 LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu);
586 GenerateConversions gc=new GenerateConversions(la, state);
587 BuildCode bc=new BuildCode(state, bf.getMap(), tu, la, pa);
590 BuildCode bc=new BuildCode(state, bf.getMap(), tu, sa, pa);
595 if (state.FLATIRGRAPH) {
596 FlatIRGraph firg = new FlatIRGraph(state,
597 state.FLATIRGRAPHTASKS,
598 state.FLATIRGRAPHUSERMETHODS,
599 state.FLATIRGRAPHLIBMETHODS);
602 if (state.OWNERSHIP) {
603 CallGraph callGraph = new CallGraph(state);
604 OwnershipAnalysis oa = new OwnershipAnalysis(state,
607 state.OWNERSHIPALLOCDEPTH,
608 state.OWNERSHIPWRITEDOTS,
609 state.OWNERSHIPWRITEALL,
610 state.OWNERSHIPALIASFILE);
616 /** Reads in a source file and adds the parse tree to the state object. */
618 private static void readSourceFile(State state, String sourcefile) throws Exception {
619 Reader fr = new BufferedReader(new FileReader(sourcefile));
620 Lex.Lexer l = new Lex.Lexer(fr);
621 java_cup.runtime.lr_parser g;
622 g = new Parse.Parser(l);
625 p=(ParseNode) g./*debug_*/ parse().value;
626 } catch (Exception e) {
627 System.err.println("Error parsing file:"+sourcefile);
631 state.addParseNode(p);
632 if (l.numErrors()!=0) {
633 System.out.println("Error parsing "+sourcefile);
634 System.exit(l.numErrors());