1487ff8affddeb02954e83703c5368c6798543f3
[IRC.git] / Robust / src / Main / Main.java
1 package Main;
2
3 import java.io.FileOutputStream;
4 import java.io.PrintStream;
5 import java.io.Reader;
6 import java.io.BufferedReader;
7 import java.io.FileReader;
8 import java.io.FileInputStream;
9 import java.util.Hashtable;
10 import java.util.Iterator;
11 import java.util.Set;
12 import java.util.Vector;
13
14 import IR.Tree.ParseNode;
15 import IR.Tree.BuildIR;
16 import IR.Tree.SemanticCheck;
17 import IR.Flat.BuildCodeMultiCore;
18 import IR.Flat.BuildFlat;
19 import IR.Flat.BuildCode;
20 import IR.Flat.Inliner;
21 import IR.ClassDescriptor;
22 import IR.State;
23 import IR.TaskDescriptor;
24 import IR.TypeUtil;
25 import Analysis.Scheduling.MCImplSynthesis;
26 import Analysis.Scheduling.Schedule;
27 import Analysis.Scheduling.ScheduleAnalysis;
28 import Analysis.Scheduling.ScheduleSimulator;
29 import Analysis.TaskStateAnalysis.TaskAnalysis;
30 import Analysis.TaskStateAnalysis.TaskTagAnalysis;
31 import Analysis.TaskStateAnalysis.TaskGraph;
32 import Analysis.CallGraph.CallGraph;
33 import Analysis.TaskStateAnalysis.FEdge;
34 import Analysis.TaskStateAnalysis.FlagState;
35 import Analysis.TaskStateAnalysis.TagAnalysis;
36 import Analysis.TaskStateAnalysis.GarbageAnalysis;
37 import Analysis.TaskStateAnalysis.ExecutionGraph;
38 import Analysis.TaskStateAnalysis.SafetyAnalysis;
39 import Analysis.Locality.LocalityAnalysis;
40 import Analysis.Locality.GenerateConversions;
41 import Analysis.Prefetch.PrefetchAnalysis;
42 import Analysis.FlatIRGraph.FlatIRGraph;
43 import Analysis.OwnershipAnalysis.OwnershipAnalysis;
44 import Analysis.Disjoint.DisjointAnalysis;
45 import Analysis.MLP.MLPAnalysis;
46 import Analysis.Loops.*;
47 import Analysis.Liveness;
48 import Analysis.ArrayReferencees;
49 import IR.MethodDescriptor;
50 import IR.Flat.FlatMethod;
51 import Interface.*;
52 import Util.GraphNode;
53 import Util.GraphNode.DFS;
54 import Util.GraphNode.SCC;
55
56 public class Main {
57
58   /** Main method for the compiler.  */
59
60   public static void main(String args[]) throws Exception {
61     String ClassLibraryPrefix="./ClassLibrary/";
62     State state=new State();
63     Vector sourcefiles=new Vector();
64     state.classpath.add(".");
65
66     String outputdir = null;
67     boolean isDistributeInfo = false;
68     boolean isDisAll = false;
69     int startnum = 0;
70
71     for(int i=0; i<args.length; i++) {
72       String option=args[i];
73       if (option.equals("-precise"))
74         IR.Flat.BuildCode.GENERATEPRECISEGC=true;
75       else if (option.equals("-prefetch"))
76         state.PREFETCH=true;
77       else if (option.equals("-dir"))
78         IR.Flat.BuildCode.PREFIX=args[++i]+"/";
79       else if (option.equals("-fastcheck"))
80         state.FASTCHECK=true;
81       else if (option.equals("-selfloop"))
82         state.selfloops.add(args[++i]);
83           else if (option.equals("-outputdir"))
84         state.outputdir = args[++i];
85       else if (option.equals("-excprefetch"))
86         state.excprefetch.add(args[++i]);
87       else if (option.equals("-classlibrary"))
88         state.classpath.add(args[++i]);
89       else if (option.equals("-inlineatomic")) {
90         state.INLINEATOMIC=true;
91         state.inlineatomicdepth=Integer.parseInt(args[++i]);
92       } else if(option.equals("-numcore")) {
93         ++i;
94         state.CORENUM = Integer.parseInt(args[i]);
95       } else if (option.equals("-mainclass"))
96         state.main=args[++i];
97       else if (option.equals("-trueprob")) {
98         state.TRUEPROB=Double.parseDouble(args[++i]);
99       } else if (option.equals("-printflat"))
100         State.PRINTFLAT=true;
101       else if (option.equals("-printscheduling"))
102         State.PRINTSCHEDULING=true;
103       else if (option.equals("-minimize"))
104         state.MINIMIZE=true;
105       else if (option.equals("-printschedulesim"))
106         State.PRINTSCHEDULESIM=true;
107       else if (option.equals("-printcriticalpath"))
108           State.PRINTCRITICALPATH=true;
109       else if (option.equals("-struct"))
110         state.structfile=args[++i];
111       else if (option.equals("-conscheck"))
112         state.CONSCHECK=true;
113       else if (option.equals("-task"))
114         state.TASK=true;
115       else if (option.equals("-abortreaders"))
116         state.ABORTREADERS=true;
117       else if (option.equals("-sandbox"))
118         state.SANDBOX=true;
119       else if (option.equals("-taskstate"))
120         state.TASKSTATE=true;
121       else if (option.equals("-tagstate"))
122         state.TAGSTATE=true;
123       else if (option.equals("-stmarray"))
124         state.STMARRAY=true;
125       else if (option.equals("-dualview"))
126         state.DUALVIEW=true;
127       else if (option.equals("-hybrid"))
128         state.HYBRID=true;
129       else if (option.equals("-flatirtasks")) {
130         state.FLATIRGRAPH=true;
131         state.FLATIRGRAPHTASKS=true;
132       } else if (option.equals("-flatirusermethods")) {
133         state.FLATIRGRAPH=true;
134         state.FLATIRGRAPHUSERMETHODS=true;
135       } else if (option.equals("-flatirlibmethods")) {
136         state.FLATIRGRAPH=true;
137         state.FLATIRGRAPHLIBMETHODS=true;
138       } else if (option.equals("-multicore"))
139         state.MULTICORE=true;
140       else if (option.equals("-multicoregc"))
141         state.MULTICOREGC=true;
142       else if (option.equals("-ownership"))
143         state.OWNERSHIP=true;
144       else if (option.equals("-ownallocdepth")) {
145         state.OWNERSHIPALLOCDEPTH=Integer.parseInt(args[++i]);
146       } else if (option.equals("-ownwritedots")) {
147         state.OWNERSHIPWRITEDOTS=true;
148         if (args[++i].equals("all")) {
149           state.OWNERSHIPWRITEALL=true;
150         }
151       } else if (option.equals("-ownaliasfile")) {
152         state.OWNERSHIPALIASFILE=args[++i];
153       } else if (option.equals("-ownaliasfiletab")) {
154         state.OWNERSHIPALIASFILE=args[++i];
155         state.OWNERSHIPALIASTAB=true;      
156       } else if (option.equals("-owndebugcallee")) {
157         state.OWNERSHIPDEBUGCALLEE=args[++i];
158       } else if (option.equals("-owndebugcaller")) {
159         state.OWNERSHIPDEBUGCALLER=args[++i];
160       } else if (option.equals("-owndebugcallcount")) {
161         state.OWNERSHIPDEBUGCALLCOUNT=Integer.parseInt(args[++i]);
162       }
163       else if (option.equals("-disjoint"))
164         state.DISJOINT=true;
165       else if (option.equals("-disjoint-k")) {
166         state.DISJOINTALLOCDEPTH=Integer.parseInt(args[++i]);
167       } else if (option.equals("-disjoint-write-dots")) {
168         state.DISJOINTWRITEDOTS = true;
169         String arg = args[++i];
170         if( arg.equals("all") ) {
171           state.DISJOINTWRITEALL = true;
172         } else if( arg.equals("final") ) {
173           state.DISJOINTWRITEALL = false;
174         } else {
175           throw new Error("disjoint-write-dots requires argument <all/final>");
176         }
177       } else if (option.equals("-disjoint-alias-file")) {
178         state.DISJOINTALIASFILE = args[++i];
179         String arg = args[++i];
180         if( arg.equals("normal") ) {
181           state.DISJOINTALIASTAB = false;
182         } else if( arg.equals("tabbed") ) {
183           state.DISJOINTALIASTAB = true;
184         } else {
185           throw new Error("disjoint-alias-file requires arguments <filename> <normal/tabbed>");
186         }
187       } else if (option.equals("-disjoint-debug-callsite")) {
188         state.DISJOINTDEBUGCALLEE=args[++i];
189         state.DISJOINTDEBUGCALLER=args[++i];
190         state.DISJOINTDEBUGCALLCOUNT=Integer.parseInt(args[++i]);
191       }
192       else if (option.equals("-optional"))
193         state.OPTIONAL=true;
194       else if (option.equals("-optimize"))
195         state.OPTIMIZE=true;
196       else if (option.equals("-dcopts"))
197         state.DCOPTS=true;
198       else if (option.equals("-arraypad"))
199         state.ARRAYPAD=true;
200       else if (option.equals("-delaycomp"))
201         state.DELAYCOMP=true;
202       else if (option.equals("-raw"))
203         state.RAW=true;
204       else if (option.equals("-scheduling"))
205         state.SCHEDULING=true;
206       else if (option.equals("-distributioninfo"))
207         isDistributeInfo=true;
208       else if (option.equals("-disall"))
209         isDisAll=true;
210       else if (option.equals("-disstart"))
211         startnum = Integer.parseInt(args[++i]);
212       else if (option.equals("-useprofile")) {
213         state.USEPROFILE=true;
214     state.profilename = args[++i];
215       }
216       else if (option.equals("-thread"))
217         state.THREAD=true;
218       else if (option.equals("-dsm"))
219         state.DSM=true;
220       else if (option.equals("-dsmtask"))
221   state.DSMTASK=true;
222       else if (option.equals("-singleTM"))
223         state.SINGLETM=true;
224       else if (option.equals("-readset"))
225         state.READSET=true;
226       else if (option.equals("-webinterface"))
227         state.WEBINTERFACE=true;
228       else if (option.equals("-instructionfailures"))
229         state.INSTRUCTIONFAILURE=true;
230       else if (option.equals("-abcclose"))
231         state.ARRAYBOUNDARYCHECK=false;
232
233       else if (option.equals("-mlp")) {
234         state.MLP            = true;
235         state.OWNERSHIP      = true;
236         state.MLP_NUMCORES   = Integer.parseInt( args[++i] );
237         state.MLP_MAXSESEAGE = Integer.parseInt( args[++i] );
238
239       } else if (option.equals("-mlpdebug")) {
240         state.MLPDEBUG=true;
241
242       } else if (option.equals("-methodeffects")) {
243         state.METHODEFFECTS=true;
244       }else if (option.equals("-help")) {
245         System.out.println("-classlibrary classlibrarydirectory -- directory where classlibrary is located");
246         System.out.println("-selfloop task -- this task doesn't self loop its parameters forever");
247         System.out.println("-dir outputdirectory -- output code in outputdirectory");
248         System.out.println("-struct structfile -- output structure declarations for repair tool");
249         System.out.println("-mainclass -- main function to call");
250         System.out.println("-dsm -- distributed shared memory support");
251         System.out.println("-singleTM -- single machine committing transactions");
252         System.out.println("-abortreaders -- abort readers");
253         System.out.println("-precise -- use precise garbage collection");
254         System.out.println("-conscheck -- turn on consistency checking");
255         System.out.println("-task -- compiler for tasks");
256         System.out.println("-fastcheck -- fastcheckpointing for Bristlecone");
257         System.out.println("-thread -- threads");
258         System.out.println("-trueprob <d> -- probability of true branch");
259         System.out.println("-printflat -- print out flat representation");
260         System.out.println("-instructionfailures -- insert code for instruction level failures");
261         System.out.println("-taskstate -- do task state analysis");
262         System.out.println("-flatirtasks -- create dot files for flat IR graphs of tasks");
263         System.out.println("-flatirusermethods -- create dot files for flat IR graphs of user methods");
264         System.out.println("-flatirlibmethods -- create dot files for flat IR graphs of library class methods");
265         System.out.println("  note: -flatirusermethods or -flatirlibmethods currently generate all class method flat IR graphs");
266         System.out.println("-ownership -- do ownership analysis");
267         System.out.println("-ownallocdepth <d> -- set allocation depth for ownership analysis");
268         System.out.println("-ownwritedots <all/final> -- write ownership graphs; can be all results or just final results");
269         System.out.println("-ownaliasfile <filename> -- write a text file showing all detected aliases in program tasks");
270         System.out.println("-optimize -- enable optimizations");
271         System.out.println("-optional -- enable optional arguments");
272         System.out.println("-abcclose close the array boundary check");
273         System.out.println("-scheduling do task scheduling");
274         System.out.println("-mlp <num cores> <max sese age> build mlp code");
275         System.out.println("-mlpdebug if mlp, report progress and interim results");
276         System.out.println("-multicore generate multi-core version binary");
277         System.out.println("-numcore set the number of cores (should be used together with -multicore), defaultly set as 1");
278         System.out.println("-interrupt generate raw version binary with interruption (should be used togethere with -raw)");
279         System.out.println("-rawconfig config raw simulator as 4xn (should be used together with -raw)");
280         System.out.println("-rawpath print out execute path information for raw version (should be used together with -raw)");
281         System.out.println("-useprofile use profiling data for scheduling (should be used together with -raw)");
282         System.out.println("-threadsimulate generate multi-thread simulate version binary");
283         System.out.println("-rawuseio use standard io to output profiling data (should be used together with -raw and -profile), it only works with single core version");
284         System.out.println("-printscheduling -- print out scheduling graphs");
285         System.out.println("-printschedulesim -- print out scheduling simulation result graphs");
286         System.out.println("-webinterface -- enable web interface");
287         System.out.println("-help -- print out help");
288         System.exit(0);
289       } else {
290         sourcefiles.add(args[i]);
291       }
292     }
293
294     //add default classpath
295     if (state.classpath.size()==1)
296       state.classpath.add(ClassLibraryPrefix);
297
298     BuildIR bir=new BuildIR(state);
299     TypeUtil tu=new TypeUtil(state, bir);
300     
301
302     SemanticCheck sc=new SemanticCheck(state,tu);
303
304     for(int i=0;i<sourcefiles.size();i++)
305       loadClass(state, bir,(String)sourcefiles.get(i));
306
307     //Stuff the runtime wants to see
308     sc.getClass("String");
309     sc.getClass("Math");
310     sc.getClass("File");
311     sc.getClass("Socket");
312     sc.getClass("ServerSocket");
313     sc.getClass("FileInputStream");
314     sc.getClass("FileOutputStream");
315     if (state.TASK) {
316       sc.getClass("TagDescriptor");
317     }
318     if (state.THREAD||state.DSM||state.SINGLETM) {
319       sc.getClass("Thread");
320     }
321
322     sc.semanticCheck();
323
324     tu.createFullTable();
325
326     BuildFlat bf=new BuildFlat(state,tu);
327     bf.buildFlat();
328     SafetyAnalysis sa=null;
329     PrefetchAnalysis pa=null;
330     MLPAnalysis mlpa=null;
331     if (state.INLINEATOMIC) {
332       Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
333       while(classit.hasNext()) {
334         ClassDescriptor cn=(ClassDescriptor)classit.next();
335         Iterator methodit=cn.getMethods();
336         while(methodit.hasNext()) {
337           // do inlining
338           MethodDescriptor md=(MethodDescriptor)methodit.next();
339           FlatMethod fm=state.getMethodFlat(md);
340           Inliner.inlineAtomic(state, tu, fm, state.inlineatomicdepth);
341         }
342       }
343     }
344
345
346     if (state.OPTIMIZE) {
347       CallGraph callgraph=new CallGraph(state);
348       CopyPropagation cp=new CopyPropagation();
349       DeadCode dc=new DeadCode();
350       GlobalFieldType gft=new GlobalFieldType(callgraph, state, tu.getMain());
351       CSE cse=new CSE(gft, tu);
352       localCSE lcse=new localCSE(gft, tu);
353       LoopOptimize lo=new LoopOptimize(gft, tu);
354       Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
355       while(classit.hasNext()) {
356         ClassDescriptor cn=(ClassDescriptor)classit.next();
357         Iterator methodit=cn.getMethods();
358         while(methodit.hasNext()) {
359           /* Classify parameters */
360           MethodDescriptor md=(MethodDescriptor)methodit.next();
361           FlatMethod fm=state.getMethodFlat(md);
362           cp.optimize(fm);
363           dc.optimize(fm);
364           lo.optimize(fm);
365           cp.optimize(fm);
366           dc.optimize(fm);
367           lcse.doAnalysis(fm);
368           cse.doAnalysis(fm);
369           cp.optimize(fm);
370           dc.optimize(fm);
371           cp.optimize(fm);
372           dc.optimize(fm);
373         }
374       }
375     }
376
377     if (state.FLATIRGRAPH) {
378       FlatIRGraph firg = new FlatIRGraph(state,
379                                          state.FLATIRGRAPHTASKS,
380                                          state.FLATIRGRAPHUSERMETHODS,
381                                          state.FLATIRGRAPHLIBMETHODS);
382     }
383     
384     if (state.OWNERSHIP && !state.MLP) {
385       CallGraph callGraph = new CallGraph(state);
386       Liveness liveness = new Liveness();
387       ArrayReferencees ar = new ArrayReferencees(state);
388       OwnershipAnalysis oa = new OwnershipAnalysis(state,
389                                                    tu,
390                                                    callGraph,
391                                                    liveness,
392                                                    ar,
393                                                    state.OWNERSHIPALLOCDEPTH,
394                                                    state.OWNERSHIPWRITEDOTS,
395                                                    state.OWNERSHIPWRITEALL,
396                                                    state.OWNERSHIPALIASFILE,
397                                                    state.METHODEFFECTS);
398     }
399
400     if (state.MLP) {
401       CallGraph callGraph = new CallGraph(state);
402       Liveness liveness = new Liveness();
403       ArrayReferencees ar = new ArrayReferencees(state);
404       OwnershipAnalysis oa = new OwnershipAnalysis(state,
405                                                    tu,
406                                                    callGraph,
407                                                    liveness,
408                                                    ar,
409                                                    state.OWNERSHIPALLOCDEPTH,
410                                                    state.OWNERSHIPWRITEDOTS,
411                                                    state.OWNERSHIPWRITEALL,
412                                                    state.OWNERSHIPALIASFILE,
413                                                    state.METHODEFFECTS);
414       mlpa = new MLPAnalysis(state,
415                              tu,
416                              callGraph,
417                              oa);
418     }    
419
420     if (state.DISJOINT) {
421       CallGraph        cg = new CallGraph(state);
422       Liveness         l  = new Liveness();
423       ArrayReferencees ar = new ArrayReferencees(state);
424       DisjointAnalysis oa = new DisjointAnalysis(state, tu, cg, l, ar);
425     }
426
427     if (state.TAGSTATE) {
428       CallGraph callgraph=new CallGraph(state);
429       TagAnalysis taganalysis=new TagAnalysis(state, callgraph);
430       TaskTagAnalysis tta=new TaskTagAnalysis(state, taganalysis, tu);
431     }
432
433     if (state.TASKSTATE) {
434       CallGraph callgraph=new CallGraph(state);
435       TagAnalysis taganalysis=new TagAnalysis(state, callgraph);
436       TaskAnalysis ta=new TaskAnalysis(state, taganalysis, tu);
437       ta.taskAnalysis();
438       TaskGraph tg=new TaskGraph(state, ta);
439       tg.createDOTfiles();
440
441       if (state.OPTIONAL) {
442         ExecutionGraph et=new ExecutionGraph(state, ta);
443         et.createExecutionGraph();
444         sa = new SafetyAnalysis(et.getExecutionGraph(), state, ta);
445         sa.doAnalysis();
446         state.storeAnalysisResult(sa.getResult());
447         state.storeOptionalTaskDescriptors(sa.getOptionalTaskDescriptors());
448       }
449
450       if (state.WEBINTERFACE) {
451         GarbageAnalysis ga=new GarbageAnalysis(state, ta);
452         WebInterface wi=new WebInterface(state, ta, tg, ga, taganalysis);
453         JhttpServer serve=new JhttpServer(8000,wi);
454         serve.run();
455       }
456
457       if (state.SCHEDULING) {
458         // Use ownership analysis to get alias information
459         CallGraph callGraph = new CallGraph(state);
460         Liveness liveness = new Liveness();
461         ArrayReferencees ar = new ArrayReferencees(state);
462         OwnershipAnalysis oa = new OwnershipAnalysis(state,
463                                                      tu,
464                                                      callGraph,
465                                                      liveness,
466                                                      ar,
467                                                      state.OWNERSHIPALLOCDEPTH,
468                                                      state.OWNERSHIPWRITEDOTS,
469                                                      state.OWNERSHIPWRITEALL,
470                                                      state.OWNERSHIPALIASFILE);
471         
472         // synthesis a layout according to target multicore processor
473         MCImplSynthesis mcImplSynthesis = new MCImplSynthesis(state,
474                                                               ta,
475                                                               oa);
476         if(isDistributeInfo) {
477             mcImplSynthesis.distribution(isDisAll, startnum);
478         } else {
479             //double timeStartAnalysis = (double) System.nanoTime();
480             mcImplSynthesis.setScheduleThreshold(20);
481             mcImplSynthesis.setProbThreshold(0);
482             mcImplSynthesis.setGenerateThreshold(30);
483             Vector<Schedule> scheduling = mcImplSynthesis.synthesis();
484             
485             //double timeEndAnalysis = (double) System.nanoTime();
486             //double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
487             //System.err.println("The analysis took" + dt +  "sec.");
488         //System.exit(0);
489
490             // generate multicore codes
491             if(state.MULTICORE) {
492                 BuildCodeMultiCore bcm=new BuildCodeMultiCore(state,
493                                                               bf.getMap(),
494                                                               tu,
495                                                               sa,
496                                                               scheduling,
497                                                               mcImplSynthesis.getCoreNum(),
498                                                               pa);
499                 bcm.setOwnershipAnalysis(oa);
500                 bcm.buildCode();
501             }
502             scheduling.clear();
503             scheduling = null;
504         }
505       }
506     }
507     if(!state.MULTICORE) {
508       if (state.DSM||state.SINGLETM) {
509         CallGraph callgraph=new CallGraph(state);
510         if (state.PREFETCH) {
511           //speed up prefetch generation using locality analysis results
512           LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu);
513           pa=new PrefetchAnalysis(state, callgraph, tu, la);
514         }
515         LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu);
516         GenerateConversions gc=new GenerateConversions(la, state);
517         BuildCode bc=new BuildCode(state, bf.getMap(), tu, la, pa, mlpa);
518         bc.buildCode();
519       } else {
520         BuildCode bc=new BuildCode(state, bf.getMap(), tu, sa, pa, mlpa);
521         bc.buildCode();
522       }
523     }
524
525     System.out.println("Lines="+state.lines);
526     System.exit(0);
527   }
528
529   public static void loadClass(State state, BuildIR bir, String sourcefile) {
530     try {
531       ParseNode pn=readSourceFile(state, sourcefile);
532       bir.buildtree(pn, null);
533     } catch (Exception e) {
534       System.out.println("Error in sourcefile:"+sourcefile);
535       e.printStackTrace();
536       System.exit(-1);
537     } catch (Error e) {
538       System.out.println("Error in sourcefile:"+sourcefile);
539       e.printStackTrace();
540       System.exit(-1);
541     }
542   }
543
544   /** Reads in a source file and adds the parse tree to the state object. */
545
546   public static ParseNode readSourceFile(State state, String sourcefile) {
547     try {
548       Reader fr= new BufferedReader(new FileReader(sourcefile));
549       Lex.Lexer l = new Lex.Lexer(fr);
550       java_cup.runtime.lr_parser g;
551       g = new Parse.Parser(l);
552       ParseNode p=null;
553       try {
554         p=(ParseNode) g./*debug_*/parse().value;
555       } catch (Exception e) {
556         System.err.println("Error parsing file:"+sourcefile);
557         e.printStackTrace();
558         System.exit(-1);
559       }
560       state.addParseNode(p);
561       if (l.numErrors()!=0) {
562         System.out.println("Error parsing "+sourcefile);
563         System.exit(l.numErrors());
564       }
565       state.lines+=l.line_num;
566       return p;
567
568     } catch (Exception e) {
569       throw new Error(e);
570     }
571   }
572 }