1 package Analysis.SSJava;
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;
14 import java.util.StringTokenizer;
15 import java.util.Vector;
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;
24 import IR.FieldDescriptor;
25 import IR.MethodDescriptor;
27 import IR.SymbolTable;
29 import IR.Flat.BuildFlat;
30 import IR.Flat.FlatMethod;
33 public class SSJavaAnalysis {
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";
50 FlowDownCheck flowDownChecker;
51 MethodAnnotationCheck methodAnnotationChecker;
54 // set containing method requires to be annoated
55 Set<MethodDescriptor> annotationRequireSet;
57 // class -> field lattice
58 Hashtable<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
60 // class -> default local variable lattice
61 Hashtable<ClassDescriptor, MethodLattice<String>> cd2methodDefault;
63 // method -> local variable lattice
64 Hashtable<MethodDescriptor, MethodLattice<String>> md2lattice;
66 // method set that does not want to have loop termination analysis
67 Hashtable<MethodDescriptor, Integer> skipLoopTerminate;
69 // map shared location to its descriptors
70 Hashtable<Location, Set<Descriptor>> mapSharedLocation2DescriptorSet;
72 // set containing a class that has at least one annoated method
73 Set<ClassDescriptor> annotationRequireClassSet;
75 // the set of method descriptor required to check the linear type property
76 Set<MethodDescriptor> linearTypeCheckMethodSet;
78 // the set of method descriptors annotated as "TRUST"
79 Set<MethodDescriptor> trustWorthyMDSet;
81 // points to method containing SSJAVA Loop
82 private MethodDescriptor methodContainingSSJavaLoop;
84 // keep the field ownership from the linear type checking
85 Hashtable<MethodDescriptor, Set<FieldDescriptor>> mapMethodToOwnedFieldSet;
89 LinearTypeCheck checker;
91 public SSJavaAnalysis(State state, TypeUtil tu, BuildFlat bf, CallGraph callgraph) {
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>();
104 this.trustWorthyMDSet = new HashSet<MethodDescriptor>();
105 this.mapMethodToOwnedFieldSet = new Hashtable<MethodDescriptor, Set<FieldDescriptor>>();
108 public void doCheck() {
109 doMethodAnnotationCheck();
110 computeLinearTypeCheckMethodSet();
112 // if (state.SSJAVADEBUG) {
115 parseLocationAnnotation();
118 doDefinitelyWrittenCheck();
122 private void inference(){
123 SSJavaInferenceEngine inferEngine = new SSJavaInferenceEngine(this, state);
124 inferEngine.inference();
127 private void debugDoLoopCheck() {
128 GlobalFieldType gft = new GlobalFieldType(callgraph, state, tu.getMain());
129 LoopOptimize lo = new LoopOptimize(gft, tu);
131 SymbolTable classtable = state.getClassSymbolTable();
133 List<ClassDescriptor> toanalyzeList = new ArrayList<ClassDescriptor>();
134 List<MethodDescriptor> toanalyzeMethodList = new ArrayList<MethodDescriptor>();
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());
143 for (int i = 0; i < toanalyzeList.size(); i++) {
144 ClassDescriptor cd = toanalyzeList.get(i);
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());
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));
167 public void addTrustMethod(MethodDescriptor md) {
168 trustWorthyMDSet.add(md);
171 public boolean isTrustMethod(MethodDescriptor md) {
172 return trustWorthyMDSet.contains(md);
175 private void computeLinearTypeCheckMethodSet() {
177 Set<MethodDescriptor> allCalledSet = callgraph.getMethodCalls(tu.getMain());
178 linearTypeCheckMethodSet.addAll(allCalledSet);
180 Set<MethodDescriptor> trustedSet = new HashSet<MethodDescriptor>();
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);
189 linearTypeCheckMethodSet.removeAll(trustedSet);
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);
202 private void doLinearTypeCheck() {
203 LinearTypeCheck checker = new LinearTypeCheck(this, state);
204 checker.linearTypeCheck();
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);
213 System.out.println();
216 private void doMethodAnnotationCheck() {
217 methodAnnotationChecker = new MethodAnnotationCheck(this, state, tu);
218 methodAnnotationChecker.methodAnnoatationCheck();
219 methodAnnotationChecker.methodAnnoataionInheritanceCheck();
222 public void doFlowDownCheck() {
223 flowDownChecker = new FlowDownCheck(this, state);
224 flowDownChecker.flowDownCheck();
227 public void doDefinitelyWrittenCheck() {
228 DefinitelyWrittenCheck checker = new DefinitelyWrittenCheck(this, state);
229 checker.definitelyWrittenCheck();
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);
247 if (state.SSJAVADEBUG) {
248 // generate lattice dot file
249 writeLatticeDotFile(cd, locOrder);
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);
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
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;
280 maxIteration = Integer.parseInt(value);
282 skipLoopTerminate.put(md, new Integer(maxIteration));
293 private void writeLatticeDotFile(ClassDescriptor cd, SSJavaLattice<String> locOrder) {
295 String className = cd.getSymbol().replaceAll("[\\W_]", "");
297 Set<Pair<String, String>> pairSet = locOrder.getOrderingPairSet();
300 BufferedWriter bw = new BufferedWriter(new FileWriter(className + ".dot"));
302 bw.write("digraph " + className + " {\n");
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();
308 String highLocId = pair.getFirst();
309 if (locOrder.isSharedLoc(highLocId)) {
310 highLocId = "\"" + highLocId + "*\"";
312 String lowLocId = pair.getSecond();
313 if (locOrder.isSharedLoc(lowLocId)) {
314 lowLocId = "\"" + lowLocId + "*\"";
316 bw.write(highLocId + " -> " + lowLocId + ";\n");
321 } catch (IOException e) {
327 private void parseMethodDefaultLatticeDefinition(ClassDescriptor cd, String value,
328 MethodLattice<String> locOrder) {
330 value = value.replaceAll(" ", ""); // remove all blank spaces
332 StringTokenizer tokenizer = new StringTokenizer(value, ",");
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.");
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));
359 locOrder.put(orderElement);
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());
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());
375 private void parseClassLatticeDefinition(ClassDescriptor cd, String value,
376 SSJavaLattice<String> locOrder) {
378 value = value.replaceAll(" ", ""); // remove all blank spaces
380 StringTokenizer tokenizer = new StringTokenizer(value, ",");
382 while (tokenizer.hasMoreTokens()) {
383 String orderElement = tokenizer.nextToken();
384 int idx = orderElement.indexOf("<");
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.");
394 } else if (orderElement.contains("*")) {
395 // spin loc definition
396 locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
399 locOrder.put(orderElement);
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());
414 public Hashtable<ClassDescriptor, SSJavaLattice<String>> getCd2lattice() {
418 public Hashtable<ClassDescriptor, MethodLattice<String>> getCd2methodDefault() {
419 return cd2methodDefault;
422 public Hashtable<MethodDescriptor, MethodLattice<String>> getMd2lattice() {
426 public SSJavaLattice<String> getClassLattice(ClassDescriptor cd) {
427 return cd2lattice.get(cd);
430 public MethodLattice<String> getMethodDefaultLattice(ClassDescriptor cd) {
431 return cd2methodDefault.get(cd);
434 public MethodLattice<String> getMethodLattice(MethodDescriptor md) {
435 if (md2lattice.containsKey(md)) {
436 return md2lattice.get(md);
438 return cd2methodDefault.get(md.getClassDesc());
442 public boolean needToCheckLinearType(MethodDescriptor md) {
443 return linearTypeCheckMethodSet.contains(md);
446 public boolean needTobeAnnotated(MethodDescriptor md) {
447 return annotationRequireSet.contains(md);
450 public boolean needToBeAnnoated(ClassDescriptor cd) {
451 return annotationRequireClassSet.contains(cd);
454 public void addAnnotationRequire(ClassDescriptor cd) {
455 annotationRequireClassSet.add(cd);
458 public void addAnnotationRequire(MethodDescriptor md) {
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);
469 public Set<MethodDescriptor> getAnnotationRequireSet() {
470 return annotationRequireSet;
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));
480 public CallGraph getCallGraph() {
484 public SSJavaLattice<String> getLattice(Descriptor d) {
486 if (d instanceof MethodDescriptor) {
487 return getMethodLattice((MethodDescriptor) d);
489 return getClassLattice((ClassDescriptor) d);
494 public boolean isSharedLocation(Location loc) {
495 SSJavaLattice<String> lattice = getLattice(loc.getDescriptor());
496 return lattice.getSharedLocSet().contains(loc.getLocIdentifier());
499 public void mapSharedLocation2Descriptor(Location loc, Descriptor d) {
500 Set<Descriptor> set = mapSharedLocation2DescriptorSet.get(loc);
502 set = new HashSet<Descriptor>();
503 mapSharedLocation2DescriptorSet.put(loc, set);
508 public BuildFlat getBuildFlat() {
512 public MethodDescriptor getMethodContainingSSJavaLoop() {
513 return methodContainingSSJavaLoop;
516 public void setMethodContainingSSJavaLoop(MethodDescriptor methodContainingSSJavaLoop) {
517 this.methodContainingSSJavaLoop = methodContainingSSJavaLoop;
520 public boolean isSSJavaUtil(ClassDescriptor cd) {
521 if (cd.getSymbol().equals("SSJAVA")) {
527 public void setFieldOnwership(MethodDescriptor md, FieldDescriptor field) {
529 Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
530 if (fieldSet == null) {
531 fieldSet = new HashSet<FieldDescriptor>();
532 mapMethodToOwnedFieldSet.put(md, fieldSet);
537 public boolean isOwnedByMethod(MethodDescriptor md, FieldDescriptor field) {
538 Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
539 if (fieldSet != null) {
540 return fieldSet.contains(field);