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