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