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