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