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