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) {
121 if (state.SSJAVAINFER) {
124 parseLocationAnnotation();
126 doDefinitelyWrittenCheck();
131 private void inference() {
132 LocationInference inferEngine = new LocationInference(this, state);
133 inferEngine.inference();
136 private void doLoopCheck() {
137 GlobalFieldType gft = new GlobalFieldType(callgraph, state, tu.getMain());
138 LoopOptimize lo = new LoopOptimize(gft, tu);
140 SymbolTable classtable = state.getClassSymbolTable();
142 List<ClassDescriptor> toanalyzeList = new ArrayList<ClassDescriptor>();
143 List<MethodDescriptor> toanalyzeMethodList = new ArrayList<MethodDescriptor>();
145 toanalyzeList.addAll(classtable.getValueSet());
146 Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
147 public int compare(ClassDescriptor o1, ClassDescriptor o2) {
148 return o1.getClassName().compareTo(o2.getClassName());
152 for (int i = 0; i < toanalyzeList.size(); i++) {
153 ClassDescriptor cd = toanalyzeList.get(i);
155 SymbolTable methodtable = cd.getMethodTable();
156 toanalyzeMethodList.clear();
157 toanalyzeMethodList.addAll(methodtable.getValueSet());
158 Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
159 public int compare(MethodDescriptor o1, MethodDescriptor o2) {
160 return o1.getSymbol().compareTo(o2.getSymbol());
164 for (int mdIdx = 0; mdIdx < toanalyzeMethodList.size(); mdIdx++) {
165 MethodDescriptor md = toanalyzeMethodList.get(mdIdx);
166 if (needTobeAnnotated(md)) {
167 lo.analyze(state.getMethodFlat(md));
168 doLoopTerminationCheck(lo, state.getMethodFlat(md));
176 public void addTrustMethod(MethodDescriptor md) {
177 trustWorthyMDSet.add(md);
180 public boolean isTrustMethod(MethodDescriptor md) {
181 return trustWorthyMDSet.contains(md);
184 private void computeLinearTypeCheckMethodSet() {
186 Set<MethodDescriptor> allCalledSet = callgraph.getMethodCalls(tu.getMain());
187 linearTypeCheckMethodSet.addAll(allCalledSet);
189 Set<MethodDescriptor> trustedSet = new HashSet<MethodDescriptor>();
191 for (Iterator iterator = trustWorthyMDSet.iterator(); iterator.hasNext();) {
192 MethodDescriptor trustMethod = (MethodDescriptor) iterator.next();
193 Set<MethodDescriptor> calledFromTrustMethodSet = callgraph.getMethodCalls(trustMethod);
194 trustedSet.add(trustMethod);
195 trustedSet.addAll(calledFromTrustMethodSet);
198 linearTypeCheckMethodSet.removeAll(trustedSet);
200 // if a method is called only by trusted method, no need to check linear
201 // type & flow down rule
202 for (Iterator iterator = trustedSet.iterator(); iterator.hasNext();) {
203 MethodDescriptor md = (MethodDescriptor) iterator.next();
204 Set<MethodDescriptor> callerSet = callgraph.getCallerSet(md);
205 if (!trustedSet.containsAll(callerSet) && !trustWorthyMDSet.contains(md)) {
206 linearTypeCheckMethodSet.add(md);
212 private void doLinearTypeCheck() {
213 LinearTypeCheck checker = new LinearTypeCheck(this, state);
214 checker.linearTypeCheck();
217 public void debugPrint() {
218 System.out.println("SSJAVA: SSJava is checking the following methods:");
219 for (Iterator<MethodDescriptor> iterator = annotationRequireSet.iterator(); iterator.hasNext();) {
220 MethodDescriptor md = iterator.next();
221 System.out.print(" " + md);
223 System.out.println();
226 private void doMethodAnnotationCheck() {
227 methodAnnotationChecker = new MethodAnnotationCheck(this, state, tu);
228 methodAnnotationChecker.methodAnnoatationCheck();
229 methodAnnotationChecker.methodAnnoataionInheritanceCheck();
230 state.setAnnotationRequireSet(annotationRequireSet);
233 public void doFlowDownCheck() {
234 flowDownChecker = new FlowDownCheck(this, state);
235 flowDownChecker.flowDownCheck();
238 public void doDefinitelyWrittenCheck() {
239 DefinitelyWrittenCheck checker = new DefinitelyWrittenCheck(this, state);
240 checker.definitelyWrittenCheck();
243 private void parseLocationAnnotation() {
244 Iterator it = state.getClassSymbolTable().getDescriptorsIterator();
245 while (it.hasNext()) {
246 ClassDescriptor cd = (ClassDescriptor) it.next();
247 // parsing location hierarchy declaration for the class
248 Vector<AnnotationDescriptor> classAnnotations = cd.getModifier().getAnnotations();
249 for (int i = 0; i < classAnnotations.size(); i++) {
250 AnnotationDescriptor an = classAnnotations.elementAt(i);
251 String marker = an.getMarker();
252 if (marker.equals(LATTICE)) {
253 SSJavaLattice<String> locOrder =
254 new SSJavaLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
255 cd2lattice.put(cd, locOrder);
256 parseClassLatticeDefinition(cd, an.getValue(), locOrder);
258 if (state.SSJAVADEBUG) {
259 // generate lattice dot file
260 writeLatticeDotFile(cd, locOrder);
263 } else if (marker.equals(METHODDEFAULT)) {
264 MethodLattice<String> locOrder =
265 new MethodLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
266 cd2methodDefault.put(cd, locOrder);
267 parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
271 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
272 MethodDescriptor md = (MethodDescriptor) method_it.next();
273 // parsing location hierarchy declaration for the method
275 if (needTobeAnnotated(md)) {
276 Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
277 if (methodAnnotations != null) {
278 for (int i = 0; i < methodAnnotations.size(); i++) {
279 AnnotationDescriptor an = methodAnnotations.elementAt(i);
280 if (an.getMarker().equals(LATTICE)) {
281 // developer explicitly defines method lattice
282 MethodLattice<String> locOrder =
283 new MethodLattice<String>(SSJavaLattice.TOP, SSJavaLattice.BOTTOM);
284 md2lattice.put(md, locOrder);
285 parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
286 } else if (an.getMarker().equals(TERMINATE)) {
287 // developer explicitly wants to skip loop termination analysis
288 String value = an.getValue();
289 int maxIteration = 0;
291 maxIteration = Integer.parseInt(value);
293 skipLoopTerminate.put(md, new Integer(maxIteration));
304 private void writeLatticeDotFile(ClassDescriptor cd, SSJavaLattice<String> locOrder) {
306 String className = cd.getSymbol().replaceAll("[\\W_]", "");
308 Set<Pair<String, String>> pairSet = locOrder.getOrderingPairSet();
311 BufferedWriter bw = new BufferedWriter(new FileWriter(className + ".dot"));
313 bw.write("digraph " + className + " {\n");
315 for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
316 // pair is in the form of <higher, lower>
317 Pair<String, String> pair = (Pair<String, String>) iterator.next();
319 String highLocId = pair.getFirst();
320 if (locOrder.isSharedLoc(highLocId)) {
321 highLocId = "\"" + highLocId + "*\"";
323 String lowLocId = pair.getSecond();
324 if (locOrder.isSharedLoc(lowLocId)) {
325 lowLocId = "\"" + lowLocId + "*\"";
327 bw.write(highLocId + " -> " + lowLocId + ";\n");
332 } catch (IOException e) {
338 private void parseMethodDefaultLatticeDefinition(ClassDescriptor cd, String value,
339 MethodLattice<String> locOrder) {
341 value = value.replaceAll(" ", ""); // remove all blank spaces
343 StringTokenizer tokenizer = new StringTokenizer(value, ",");
345 while (tokenizer.hasMoreTokens()) {
346 String orderElement = tokenizer.nextToken();
347 int idx = orderElement.indexOf("<");
348 if (idx > 0) {// relative order element
349 String lowerLoc = orderElement.substring(0, idx);
350 String higherLoc = orderElement.substring(idx + 1);
351 locOrder.put(higherLoc, lowerLoc);
352 if (locOrder.isIntroducingCycle(higherLoc)) {
353 throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
354 + " introduces a cycle.");
356 } else if (orderElement.startsWith(THISLOC + "=")) {
357 String thisLoc = orderElement.substring(8);
358 locOrder.setThisLoc(thisLoc);
359 } else if (orderElement.startsWith(GLOBALLOC + "=")) {
360 String globalLoc = orderElement.substring(10);
361 locOrder.setGlobalLoc(globalLoc);
362 } else if (orderElement.startsWith(RETURNLOC + "=")) {
363 String returnLoc = orderElement.substring(10);
364 locOrder.setReturnLoc(returnLoc);
365 } else if (orderElement.endsWith("*")) {
366 // spin loc definition
367 locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
370 locOrder.put(orderElement);
375 if (locOrder.getThisLoc() != null && !locOrder.containsKey(locOrder.getThisLoc())) {
376 throw new Error("Variable 'this' location '" + locOrder.getThisLoc()
377 + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
380 if (locOrder.getGlobalLoc() != null && !locOrder.containsKey(locOrder.getGlobalLoc())) {
381 throw new Error("Variable global location '" + locOrder.getGlobalLoc()
382 + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
386 private void parseClassLatticeDefinition(ClassDescriptor cd, String value,
387 SSJavaLattice<String> locOrder) {
389 value = value.replaceAll(" ", ""); // remove all blank spaces
391 StringTokenizer tokenizer = new StringTokenizer(value, ",");
393 while (tokenizer.hasMoreTokens()) {
394 String orderElement = tokenizer.nextToken();
395 int idx = orderElement.indexOf("<");
397 if (idx > 0) {// relative order element
398 String lowerLoc = orderElement.substring(0, idx);
399 String higherLoc = orderElement.substring(idx + 1);
400 locOrder.put(higherLoc, lowerLoc);
401 if (locOrder.isIntroducingCycle(higherLoc)) {
402 throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
403 + " introduces a cycle.");
405 } else if (orderElement.contains("*")) {
406 // spin loc definition
407 locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
410 locOrder.put(orderElement);
415 Set<String> spinLocSet = locOrder.getSharedLocSet();
416 for (Iterator iterator = spinLocSet.iterator(); iterator.hasNext();) {
417 String spinLoc = (String) iterator.next();
418 if (!locOrder.containsKey(spinLoc)) {
419 throw new Error("Spin location '" + spinLoc
420 + "' is not defined in the default local variable lattice at " + cd.getSourceFileName());
425 public Hashtable<ClassDescriptor, SSJavaLattice<String>> getCd2lattice() {
429 public Hashtable<ClassDescriptor, MethodLattice<String>> getCd2methodDefault() {
430 return cd2methodDefault;
433 public Hashtable<MethodDescriptor, MethodLattice<String>> getMd2lattice() {
437 public SSJavaLattice<String> getClassLattice(ClassDescriptor cd) {
438 return cd2lattice.get(cd);
441 public MethodLattice<String> getMethodDefaultLattice(ClassDescriptor cd) {
442 return cd2methodDefault.get(cd);
445 public MethodLattice<String> getMethodLattice(MethodDescriptor md) {
446 if (md2lattice.containsKey(md)) {
447 return md2lattice.get(md);
450 if (cd2methodDefault.containsKey(md.getClassDesc())) {
451 return cd2methodDefault.get(md.getClassDesc());
453 throw new Error("Method Lattice of " + md + " is not defined.");
459 public boolean needToCheckLinearType(MethodDescriptor md) {
460 return linearTypeCheckMethodSet.contains(md);
463 public boolean needTobeAnnotated(MethodDescriptor md) {
464 return annotationRequireSet.contains(md);
467 public boolean needToBeAnnoated(ClassDescriptor cd) {
468 return annotationRequireClassSet.contains(cd);
471 public void addAnnotationRequire(ClassDescriptor cd) {
472 annotationRequireClassSet.add(cd);
475 public void addAnnotationRequire(MethodDescriptor md) {
477 ClassDescriptor cd = md.getClassDesc();
478 // if a method requires to be annotated, class containg that method also
479 // requires to be annotated
480 if (!isSSJavaUtil(cd)) {
481 annotationRequireClassSet.add(cd);
482 annotationRequireSet.add(md);
486 public Set<MethodDescriptor> getAnnotationRequireSet() {
487 return annotationRequireSet;
490 public void doLoopTerminationCheck(LoopOptimize lo, FlatMethod fm) {
491 LoopTerminate lt = new LoopTerminate(this, state);
492 if (needTobeAnnotated(fm.getMethod())) {
493 lt.terminateAnalysis(fm, lo.getLoopInvariant(fm));
497 public CallGraph getCallGraph() {
501 public SSJavaLattice<String> getLattice(Descriptor d) {
503 if (d instanceof MethodDescriptor) {
504 return getMethodLattice((MethodDescriptor) d);
506 return getClassLattice((ClassDescriptor) d);
511 public boolean isSharedLocation(Location loc) {
512 SSJavaLattice<String> lattice = getLattice(loc.getDescriptor());
513 return lattice.getSharedLocSet().contains(loc.getLocIdentifier());
516 public void mapSharedLocation2Descriptor(Location loc, Descriptor d) {
517 Set<Descriptor> set = mapSharedLocation2DescriptorSet.get(loc);
519 set = new HashSet<Descriptor>();
520 mapSharedLocation2DescriptorSet.put(loc, set);
525 public BuildFlat getBuildFlat() {
529 public MethodDescriptor getMethodContainingSSJavaLoop() {
530 return methodContainingSSJavaLoop;
533 public void setMethodContainingSSJavaLoop(MethodDescriptor methodContainingSSJavaLoop) {
534 this.methodContainingSSJavaLoop = methodContainingSSJavaLoop;
537 public boolean isSSJavaUtil(ClassDescriptor cd) {
538 if (cd.getSymbol().equals("SSJAVA")) {
544 public void setFieldOnwership(MethodDescriptor md, FieldDescriptor field) {
546 Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
547 if (fieldSet == null) {
548 fieldSet = new HashSet<FieldDescriptor>();
549 mapMethodToOwnedFieldSet.put(md, fieldSet);
554 public boolean isOwnedByMethod(MethodDescriptor md, FieldDescriptor field) {
555 Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
556 if (fieldSet != null) {
557 return fieldSet.contains(field);
562 public FlatNode getSSJavaLoopEntrance() {
563 return ssjavaLoopEntrance;
566 public void setSSJavaLoopEntrance(FlatNode ssjavaLoopEntrance) {
567 this.ssjavaLoopEntrance = ssjavaLoopEntrance;
570 public void addSameHeightWriteFlatNode(FlatNode fn) {
571 this.sameHeightWriteFlatNodeSet.add(fn);
574 public boolean isSameHeightWrite(FlatNode fn) {
575 return this.sameHeightWriteFlatNodeSet.contains(fn);