changes.
[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.HashMap;
10 import java.util.HashSet;
11 import java.util.Hashtable;
12 import java.util.Iterator;
13 import java.util.LinkedList;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Set;
17 import java.util.StringTokenizer;
18 import java.util.Vector;
19
20 import Analysis.CallGraph.CallGraph;
21 import Analysis.Loops.GlobalFieldType;
22 import Analysis.Loops.LoopOptimize;
23 import Analysis.Loops.LoopTerminate;
24 import IR.AnnotationDescriptor;
25 import IR.ClassDescriptor;
26 import IR.Descriptor;
27 import IR.FieldDescriptor;
28 import IR.MethodDescriptor;
29 import IR.State;
30 import IR.SymbolTable;
31 import IR.TypeUtil;
32 import IR.Flat.BuildFlat;
33 import IR.Flat.FlatMethod;
34 import IR.Flat.FlatNode;
35 import Util.Pair;
36
37 public class SSJavaAnalysis {
38
39   public static final String SSJAVA = "SSJAVA";
40   public static final String LATTICE = "LATTICE";
41   public static final String METHODDEFAULT = "METHODDEFAULT";
42   public static final String THISLOC = "THISLOC";
43   public static final String GLOBALLOC = "GLOBALLOC";
44   public static final String RETURNLOC = "RETURNLOC";
45   public static final String PCLOC = "PCLOC";
46   public static final String LOC = "LOC";
47   public static final String DELTA = "DELTA";
48   public static final String TERMINATE = "TERMINATE";
49   public static final String DELEGATE = "DELEGATE";
50   public static final String DELEGATETHIS = "DELEGATETHIS";
51   public static final String TRUST = "TRUST";
52
53   public static final String TOP = "_top_";
54   public static final String BOTTOM = "_bottom_";
55
56   State state;
57   TypeUtil tu;
58   FlowDownCheck flowDownChecker;
59   MethodAnnotationCheck methodAnnotationChecker;
60   BuildFlat bf;
61
62   // set containing method requires to be annoated
63   Set<MethodDescriptor> annotationRequireSet;
64
65   // class -> field lattice
66   Hashtable<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
67
68   // class -> default local variable lattice
69   Hashtable<ClassDescriptor, MethodLattice<String>> cd2methodDefault;
70
71   // method -> local variable lattice
72   Hashtable<MethodDescriptor, MethodLattice<String>> md2lattice;
73
74   // method set that does not want to have loop termination analysis
75   Hashtable<MethodDescriptor, Integer> skipLoopTerminate;
76
77   // map shared location to its descriptors
78   Hashtable<Location, Set<Descriptor>> mapSharedLocation2DescriptorSet;
79
80   // set containing a class that has at least one annoated method
81   Set<ClassDescriptor> annotationRequireClassSet;
82
83   // the set of method descriptor required to check the linear type property
84   Set<MethodDescriptor> linearTypeCheckMethodSet;
85
86   // the set of method descriptors annotated as "TRUST"
87   Set<MethodDescriptor> trustWorthyMDSet;
88
89   // method -> the initial program counter location
90   Map<MethodDescriptor, CompositeLocation> md2pcLoc;
91
92   // points to method containing SSJAVA Loop
93   private MethodDescriptor methodContainingSSJavaLoop;
94
95   private FlatNode ssjavaLoopEntrance;
96
97   // keep the field ownership from the linear type checking
98   Hashtable<MethodDescriptor, Set<FieldDescriptor>> mapMethodToOwnedFieldSet;
99
100   Set<FlatNode> sameHeightWriteFlatNodeSet;
101
102   CallGraph callgraph;
103
104   LinearTypeCheck checker;
105
106   // maps a descriptor to its known dependents: namely
107   // methods or tasks that call the descriptor's method
108   // AND are part of this analysis (reachable from main)
109   private Hashtable<Descriptor, Set<MethodDescriptor>> mapDescriptorToSetDependents;
110
111   private LinkedList<MethodDescriptor> sortedDescriptors;
112
113   public SSJavaAnalysis(State state, TypeUtil tu, BuildFlat bf, CallGraph callgraph) {
114     this.state = state;
115     this.tu = tu;
116     this.callgraph = callgraph;
117     this.cd2lattice = new Hashtable<ClassDescriptor, SSJavaLattice<String>>();
118     this.cd2methodDefault = new Hashtable<ClassDescriptor, MethodLattice<String>>();
119     this.md2lattice = new Hashtable<MethodDescriptor, MethodLattice<String>>();
120     this.annotationRequireSet = new HashSet<MethodDescriptor>();
121     this.annotationRequireClassSet = new HashSet<ClassDescriptor>();
122     this.skipLoopTerminate = new Hashtable<MethodDescriptor, Integer>();
123     this.mapSharedLocation2DescriptorSet = new Hashtable<Location, Set<Descriptor>>();
124     this.linearTypeCheckMethodSet = new HashSet<MethodDescriptor>();
125     this.bf = bf;
126     this.trustWorthyMDSet = new HashSet<MethodDescriptor>();
127     this.mapMethodToOwnedFieldSet = new Hashtable<MethodDescriptor, Set<FieldDescriptor>>();
128     this.sameHeightWriteFlatNodeSet = new HashSet<FlatNode>();
129     this.mapDescriptorToSetDependents = new Hashtable<Descriptor, Set<MethodDescriptor>>();
130     this.sortedDescriptors = new LinkedList<MethodDescriptor>();
131     this.md2pcLoc = new HashMap<MethodDescriptor, CompositeLocation>();
132   }
133
134   public void doCheck() {
135     doMethodAnnotationCheck();
136
137     if (state.SSJAVA) {
138       computeLinearTypeCheckMethodSet();
139       doLinearTypeCheck();
140     }
141
142     init();
143
144     if (state.SSJAVADEBUG) {
145       // debug_printAnnotationRequiredSet();
146     }
147     if (state.SSJAVAINFER) {
148       inference();
149       System.exit(0);
150     } else {
151       parseLocationAnnotation();
152       doFlowDownCheck();
153       doDefinitelyWrittenCheck();
154       doLoopCheck();
155     }
156   }
157
158   private void init() {
159     // perform topological sort over the set of methods accessed by the main
160     // event loop
161     Set<MethodDescriptor> methodDescriptorsToAnalyze = new HashSet<MethodDescriptor>();
162     methodDescriptorsToAnalyze.addAll(getAnnotationRequireSet());
163     sortedDescriptors = topologicalSort(methodDescriptorsToAnalyze);
164   }
165
166   public LinkedList<MethodDescriptor> getSortedDescriptors() {
167     return (LinkedList<MethodDescriptor>) sortedDescriptors.clone();
168   }
169
170   private void inference() {
171     LocationInference inferEngine = new LocationInference(this, state);
172     inferEngine.inference();
173   }
174
175   private void doLoopCheck() {
176     GlobalFieldType gft = new GlobalFieldType(callgraph, state, tu.getMain());
177     LoopOptimize lo = new LoopOptimize(gft, tu);
178
179     SymbolTable classtable = state.getClassSymbolTable();
180
181     List<ClassDescriptor> toanalyzeList = new ArrayList<ClassDescriptor>();
182     List<MethodDescriptor> toanalyzeMethodList = new ArrayList<MethodDescriptor>();
183
184     toanalyzeList.addAll(classtable.getValueSet());
185     Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
186       public int compare(ClassDescriptor o1, ClassDescriptor o2) {
187         return o1.getClassName().compareTo(o2.getClassName());
188       }
189     });
190
191     for (int i = 0; i < toanalyzeList.size(); i++) {
192       ClassDescriptor cd = toanalyzeList.get(i);
193
194       SymbolTable methodtable = cd.getMethodTable();
195       toanalyzeMethodList.clear();
196       toanalyzeMethodList.addAll(methodtable.getValueSet());
197       Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
198         public int compare(MethodDescriptor o1, MethodDescriptor o2) {
199           return o1.getSymbol().compareTo(o2.getSymbol());
200         }
201       });
202
203       for (int mdIdx = 0; mdIdx < toanalyzeMethodList.size(); mdIdx++) {
204         MethodDescriptor md = toanalyzeMethodList.get(mdIdx);
205         if (needTobeAnnotated(md)) {
206           lo.analyze(state.getMethodFlat(md));
207           doLoopTerminationCheck(lo, state.getMethodFlat(md));
208         }
209       }
210
211     }
212
213   }
214
215   public void addTrustMethod(MethodDescriptor md) {
216     trustWorthyMDSet.add(md);
217   }
218
219   public boolean isTrustMethod(MethodDescriptor md) {
220     return trustWorthyMDSet.contains(md);
221   }
222
223   private void computeLinearTypeCheckMethodSet() {
224
225     Set<MethodDescriptor> allCalledSet = callgraph.getMethodCalls(tu.getMain());
226     linearTypeCheckMethodSet.addAll(allCalledSet);
227
228     Set<MethodDescriptor> trustedSet = new HashSet<MethodDescriptor>();
229
230     for (Iterator iterator = trustWorthyMDSet.iterator(); iterator.hasNext();) {
231       MethodDescriptor trustMethod = (MethodDescriptor) iterator.next();
232       Set<MethodDescriptor> calledFromTrustMethodSet = callgraph.getMethodCalls(trustMethod);
233       trustedSet.add(trustMethod);
234       trustedSet.addAll(calledFromTrustMethodSet);
235     }
236
237     linearTypeCheckMethodSet.removeAll(trustedSet);
238
239     // if a method is called only by trusted method, no need to check linear
240     // type & flow down rule
241     for (Iterator iterator = trustedSet.iterator(); iterator.hasNext();) {
242       MethodDescriptor md = (MethodDescriptor) iterator.next();
243       Set<MethodDescriptor> callerSet = callgraph.getCallerSet(md);
244       if (!trustedSet.containsAll(callerSet) && !trustWorthyMDSet.contains(md)) {
245         linearTypeCheckMethodSet.add(md);
246       }
247     }
248
249   }
250
251   private void doLinearTypeCheck() {
252     LinearTypeCheck checker = new LinearTypeCheck(this, state);
253     checker.linearTypeCheck();
254   }
255
256   public void debug_printAnnotationRequiredSet() {
257     System.out.println("SSJAVA: SSJava is checking the following methods:");
258     for (Iterator<MethodDescriptor> iterator = annotationRequireSet.iterator(); iterator.hasNext();) {
259       MethodDescriptor md = iterator.next();
260       System.out.println(md);
261     }
262     System.out.println();
263   }
264
265   private void doMethodAnnotationCheck() {
266     methodAnnotationChecker = new MethodAnnotationCheck(this, state, tu);
267     methodAnnotationChecker.methodAnnoatationCheck();
268     methodAnnotationChecker.methodAnnoataionInheritanceCheck();
269     if (state.SSJAVAINFER) {
270       annotationRequireClassSet.add(methodContainingSSJavaLoop.getClassDesc());
271       annotationRequireSet.add(methodContainingSSJavaLoop);
272     }
273     state.setAnnotationRequireSet(annotationRequireSet);
274   }
275
276   public void doFlowDownCheck() {
277     flowDownChecker = new FlowDownCheck(this, state);
278     flowDownChecker.flowDownCheck();
279   }
280
281   public void doDefinitelyWrittenCheck() {
282     DefinitelyWrittenCheck checker = new DefinitelyWrittenCheck(this, state);
283     checker.definitelyWrittenCheck();
284   }
285
286   private void parseLocationAnnotation() {
287     Iterator it = state.getClassSymbolTable().getDescriptorsIterator();
288     while (it.hasNext()) {
289       ClassDescriptor cd = (ClassDescriptor) it.next();
290       // parsing location hierarchy declaration for the class
291       Vector<AnnotationDescriptor> classAnnotations = cd.getModifier().getAnnotations();
292       for (int i = 0; i < classAnnotations.size(); i++) {
293         AnnotationDescriptor an = classAnnotations.elementAt(i);
294         String marker = an.getMarker();
295         if (marker.equals(LATTICE)) {
296           SSJavaLattice<String> locOrder =
297               new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM);
298           cd2lattice.put(cd, locOrder);
299           parseClassLatticeDefinition(cd, an.getValue(), locOrder);
300
301           if (state.SSJAVADEBUG) {
302             // generate lattice dot file
303             writeLatticeDotFile(cd, null, locOrder);
304           }
305
306         } else if (marker.equals(METHODDEFAULT)) {
307           MethodLattice<String> locOrder =
308               new MethodLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM);
309           cd2methodDefault.put(cd, locOrder);
310           parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
311         }
312       }
313
314       for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
315         MethodDescriptor md = (MethodDescriptor) method_it.next();
316         // parsing location hierarchy declaration for the method
317
318         if (needTobeAnnotated(md)) {
319           Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
320           if (methodAnnotations != null) {
321             for (int i = 0; i < methodAnnotations.size(); i++) {
322               AnnotationDescriptor an = methodAnnotations.elementAt(i);
323               if (an.getMarker().equals(LATTICE)) {
324                 // developer explicitly defines method lattice
325                 MethodLattice<String> locOrder =
326                     new MethodLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM);
327                 md2lattice.put(md, locOrder);
328                 parseMethodDefaultLatticeDefinition(cd, an.getValue(), locOrder);
329               } else if (an.getMarker().equals(TERMINATE)) {
330                 // developer explicitly wants to skip loop termination analysis
331                 String value = an.getValue();
332                 int maxIteration = 0;
333                 if (value != null) {
334                   maxIteration = Integer.parseInt(value);
335                 }
336                 skipLoopTerminate.put(md, new Integer(maxIteration));
337               }
338             }
339           }
340         }
341
342       }
343
344     }
345   }
346
347   public <T> void writeLatticeDotFile(ClassDescriptor cd, MethodDescriptor md,
348       SSJavaLattice<T> locOrder) {
349
350     String fileName = "lattice_";
351     if (md != null) {
352       fileName +=
353           cd.getSymbol().replaceAll("[\\W_]", "") + "_" + md.getSymbol().replaceAll("[\\W_]", "");
354     } else {
355       fileName += cd.getSymbol().replaceAll("[\\W_]", "");
356     }
357
358     Set<Pair<T, T>> pairSet = locOrder.getOrderingPairSet();
359
360     if (pairSet.size() > 0) {
361       try {
362         BufferedWriter bw = new BufferedWriter(new FileWriter(fileName + ".dot"));
363
364         bw.write("digraph " + fileName + " {\n");
365
366         for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
367           // pair is in the form of <higher, lower>
368           Pair<T, T> pair = (Pair<T, T>) iterator.next();
369
370           T highLocId = pair.getFirst();
371           String highLocStr, lowLocStr;
372           if (locOrder.isSharedLoc(highLocId)) {
373             highLocStr = "\"" + highLocId + "*\"";
374           } else {
375             highLocStr = highLocId.toString();
376           }
377           T lowLocId = pair.getSecond();
378           if (locOrder.isSharedLoc(lowLocId)) {
379             lowLocStr = "\"" + lowLocId + "*\"";
380           } else {
381             lowLocStr = lowLocId.toString();
382           }
383           bw.write(highLocStr + " -> " + lowLocStr + ";\n");
384         }
385         bw.write("}\n");
386         bw.close();
387
388       } catch (IOException e) {
389         e.printStackTrace();
390       }
391
392     }
393
394   }
395
396   private void parseMethodDefaultLatticeDefinition(ClassDescriptor cd, String value,
397       MethodLattice<String> locOrder) {
398
399     value = value.replaceAll(" ", ""); // remove all blank spaces
400
401     StringTokenizer tokenizer = new StringTokenizer(value, ",");
402
403     while (tokenizer.hasMoreTokens()) {
404       String orderElement = tokenizer.nextToken();
405       int idx = orderElement.indexOf("<");
406       if (idx > 0) {// relative order element
407         String lowerLoc = orderElement.substring(0, idx);
408         String higherLoc = orderElement.substring(idx + 1);
409         locOrder.put(higherLoc, lowerLoc);
410         if (locOrder.isIntroducingCycle(higherLoc)) {
411           throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
412               + " introduces a cycle.");
413         }
414       } else if (orderElement.startsWith(THISLOC + "=")) {
415         String thisLoc = orderElement.substring(8);
416         locOrder.setThisLoc(thisLoc);
417       } else if (orderElement.startsWith(GLOBALLOC + "=")) {
418         String globalLoc = orderElement.substring(10);
419         locOrder.setGlobalLoc(globalLoc);
420       } else if (orderElement.startsWith(RETURNLOC + "=")) {
421         String returnLoc = orderElement.substring(10);
422         locOrder.setReturnLoc(returnLoc);
423       } else if (orderElement.endsWith("*")) {
424         // spin loc definition
425         locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
426       } else {
427         // single element
428         locOrder.put(orderElement);
429       }
430     }
431
432     // sanity checks
433     if (locOrder.getThisLoc() != null && !locOrder.containsKey(locOrder.getThisLoc())) {
434       throw new Error("Variable 'this' location '" + locOrder.getThisLoc()
435           + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
436     }
437
438     if (locOrder.getGlobalLoc() != null && !locOrder.containsKey(locOrder.getGlobalLoc())) {
439       throw new Error("Variable global location '" + locOrder.getGlobalLoc()
440           + "' is not defined in the local variable lattice at " + cd.getSourceFileName());
441     }
442   }
443
444   private void parseClassLatticeDefinition(ClassDescriptor cd, String value,
445       SSJavaLattice<String> locOrder) {
446
447     value = value.replaceAll(" ", ""); // remove all blank spaces
448
449     StringTokenizer tokenizer = new StringTokenizer(value, ",");
450
451     while (tokenizer.hasMoreTokens()) {
452       String orderElement = tokenizer.nextToken();
453       int idx = orderElement.indexOf("<");
454
455       if (idx > 0) {// relative order element
456         String lowerLoc = orderElement.substring(0, idx);
457         String higherLoc = orderElement.substring(idx + 1);
458         locOrder.put(higherLoc, lowerLoc);
459         if (locOrder.isIntroducingCycle(higherLoc)) {
460           throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
461               + " introduces a cycle.");
462         }
463       } else if (orderElement.contains("*")) {
464         // spin loc definition
465         locOrder.addSharedLoc(orderElement.substring(0, orderElement.length() - 1));
466       } else {
467         // single element
468         locOrder.put(orderElement);
469       }
470     }
471
472     // sanity check
473     Set<String> spinLocSet = locOrder.getSharedLocSet();
474     for (Iterator iterator = spinLocSet.iterator(); iterator.hasNext();) {
475       String spinLoc = (String) iterator.next();
476       if (!locOrder.containsKey(spinLoc)) {
477         throw new Error("Spin location '" + spinLoc
478             + "' is not defined in the default local variable lattice at " + cd.getSourceFileName());
479       }
480     }
481   }
482
483   public Hashtable<ClassDescriptor, SSJavaLattice<String>> getCd2lattice() {
484     return cd2lattice;
485   }
486
487   public Hashtable<ClassDescriptor, MethodLattice<String>> getCd2methodDefault() {
488     return cd2methodDefault;
489   }
490
491   public Hashtable<MethodDescriptor, MethodLattice<String>> getMd2lattice() {
492     return md2lattice;
493   }
494
495   public SSJavaLattice<String> getClassLattice(ClassDescriptor cd) {
496     return cd2lattice.get(cd);
497   }
498
499   public MethodLattice<String> getMethodDefaultLattice(ClassDescriptor cd) {
500     return cd2methodDefault.get(cd);
501   }
502
503   public MethodLattice<String> getMethodLattice(MethodDescriptor md) {
504     if (md2lattice.containsKey(md)) {
505       return md2lattice.get(md);
506     } else {
507
508       if (cd2methodDefault.containsKey(md.getClassDesc())) {
509         return cd2methodDefault.get(md.getClassDesc());
510       } else {
511         throw new Error("Method Lattice of " + md + " is not defined.");
512       }
513
514     }
515   }
516
517   public CompositeLocation getPCLocation(MethodDescriptor md) {
518     if (!md2pcLoc.containsKey(md)) {
519       // by default, the initial pc location is TOP
520       CompositeLocation pcLoc = new CompositeLocation(new Location(md, Location.TOP));
521       md2pcLoc.put(md, pcLoc);
522     }
523     return md2pcLoc.get(md);
524   }
525
526   public void setPCLocation(MethodDescriptor md, CompositeLocation pcLoc) {
527     md2pcLoc.put(md, pcLoc);
528   }
529
530   public boolean needToCheckLinearType(MethodDescriptor md) {
531     return linearTypeCheckMethodSet.contains(md);
532   }
533
534   public boolean needTobeAnnotated(MethodDescriptor md) {
535     return annotationRequireSet.contains(md);
536   }
537
538   public boolean needToBeAnnoated(ClassDescriptor cd) {
539     return annotationRequireClassSet.contains(cd);
540   }
541
542   public void addAnnotationRequire(ClassDescriptor cd) {
543     annotationRequireClassSet.add(cd);
544   }
545
546   public void addAnnotationRequire(MethodDescriptor md) {
547
548     ClassDescriptor cd = md.getClassDesc();
549     // if a method requires to be annotated, class containg that method also
550     // requires to be annotated
551     if (!isSSJavaUtil(cd)) {
552       annotationRequireClassSet.add(cd);
553       annotationRequireSet.add(md);
554     }
555   }
556
557   public Set<MethodDescriptor> getAnnotationRequireSet() {
558     return annotationRequireSet;
559   }
560
561   public void doLoopTerminationCheck(LoopOptimize lo, FlatMethod fm) {
562     LoopTerminate lt = new LoopTerminate(this, state);
563     if (needTobeAnnotated(fm.getMethod())) {
564       lt.terminateAnalysis(fm, lo.getLoopInvariant(fm));
565     }
566   }
567
568   public CallGraph getCallGraph() {
569     return callgraph;
570   }
571
572   public SSJavaLattice<String> getLattice(Descriptor d) {
573
574     if (d instanceof MethodDescriptor) {
575       return getMethodLattice((MethodDescriptor) d);
576     } else {
577       return getClassLattice((ClassDescriptor) d);
578     }
579
580   }
581
582   public boolean isSharedLocation(Location loc) {
583     SSJavaLattice<String> lattice = getLattice(loc.getDescriptor());
584     return lattice.getSharedLocSet().contains(loc.getLocIdentifier());
585   }
586
587   public void mapSharedLocation2Descriptor(Location loc, Descriptor d) {
588     Set<Descriptor> set = mapSharedLocation2DescriptorSet.get(loc);
589     if (set == null) {
590       set = new HashSet<Descriptor>();
591       mapSharedLocation2DescriptorSet.put(loc, set);
592     }
593     set.add(d);
594   }
595
596   public BuildFlat getBuildFlat() {
597     return bf;
598   }
599
600   public MethodDescriptor getMethodContainingSSJavaLoop() {
601     return methodContainingSSJavaLoop;
602   }
603
604   public void setMethodContainingSSJavaLoop(MethodDescriptor methodContainingSSJavaLoop) {
605     this.methodContainingSSJavaLoop = methodContainingSSJavaLoop;
606   }
607
608   public boolean isSSJavaUtil(ClassDescriptor cd) {
609     if (cd.getSymbol().equals("SSJAVA")) {
610       return true;
611     }
612     return false;
613   }
614
615   public void setFieldOnwership(MethodDescriptor md, FieldDescriptor field) {
616
617     Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
618     if (fieldSet == null) {
619       fieldSet = new HashSet<FieldDescriptor>();
620       mapMethodToOwnedFieldSet.put(md, fieldSet);
621     }
622     fieldSet.add(field);
623   }
624
625   public boolean isOwnedByMethod(MethodDescriptor md, FieldDescriptor field) {
626     Set<FieldDescriptor> fieldSet = mapMethodToOwnedFieldSet.get(md);
627     if (fieldSet != null) {
628       return fieldSet.contains(field);
629     }
630     return false;
631   }
632
633   public FlatNode getSSJavaLoopEntrance() {
634     return ssjavaLoopEntrance;
635   }
636
637   public void setSSJavaLoopEntrance(FlatNode ssjavaLoopEntrance) {
638     this.ssjavaLoopEntrance = ssjavaLoopEntrance;
639   }
640
641   public void addSameHeightWriteFlatNode(FlatNode fn) {
642     this.sameHeightWriteFlatNodeSet.add(fn);
643   }
644
645   public boolean isSameHeightWrite(FlatNode fn) {
646     return this.sameHeightWriteFlatNodeSet.contains(fn);
647   }
648
649   public LinkedList<MethodDescriptor> topologicalSort(Set<MethodDescriptor> toSort) {
650
651     Set<MethodDescriptor> discovered = new HashSet<MethodDescriptor>();
652
653     LinkedList<MethodDescriptor> sorted = new LinkedList<MethodDescriptor>();
654
655     Iterator<MethodDescriptor> itr = toSort.iterator();
656     while (itr.hasNext()) {
657       MethodDescriptor d = itr.next();
658
659       if (!discovered.contains(d)) {
660         dfsVisit(d, toSort, sorted, discovered);
661       }
662     }
663
664     return sorted;
665   }
666
667   // While we're doing DFS on call graph, remember
668   // dependencies for efficient queuing of methods
669   // during interprocedural analysis:
670   //
671   // a dependent of a method decriptor d for this analysis is:
672   // 1) a method or task that invokes d
673   // 2) in the descriptorsToAnalyze set
674   private void dfsVisit(MethodDescriptor md, Set<MethodDescriptor> toSort,
675       LinkedList<MethodDescriptor> sorted, Set<MethodDescriptor> discovered) {
676
677     discovered.add(md);
678
679     Iterator itr2 = callgraph.getCalleeSet(md).iterator();
680     while (itr2.hasNext()) {
681       MethodDescriptor dCallee = (MethodDescriptor) itr2.next();
682       addDependent(dCallee, md);
683     }
684
685     Iterator itr = callgraph.getCallerSet(md).iterator();
686     while (itr.hasNext()) {
687       MethodDescriptor dCaller = (MethodDescriptor) itr.next();
688       // only consider callers in the original set to analyze
689       if (!toSort.contains(dCaller)) {
690         continue;
691       }
692       if (!discovered.contains(dCaller)) {
693         addDependent(md, // callee
694             dCaller // caller
695         );
696
697         dfsVisit(dCaller, toSort, sorted, discovered);
698       }
699     }
700
701     // for leaf-nodes last now!
702     sorted.addLast(md);
703   }
704
705   public void addDependent(MethodDescriptor callee, MethodDescriptor caller) {
706     Set<MethodDescriptor> deps = mapDescriptorToSetDependents.get(callee);
707     if (deps == null) {
708       deps = new HashSet<MethodDescriptor>();
709     }
710     deps.add(caller);
711     mapDescriptorToSetDependents.put(callee, deps);
712   }
713
714   public Set<MethodDescriptor> getDependents(MethodDescriptor callee) {
715     Set<MethodDescriptor> deps = mapDescriptorToSetDependents.get(callee);
716     if (deps == null) {
717       deps = new HashSet<MethodDescriptor>();
718       mapDescriptorToSetDependents.put(callee, deps);
719     }
720     return deps;
721   }
722
723 }