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