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