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