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