fixes on analyses to compile the eyetracking benchmark
[IRC.git] / Robust / src / Analysis / SSJava / SSJavaAnalysis.java
1 package Analysis.SSJava;
2
3 import java.io.BufferedWriter;
4 import java.io.FileWriter;
5 import java.io.IOException;
6 import java.util.ArrayList;
7 import java.util.Collections;
8 import java.util.Comparator;
9 import java.util.HashSet;
10 import java.util.Hashtable;
11 import java.util.Iterator;
12 import java.util.List;
13 import java.util.Set;
14 import java.util.StringTokenizer;
15 import java.util.Vector;
16
17 import Analysis.CallGraph.CallGraph;
18 import Analysis.Loops.GlobalFieldType;
19 import Analysis.Loops.LoopOptimize;
20 import Analysis.Loops.LoopTerminate;
21 import IR.AnnotationDescriptor;
22 import IR.ClassDescriptor;
23 import IR.Descriptor;
24 import IR.FieldDescriptor;
25 import IR.MethodDescriptor;
26 import IR.State;
27 import IR.SymbolTable;
28 import IR.TypeUtil;
29 import IR.Flat.BuildFlat;
30 import IR.Flat.FlatMethod;
31 import IR.Flat.FlatNode;
32 import Util.Pair;
33
34 public class SSJavaAnalysis {
35
36   public static final String SSJAVA = "SSJAVA";
37   public static final String LATTICE = "LATTICE";
38   public static final String METHODDEFAULT = "METHODDEFAULT";
39   public static final String THISLOC = "THISLOC";
40   public static final String GLOBALLOC = "GLOBALLOC";
41   public static final String RETURNLOC = "RETURNLOC";
42   public static final String LOC = "LOC";
43   public static final String DELTA = "DELTA";
44   public static final String TERMINATE = "TERMINATE";
45   public static final String DELEGATE = "DELEGATE";
46   public static final String DELEGATETHIS = "DELEGATETHIS";
47   public static final String TRUST = "TRUST";
48
49   State state;
50   TypeUtil tu;
51   FlowDownCheck flowDownChecker;
52   MethodAnnotationCheck methodAnnotationChecker;
53   BuildFlat bf;
54
55   // set containing method requires to be annoated
56   Set<MethodDescriptor> annotationRequireSet;
57
58   // class -> field lattice
59   Hashtable<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
60
61   // class -> default local variable lattice
62   Hashtable<ClassDescriptor, MethodLattice<String>> cd2methodDefault;
63
64   // method -> local variable lattice
65   Hashtable<MethodDescriptor, MethodLattice<String>> md2lattice;
66
67   // method set that does not want to have loop termination analysis
68   Hashtable<MethodDescriptor, Integer> skipLoopTerminate;
69
70   // map shared location to its descriptors
71   Hashtable<Location, Set<Descriptor>> mapSharedLocation2DescriptorSet;
72
73   // set containing a class that has at least one annoated method
74   Set<ClassDescriptor> annotationRequireClassSet;
75
76   // the set of method descriptor required to check the linear type property
77   Set<MethodDescriptor> linearTypeCheckMethodSet;
78
79   // the set of method descriptors annotated as "TRUST"
80   Set<MethodDescriptor> trustWorthyMDSet;
81
82   // points to method containing SSJAVA Loop
83   private MethodDescriptor methodContainingSSJavaLoop;
84
85   private FlatNode ssjavaLoopEntrance;
86
87   // keep the field ownership from the linear type checking
88   Hashtable<MethodDescriptor, Set<FieldDescriptor>> mapMethodToOwnedFieldSet;
89
90   CallGraph callgraph;
91
92   LinearTypeCheck checker;
93
94   public SSJavaAnalysis(State state, TypeUtil tu, BuildFlat bf, CallGraph callgraph) {
95     this.state = state;
96     this.tu = tu;
97     this.callgraph = callgraph;
98     this.cd2lattice = new Hashtable<ClassDescriptor, SSJavaLattice<String>>();
99     this.cd2methodDefault = new Hashtable<ClassDescriptor, MethodLattice<String>>();
100     this.md2lattice = new Hashtable<MethodDescriptor, MethodLattice<String>>();
101     this.annotationRequireSet = new HashSet<MethodDescriptor>();
102     this.annotationRequireClassSet = new HashSet<ClassDescriptor>();
103     this.skipLoopTerminate = new Hashtable<MethodDescriptor, Integer>();
104     this.mapSharedLocation2DescriptorSet = new Hashtable<Location, Set<Descriptor>>();
105     this.linearTypeCheckMethodSet = new HashSet<MethodDescriptor>();
106     this.bf = bf;
107     this.trustWorthyMDSet = new HashSet<MethodDescriptor>();
108     this.mapMethodToOwnedFieldSet = new Hashtable<MethodDescriptor, Set<FieldDescriptor>>();
109   }
110
111   public void doCheck() {
112     doMethodAnnotationCheck();
113     computeLinearTypeCheckMethodSet();
114     doLinearTypeCheck();
115     // if (state.SSJAVADEBUG) {
116     // debugPrint();
117     // }
118     parseLocationAnnotation();
119     // inference();
120     doFlowDownCheck();
121     doDefinitelyWrittenCheck();
122     doLoopCheck();
123   }
124
125   private void inference() {
126     SSJavaInferenceEngine inferEngine = new SSJavaInferenceEngine(this, state);
127     inferEngine.inference();
128   }
129
130   private void doLoopCheck() {
131     GlobalFieldType gft = new GlobalFieldType(callgraph, state, tu.getMain());
132     LoopOptimize lo = new LoopOptimize(gft, tu);
133
134     SymbolTable classtable = state.getClassSymbolTable();
135
136     List<ClassDescriptor> toanalyzeList = new ArrayList<ClassDescriptor>();
137     List<MethodDescriptor> toanalyzeMethodList = new ArrayList<MethodDescriptor>();
138
139     toanalyzeList.addAll(classtable.getValueSet());
140     Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
141       public int compare(ClassDescriptor o1, ClassDescriptor o2) {
142         return o1.getClassName().compareTo(o2.getClassName());
143       }
144     });
145
146     for (int i = 0; i < toanalyzeList.size(); i++) {
147       ClassDescriptor cd = toanalyzeList.get(i);
148
149       SymbolTable methodtable = cd.getMethodTable();
150       toanalyzeMethodList.clear();
151       toanalyzeMethodList.addAll(methodtable.getValueSet());
152       Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
153         public int compare(MethodDescriptor o1, MethodDescriptor o2) {
154           return o1.getSymbol().compareTo(o2.getSymbol());
155         }
156       });
157
158       for (int mdIdx = 0; mdIdx < toanalyzeMethodList.size(); mdIdx++) {
159         MethodDescriptor md = toanalyzeMethodList.get(mdIdx);
160         if (needTobeAnnotated(md)) {
161           lo.analyze(state.getMethodFlat(md));
162           doLoopTerminationCheck(lo, state.getMethodFlat(md));
163         }
164       }
165
166     }
167
168   }
169
170   public void addTrustMethod(MethodDescriptor md) {
171     trustWorthyMDSet.add(md);
172   }
173
174   public boolean isTrustMethod(MethodDescriptor md) {
175     return trustWorthyMDSet.contains(md);
176   }
177
178   private void computeLinearTypeCheckMethodSet() {
179
180     Set<MethodDescriptor> allCalledSet = callgraph.getMethodCalls(tu.getMain());
181     linearTypeCheckMethodSet.addAll(allCalledSet);
182
183     Set<MethodDescriptor> trustedSet = new HashSet<MethodDescriptor>();
184
185     for (Iterator iterator = trustWorthyMDSet.iterator(); iterator.hasNext();) {
186       MethodDescriptor trustMethod = (MethodDescriptor) iterator.next();
187       Set<MethodDescriptor> calledFromTrustMethodSet = callgraph.getMethodCalls(trustMethod);
188       trustedSet.add(trustMethod);
189       trustedSet.addAll(calledFromTrustMethodSet);
190     }
191
192     linearTypeCheckMethodSet.removeAll(trustedSet);
193
194     // if a method is called only by trusted method, no need to check linear
195     // type & flow down rule
196     for (Iterator iterator = trustedSet.iterator(); iterator.hasNext();) {
197       MethodDescriptor md = (MethodDescriptor) iterator.next();
198       Set<MethodDescriptor> callerSet = callgraph.getCallerSet(md);
199       if (!trustedSet.containsAll(callerSet) && !trustWorthyMDSet.contains(md)) {
200         linearTypeCheckMethodSet.add(md);
201       }
202     }
203
204   }
205
206   private void doLinearTypeCheck() {
207     LinearTypeCheck checker = new LinearTypeCheck(this, state);
208     checker.linearTypeCheck();
209   }
210
211   public void debugPrint() {
212     System.out.println("SSJAVA: SSJava is checking the following methods:");
213     for (Iterator<MethodDescriptor> iterator = annotationRequireSet.iterator(); iterator.hasNext();) {
214       MethodDescriptor md = iterator.next();
215       System.out.print(" " + md);
216     }
217     System.out.println();
218   }
219
220   private void doMethodAnnotationCheck() {
221     methodAnnotationChecker = new MethodAnnotationCheck(this, state, tu);
222     methodAnnotationChecker.methodAnnoatationCheck();
223     methodAnnotationChecker.methodAnnoataionInheritanceCheck();
224   }
225
226   public void doFlowDownCheck() {
227     flowDownChecker = new FlowDownCheck(this, state);
228     flowDownChecker.flowDownCheck();
229   }
230
231   public void doDefinitelyWrittenCheck() {
232     DefinitelyWrittenCheck checker = new DefinitelyWrittenCheck(this, state);
233     checker.definitelyWrittenCheck();
234   }
235
236   private void parseLocationAnnotation() {
237     Iterator it = state.getClassSymbolTable().getDescriptorsIterator();
238     while (it.hasNext()) {
239       ClassDescriptor cd = (ClassDescriptor) it.next();
240       // parsing location hierarchy declaration for the class
241       Vector<AnnotationDescriptor> classAnnotations = cd.getModifier().getAnnotations();
242       for (int i = 0; i < classAnnotations.size(); i++) {
243         AnnotationDescriptor an = classAnnotations.elementAt(i);
244         String marker = an.getMarker();
245         if (marker.equals(LATTICE)) {
246           SSJavaLattice<String> locOrder =
247               new SSJavaLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
248           cd2lattice.put(cd, locOrder);
249           parseClassLatticeDefinition(cd, an.getValue(), locOrder);
250
251           if (state.SSJAVADEBUG) {
252             // generate lattice dot file
253             writeLatticeDotFile(cd, locOrder);
254           }
255
256         } else if (marker.equals(METHODDEFAULT)) {
257           MethodLattice<String> locOrder =
258               new MethodLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
259           cd2methodDefault.put(cd, locOrder);
260           parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
261         }
262       }
263
264       for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
265         MethodDescriptor md = (MethodDescriptor) method_it.next();
266         // parsing location hierarchy declaration for the method
267
268         if (needTobeAnnotated(md)) {
269           Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
270           if (methodAnnotations != null) {
271             for (int i = 0; i < methodAnnotations.size(); i++) {
272               AnnotationDescriptor an = methodAnnotations.elementAt(i);
273               if (an.getMarker().equals(LATTICE)) {
274                 // developer explicitly defines method lattice
275                 MethodLattice<String> locOrder =
276                     new MethodLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
277                 md2lattice.put(md, locOrder);
278                 parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
279               } else if (an.getMarker().equals(TERMINATE)) {
280                 // developer explicitly wants to skip loop termination analysis
281                 String value = an.getValue();
282                 int maxIteration = 0;
283                 if (value != null) {
284                   maxIteration = Integer.parseInt(value);
285                 }
286                 skipLoopTerminate.put(md, new Integer(maxIteration));
287               }
288             }
289           }
290         }
291
292       }
293
294     }
295   }
296
297   private void writeLatticeDotFile(ClassDescriptor cd, SSJavaLattice<String> locOrder) {
298
299     String className = cd.getSymbol().replaceAll("[\\W_]", "");
300
301     Set<Pair<String, String>> pairSet = locOrder.getOrderingPairSet();
302
303     try {
304       BufferedWriter bw = new BufferedWriter(new FileWriter(className + ".dot"));
305
306       bw.write("digraph " + className + " {\n");
307
308       for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
309         // pair is in the form of <higher, lower>
310         Pair<String, String> pair = (Pair<String, String>) iterator.next();
311
312         String highLocId = pair.getFirst();
313         if (locOrder.isSharedLoc(highLocId)) {
314           highLocId = "\"" + highLocId + "*\"";
315         }
316         String lowLocId = pair.getSecond();
317         if (locOrder.isSharedLoc(lowLocId)) {
318           lowLocId = "\"" + lowLocId + "*\"";
319         }
320         bw.write(highLocId + " -> " + lowLocId + ";\n");
321       }
322       bw.write("}\n");
323       bw.close();
324
325     } catch (IOException e) {
326       e.printStackTrace();
327     }
328
329   }
330
331   private void parseMethodDefaultLatticeDefinition(ClassDescriptor cd, String value,
332       MethodLattice<String> locOrder) {
333
334     value = value.replaceAll(" ", ""); // remove all blank spaces
335
336     StringTokenizer tokenizer = new StringTokenizer(value, ",");
337
338     while (tokenizer.hasMoreTokens()) {
339       String orderElement = tokenizer.nextToken();
340       int idx = orderElement.indexOf("<");
341       if (idx > 0) {// relative order element
342         String lowerLoc = orderElement.substring(0, idx);
343         String higherLoc = orderElement.substring(idx + 1);
344         locOrder.put(higherLoc, lowerLoc);
345         if (locOrder.isIntroducingCycle(higherLoc)) {
346           throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
347               + " introduces a cycle.");
348         }
349       } else if (orderElement.startsWith(THISLOC + "=")) {
350         String thisLoc = orderElement.substring(8);
351         locOrder.setThisLoc(thisLoc);
352       } else if (orderElement.startsWith(GLOBALLOC + "=")) {
353         String globalLoc = orderElement.substring(10);
354         locOrder.setGlobalLoc(globalLoc);
355       } else if (orderElement.startsWith(RETURNLOC + "=")) {
356         String returnLoc = orderElement.substring(10);
357         locOrder.setReturnLoc(returnLoc);
358       } else if (orderElement.endsWith("*")) {
359         // spin loc definition
360         locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
361       } else {
362         // single element
363         locOrder.put(orderElement);
364       }
365     }
366
367     // sanity checks
368     if (locOrder.getThisLoc() != null && !locOrder.containsKey(locOrder.getThisLoc())) {
369       throw new Error("Variable 'this' location '" + locOrder.getThisLoc()
370           + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
371     }
372
373     if (locOrder.getGlobalLoc() != null && !locOrder.containsKey(locOrder.getGlobalLoc())) {
374       throw new Error("Variable global location '" + locOrder.getGlobalLoc()
375           + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
376     }
377   }
378
379   private void parseClassLatticeDefinition(ClassDescriptor cd, String value,
380       SSJavaLattice<String> locOrder) {
381
382     value = value.replaceAll(" ", ""); // remove all blank spaces
383
384     StringTokenizer tokenizer = new StringTokenizer(value, ",");
385
386     while (tokenizer.hasMoreTokens()) {
387       String orderElement = tokenizer.nextToken();
388       int idx = orderElement.indexOf("<");
389
390       if (idx > 0) {// relative order element
391         String lowerLoc = orderElement.substring(0, idx);
392         String higherLoc = orderElement.substring(idx + 1);
393         locOrder.put(higherLoc, lowerLoc);
394         if (locOrder.isIntroducingCycle(higherLoc)) {
395           throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
396               + " introduces a cycle.");
397         }
398       } else if (orderElement.contains("*")) {
399         // spin loc definition
400         locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
401       } else {
402         // single element
403         locOrder.put(orderElement);
404       }
405     }
406
407     // sanity check
408     Set<String> spinLocSet = locOrder.getSharedLocSet();
409     for (Iterator iterator = spinLocSet.iterator(); iterator.hasNext();) {
410       String spinLoc = (String) iterator.next();
411       if (!locOrder.containsKey(spinLoc)) {
412         throw new Error("Spin location '" + spinLoc
413             + "' is not defined in the default local variable lattice at " + cd.getSourceFileName());
414       }
415     }
416   }
417
418   public Hashtable<ClassDescriptor, SSJavaLattice<String>> getCd2lattice() {
419     return cd2lattice;
420   }
421
422   public Hashtable<ClassDescriptor, MethodLattice<String>> getCd2methodDefault() {
423     return cd2methodDefault;
424   }
425
426   public Hashtable<MethodDescriptor, MethodLattice<String>> getMd2lattice() {
427     return md2lattice;
428   }
429
430   public SSJavaLattice<String> getClassLattice(ClassDescriptor cd) {
431     return cd2lattice.get(cd);
432   }
433
434   public MethodLattice<String> getMethodDefaultLattice(ClassDescriptor cd) {
435     return cd2methodDefault.get(cd);
436   }
437
438   public MethodLattice<String> getMethodLattice(MethodDescriptor md) {
439     if (md2lattice.containsKey(md)) {
440       return md2lattice.get(md);
441     } else {
442
443       if (cd2methodDefault.containsKey(md.getClassDesc())) {
444         return cd2methodDefault.get(md.getClassDesc());
445       } else {
446         throw new Error("Method Lattice of " + md + " is not defined.");
447       }
448
449     }
450   }
451
452   public boolean needToCheckLinearType(MethodDescriptor md) {
453     return linearTypeCheckMethodSet.contains(md);
454   }
455
456   public boolean needTobeAnnotated(MethodDescriptor md) {
457     return annotationRequireSet.contains(md);
458   }
459
460   public boolean needToBeAnnoated(ClassDescriptor cd) {
461     return annotationRequireClassSet.contains(cd);
462   }
463
464   public void addAnnotationRequire(ClassDescriptor cd) {
465     annotationRequireClassSet.add(cd);
466   }
467
468   public void addAnnotationRequire(MethodDescriptor md) {
469
470     ClassDescriptor cd = md.getClassDesc();
471     // if a method requires to be annotated, class containg that method also
472     // requires to be annotated
473     if (!isSSJavaUtil(cd)) {
474       annotationRequireClassSet.add(cd);
475       annotationRequireSet.add(md);
476     }
477   }
478
479   public Set<MethodDescriptor> getAnnotationRequireSet() {
480     return annotationRequireSet;
481   }
482
483   public void doLoopTerminationCheck(LoopOptimize lo, FlatMethod fm) {
484     LoopTerminate lt = new LoopTerminate(this, state);
485     if (needTobeAnnotated(fm.getMethod())) {
486       lt.terminateAnalysis(fm, lo.getLoopInvariant(fm));
487     }
488   }
489
490   public CallGraph getCallGraph() {
491     return callgraph;
492   }
493
494   public SSJavaLattice<String> getLattice(Descriptor d) {
495
496     if (d instanceof MethodDescriptor) {
497       return getMethodLattice((MethodDescriptor) d);
498     } else {
499       return getClassLattice((ClassDescriptor) d);
500     }
501
502   }
503
504   public boolean isSharedLocation(Location loc) {
505     SSJavaLattice<String> lattice = getLattice(loc.getDescriptor());
506     return lattice.getSharedLocSet().contains(loc.getLocIdentifier());
507   }
508
509   public void mapSharedLocation2Descriptor(Location loc, Descriptor d) {
510     Set<Descriptor> set = mapSharedLocation2DescriptorSet.get(loc);
511     if (set == null) {
512       set = new HashSet<Descriptor>();
513       mapSharedLocation2DescriptorSet.put(loc, set);
514     }
515     set.add(d);
516   }
517
518   public BuildFlat getBuildFlat() {
519     return bf;
520   }
521
522   public MethodDescriptor getMethodContainingSSJavaLoop() {
523     return methodContainingSSJavaLoop;
524   }
525
526   public void setMethodContainingSSJavaLoop(MethodDescriptor methodContainingSSJavaLoop) {
527     this.methodContainingSSJavaLoop = methodContainingSSJavaLoop;
528   }
529
530   public boolean isSSJavaUtil(ClassDescriptor cd) {
531     if (cd.getSymbol().equals("SSJAVA")) {
532       return true;
533     }
534     return false;
535   }
536
537   public void setFieldOnwership(MethodDescriptor md, FieldDescriptor field) {
538
539     Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
540     if (fieldSet == null) {
541       fieldSet = new HashSet<FieldDescriptor>();
542       mapMethodToOwnedFieldSet.put(md, fieldSet);
543     }
544     fieldSet.add(field);
545   }
546
547   public boolean isOwnedByMethod(MethodDescriptor md, FieldDescriptor field) {
548     Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
549     if (fieldSet != null) {
550       return fieldSet.contains(field);
551     }
552     return false;
553   }
554
555   public FlatNode getSSJavaLoopEntrance() {
556     return ssjavaLoopEntrance;
557   }
558
559   public void setSSJavaLoopEntrance(FlatNode ssjavaLoopEntrance) {
560     this.ssjavaLoopEntrance = ssjavaLoopEntrance;
561   }
562
563 }