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