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