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;
31 import IR.Flat.FlatNode;
34 public class SSJavaAnalysis {
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";
51 FlowDownCheck flowDownChecker;
52 MethodAnnotationCheck methodAnnotationChecker;
55 // set containing method requires to be annoated
56 Set<MethodDescriptor> annotationRequireSet;
58 // class -> field lattice
59 Hashtable<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
61 // class -> default local variable lattice
62 Hashtable<ClassDescriptor, MethodLattice<String>> cd2methodDefault;
64 // method -> local variable lattice
65 Hashtable<MethodDescriptor, MethodLattice<String>> md2lattice;
67 // method set that does not want to have loop termination analysis
68 Hashtable<MethodDescriptor, Integer> skipLoopTerminate;
70 // map shared location to its descriptors
71 Hashtable<Location, Set<Descriptor>> mapSharedLocation2DescriptorSet;
73 // set containing a class that has at least one annoated method
74 Set<ClassDescriptor> annotationRequireClassSet;
76 // the set of method descriptor required to check the linear type property
77 Set<MethodDescriptor> linearTypeCheckMethodSet;
79 // the set of method descriptors annotated as "TRUST"
80 Set<MethodDescriptor> trustWorthyMDSet;
82 // points to method containing SSJAVA Loop
83 private MethodDescriptor methodContainingSSJavaLoop;
85 private FlatNode ssjavaLoopEntrance;
87 // keep the field ownership from the linear type checking
88 Hashtable<MethodDescriptor, Set<FieldDescriptor>> mapMethodToOwnedFieldSet;
90 Set<FlatNode> sameHeightWriteFlatNodeSet;
94 LinearTypeCheck checker;
96 public SSJavaAnalysis(State state, TypeUtil tu, BuildFlat bf, CallGraph callgraph) {
99 this.callgraph = callgraph;
100 this.cd2lattice = new Hashtable<ClassDescriptor, SSJavaLattice<String>>();
101 this.cd2methodDefault = new Hashtable<ClassDescriptor, MethodLattice<String>>();
102 this.md2lattice = new Hashtable<MethodDescriptor, MethodLattice<String>>();
103 this.annotationRequireSet = new HashSet<MethodDescriptor>();
104 this.annotationRequireClassSet = new HashSet<ClassDescriptor>();
105 this.skipLoopTerminate = new Hashtable<MethodDescriptor, Integer>();
106 this.mapSharedLocation2DescriptorSet = new Hashtable<Location, Set<Descriptor>>();
107 this.linearTypeCheckMethodSet = new HashSet<MethodDescriptor>();
109 this.trustWorthyMDSet = new HashSet<MethodDescriptor>();
110 this.mapMethodToOwnedFieldSet = new Hashtable<MethodDescriptor, Set<FieldDescriptor>>();
111 this.sameHeightWriteFlatNodeSet = new HashSet<FlatNode>();
114 public void doCheck() {
115 doMethodAnnotationCheck();
116 computeLinearTypeCheckMethodSet();
118 // if (state.SSJAVADEBUG) {
122 parseLocationAnnotation();
124 doDefinitelyWrittenCheck();
128 private void inference() {
129 LocationInference inferEngine = new LocationInference(this, state);
130 inferEngine.inference();
133 private void doLoopCheck() {
134 GlobalFieldType gft = new GlobalFieldType(callgraph, state, tu.getMain());
135 LoopOptimize lo = new LoopOptimize(gft, tu);
137 SymbolTable classtable = state.getClassSymbolTable();
139 List<ClassDescriptor> toanalyzeList = new ArrayList<ClassDescriptor>();
140 List<MethodDescriptor> toanalyzeMethodList = new ArrayList<MethodDescriptor>();
142 toanalyzeList.addAll(classtable.getValueSet());
143 Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
144 public int compare(ClassDescriptor o1, ClassDescriptor o2) {
145 return o1.getClassName().compareTo(o2.getClassName());
149 for (int i = 0; i < toanalyzeList.size(); i++) {
150 ClassDescriptor cd = toanalyzeList.get(i);
152 SymbolTable methodtable = cd.getMethodTable();
153 toanalyzeMethodList.clear();
154 toanalyzeMethodList.addAll(methodtable.getValueSet());
155 Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
156 public int compare(MethodDescriptor o1, MethodDescriptor o2) {
157 return o1.getSymbol().compareTo(o2.getSymbol());
161 for (int mdIdx = 0; mdIdx < toanalyzeMethodList.size(); mdIdx++) {
162 MethodDescriptor md = toanalyzeMethodList.get(mdIdx);
163 if (needTobeAnnotated(md)) {
164 lo.analyze(state.getMethodFlat(md));
165 doLoopTerminationCheck(lo, state.getMethodFlat(md));
173 public void addTrustMethod(MethodDescriptor md) {
174 trustWorthyMDSet.add(md);
177 public boolean isTrustMethod(MethodDescriptor md) {
178 return trustWorthyMDSet.contains(md);
181 private void computeLinearTypeCheckMethodSet() {
183 Set<MethodDescriptor> allCalledSet = callgraph.getMethodCalls(tu.getMain());
184 linearTypeCheckMethodSet.addAll(allCalledSet);
186 Set<MethodDescriptor> trustedSet = new HashSet<MethodDescriptor>();
188 for (Iterator iterator = trustWorthyMDSet.iterator(); iterator.hasNext();) {
189 MethodDescriptor trustMethod = (MethodDescriptor) iterator.next();
190 Set<MethodDescriptor> calledFromTrustMethodSet = callgraph.getMethodCalls(trustMethod);
191 trustedSet.add(trustMethod);
192 trustedSet.addAll(calledFromTrustMethodSet);
195 linearTypeCheckMethodSet.removeAll(trustedSet);
197 // if a method is called only by trusted method, no need to check linear
198 // type & flow down rule
199 for (Iterator iterator = trustedSet.iterator(); iterator.hasNext();) {
200 MethodDescriptor md = (MethodDescriptor) iterator.next();
201 Set<MethodDescriptor> callerSet = callgraph.getCallerSet(md);
202 if (!trustedSet.containsAll(callerSet) && !trustWorthyMDSet.contains(md)) {
203 linearTypeCheckMethodSet.add(md);
209 private void doLinearTypeCheck() {
210 LinearTypeCheck checker = new LinearTypeCheck(this, state);
211 checker.linearTypeCheck();
214 public void debugPrint() {
215 System.out.println("SSJAVA: SSJava is checking the following methods:");
216 for (Iterator<MethodDescriptor> iterator = annotationRequireSet.iterator(); iterator.hasNext();) {
217 MethodDescriptor md = iterator.next();
218 System.out.print(" " + md);
220 System.out.println();
223 private void doMethodAnnotationCheck() {
224 methodAnnotationChecker = new MethodAnnotationCheck(this, state, tu);
225 methodAnnotationChecker.methodAnnoatationCheck();
226 methodAnnotationChecker.methodAnnoataionInheritanceCheck();
229 public void doFlowDownCheck() {
230 flowDownChecker = new FlowDownCheck(this, state);
231 flowDownChecker.flowDownCheck();
234 public void doDefinitelyWrittenCheck() {
235 DefinitelyWrittenCheck checker = new DefinitelyWrittenCheck(this, state);
236 checker.definitelyWrittenCheck();
239 private void parseLocationAnnotation() {
240 Iterator it = state.getClassSymbolTable().getDescriptorsIterator();
241 while (it.hasNext()) {
242 ClassDescriptor cd = (ClassDescriptor) it.next();
243 // parsing location hierarchy declaration for the class
244 Vector<AnnotationDescriptor> classAnnotations = cd.getModifier().getAnnotations();
245 for (int i = 0; i < classAnnotations.size(); i++) {
246 AnnotationDescriptor an = classAnnotations.elementAt(i);
247 String marker = an.getMarker();
248 if (marker.equals(LATTICE)) {
249 SSJavaLattice<String> locOrder =
250 new SSJavaLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
251 cd2lattice.put(cd, locOrder);
252 parseClassLatticeDefinition(cd, an.getValue(), locOrder);
254 if (state.SSJAVADEBUG) {
255 // generate lattice dot file
256 writeLatticeDotFile(cd, locOrder);
259 } else if (marker.equals(METHODDEFAULT)) {
260 MethodLattice<String> locOrder =
261 new MethodLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
262 cd2methodDefault.put(cd, locOrder);
263 parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
267 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
268 MethodDescriptor md = (MethodDescriptor) method_it.next();
269 // parsing location hierarchy declaration for the method
271 if (needTobeAnnotated(md)) {
272 Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
273 if (methodAnnotations != null) {
274 for (int i = 0; i < methodAnnotations.size(); i++) {
275 AnnotationDescriptor an = methodAnnotations.elementAt(i);
276 if (an.getMarker().equals(LATTICE)) {
277 // developer explicitly defines method lattice
278 MethodLattice<String> locOrder =
279 new MethodLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
280 md2lattice.put(md, locOrder);
281 parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
282 } else if (an.getMarker().equals(TERMINATE)) {
283 // developer explicitly wants to skip loop termination analysis
284 String value = an.getValue();
285 int maxIteration = 0;
287 maxIteration = Integer.parseInt(value);
289 skipLoopTerminate.put(md, new Integer(maxIteration));
300 private void writeLatticeDotFile(ClassDescriptor cd, SSJavaLattice<String> locOrder) {
302 String className = cd.getSymbol().replaceAll("[\\W_]", "");
304 Set<Pair<String, String>> pairSet = locOrder.getOrderingPairSet();
307 BufferedWriter bw = new BufferedWriter(new FileWriter(className + ".dot"));
309 bw.write("digraph " + className + " {\n");
311 for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
312 // pair is in the form of <higher, lower>
313 Pair<String, String> pair = (Pair<String, String>) iterator.next();
315 String highLocId = pair.getFirst();
316 if (locOrder.isSharedLoc(highLocId)) {
317 highLocId = "\"" + highLocId + "*\"";
319 String lowLocId = pair.getSecond();
320 if (locOrder.isSharedLoc(lowLocId)) {
321 lowLocId = "\"" + lowLocId + "*\"";
323 bw.write(highLocId + " -> " + lowLocId + ";\n");
328 } catch (IOException e) {
334 private void parseMethodDefaultLatticeDefinition(ClassDescriptor cd, String value,
335 MethodLattice<String> locOrder) {
337 value = value.replaceAll(" ", ""); // remove all blank spaces
339 StringTokenizer tokenizer = new StringTokenizer(value, ",");
341 while (tokenizer.hasMoreTokens()) {
342 String orderElement = tokenizer.nextToken();
343 int idx = orderElement.indexOf("<");
344 if (idx > 0) {// relative order element
345 String lowerLoc = orderElement.substring(0, idx);
346 String higherLoc = orderElement.substring(idx + 1);
347 locOrder.put(higherLoc, lowerLoc);
348 if (locOrder.isIntroducingCycle(higherLoc)) {
349 throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
350 + " introduces a cycle.");
352 } else if (orderElement.startsWith(THISLOC + "=")) {
353 String thisLoc = orderElement.substring(8);
354 locOrder.setThisLoc(thisLoc);
355 } else if (orderElement.startsWith(GLOBALLOC + "=")) {
356 String globalLoc = orderElement.substring(10);
357 locOrder.setGlobalLoc(globalLoc);
358 } else if (orderElement.startsWith(RETURNLOC + "=")) {
359 String returnLoc = orderElement.substring(10);
360 locOrder.setReturnLoc(returnLoc);
361 } else if (orderElement.endsWith("*")) {
362 // spin loc definition
363 locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
366 locOrder.put(orderElement);
371 if (locOrder.getThisLoc() != null && !locOrder.containsKey(locOrder.getThisLoc())) {
372 throw new Error("Variable 'this' location '" + locOrder.getThisLoc()
373 + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
376 if (locOrder.getGlobalLoc() != null && !locOrder.containsKey(locOrder.getGlobalLoc())) {
377 throw new Error("Variable global location '" + locOrder.getGlobalLoc()
378 + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
382 private void parseClassLatticeDefinition(ClassDescriptor cd, String value,
383 SSJavaLattice<String> locOrder) {
385 value = value.replaceAll(" ", ""); // remove all blank spaces
387 StringTokenizer tokenizer = new StringTokenizer(value, ",");
389 while (tokenizer.hasMoreTokens()) {
390 String orderElement = tokenizer.nextToken();
391 int idx = orderElement.indexOf("<");
393 if (idx > 0) {// relative order element
394 String lowerLoc = orderElement.substring(0, idx);
395 String higherLoc = orderElement.substring(idx + 1);
396 locOrder.put(higherLoc, lowerLoc);
397 if (locOrder.isIntroducingCycle(higherLoc)) {
398 throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
399 + " introduces a cycle.");
401 } else if (orderElement.contains("*")) {
402 // spin loc definition
403 locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
406 locOrder.put(orderElement);
411 Set<String> spinLocSet = locOrder.getSharedLocSet();
412 for (Iterator iterator = spinLocSet.iterator(); iterator.hasNext();) {
413 String spinLoc = (String) iterator.next();
414 if (!locOrder.containsKey(spinLoc)) {
415 throw new Error("Spin location '" + spinLoc
416 + "' is not defined in the default local variable lattice at " + cd.getSourceFileName());
421 public Hashtable<ClassDescriptor, SSJavaLattice<String>> getCd2lattice() {
425 public Hashtable<ClassDescriptor, MethodLattice<String>> getCd2methodDefault() {
426 return cd2methodDefault;
429 public Hashtable<MethodDescriptor, MethodLattice<String>> getMd2lattice() {
433 public SSJavaLattice<String> getClassLattice(ClassDescriptor cd) {
434 return cd2lattice.get(cd);
437 public MethodLattice<String> getMethodDefaultLattice(ClassDescriptor cd) {
438 return cd2methodDefault.get(cd);
441 public MethodLattice<String> getMethodLattice(MethodDescriptor md) {
442 if (md2lattice.containsKey(md)) {
443 return md2lattice.get(md);
446 if (cd2methodDefault.containsKey(md.getClassDesc())) {
447 return cd2methodDefault.get(md.getClassDesc());
449 throw new Error("Method Lattice of " + md + " is not defined.");
455 public boolean needToCheckLinearType(MethodDescriptor md) {
456 return linearTypeCheckMethodSet.contains(md);
459 public boolean needTobeAnnotated(MethodDescriptor md) {
460 return annotationRequireSet.contains(md);
463 public boolean needToBeAnnoated(ClassDescriptor cd) {
464 return annotationRequireClassSet.contains(cd);
467 public void addAnnotationRequire(ClassDescriptor cd) {
468 annotationRequireClassSet.add(cd);
471 public void addAnnotationRequire(MethodDescriptor md) {
473 ClassDescriptor cd = md.getClassDesc();
474 // if a method requires to be annotated, class containg that method also
475 // requires to be annotated
476 if (!isSSJavaUtil(cd)) {
477 annotationRequireClassSet.add(cd);
478 annotationRequireSet.add(md);
482 public Set<MethodDescriptor> getAnnotationRequireSet() {
483 return annotationRequireSet;
486 public void doLoopTerminationCheck(LoopOptimize lo, FlatMethod fm) {
487 LoopTerminate lt = new LoopTerminate(this, state);
488 if (needTobeAnnotated(fm.getMethod())) {
489 lt.terminateAnalysis(fm, lo.getLoopInvariant(fm));
493 public CallGraph getCallGraph() {
497 public SSJavaLattice<String> getLattice(Descriptor d) {
499 if (d instanceof MethodDescriptor) {
500 return getMethodLattice((MethodDescriptor) d);
502 return getClassLattice((ClassDescriptor) d);
507 public boolean isSharedLocation(Location loc) {
508 SSJavaLattice<String> lattice = getLattice(loc.getDescriptor());
509 return lattice.getSharedLocSet().contains(loc.getLocIdentifier());
512 public void mapSharedLocation2Descriptor(Location loc, Descriptor d) {
513 Set<Descriptor> set = mapSharedLocation2DescriptorSet.get(loc);
515 set = new HashSet<Descriptor>();
516 mapSharedLocation2DescriptorSet.put(loc, set);
521 public BuildFlat getBuildFlat() {
525 public MethodDescriptor getMethodContainingSSJavaLoop() {
526 return methodContainingSSJavaLoop;
529 public void setMethodContainingSSJavaLoop(MethodDescriptor methodContainingSSJavaLoop) {
530 this.methodContainingSSJavaLoop = methodContainingSSJavaLoop;
533 public boolean isSSJavaUtil(ClassDescriptor cd) {
534 if (cd.getSymbol().equals("SSJAVA")) {
540 public void setFieldOnwership(MethodDescriptor md, FieldDescriptor field) {
542 Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
543 if (fieldSet == null) {
544 fieldSet = new HashSet<FieldDescriptor>();
545 mapMethodToOwnedFieldSet.put(md, fieldSet);
550 public boolean isOwnedByMethod(MethodDescriptor md, FieldDescriptor field) {
551 Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
552 if (fieldSet != null) {
553 return fieldSet.contains(field);
558 public FlatNode getSSJavaLoopEntrance() {
559 return ssjavaLoopEntrance;
562 public void setSSJavaLoopEntrance(FlatNode ssjavaLoopEntrance) {
563 this.ssjavaLoopEntrance = ssjavaLoopEntrance;
566 public void addSameHeightWriteFlatNode(FlatNode fn) {
567 this.sameHeightWriteFlatNodeSet.add(fn);
570 public boolean isSameHeightWrite(FlatNode fn) {
571 return this.sameHeightWriteFlatNodeSet.contains(fn);