generate annotated source code again but it's still not the correct one...
[IRC.git] / Robust / src / Analysis / SSJava / LocationInference.java
1 package Analysis.SSJava;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.FileReader;
6 import java.io.FileWriter;
7 import java.io.IOException;
8 import java.util.ArrayList;
9 import java.util.Collections;
10 import java.util.Comparator;
11 import java.util.HashMap;
12 import java.util.HashSet;
13 import java.util.Iterator;
14 import java.util.LinkedList;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Set;
18 import java.util.Stack;
19 import java.util.Vector;
20
21 import IR.ClassDescriptor;
22 import IR.Descriptor;
23 import IR.FieldDescriptor;
24 import IR.MethodDescriptor;
25 import IR.NameDescriptor;
26 import IR.Operation;
27 import IR.State;
28 import IR.SymbolTable;
29 import IR.TypeDescriptor;
30 import IR.VarDescriptor;
31 import IR.Tree.ArrayAccessNode;
32 import IR.Tree.AssignmentNode;
33 import IR.Tree.BlockExpressionNode;
34 import IR.Tree.BlockNode;
35 import IR.Tree.BlockStatementNode;
36 import IR.Tree.CastNode;
37 import IR.Tree.CreateObjectNode;
38 import IR.Tree.DeclarationNode;
39 import IR.Tree.ExpressionNode;
40 import IR.Tree.FieldAccessNode;
41 import IR.Tree.IfStatementNode;
42 import IR.Tree.Kind;
43 import IR.Tree.LiteralNode;
44 import IR.Tree.LoopNode;
45 import IR.Tree.MethodInvokeNode;
46 import IR.Tree.NameNode;
47 import IR.Tree.OpNode;
48 import IR.Tree.ReturnNode;
49 import IR.Tree.SubBlockNode;
50 import IR.Tree.SwitchStatementNode;
51 import IR.Tree.TertiaryNode;
52 import IR.Tree.TreeNode;
53 import Util.Pair;
54
55 public class LocationInference {
56
57   State state;
58   SSJavaAnalysis ssjava;
59
60   List<ClassDescriptor> toanalyzeList;
61   List<MethodDescriptor> toanalyzeMethodList;
62   Map<MethodDescriptor, FlowGraph> mapMethodDescriptorToFlowGraph;
63
64   // map a method descriptor to its set of parameter descriptors
65   Map<MethodDescriptor, Set<Descriptor>> mapMethodDescriptorToParamDescSet;
66
67   // keep current descriptors to visit in fixed-point interprocedural analysis,
68   private Stack<MethodDescriptor> methodDescriptorsToVisitStack;
69
70   // map a class descriptor to a field lattice
71   private Map<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
72
73   // map a method descriptor to a method lattice
74   private Map<MethodDescriptor, SSJavaLattice<String>> md2lattice;
75
76   // map a method descriptor to the set of method invocation nodes which are
77   // invoked by the method descriptor
78   private Map<MethodDescriptor, Set<MethodInvokeNode>> mapMethodDescriptorToMethodInvokeNodeSet;
79
80   private Map<MethodInvokeNode, Map<Integer, NodeTupleSet>> mapMethodInvokeNodeToArgIdxMap;
81
82   private Map<MethodDescriptor, MethodLocationInfo> mapMethodDescToMethodLocationInfo;
83
84   private Map<ClassDescriptor, LocationInfo> mapClassToLocationInfo;
85
86   private Map<MethodDescriptor, Set<MethodDescriptor>> mapMethodToCalleeSet;
87
88   private Map<MethodDescriptor, Set<FlowNode>> mapMethodDescToParamNodeFlowsToReturnValue;
89
90   private Map<String, Vector<String>> mapFileNameToLineVector;
91
92   private Map<Descriptor, Integer> mapDescToDefinitionLine;
93
94   public static final String GLOBALLOC = "GLOBALLOC";
95
96   public static final String TOPLOC = "TOPLOC";
97
98   public static final Descriptor GLOBALDESC = new NameDescriptor(GLOBALLOC);
99
100   public static final Descriptor TOPDESC = new NameDescriptor(TOPLOC);
101
102   public static String newline = System.getProperty("line.separator");
103
104   LocationInfo curMethodInfo;
105
106   boolean debug = true;
107
108   public LocationInference(SSJavaAnalysis ssjava, State state) {
109     this.ssjava = ssjava;
110     this.state = state;
111     this.toanalyzeList = new ArrayList<ClassDescriptor>();
112     this.toanalyzeMethodList = new ArrayList<MethodDescriptor>();
113     this.mapMethodDescriptorToFlowGraph = new HashMap<MethodDescriptor, FlowGraph>();
114     this.cd2lattice = new HashMap<ClassDescriptor, SSJavaLattice<String>>();
115     this.md2lattice = new HashMap<MethodDescriptor, SSJavaLattice<String>>();
116     this.methodDescriptorsToVisitStack = new Stack<MethodDescriptor>();
117     this.mapMethodDescriptorToMethodInvokeNodeSet =
118         new HashMap<MethodDescriptor, Set<MethodInvokeNode>>();
119     this.mapMethodInvokeNodeToArgIdxMap =
120         new HashMap<MethodInvokeNode, Map<Integer, NodeTupleSet>>();
121     this.mapMethodDescToMethodLocationInfo = new HashMap<MethodDescriptor, MethodLocationInfo>();
122     this.mapMethodToCalleeSet = new HashMap<MethodDescriptor, Set<MethodDescriptor>>();
123     this.mapClassToLocationInfo = new HashMap<ClassDescriptor, LocationInfo>();
124
125     this.mapFileNameToLineVector = new HashMap<String, Vector<String>>();
126     this.mapDescToDefinitionLine = new HashMap<Descriptor, Integer>();
127     this.mapMethodDescToParamNodeFlowsToReturnValue =
128         new HashMap<MethodDescriptor, Set<FlowNode>>();
129   }
130
131   public void setupToAnalyze() {
132     SymbolTable classtable = state.getClassSymbolTable();
133     toanalyzeList.clear();
134     toanalyzeList.addAll(classtable.getValueSet());
135     // Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
136     // public int compare(ClassDescriptor o1, ClassDescriptor o2) {
137     // return o1.getClassName().compareToIgnoreCase(o2.getClassName());
138     // }
139     // });
140   }
141
142   public void setupToAnalazeMethod(ClassDescriptor cd) {
143
144     SymbolTable methodtable = cd.getMethodTable();
145     toanalyzeMethodList.clear();
146     toanalyzeMethodList.addAll(methodtable.getValueSet());
147     Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
148       public int compare(MethodDescriptor o1, MethodDescriptor o2) {
149         return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
150       }
151     });
152   }
153
154   public boolean toAnalyzeMethodIsEmpty() {
155     return toanalyzeMethodList.isEmpty();
156   }
157
158   public boolean toAnalyzeIsEmpty() {
159     return toanalyzeList.isEmpty();
160   }
161
162   public ClassDescriptor toAnalyzeNext() {
163     return toanalyzeList.remove(0);
164   }
165
166   public MethodDescriptor toAnalyzeMethodNext() {
167     return toanalyzeMethodList.remove(0);
168   }
169
170   public void inference() {
171
172     // 1) construct value flow graph
173     constructFlowGraph();
174
175     // 2) construct lattices
176     inferLattices();
177
178     simplifyLattices();
179
180     debug_writeLatticeDotFile();
181
182     // 3) check properties
183     checkLattices();
184
185     // 4) generate annotated source codes
186     generateAnnoatedCode();
187
188   }
189
190   private void addMapClassDefinitionToLineNum(ClassDescriptor cd, String strLine, int lineNum) {
191
192     String classSymbol = cd.getSymbol();
193     int idx = classSymbol.lastIndexOf("$");
194     if (idx != -1) {
195       classSymbol = classSymbol.substring(idx + 1);
196     }
197
198     String pattern = "class " + classSymbol + " ";
199     if (strLine.indexOf(pattern) != -1) {
200       mapDescToDefinitionLine.put(cd, lineNum);
201     }
202   }
203
204   private void addMapMethodDefinitionToLineNum(Set<MethodDescriptor> methodSet, String strLine,
205       int lineNum) {
206     for (Iterator iterator = methodSet.iterator(); iterator.hasNext();) {
207       MethodDescriptor md = (MethodDescriptor) iterator.next();
208       String pattern = md.getMethodDeclaration();
209       if (strLine.indexOf(pattern) != -1) {
210         mapDescToDefinitionLine.put(md, lineNum);
211         methodSet.remove(md);
212         return;
213       }
214     }
215
216   }
217
218   private void readOriginalSourceFiles() {
219
220     SymbolTable classtable = state.getClassSymbolTable();
221
222     Set<ClassDescriptor> classDescSet = new HashSet<ClassDescriptor>();
223     classDescSet.addAll(classtable.getValueSet());
224
225     try {
226       // inefficient implement. it may re-visit the same file if the file
227       // contains more than one class definitions.
228       for (Iterator iterator = classDescSet.iterator(); iterator.hasNext();) {
229         ClassDescriptor cd = (ClassDescriptor) iterator.next();
230
231         Set<MethodDescriptor> methodSet = new HashSet<MethodDescriptor>();
232         methodSet.addAll(cd.getMethodTable().getValueSet());
233
234         String sourceFileName = cd.getSourceFileName();
235         Vector<String> lineVec = new Vector<String>();
236
237         mapFileNameToLineVector.put(sourceFileName, lineVec);
238
239         BufferedReader in = new BufferedReader(new FileReader(sourceFileName));
240         String strLine;
241         int lineNum = 1;
242         lineVec.add(""); // the index is started from 1.
243         while ((strLine = in.readLine()) != null) {
244           lineVec.add(lineNum, strLine);
245           addMapClassDefinitionToLineNum(cd, strLine, lineNum);
246           addMapMethodDefinitionToLineNum(methodSet, strLine, lineNum);
247           lineNum++;
248         }
249
250       }
251
252     } catch (IOException e) {
253       e.printStackTrace();
254     }
255
256   }
257
258   private String generateLatticeDefinition(Descriptor desc) {
259
260     Set<String> sharedLocSet = new HashSet<String>();
261
262     SSJavaLattice<String> lattice = getLattice(desc);
263     String rtr = "@LATTICE(\"";
264
265     Map<String, Set<String>> map = lattice.getTable();
266     Set<String> keySet = map.keySet();
267     boolean first = true;
268     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
269       String key = (String) iterator.next();
270       if (!key.equals(lattice.getTopItem())) {
271         Set<String> connectedSet = map.get(key);
272
273         if (connectedSet.size() == 1) {
274           if (connectedSet.iterator().next().equals(lattice.getBottomItem())) {
275             if (!first) {
276               rtr += ",";
277             } else {
278               rtr += "LOC,";
279               first = false;
280             }
281             rtr += key;
282             if (lattice.isSharedLoc(key)) {
283               rtr += "," + key + "*";
284             }
285           }
286         }
287
288         for (Iterator iterator2 = connectedSet.iterator(); iterator2.hasNext();) {
289           String loc = (String) iterator2.next();
290           if (!loc.equals(lattice.getBottomItem())) {
291             if (!first) {
292               rtr += ",";
293             } else {
294               rtr += "LOC,";
295               first = false;
296             }
297             rtr += loc + "<" + key;
298             if (lattice.isSharedLoc(key) && (!sharedLocSet.contains(key))) {
299               rtr += "," + key + "*";
300               sharedLocSet.add(key);
301             }
302             if (lattice.isSharedLoc(loc) && (!sharedLocSet.contains(loc))) {
303               rtr += "," + loc + "*";
304               sharedLocSet.add(loc);
305             }
306
307           }
308         }
309       }
310     }
311
312     rtr += "\")";
313
314     if (desc instanceof MethodDescriptor) {
315       TypeDescriptor returnType = ((MethodDescriptor) desc).getReturnType();
316
317       MethodLocationInfo methodLocInfo = getMethodLocationInfo((MethodDescriptor) desc);
318
319       if (returnType != null && (!returnType.isVoid())) {
320         rtr +=
321             "\n@RETURNLOC(\"" + generateLocationAnnoatation(methodLocInfo.getReturnLoc()) + "\")";
322       }
323       rtr += "\n@THISLOC(\"this\")\n@GLOBALLOC(\"GLOBALLOC\")";
324
325       if (lattice.containsKey("PCLOC")) {
326         rtr += "\n@PCLOC(\"PCLOC\")";
327       }
328     }
329
330     return rtr;
331   }
332
333   private void generateAnnoatedCode() {
334
335     readOriginalSourceFiles();
336
337     setupToAnalyze();
338     while (!toAnalyzeIsEmpty()) {
339       ClassDescriptor cd = toAnalyzeNext();
340
341       setupToAnalazeMethod(cd);
342
343       LocationInfo locInfo = mapClassToLocationInfo.get(cd);
344       String sourceFileName = cd.getSourceFileName();
345
346       if (cd.isInterface()) {
347         continue;
348       }
349
350       int classDefLine = mapDescToDefinitionLine.get(cd);
351       Vector<String> sourceVec = mapFileNameToLineVector.get(sourceFileName);
352       
353
354       if (locInfo == null) {
355         locInfo = getLocationInfo(cd);
356       }
357
358       for (Iterator iter = cd.getFields(); iter.hasNext();) {
359         Descriptor fieldDesc = (Descriptor) iter.next();
360         String locIdentifier = locInfo.getFieldInferLocation(fieldDesc).getLocIdentifier();
361         if (!getLattice(cd).containsKey(locIdentifier)) {
362           getLattice(cd).put(locIdentifier);
363         }
364       }
365
366       String fieldLatticeDefStr = generateLatticeDefinition(cd);
367       String annoatedSrc = fieldLatticeDefStr + newline + sourceVec.get(classDefLine);
368       sourceVec.set(classDefLine, annoatedSrc);
369
370       // generate annotations for field declarations
371       LocationInfo fieldLocInfo = getLocationInfo(cd);
372       Map<Descriptor, CompositeLocation> inferLocMap = fieldLocInfo.getMapDescToInferLocation();
373
374       for (Iterator iter = cd.getFields(); iter.hasNext();) {
375         FieldDescriptor fd = (FieldDescriptor) iter.next();
376
377         String locAnnotationStr;
378         if (inferLocMap.containsKey(fd)) {
379           CompositeLocation inferLoc = inferLocMap.get(fd);
380           locAnnotationStr = "@LOC(\"" + generateLocationAnnoatation(inferLoc) + "\")";
381         } else {
382           // if the field is not accssed by SS part, just assigns dummy
383           // location
384           locAnnotationStr = "@LOC(\"LOC\")";
385         }
386         int fdLineNum = fd.getLineNum();
387         String orgFieldDeclarationStr = sourceVec.get(fdLineNum);
388         String fieldDeclaration = fd.toString();
389         fieldDeclaration = fieldDeclaration.substring(0, fieldDeclaration.length() - 1);
390
391         String annoatedStr = locAnnotationStr + " " + orgFieldDeclarationStr;
392         sourceVec.set(fdLineNum, annoatedStr);
393
394       }
395
396       while (!toAnalyzeMethodIsEmpty()) {
397         MethodDescriptor md = toAnalyzeMethodNext();
398
399         if (!ssjava.needTobeAnnotated(md)) {
400           continue;
401         }
402
403         SSJavaLattice<String> methodLattice = md2lattice.get(md);
404         if (methodLattice != null) {
405
406           int methodDefLine = md.getLineNum();
407
408           MethodLocationInfo methodLocInfo = getMethodLocationInfo(md);
409
410           Map<Descriptor, CompositeLocation> methodInferLocMap =
411               methodLocInfo.getMapDescToInferLocation();
412           Set<Descriptor> localVarDescSet = methodInferLocMap.keySet();
413
414           for (Iterator iterator = localVarDescSet.iterator(); iterator.hasNext();) {
415             Descriptor localVarDesc = (Descriptor) iterator.next();
416             CompositeLocation inferLoc = methodInferLocMap.get(localVarDesc);
417
418             String locAnnotationStr = "@LOC(\"" + generateLocationAnnoatation(inferLoc) + "\")";
419
420             if (!isParameter(md, localVarDesc)) {
421               if (mapDescToDefinitionLine.containsKey(localVarDesc)) {
422                 int varLineNum = mapDescToDefinitionLine.get(localVarDesc);
423                 String orgSourceLine = sourceVec.get(varLineNum);
424                 int idx =
425                     orgSourceLine.indexOf(generateVarDeclaration((VarDescriptor) localVarDesc));
426                 assert (idx != -1);
427                 String annoatedStr =
428                     orgSourceLine.substring(0, idx) + locAnnotationStr + " "
429                         + orgSourceLine.substring(idx);
430                 sourceVec.set(varLineNum, annoatedStr);
431               }
432             } else {
433               String methodDefStr = sourceVec.get(methodDefLine);
434
435               int idx =
436                   getParamLocation(methodDefStr,
437                       generateVarDeclaration((VarDescriptor) localVarDesc));
438
439               assert (idx != -1);
440
441               String annoatedStr =
442                   methodDefStr.substring(0, idx) + locAnnotationStr + " "
443                       + methodDefStr.substring(idx);
444               sourceVec.set(methodDefLine, annoatedStr);
445             }
446
447           }
448
449           String methodLatticeDefStr = generateLatticeDefinition(md);
450           String annoatedStr = methodLatticeDefStr + newline + sourceVec.get(methodDefLine);
451           sourceVec.set(methodDefLine, annoatedStr);
452
453         }
454       }
455
456     }
457
458     codeGen();
459   }
460
461   private int getParamLocation(String methodStr, String paramStr) {
462
463     String pattern = paramStr + ",";
464
465     int idx = methodStr.indexOf(pattern);
466     if (idx != -1) {
467       return idx;
468     } else {
469       pattern = paramStr + ")";
470       return methodStr.indexOf(pattern);
471     }
472
473   }
474
475   private String generateVarDeclaration(VarDescriptor varDesc) {
476
477     TypeDescriptor td = varDesc.getType();
478     String rtr = td.toString();
479     if (td.isArray()) {
480       for (int i = 0; i < td.getArrayCount(); i++) {
481         rtr += "[]";
482       }
483     }
484     rtr += " " + varDesc.getName();
485     return rtr;
486
487   }
488
489   private String generateLocationAnnoatation(CompositeLocation loc) {
490     String rtr = "";
491     // method location
492     Location methodLoc = loc.get(0);
493     rtr += methodLoc.getLocIdentifier();
494
495     for (int i = 1; i < loc.getSize(); i++) {
496       Location element = loc.get(i);
497       rtr += "," + element.getDescriptor().getSymbol() + "." + element.getLocIdentifier();
498     }
499
500     return rtr;
501   }
502
503   private boolean isParameter(MethodDescriptor md, Descriptor localVarDesc) {
504     return getFlowGraph(md).isParamDesc(localVarDesc);
505   }
506
507   private String extractFileName(String fileName) {
508     int idx = fileName.lastIndexOf("/");
509     if (idx == -1) {
510       return fileName;
511     } else {
512       return fileName.substring(idx + 1);
513     }
514
515   }
516
517   private void codeGen() {
518
519     Set<String> originalFileNameSet = mapFileNameToLineVector.keySet();
520     for (Iterator iterator = originalFileNameSet.iterator(); iterator.hasNext();) {
521       String orgFileName = (String) iterator.next();
522       String outputFileName = extractFileName(orgFileName);
523
524       Vector<String> sourceVec = mapFileNameToLineVector.get(orgFileName);
525
526       try {
527
528         FileWriter fileWriter = new FileWriter("./infer/" + outputFileName);
529         BufferedWriter out = new BufferedWriter(fileWriter);
530
531         for (int i = 0; i < sourceVec.size(); i++) {
532           out.write(sourceVec.get(i));
533           out.newLine();
534         }
535         out.close();
536       } catch (IOException e) {
537         e.printStackTrace();
538       }
539
540     }
541
542   }
543
544   private void simplifyLattices() {
545
546     // generate lattice dot file
547     setupToAnalyze();
548
549     while (!toAnalyzeIsEmpty()) {
550       ClassDescriptor cd = toAnalyzeNext();
551
552       setupToAnalazeMethod(cd);
553
554       SSJavaLattice<String> classLattice = cd2lattice.get(cd);
555       if (classLattice != null) {
556         classLattice.removeRedundantEdges();
557       }
558
559       while (!toAnalyzeMethodIsEmpty()) {
560         MethodDescriptor md = toAnalyzeMethodNext();
561         SSJavaLattice<String> methodLattice = md2lattice.get(md);
562         if (methodLattice != null) {
563           methodLattice.removeRedundantEdges();
564         }
565       }
566     }
567
568   }
569
570   private void checkLattices() {
571
572     LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
573
574     // current descriptors to visit in fixed-point interprocedural analysis,
575     // prioritized by
576     // dependency in the call graph
577     methodDescriptorsToVisitStack.clear();
578
579     // descriptorListToAnalyze.removeFirst();
580
581     Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
582     methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
583
584     while (!descriptorListToAnalyze.isEmpty()) {
585       MethodDescriptor md = descriptorListToAnalyze.removeFirst();
586       checkLatticesOfVirtualMethods(md);
587     }
588
589   }
590
591   private void debug_writeLatticeDotFile() {
592     // generate lattice dot file
593
594     setupToAnalyze();
595
596     while (!toAnalyzeIsEmpty()) {
597       ClassDescriptor cd = toAnalyzeNext();
598
599       setupToAnalazeMethod(cd);
600
601       SSJavaLattice<String> classLattice = cd2lattice.get(cd);
602       if (classLattice != null) {
603         ssjava.writeLatticeDotFile(cd, null, classLattice);
604         debug_printDescriptorToLocNameMapping(cd);
605       }
606
607       while (!toAnalyzeMethodIsEmpty()) {
608         MethodDescriptor md = toAnalyzeMethodNext();
609         SSJavaLattice<String> methodLattice = md2lattice.get(md);
610         if (methodLattice != null) {
611           ssjava.writeLatticeDotFile(cd, md, methodLattice);
612           debug_printDescriptorToLocNameMapping(md);
613         }
614       }
615     }
616
617   }
618
619   private void debug_printDescriptorToLocNameMapping(Descriptor desc) {
620
621     LocationInfo info = getLocationInfo(desc);
622     System.out.println("## " + desc + " ##");
623     System.out.println(info.getMapDescToInferLocation());
624     LocationInfo locInfo = getLocationInfo(desc);
625     System.out.println("mapping=" + locInfo.getMapLocSymbolToDescSet());
626     System.out.println("###################");
627
628   }
629
630   private void inferLattices() {
631
632     // do fixed-point analysis
633
634     ssjava.init();
635     LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
636
637     Collections.sort(descriptorListToAnalyze, new Comparator<MethodDescriptor>() {
638       public int compare(MethodDescriptor o1, MethodDescriptor o2) {
639         return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
640       }
641     });
642
643     // current descriptors to visit in fixed-point interprocedural analysis,
644     // prioritized by
645     // dependency in the call graph
646     methodDescriptorsToVisitStack.clear();
647
648     // descriptorListToAnalyze.removeFirst();
649
650     Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
651     methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
652
653     while (!descriptorListToAnalyze.isEmpty()) {
654       MethodDescriptor md = descriptorListToAnalyze.removeFirst();
655       methodDescriptorsToVisitStack.add(md);
656     }
657
658     // analyze scheduled methods until there are no more to visit
659     while (!methodDescriptorsToVisitStack.isEmpty()) {
660       // start to analyze leaf node
661       MethodDescriptor md = methodDescriptorsToVisitStack.pop();
662
663       SSJavaLattice<String> methodLattice =
664           new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM);
665
666       MethodLocationInfo methodInfo = new MethodLocationInfo(md);
667       curMethodInfo = methodInfo;
668
669       System.out.println();
670       System.out.println("SSJAVA: Inferencing the lattice from " + md);
671
672       try {
673         analyzeMethodLattice(md, methodLattice, methodInfo);
674       } catch (CyclicFlowException e) {
675         throw new Error("Fail to generate the method lattice for " + md);
676       }
677
678       SSJavaLattice<String> prevMethodLattice = getMethodLattice(md);
679       MethodLocationInfo prevMethodInfo = getMethodLocationInfo(md);
680
681       if ((!methodLattice.equals(prevMethodLattice)) || (!methodInfo.equals(prevMethodInfo))) {
682
683         setMethodLattice(md, methodLattice);
684         setMethodLocInfo(md, methodInfo);
685
686         // results for callee changed, so enqueue dependents caller for
687         // further analysis
688         Iterator<MethodDescriptor> depsItr = ssjava.getDependents(md).iterator();
689         while (depsItr.hasNext()) {
690           MethodDescriptor methodNext = depsItr.next();
691           if (!methodDescriptorsToVisitStack.contains(methodNext)
692               && methodDescriptorToVistSet.contains(methodNext)) {
693             methodDescriptorsToVisitStack.add(methodNext);
694           }
695         }
696
697       }
698
699     }
700
701     descriptorListToAnalyze = ssjava.getSortedDescriptors();
702     for (Iterator iterator = descriptorListToAnalyze.iterator(); iterator.hasNext();) {
703       MethodDescriptor md = (MethodDescriptor) iterator.next();
704       calculateExtraLocations(md);
705     }
706
707   }
708
709   private void setMethodLocInfo(MethodDescriptor md, MethodLocationInfo methodInfo) {
710     mapMethodDescToMethodLocationInfo.put(md, methodInfo);
711   }
712
713   private void checkLatticesOfVirtualMethods(MethodDescriptor md) {
714
715     if (!md.isStatic()) {
716       Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
717       setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
718
719       for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
720         MethodDescriptor mdCallee = (MethodDescriptor) iterator.next();
721         if (!md.equals(mdCallee)) {
722           checkConsistency(md, mdCallee);
723         }
724       }
725
726     }
727
728   }
729
730   private void checkConsistency(MethodDescriptor md1, MethodDescriptor md2) {
731
732     // check that two lattice have the same relations between parameters(+PC
733     // LOC, GLOBAL_LOC RETURN LOC)
734
735     List<CompositeLocation> list1 = new ArrayList<CompositeLocation>();
736     List<CompositeLocation> list2 = new ArrayList<CompositeLocation>();
737
738     MethodLocationInfo locInfo1 = getMethodLocationInfo(md1);
739     MethodLocationInfo locInfo2 = getMethodLocationInfo(md2);
740
741     Map<Integer, CompositeLocation> paramMap1 = locInfo1.getMapParamIdxToInferLoc();
742     Map<Integer, CompositeLocation> paramMap2 = locInfo2.getMapParamIdxToInferLoc();
743
744     int numParam = locInfo1.getMapParamIdxToInferLoc().keySet().size();
745
746     // add location types of paramters
747     for (int idx = 0; idx < numParam; idx++) {
748       list1.add(paramMap1.get(Integer.valueOf(idx)));
749       list2.add(paramMap2.get(Integer.valueOf(idx)));
750     }
751
752     // add program counter location
753     list1.add(locInfo1.getPCLoc());
754     list2.add(locInfo2.getPCLoc());
755
756     if (!md1.getReturnType().isVoid()) {
757       // add return value location
758       CompositeLocation rtrLoc1 = getMethodLocationInfo(md1).getReturnLoc();
759       CompositeLocation rtrLoc2 = getMethodLocationInfo(md2).getReturnLoc();
760       list1.add(rtrLoc1);
761       list2.add(rtrLoc2);
762     }
763
764     // add global location type
765     if (md1.isStatic()) {
766       CompositeLocation globalLoc1 =
767           new CompositeLocation(new Location(md1, locInfo1.getGlobalLocName()));
768       CompositeLocation globalLoc2 =
769           new CompositeLocation(new Location(md2, locInfo2.getGlobalLocName()));
770       list1.add(globalLoc1);
771       list2.add(globalLoc2);
772     }
773
774     for (int i = 0; i < list1.size(); i++) {
775       CompositeLocation locA1 = list1.get(i);
776       CompositeLocation locA2 = list2.get(i);
777       for (int k = 0; k < list1.size(); k++) {
778         if (i != k) {
779           CompositeLocation locB1 = list1.get(k);
780           CompositeLocation locB2 = list2.get(k);
781           boolean r1 = isGreaterThan(getLattice(md1), locA1, locB1);
782
783           boolean r2 = isGreaterThan(getLattice(md1), locA2, locB2);
784
785           if (r1 != r2) {
786             throw new Error("The method " + md1 + " is not consistent with the method " + md2
787                 + ".:: They have a different ordering relation between locations (" + locA1 + ","
788                 + locB1 + ") and (" + locA2 + "," + locB2 + ").");
789           }
790         }
791       }
792     }
793
794   }
795
796   private String getSymbol(int idx, FlowNode node) {
797     Descriptor desc = node.getDescTuple().get(idx);
798     return desc.getSymbol();
799   }
800
801   private Descriptor getDescriptor(int idx, FlowNode node) {
802     Descriptor desc = node.getDescTuple().get(idx);
803     return desc;
804   }
805
806   private void analyzeMethodLattice(MethodDescriptor md, SSJavaLattice<String> methodLattice,
807       MethodLocationInfo methodInfo) throws CyclicFlowException {
808
809     // first take a look at method invocation nodes to newly added relations
810     // from the callee
811     analyzeLatticeMethodInvocationNode(md, methodLattice, methodInfo);
812
813     if (!md.isStatic()) {
814       // set the this location
815       String thisLocSymbol = md.getThis().getSymbol();
816       methodInfo.setThisLocName(thisLocSymbol);
817     }
818
819     // set the global location
820     methodInfo.setGlobalLocName(LocationInference.GLOBALLOC);
821     methodInfo.mapDescriptorToLocation(GLOBALDESC, new CompositeLocation(
822         new Location(md, GLOBALLOC)));
823
824     // visit each node of method flow graph
825     FlowGraph fg = getFlowGraph(md);
826     Set<FlowNode> nodeSet = fg.getNodeSet();
827
828     // for the method lattice, we need to look at the first element of
829     // NTuple<Descriptor>
830     for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
831       FlowNode srcNode = (FlowNode) iterator.next();
832
833       Set<FlowEdge> outEdgeSet = srcNode.getOutEdgeSet();
834       for (Iterator iterator2 = outEdgeSet.iterator(); iterator2.hasNext();) {
835         FlowEdge outEdge = (FlowEdge) iterator2.next();
836         FlowNode dstNode = outEdge.getDst();
837
838         NTuple<Descriptor> srcNodeTuple = srcNode.getDescTuple();
839         NTuple<Descriptor> dstNodeTuple = dstNode.getDescTuple();
840
841         if (outEdge.getInitTuple().equals(srcNodeTuple)
842             && outEdge.getEndTuple().equals(dstNodeTuple)) {
843
844           if ((srcNodeTuple.size() > 1 && dstNodeTuple.size() > 1)
845               && srcNodeTuple.get(0).equals(dstNodeTuple.get(0))) {
846
847             // value flows between fields
848             Descriptor desc = srcNodeTuple.get(0);
849             ClassDescriptor classDesc;
850
851             if (desc.equals(GLOBALDESC)) {
852               classDesc = md.getClassDesc();
853             } else {
854               VarDescriptor varDesc = (VarDescriptor) srcNodeTuple.get(0);
855               classDesc = varDesc.getType().getClassDesc();
856             }
857             extractRelationFromFieldFlows(classDesc, srcNode, dstNode, 1);
858
859           } else {
860             // value flow between local var - local var or local var - field
861             addRelationToLattice(md, methodLattice, methodInfo, srcNode, dstNode);
862           }
863         }
864       }
865     }
866
867   }
868
869   private void calculateExtraLocations(MethodDescriptor md) {
870     // calcualte pcloc, returnloc,...
871
872     System.out.println("#calculateExtraLocations=" + md);
873     SSJavaLattice<String> methodLattice = getMethodLattice(md);
874     MethodLocationInfo methodInfo = getMethodLocationInfo(md);
875     FlowGraph fg = getFlowGraph(md);
876     Set<FlowNode> nodeSet = fg.getNodeSet();
877
878     for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
879       FlowNode flowNode = (FlowNode) iterator.next();
880       if (flowNode.isDeclaratonNode()) {
881         CompositeLocation inferLoc = methodInfo.getInferLocation(flowNode.getDescTuple().get(0));
882         String locIdentifier = inferLoc.get(0).getLocIdentifier();
883         if (!methodLattice.containsKey(locIdentifier)) {
884           methodLattice.put(locIdentifier);
885         }
886
887       }
888     }
889
890     // create mapping from param idx to inferred composite location
891
892     int offset;
893     if (!md.isStatic()) {
894       // add 'this' reference location
895       offset = 1;
896       methodInfo.addMapParamIdxToInferLoc(0, methodInfo.getInferLocation(md.getThis()));
897     } else {
898       offset = 0;
899     }
900
901     for (int idx = 0; idx < md.numParameters(); idx++) {
902       Descriptor paramDesc = md.getParameter(idx);
903       CompositeLocation inferParamLoc = methodInfo.getInferLocation(paramDesc);
904       methodInfo.addMapParamIdxToInferLoc(idx + offset, inferParamLoc);
905     }
906
907     Map<Integer, CompositeLocation> mapParamToLoc = methodInfo.getMapParamIdxToInferLoc();
908     Set<Integer> keySet = mapParamToLoc.keySet();
909
910     try {
911       if (!ssjava.getMethodContainingSSJavaLoop().equals(md)) {
912         // calculate the initial program counter location
913         // PC location is higher than location types of all parameters
914         String pcLocSymbol = "PCLOC";
915         for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
916           Integer paramIdx = (Integer) iterator.next();
917           CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
918           String paramLocLocalSymbol = inferLoc.get(0).getLocIdentifier();
919           if (!methodLattice.isGreaterThan(pcLocSymbol, paramLocLocalSymbol)) {
920             addRelationHigherToLower(methodLattice, methodInfo, pcLocSymbol, paramLocLocalSymbol);
921
922             Set<String> higherLocSet = getHigherLocSymbolThan(methodLattice, paramLocLocalSymbol);
923             higherLocSet.remove(pcLocSymbol);
924             for (Iterator iterator2 = higherLocSet.iterator(); iterator2.hasNext();) {
925               String loc = (String) iterator2.next();
926               addRelationHigherToLower(methodLattice, methodInfo, pcLocSymbol, loc);
927             }
928           }
929         }
930       }
931
932       // calculate a return location
933       // the return location type is lower than all parameters and location
934       // types
935       // of return values
936       if (!md.getReturnType().isVoid()) {
937         System.out.println("@@@@@ RETURN md=" + md);
938         // first, generate the set of return value location types that starts
939         // with
940         // 'this' reference
941
942         Set<CompositeLocation> inferFieldReturnLocSet = new HashSet<CompositeLocation>();
943
944         Set<FlowNode> paramFlowNode = getParamNodeFlowingToReturnValue(md);
945         Set<CompositeLocation> inferParamLocSet = new HashSet<CompositeLocation>();
946         if (paramFlowNode != null) {
947           for (Iterator iterator = paramFlowNode.iterator(); iterator.hasNext();) {
948             FlowNode fn = (FlowNode) iterator.next();
949             CompositeLocation inferLoc =
950                 generateInferredCompositeLocation(methodInfo, getFlowGraph(md).getLocationTuple(fn));
951             inferParamLocSet.add(inferLoc);
952           }
953         }
954
955         Set<FlowNode> returnNodeSet = fg.getReturnNodeSet();
956         skip: for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
957           FlowNode returnNode = (FlowNode) iterator.next();
958           CompositeLocation inferReturnLoc =
959               generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
960           if (inferReturnLoc.get(0).getLocIdentifier().equals("this")) {
961             // if the location type of the return value matches "this" reference
962             // then, check whether this return value is equal to/lower than all
963             // of
964             // parameters that possibly flow into the return values
965             for (Iterator iterator2 = inferParamLocSet.iterator(); iterator2.hasNext();) {
966               CompositeLocation paramInferLoc = (CompositeLocation) iterator2.next();
967
968               if ((!paramInferLoc.equals(inferReturnLoc))
969                   && !isGreaterThan(methodLattice, paramInferLoc, inferReturnLoc)) {
970                 continue skip;
971               }
972             }
973             inferFieldReturnLocSet.add(inferReturnLoc);
974
975           }
976         }
977
978         if (inferFieldReturnLocSet.size() > 0) {
979
980           CompositeLocation returnLoc = getLowest(methodLattice, inferFieldReturnLocSet);
981           methodInfo.setReturnLoc(returnLoc);
982
983         } else {
984           String returnLocSymbol = "RETURNLOC";
985           CompositeLocation returnLocInferLoc =
986               new CompositeLocation(new Location(md, returnLocSymbol));
987           methodInfo.setReturnLoc(returnLocInferLoc);
988
989           for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
990             Integer paramIdx = (Integer) iterator.next();
991             CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
992             String paramLocLocalSymbol = inferLoc.get(0).getLocIdentifier();
993             if (!methodLattice.isGreaterThan(paramLocLocalSymbol, returnLocSymbol)) {
994               addRelationHigherToLower(methodLattice, methodInfo, paramLocLocalSymbol,
995                   returnLocSymbol);
996             }
997           }
998
999           for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
1000             FlowNode returnNode = (FlowNode) iterator.next();
1001             CompositeLocation inferLoc =
1002                 generateInferredCompositeLocation(methodInfo, fg.getLocationTuple(returnNode));
1003             if (!isGreaterThan(methodLattice, inferLoc, returnLocInferLoc)) {
1004               addRelation(methodLattice, methodInfo, inferLoc, returnLocInferLoc);
1005             }
1006           }
1007
1008         }
1009
1010       }
1011     } catch (CyclicFlowException e) {
1012       e.printStackTrace();
1013     }
1014
1015   }
1016
1017   private Set<String> getHigherLocSymbolThan(SSJavaLattice<String> lattice, String loc) {
1018     Set<String> higherLocSet = new HashSet<String>();
1019
1020     Set<String> locSet = lattice.getTable().keySet();
1021     for (Iterator iterator = locSet.iterator(); iterator.hasNext();) {
1022       String element = (String) iterator.next();
1023       if (lattice.isGreaterThan(element, loc) && (!element.equals(lattice.getTopItem()))) {
1024         higherLocSet.add(element);
1025       }
1026     }
1027     return higherLocSet;
1028   }
1029
1030   private CompositeLocation getLowest(SSJavaLattice<String> methodLattice,
1031       Set<CompositeLocation> set) {
1032
1033     CompositeLocation lowest = set.iterator().next();
1034
1035     if (set.size() == 1) {
1036       return lowest;
1037     }
1038
1039     for (Iterator iterator = set.iterator(); iterator.hasNext();) {
1040       CompositeLocation loc = (CompositeLocation) iterator.next();
1041       if (isGreaterThan(methodLattice, lowest, loc)) {
1042         lowest = loc;
1043       }
1044     }
1045     return lowest;
1046   }
1047
1048   private boolean isGreaterThan(SSJavaLattice<String> methodLattice, CompositeLocation comp1,
1049       CompositeLocation comp2) {
1050
1051     int size = comp1.getSize() >= comp2.getSize() ? comp2.getSize() : comp1.getSize();
1052
1053     for (int idx = 0; idx < size; idx++) {
1054       Location loc1 = comp1.get(idx);
1055       Location loc2 = comp2.get(idx);
1056
1057       Descriptor desc1 = loc1.getDescriptor();
1058       Descriptor desc2 = loc2.getDescriptor();
1059
1060       if (!desc1.equals(desc2)) {
1061         throw new Error("Fail to compare " + comp1 + " and " + comp2);
1062       }
1063
1064       String symbol1 = loc1.getLocIdentifier();
1065       String symbol2 = loc2.getLocIdentifier();
1066
1067       SSJavaLattice<String> lattice;
1068       if (idx == 0) {
1069         lattice = methodLattice;
1070       } else {
1071         lattice = getLattice(desc1);
1072       }
1073       if (symbol1.equals(symbol2)) {
1074         continue;
1075       } else if (lattice.isGreaterThan(symbol1, symbol2)) {
1076         return true;
1077       } else {
1078         return false;
1079       }
1080
1081     }
1082
1083     return false;
1084   }
1085
1086   private void recursiveAddRelationToLattice(int idx, MethodDescriptor md,
1087       CompositeLocation srcInferLoc, CompositeLocation dstInferLoc) throws CyclicFlowException {
1088
1089     String srcLocSymbol = srcInferLoc.get(idx).getLocIdentifier();
1090     String dstLocSymbol = dstInferLoc.get(idx).getLocIdentifier();
1091
1092     if (srcLocSymbol.equals(dstLocSymbol)) {
1093       recursiveAddRelationToLattice(idx + 1, md, srcInferLoc, dstInferLoc);
1094     } else {
1095
1096       Descriptor parentDesc = srcInferLoc.get(idx).getDescriptor();
1097       LocationInfo locInfo = getLocationInfo(parentDesc);
1098
1099       addRelationHigherToLower(getLattice(parentDesc), getLocationInfo(parentDesc), srcLocSymbol,
1100           dstLocSymbol);
1101     }
1102
1103   }
1104
1105   private void analyzeLatticeMethodInvocationNode(MethodDescriptor mdCaller,
1106       SSJavaLattice<String> methodLattice, MethodLocationInfo methodInfo)
1107       throws CyclicFlowException {
1108
1109     // the transformation for a call site propagates all relations between
1110     // parameters from the callee
1111     // if the method is virtual, it also grab all relations from any possible
1112     // callees
1113
1114     Set<MethodInvokeNode> setMethodInvokeNode =
1115         mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
1116
1117     if (setMethodInvokeNode != null) {
1118
1119       for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
1120         MethodInvokeNode min = (MethodInvokeNode) iterator.next();
1121         MethodDescriptor mdCallee = min.getMethod();
1122         Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
1123         if (mdCallee.isStatic()) {
1124           setPossibleCallees.add(mdCallee);
1125         } else {
1126           Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
1127           // removes method descriptors that are not invoked by the caller
1128           calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
1129           setPossibleCallees.addAll(calleeSet);
1130         }
1131
1132         for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
1133           MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
1134           propagateRelationToCaller(min, mdCaller, possibleMdCallee, methodLattice, methodInfo);
1135         }
1136
1137       }
1138     }
1139
1140   }
1141
1142   private void propagateRelationToCaller(MethodInvokeNode min, MethodDescriptor mdCaller,
1143       MethodDescriptor possibleMdCallee, SSJavaLattice<String> methodLattice,
1144       MethodLocationInfo methodInfo) throws CyclicFlowException {
1145
1146     SSJavaLattice<String> calleeLattice = getMethodLattice(possibleMdCallee);
1147     MethodLocationInfo calleeLocInfo = getMethodLocationInfo(possibleMdCallee);
1148     FlowGraph calleeFlowGraph = getFlowGraph(possibleMdCallee);
1149
1150     int numParam = calleeLocInfo.getNumParam();
1151     for (int i = 0; i < numParam; i++) {
1152       CompositeLocation param1 = calleeLocInfo.getParamCompositeLocation(i);
1153       for (int k = 0; k < numParam; k++) {
1154         if (i != k) {
1155           CompositeLocation param2 = calleeLocInfo.getParamCompositeLocation(k);
1156           if (isGreaterThan(getLattice(possibleMdCallee), param1, param2)) {
1157             NodeTupleSet argDescTupleSet1 = getNodeTupleSetByArgIdx(min, i);
1158             NodeTupleSet argDescTupleSet2 = getNodeTupleSetByArgIdx(min, k);
1159
1160             // the callee has the relation in which param1 is higher than param2
1161             // therefore, the caller has to have the relation in which arg1 is
1162             // higher than arg2
1163
1164             for (Iterator<NTuple<Descriptor>> iterator = argDescTupleSet1.iterator(); iterator
1165                 .hasNext();) {
1166               NTuple<Descriptor> argDescTuple1 = iterator.next();
1167
1168               for (Iterator<NTuple<Descriptor>> iterator2 = argDescTupleSet2.iterator(); iterator2
1169                   .hasNext();) {
1170                 NTuple<Descriptor> argDescTuple2 = iterator2.next();
1171
1172                 // retreive inferred location by the local var descriptor
1173
1174                 NTuple<Location> tuple1 = getFlowGraph(mdCaller).getLocationTuple(argDescTuple1);
1175                 NTuple<Location> tuple2 = getFlowGraph(mdCaller).getLocationTuple(argDescTuple2);
1176
1177                 // CompositeLocation higherInferLoc =
1178                 // methodInfo.getInferLocation(argTuple1.get(0));
1179                 // CompositeLocation lowerInferLoc =
1180                 // methodInfo.getInferLocation(argTuple2.get(0));
1181
1182                 CompositeLocation inferLoc1 = generateInferredCompositeLocation(methodInfo, tuple1);
1183                 CompositeLocation inferLoc2 = generateInferredCompositeLocation(methodInfo, tuple2);
1184
1185                 // addRelation(methodLattice, methodInfo, inferLoc1, inferLoc2);
1186
1187                 addFlowGraphEdge(mdCaller, argDescTuple1, argDescTuple2);
1188
1189               }
1190
1191             }
1192
1193           }
1194         }
1195       }
1196     }
1197
1198   }
1199
1200   private CompositeLocation generateInferredCompositeLocation(MethodLocationInfo methodInfo,
1201       NTuple<Location> tuple) {
1202
1203     // first, retrieve inferred location by the local var descriptor
1204     CompositeLocation inferLoc = new CompositeLocation();
1205
1206     CompositeLocation localVarInferLoc =
1207         methodInfo.getInferLocation(tuple.get(0).getLocDescriptor());
1208
1209     localVarInferLoc.get(0).setLocDescriptor(tuple.get(0).getLocDescriptor());
1210
1211     for (int i = 0; i < localVarInferLoc.getSize(); i++) {
1212       inferLoc.addLocation(localVarInferLoc.get(i));
1213     }
1214
1215     for (int i = 1; i < tuple.size(); i++) {
1216       Location cur = tuple.get(i);
1217       Descriptor enclosingDesc = cur.getDescriptor();
1218       Descriptor curDesc = cur.getLocDescriptor();
1219
1220       Location inferLocElement;
1221       if (curDesc == null) {
1222         // in this case, we have a newly generated location.
1223         inferLocElement = new Location(enclosingDesc, cur.getLocIdentifier());
1224       } else {
1225         String fieldLocSymbol =
1226             getLocationInfo(enclosingDesc).getInferLocation(curDesc).get(0).getLocIdentifier();
1227         inferLocElement = new Location(enclosingDesc, fieldLocSymbol);
1228         inferLocElement.setLocDescriptor(curDesc);
1229       }
1230
1231       inferLoc.addLocation(inferLocElement);
1232
1233     }
1234
1235     assert (inferLoc.get(0).getLocDescriptor().getSymbol() == inferLoc.get(0).getLocIdentifier());
1236     return inferLoc;
1237   }
1238
1239   private void addRelation(SSJavaLattice<String> methodLattice, MethodLocationInfo methodInfo,
1240       CompositeLocation srcInferLoc, CompositeLocation dstInferLoc) throws CyclicFlowException {
1241
1242     System.out.println("addRelation --- srcInferLoc=" + srcInferLoc + "  dstInferLoc="
1243         + dstInferLoc);
1244     String srcLocalLocSymbol = srcInferLoc.get(0).getLocIdentifier();
1245     String dstLocalLocSymbol = dstInferLoc.get(0).getLocIdentifier();
1246
1247     if (srcInferLoc.getSize() == 1 && dstInferLoc.getSize() == 1) {
1248       // add a new relation to the local lattice
1249       addRelationHigherToLower(methodLattice, methodInfo, srcLocalLocSymbol, dstLocalLocSymbol);
1250     } else if (srcInferLoc.getSize() > 1 && dstInferLoc.getSize() > 1) {
1251       // both src and dst have assigned to a composite location
1252
1253       if (!srcLocalLocSymbol.equals(dstLocalLocSymbol)) {
1254         addRelationHigherToLower(methodLattice, methodInfo, srcLocalLocSymbol, dstLocalLocSymbol);
1255       } else {
1256         recursivelyAddRelation(1, srcInferLoc, dstInferLoc);
1257       }
1258     } else {
1259       // either src or dst has assigned to a composite location
1260       if (!srcLocalLocSymbol.equals(dstLocalLocSymbol)) {
1261         addRelationHigherToLower(methodLattice, methodInfo, srcLocalLocSymbol, dstLocalLocSymbol);
1262       }
1263     }
1264
1265     System.out.println();
1266
1267   }
1268
1269   public LocationInfo getLocationInfo(Descriptor d) {
1270     if (d instanceof MethodDescriptor) {
1271       return getMethodLocationInfo((MethodDescriptor) d);
1272     } else {
1273       return getFieldLocationInfo((ClassDescriptor) d);
1274     }
1275   }
1276
1277   private MethodLocationInfo getMethodLocationInfo(MethodDescriptor md) {
1278
1279     if (!mapMethodDescToMethodLocationInfo.containsKey(md)) {
1280       mapMethodDescToMethodLocationInfo.put(md, new MethodLocationInfo(md));
1281     }
1282
1283     return mapMethodDescToMethodLocationInfo.get(md);
1284
1285   }
1286
1287   private LocationInfo getFieldLocationInfo(ClassDescriptor cd) {
1288
1289     if (!mapClassToLocationInfo.containsKey(cd)) {
1290       mapClassToLocationInfo.put(cd, new LocationInfo(cd));
1291     }
1292
1293     return mapClassToLocationInfo.get(cd);
1294
1295   }
1296
1297   private void addRelationToLattice(MethodDescriptor md, SSJavaLattice<String> methodLattice,
1298       MethodLocationInfo methodInfo, FlowNode srcNode, FlowNode dstNode) throws CyclicFlowException {
1299
1300     System.out.println();
1301     System.out.println("### addRelationToLattice src=" + srcNode + " dst=" + dstNode);
1302
1303     // add a new binary relation of dstNode < srcNode
1304     FlowGraph flowGraph = getFlowGraph(md);
1305     try {
1306       System.out.println("***** src composite case::");
1307       calculateCompositeLocation(flowGraph, methodLattice, methodInfo, srcNode);
1308
1309       CompositeLocation srcInferLoc =
1310           generateInferredCompositeLocation(methodInfo, flowGraph.getLocationTuple(srcNode));
1311       CompositeLocation dstInferLoc =
1312           generateInferredCompositeLocation(methodInfo, flowGraph.getLocationTuple(dstNode));
1313       addRelation(methodLattice, methodInfo, srcInferLoc, dstInferLoc);
1314     } catch (CyclicFlowException e) {
1315       // there is a cyclic value flow... try to calculate a composite location
1316       // for the destination node
1317       System.out.println("***** dst composite case::");
1318       calculateCompositeLocation(flowGraph, methodLattice, methodInfo, dstNode);
1319       CompositeLocation srcInferLoc =
1320           generateInferredCompositeLocation(methodInfo, flowGraph.getLocationTuple(srcNode));
1321       CompositeLocation dstInferLoc =
1322           generateInferredCompositeLocation(methodInfo, flowGraph.getLocationTuple(dstNode));
1323       try {
1324         addRelation(methodLattice, methodInfo, srcInferLoc, dstInferLoc);
1325       } catch (CyclicFlowException e1) {
1326         throw new Error("Failed to merge cyclic value flows into a shared location.");
1327       }
1328     }
1329
1330   }
1331
1332   private void recursivelyAddRelation(int idx, CompositeLocation srcInferLoc,
1333       CompositeLocation dstInferLoc) throws CyclicFlowException {
1334
1335     String srcLocSymbol = srcInferLoc.get(idx).getLocIdentifier();
1336     String dstLocSymbol = dstInferLoc.get(idx).getLocIdentifier();
1337
1338     Descriptor parentDesc = srcInferLoc.get(idx).getDescriptor();
1339
1340     if (srcLocSymbol.equals(dstLocSymbol)) {
1341       // check if it is the case of shared location
1342       if (srcInferLoc.getSize() == (idx + 1) && dstInferLoc.getSize() == (idx + 1)) {
1343         Location inferLocElement = srcInferLoc.get(idx);
1344         System.out.println("SET SHARED LOCATION=" + inferLocElement);
1345         getLattice(inferLocElement.getDescriptor())
1346             .addSharedLoc(inferLocElement.getLocIdentifier());
1347       } else if (srcInferLoc.getSize() > (idx + 1) && dstInferLoc.getSize() > (idx + 1)) {
1348         recursivelyAddRelation(idx + 1, srcInferLoc, dstInferLoc);
1349       }
1350     } else {
1351       addRelationHigherToLower(getLattice(parentDesc), getLocationInfo(parentDesc), srcLocSymbol,
1352           dstLocSymbol);
1353     }
1354   }
1355
1356   private void recursivelyAddCompositeRelation(MethodDescriptor md, FlowGraph flowGraph,
1357       MethodLocationInfo methodInfo, FlowNode srcNode, FlowNode dstNode, Descriptor srcDesc,
1358       Descriptor dstDesc) throws CyclicFlowException {
1359
1360     CompositeLocation inferSrcLoc;
1361     CompositeLocation inferDstLoc = methodInfo.getInferLocation(dstDesc);
1362
1363     if (srcNode.getDescTuple().size() > 1) {
1364       // field access
1365       inferSrcLoc = new CompositeLocation();
1366
1367       NTuple<Location> locTuple = flowGraph.getLocationTuple(srcNode);
1368       for (int i = 0; i < locTuple.size(); i++) {
1369         inferSrcLoc.addLocation(locTuple.get(i));
1370       }
1371
1372     } else {
1373       inferSrcLoc = methodInfo.getInferLocation(srcDesc);
1374     }
1375
1376     if (dstNode.getDescTuple().size() > 1) {
1377       // field access
1378       inferDstLoc = new CompositeLocation();
1379
1380       NTuple<Location> locTuple = flowGraph.getLocationTuple(dstNode);
1381       for (int i = 0; i < locTuple.size(); i++) {
1382         inferDstLoc.addLocation(locTuple.get(i));
1383       }
1384
1385     } else {
1386       inferDstLoc = methodInfo.getInferLocation(dstDesc);
1387     }
1388
1389     recursiveAddRelationToLattice(1, md, inferSrcLoc, inferDstLoc);
1390   }
1391
1392   private void addPrefixMapping(Map<NTuple<Location>, Set<NTuple<Location>>> map,
1393       NTuple<Location> prefix, NTuple<Location> element) {
1394
1395     if (!map.containsKey(prefix)) {
1396       map.put(prefix, new HashSet<NTuple<Location>>());
1397     }
1398     map.get(prefix).add(element);
1399   }
1400
1401   private boolean calculateCompositeLocation(FlowGraph flowGraph,
1402       SSJavaLattice<String> methodLattice, MethodLocationInfo methodInfo, FlowNode flowNode)
1403       throws CyclicFlowException {
1404
1405     Descriptor localVarDesc = flowNode.getDescTuple().get(0);
1406     NTuple<Location> flowNodelocTuple = flowGraph.getLocationTuple(flowNode);
1407
1408     if (localVarDesc.equals(methodInfo.getMethodDesc())) {
1409       return false;
1410     }
1411
1412     Set<FlowNode> inNodeSet = flowGraph.getIncomingFlowNodeSet(flowNode);
1413     Set<FlowNode> reachableNodeSet = flowGraph.getReachableFlowNodeSet(flowNode);
1414
1415     Map<NTuple<Location>, Set<NTuple<Location>>> mapPrefixToIncomingLocTupleSet =
1416         new HashMap<NTuple<Location>, Set<NTuple<Location>>>();
1417
1418     List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
1419
1420     for (Iterator iterator = inNodeSet.iterator(); iterator.hasNext();) {
1421       FlowNode inNode = (FlowNode) iterator.next();
1422       NTuple<Location> inNodeTuple = flowGraph.getLocationTuple(inNode);
1423
1424       CompositeLocation inNodeInferredLoc =
1425           generateInferredCompositeLocation(methodInfo, inNodeTuple);
1426
1427       NTuple<Location> inNodeInferredLocTuple = inNodeInferredLoc.getTuple();
1428
1429       for (int i = 1; i < inNodeInferredLocTuple.size(); i++) {
1430         NTuple<Location> prefix = inNodeInferredLocTuple.subList(0, i);
1431         if (!prefixList.contains(prefix)) {
1432           prefixList.add(prefix);
1433         }
1434         addPrefixMapping(mapPrefixToIncomingLocTupleSet, prefix, inNodeInferredLocTuple);
1435       }
1436     }
1437
1438     Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
1439       public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
1440         int s0 = arg0.size();
1441         int s1 = arg1.size();
1442         if (s0 > s1) {
1443           return -1;
1444         } else if (s0 == s1) {
1445           return 0;
1446         } else {
1447           return 1;
1448         }
1449       }
1450     });
1451
1452     System.out.println("prefixList=" + prefixList);
1453     System.out.println("reachableNodeSet=" + reachableNodeSet);
1454
1455     // find out reachable nodes that have the longest common prefix
1456     for (int i = 0; i < prefixList.size(); i++) {
1457       NTuple<Location> curPrefix = prefixList.get(i);
1458       Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
1459
1460       for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
1461         FlowNode reachableNode = (FlowNode) iterator2.next();
1462         NTuple<Location> reachLocTuple = flowGraph.getLocationTuple(reachableNode);
1463         CompositeLocation reachLocInferLoc =
1464             generateInferredCompositeLocation(methodInfo, reachLocTuple);
1465         if (reachLocInferLoc.getTuple().startsWith(curPrefix)) {
1466           reachableCommonPrefixSet.add(reachLocTuple);
1467         }
1468       }
1469
1470       if (!reachableCommonPrefixSet.isEmpty()) {
1471         // found reachable nodes that start with the prefix curPrefix
1472         // need to assign a composite location
1473
1474         // first, check if there are more than one the set of locations that has
1475         // the same length of the longest reachable prefix, no way to assign
1476         // a composite location to the input local var
1477         prefixSanityCheck(prefixList, i, flowGraph, reachableNodeSet);
1478
1479         Set<NTuple<Location>> incomingCommonPrefixSet =
1480             mapPrefixToIncomingLocTupleSet.get(curPrefix);
1481
1482         int idx = curPrefix.size();
1483         NTuple<Location> element = incomingCommonPrefixSet.iterator().next();
1484         Descriptor desc = element.get(idx).getDescriptor();
1485
1486         SSJavaLattice<String> lattice = getLattice(desc);
1487         LocationInfo locInfo = getLocationInfo(desc);
1488
1489         CompositeLocation inferLocation =
1490             generateInferredCompositeLocation(methodInfo, flowNodelocTuple);
1491
1492         // methodInfo.getInferLocation(localVarDesc);
1493         CompositeLocation newInferLocation = new CompositeLocation();
1494
1495         if (inferLocation.getTuple().startsWith(curPrefix)) {
1496           // the same infer location is already existed. no need to do
1497           // anything
1498           System.out.println("NO ATTEMPT TO MAKE A COMPOSITE LOCATION curPrefix=" + curPrefix);
1499           return true;
1500         } else {
1501           // assign a new composite location
1502
1503           // String oldMethodLocationSymbol =
1504           // inferLocation.get(0).getLocIdentifier();
1505           String newLocSymbol = "Loc" + (SSJavaLattice.seed++);
1506           for (int locIdx = 0; locIdx < curPrefix.size(); locIdx++) {
1507             newInferLocation.addLocation(curPrefix.get(locIdx));
1508           }
1509           Location newLocationElement = new Location(desc, newLocSymbol);
1510           newInferLocation.addLocation(newLocationElement);
1511
1512           // maps local variable to location types of the common prefix
1513           methodInfo.mapDescriptorToLocation(localVarDesc, newInferLocation.clone());
1514
1515           // methodInfo.mapDescriptorToLocation(localVarDesc, newInferLocation);
1516           addMapLocSymbolToInferredLocation(methodInfo.getMethodDesc(), localVarDesc,
1517               newInferLocation);
1518           methodInfo.removeMaplocalVarToLocSet(localVarDesc);
1519
1520           // add the field/var descriptor to the set of the location symbol
1521           int lastIdx = flowNode.getDescTuple().size() - 1;
1522           Descriptor lastFlowNodeDesc = flowNode.getDescTuple().get(lastIdx);
1523           Descriptor enclosinglastLastFlowNodeDesc = flowNodelocTuple.get(lastIdx).getDescriptor();
1524
1525           CompositeLocation newlyInferredLocForFlowNode =
1526               generateInferredCompositeLocation(methodInfo, flowNodelocTuple);
1527           Location lastInferLocElement =
1528               newlyInferredLocForFlowNode.get(newlyInferredLocForFlowNode.getSize() - 1);
1529           Descriptor enclosingLastInferLocElement = lastInferLocElement.getDescriptor();
1530
1531           // getLocationInfo(enclosingLastInferLocElement).addMapLocSymbolToDescSet(
1532           // lastInferLocElement.getLocIdentifier(), lastFlowNodeDesc);
1533           getLocationInfo(enclosingLastInferLocElement).addMapLocSymbolToRelatedInferLoc(
1534               lastInferLocElement.getLocIdentifier(), enclosinglastLastFlowNodeDesc,
1535               lastFlowNodeDesc);
1536
1537           // clean up the previous location
1538           // Location prevInferLocElement =
1539           // inferLocation.get(inferLocation.getSize() - 1);
1540           // Descriptor prevEnclosingDesc = prevInferLocElement.getDescriptor();
1541           //
1542           // SSJavaLattice<String> targetLattice;
1543           // LocationInfo targetInfo;
1544           // if (prevEnclosingDesc.equals(methodInfo.getMethodDesc())) {
1545           // targetLattice = methodLattice;
1546           // targetInfo = methodInfo;
1547           // } else {
1548           // targetLattice = getLattice(prevInferLocElement.getDescriptor());
1549           // targetInfo = getLocationInfo(prevInferLocElement.getDescriptor());
1550           // }
1551           //
1552           // Set<Pair<Descriptor, Descriptor>> associstedDescSet =
1553           // targetInfo.getRelatedInferLocSet(prevInferLocElement.getLocIdentifier());
1554           //
1555           // if (associstedDescSet.size() == 1) {
1556           // targetLattice.remove(prevInferLocElement.getLocIdentifier());
1557           // } else {
1558           // associstedDescSet.remove(lastFlowNodeDesc);
1559           // }
1560
1561         }
1562
1563         System.out.println("curPrefix=" + curPrefix);
1564         System.out.println("ASSIGN NEW COMPOSITE LOCATION =" + newInferLocation + "    to "
1565             + flowNode);
1566
1567         String newlyInsertedLocName =
1568             newInferLocation.get(newInferLocation.getSize() - 1).getLocIdentifier();
1569
1570         System.out.println("-- add in-flow");
1571         for (Iterator iterator = incomingCommonPrefixSet.iterator(); iterator.hasNext();) {
1572           NTuple<Location> tuple = (NTuple<Location>) iterator.next();
1573           Location loc = tuple.get(idx);
1574           String higher = loc.getLocIdentifier();
1575           addRelationHigherToLower(lattice, locInfo, higher, newlyInsertedLocName);
1576         }
1577
1578         System.out.println("-- add out flow");
1579         for (Iterator iterator = reachableCommonPrefixSet.iterator(); iterator.hasNext();) {
1580           NTuple<Location> tuple = (NTuple<Location>) iterator.next();
1581           if (tuple.size() > idx) {
1582             Location loc = tuple.get(idx);
1583             String lower = loc.getLocIdentifier();
1584             // String lower =
1585             // locInfo.getFieldInferLocation(loc.getLocDescriptor()).getLocIdentifier();
1586             addRelationHigherToLower(lattice, locInfo, newlyInsertedLocName, lower);
1587           }
1588         }
1589
1590         return true;
1591       }
1592
1593     }
1594
1595     return false;
1596
1597   }
1598
1599   private void addMapLocSymbolToInferredLocation(MethodDescriptor md, Descriptor localVar,
1600       CompositeLocation inferLoc) {
1601
1602     Location locElement = inferLoc.get((inferLoc.getSize() - 1));
1603     Descriptor enclosingDesc = locElement.getDescriptor();
1604     LocationInfo locInfo = getLocationInfo(enclosingDesc);
1605     locInfo.addMapLocSymbolToRelatedInferLoc(locElement.getLocIdentifier(), md, localVar);
1606   }
1607
1608   private boolean isCompositeLocation(CompositeLocation cl) {
1609     return cl.getSize() > 1;
1610   }
1611
1612   private boolean containsNonPrimitiveElement(Set<Descriptor> descSet) {
1613     for (Iterator iterator = descSet.iterator(); iterator.hasNext();) {
1614       Descriptor desc = (Descriptor) iterator.next();
1615
1616       if (desc.equals(LocationInference.GLOBALDESC)) {
1617         return true;
1618       } else if (desc instanceof VarDescriptor) {
1619         if (!((VarDescriptor) desc).getType().isPrimitive()) {
1620           return true;
1621         }
1622       } else if (desc instanceof FieldDescriptor) {
1623         if (!((FieldDescriptor) desc).getType().isPrimitive()) {
1624           return true;
1625         }
1626       }
1627
1628     }
1629     return false;
1630   }
1631
1632   private void addRelationHigherToLower(SSJavaLattice<String> lattice, LocationInfo locInfo,
1633       String higher, String lower) throws CyclicFlowException {
1634
1635     System.out.println("---addRelationHigherToLower " + higher + " -> " + lower
1636         + " to the lattice of " + locInfo.getDescIdentifier());
1637     // if (higher.equals(lower) && lattice.isSharedLoc(higher)) {
1638     // return;
1639     // }
1640     Set<String> cycleElementSet = lattice.getPossibleCycleElements(higher, lower);
1641
1642     boolean hasNonPrimitiveElement = false;
1643     for (Iterator iterator = cycleElementSet.iterator(); iterator.hasNext();) {
1644       String cycleElementLocSymbol = (String) iterator.next();
1645
1646       Set<Descriptor> descSet = locInfo.getDescSet(cycleElementLocSymbol);
1647       if (containsNonPrimitiveElement(descSet)) {
1648         hasNonPrimitiveElement = true;
1649         break;
1650       }
1651     }
1652
1653     if (hasNonPrimitiveElement) {
1654       System.out.println("#Check cycle= " + lower + " < " + higher + "     cycleElementSet="
1655           + cycleElementSet);
1656       // if there is non-primitive element in the cycle, no way to merge cyclic
1657       // elements into the shared location
1658       throw new CyclicFlowException();
1659     }
1660
1661     if (cycleElementSet.size() > 0) {
1662
1663       String newSharedLoc = "SharedLoc" + (SSJavaLattice.seed++);
1664
1665       System.out.println("---ASSIGN NEW SHARED LOC=" + newSharedLoc + "   to  " + cycleElementSet);
1666       lattice.mergeIntoSharedLocation(cycleElementSet, newSharedLoc);
1667
1668       for (Iterator iterator = cycleElementSet.iterator(); iterator.hasNext();) {
1669         String oldLocSymbol = (String) iterator.next();
1670
1671         Set<Pair<Descriptor, Descriptor>> inferLocSet = locInfo.getRelatedInferLocSet(oldLocSymbol);
1672         System.out.println("---update related locations=" + inferLocSet);
1673         for (Iterator iterator2 = inferLocSet.iterator(); iterator2.hasNext();) {
1674           Pair<Descriptor, Descriptor> pair = (Pair<Descriptor, Descriptor>) iterator2.next();
1675           Descriptor enclosingDesc = pair.getFirst();
1676           Descriptor desc = pair.getSecond();
1677
1678           CompositeLocation inferLoc;
1679           if (curMethodInfo.md.equals(enclosingDesc)) {
1680             inferLoc = curMethodInfo.getInferLocation(desc);
1681           } else {
1682             inferLoc = getLocationInfo(enclosingDesc).getInferLocation(desc);
1683           }
1684
1685           Location locElement = inferLoc.get(inferLoc.getSize() - 1);
1686
1687           locElement.setLocIdentifier(newSharedLoc);
1688           locInfo.addMapLocSymbolToRelatedInferLoc(newSharedLoc, enclosingDesc, desc);
1689
1690           if (curMethodInfo.md.equals(enclosingDesc)) {
1691             inferLoc = curMethodInfo.getInferLocation(desc);
1692           } else {
1693             inferLoc = getLocationInfo(enclosingDesc).getInferLocation(desc);
1694           }
1695           System.out.println("---New Infer Loc=" + inferLoc);
1696
1697         }
1698         locInfo.removeRelatedInferLocSet(oldLocSymbol, newSharedLoc);
1699
1700       }
1701
1702       lattice.addSharedLoc(newSharedLoc);
1703
1704     } else if (!lattice.isGreaterThan(higher, lower)) {
1705       lattice.addRelationHigherToLower(higher, lower);
1706     }
1707   }
1708
1709   private void replaceOldLocWithNewLoc(SSJavaLattice<String> methodLattice, String oldLocSymbol,
1710       String newLocSymbol) {
1711
1712     if (methodLattice.containsKey(oldLocSymbol)) {
1713       methodLattice.substituteLocation(oldLocSymbol, newLocSymbol);
1714     }
1715
1716   }
1717
1718   private void prefixSanityCheck(List<NTuple<Location>> prefixList, int curIdx,
1719       FlowGraph flowGraph, Set<FlowNode> reachableNodeSet) {
1720
1721     NTuple<Location> curPrefix = prefixList.get(curIdx);
1722
1723     for (int i = curIdx + 1; i < prefixList.size(); i++) {
1724       NTuple<Location> prefixTuple = prefixList.get(i);
1725
1726       if (curPrefix.startsWith(prefixTuple)) {
1727         continue;
1728       }
1729
1730       for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
1731         FlowNode reachableNode = (FlowNode) iterator2.next();
1732         NTuple<Location> reachLocTuple = flowGraph.getLocationTuple(reachableNode);
1733         if (reachLocTuple.startsWith(prefixTuple)) {
1734           // TODO
1735           throw new Error("Failed to generate a composite location");
1736         }
1737       }
1738     }
1739   }
1740
1741   public boolean isPrimitiveLocalVariable(FlowNode node) {
1742     VarDescriptor varDesc = (VarDescriptor) node.getDescTuple().get(0);
1743     return varDesc.getType().isPrimitive();
1744   }
1745
1746   private SSJavaLattice<String> getLattice(Descriptor d) {
1747     if (d instanceof MethodDescriptor) {
1748       return getMethodLattice((MethodDescriptor) d);
1749     } else {
1750       return getFieldLattice((ClassDescriptor) d);
1751     }
1752   }
1753
1754   private SSJavaLattice<String> getMethodLattice(MethodDescriptor md) {
1755     if (!md2lattice.containsKey(md)) {
1756       md2lattice.put(md, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
1757     }
1758     return md2lattice.get(md);
1759   }
1760
1761   private void setMethodLattice(MethodDescriptor md, SSJavaLattice<String> lattice) {
1762     md2lattice.put(md, lattice);
1763   }
1764
1765   private void extractRelationFromFieldFlows(ClassDescriptor cd, FlowNode srcNode,
1766       FlowNode dstNode, int idx) throws CyclicFlowException {
1767
1768     if (srcNode.getDescTuple().get(idx).equals(dstNode.getDescTuple().get(idx))
1769         && srcNode.getDescTuple().size() > (idx + 1) && dstNode.getDescTuple().size() > (idx + 1)) {
1770       // value flow between fields: we don't need to add a binary relation
1771       // for this case
1772
1773       Descriptor desc = srcNode.getDescTuple().get(idx);
1774       ClassDescriptor classDesc;
1775
1776       if (idx == 0) {
1777         classDesc = ((VarDescriptor) desc).getType().getClassDesc();
1778       } else {
1779         classDesc = ((FieldDescriptor) desc).getType().getClassDesc();
1780       }
1781
1782       extractRelationFromFieldFlows(classDesc, srcNode, dstNode, idx + 1);
1783
1784     } else {
1785
1786       Descriptor srcFieldDesc = srcNode.getDescTuple().get(idx);
1787       Descriptor dstFieldDesc = dstNode.getDescTuple().get(idx);
1788
1789       // add a new binary relation of dstNode < srcNode
1790       SSJavaLattice<String> fieldLattice = getFieldLattice(cd);
1791       LocationInfo fieldInfo = getFieldLocationInfo(cd);
1792
1793       String srcSymbol = fieldInfo.getFieldInferLocation(srcFieldDesc).getLocIdentifier();
1794       String dstSymbol = fieldInfo.getFieldInferLocation(dstFieldDesc).getLocIdentifier();
1795
1796       addRelationHigherToLower(fieldLattice, fieldInfo, srcSymbol, dstSymbol);
1797
1798     }
1799
1800   }
1801
1802   public SSJavaLattice<String> getFieldLattice(ClassDescriptor cd) {
1803     if (!cd2lattice.containsKey(cd)) {
1804       cd2lattice.put(cd, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
1805     }
1806     return cd2lattice.get(cd);
1807   }
1808
1809   public LinkedList<MethodDescriptor> computeMethodList() {
1810
1811     Set<MethodDescriptor> toSort = new HashSet<MethodDescriptor>();
1812
1813     setupToAnalyze();
1814
1815     Set<MethodDescriptor> visited = new HashSet<MethodDescriptor>();
1816     Set<MethodDescriptor> reachableCallee = new HashSet<MethodDescriptor>();
1817
1818     while (!toAnalyzeIsEmpty()) {
1819       ClassDescriptor cd = toAnalyzeNext();
1820
1821       setupToAnalazeMethod(cd);
1822       toanalyzeMethodList.removeAll(visited);
1823
1824       while (!toAnalyzeMethodIsEmpty()) {
1825         MethodDescriptor md = toAnalyzeMethodNext();
1826         if ((!visited.contains(md))
1827             && (ssjava.needTobeAnnotated(md) || reachableCallee.contains(md))) {
1828
1829           // creates a mapping from a method descriptor to virtual methods
1830           Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
1831           if (md.isStatic()) {
1832             setPossibleCallees.add(md);
1833           } else {
1834             setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
1835           }
1836
1837           Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getCalleeSet(md);
1838           Set<MethodDescriptor> needToAnalyzeCalleeSet = new HashSet<MethodDescriptor>();
1839
1840           for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
1841             MethodDescriptor calleemd = (MethodDescriptor) iterator.next();
1842             if ((!ssjava.isTrustMethod(calleemd))
1843                 && (!ssjava.isSSJavaUtil(calleemd.getClassDesc()))) {
1844               if (!visited.contains(calleemd)) {
1845                 toanalyzeMethodList.add(calleemd);
1846               }
1847               reachableCallee.add(calleemd);
1848               needToAnalyzeCalleeSet.add(calleemd);
1849             }
1850           }
1851
1852           mapMethodToCalleeSet.put(md, needToAnalyzeCalleeSet);
1853
1854           visited.add(md);
1855
1856           toSort.add(md);
1857         }
1858       }
1859     }
1860
1861     return ssjava.topologicalSort(toSort);
1862
1863   }
1864
1865   public void constructFlowGraph() {
1866
1867     LinkedList<MethodDescriptor> methodDescList = computeMethodList();
1868
1869
1870     while (!methodDescList.isEmpty()) {
1871       MethodDescriptor md = methodDescList.removeLast();
1872       if (state.SSJAVADEBUG) {
1873         System.out.println();
1874         System.out.println("SSJAVA: Constructing a flow graph: " + md);
1875
1876         // creates a mapping from a parameter descriptor to its index
1877         Map<Descriptor, Integer> mapParamDescToIdx = new HashMap<Descriptor, Integer>();
1878         int offset = 0;
1879         if (!md.isStatic()) {
1880           offset = 1;
1881           mapParamDescToIdx.put(md.getThis(), 0);
1882         }
1883
1884         for (int i = 0; i < md.numParameters(); i++) {
1885           Descriptor paramDesc = (Descriptor) md.getParameter(i);
1886           mapParamDescToIdx.put(paramDesc, new Integer(i + offset));
1887         }
1888
1889         FlowGraph fg = new FlowGraph(md, mapParamDescToIdx);
1890         mapMethodDescriptorToFlowGraph.put(md, fg);
1891
1892         analyzeMethodBody(md.getClassDesc(), md);
1893       }
1894     }
1895     _debug_printGraph();
1896
1897   }
1898
1899   private void analyzeMethodBody(ClassDescriptor cd, MethodDescriptor md) {
1900     BlockNode bn = state.getMethodBody(md);
1901     NodeTupleSet implicitFlowTupleSet = new NodeTupleSet();
1902     analyzeFlowBlockNode(md, md.getParameterTable(), bn, implicitFlowTupleSet);
1903   }
1904
1905   private void analyzeFlowBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn,
1906       NodeTupleSet implicitFlowTupleSet) {
1907
1908     bn.getVarTable().setParent(nametable);
1909     for (int i = 0; i < bn.size(); i++) {
1910       BlockStatementNode bsn = bn.get(i);
1911       analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
1912     }
1913
1914   }
1915
1916   private void analyzeBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
1917       BlockStatementNode bsn, NodeTupleSet implicitFlowTupleSet) {
1918
1919     switch (bsn.kind()) {
1920     case Kind.BlockExpressionNode:
1921       analyzeBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, implicitFlowTupleSet);
1922       break;
1923
1924     case Kind.DeclarationNode:
1925       analyzeFlowDeclarationNode(md, nametable, (DeclarationNode) bsn, implicitFlowTupleSet);
1926       break;
1927
1928     case Kind.IfStatementNode:
1929       analyzeFlowIfStatementNode(md, nametable, (IfStatementNode) bsn, implicitFlowTupleSet);
1930       break;
1931
1932     case Kind.LoopNode:
1933       analyzeFlowLoopNode(md, nametable, (LoopNode) bsn, implicitFlowTupleSet);
1934       break;
1935
1936     case Kind.ReturnNode:
1937       analyzeFlowReturnNode(md, nametable, (ReturnNode) bsn, implicitFlowTupleSet);
1938       break;
1939
1940     case Kind.SubBlockNode:
1941       analyzeFlowSubBlockNode(md, nametable, (SubBlockNode) bsn, implicitFlowTupleSet);
1942       break;
1943
1944     case Kind.ContinueBreakNode:
1945       break;
1946
1947     case Kind.SwitchStatementNode:
1948       analyzeSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
1949       break;
1950
1951     }
1952
1953   }
1954
1955   private void analyzeSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
1956       SwitchStatementNode bsn) {
1957     // TODO Auto-generated method stub
1958   }
1959
1960   private void analyzeFlowSubBlockNode(MethodDescriptor md, SymbolTable nametable,
1961       SubBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
1962     analyzeFlowBlockNode(md, nametable, sbn.getBlockNode(), implicitFlowTupleSet);
1963   }
1964
1965   private void analyzeFlowReturnNode(MethodDescriptor md, SymbolTable nametable, ReturnNode rn,
1966       NodeTupleSet implicitFlowTupleSet) {
1967
1968     ExpressionNode returnExp = rn.getReturnExpression();
1969
1970     if (returnExp != null) {
1971       NodeTupleSet nodeSet = new NodeTupleSet();
1972       analyzeFlowExpressionNode(md, nametable, returnExp, nodeSet, false);
1973
1974       FlowGraph fg = getFlowGraph(md);
1975
1976       // annotate the elements of the node set as the return location
1977       for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1978         NTuple<Descriptor> returnDescTuple = (NTuple<Descriptor>) iterator.next();
1979         fg.addReturnFlowNode(returnDescTuple);
1980         for (Iterator iterator2 = implicitFlowTupleSet.iterator(); iterator2.hasNext();) {
1981           NTuple<Descriptor> implicitFlowDescTuple = (NTuple<Descriptor>) iterator2.next();
1982           fg.addValueFlowEdge(implicitFlowDescTuple, returnDescTuple);
1983         }
1984       }
1985     }
1986
1987   }
1988
1989   private void analyzeFlowLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln,
1990       NodeTupleSet implicitFlowTupleSet) {
1991
1992     if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
1993
1994       NodeTupleSet condTupleNode = new NodeTupleSet();
1995       analyzeFlowExpressionNode(md, nametable, ln.getCondition(), condTupleNode, null,
1996           implicitFlowTupleSet, false);
1997       condTupleNode.addTupleSet(implicitFlowTupleSet);
1998
1999       // add edges from condNodeTupleSet to all nodes of conditional nodes
2000       analyzeFlowBlockNode(md, nametable, ln.getBody(), condTupleNode);
2001
2002     } else {
2003       // check 'for loop' case
2004       BlockNode bn = ln.getInitializer();
2005       bn.getVarTable().setParent(nametable);
2006       for (int i = 0; i < bn.size(); i++) {
2007         BlockStatementNode bsn = bn.get(i);
2008         analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
2009       }
2010
2011       NodeTupleSet condTupleNode = new NodeTupleSet();
2012       analyzeFlowExpressionNode(md, bn.getVarTable(), ln.getCondition(), condTupleNode, null,
2013           implicitFlowTupleSet, false);
2014       condTupleNode.addTupleSet(implicitFlowTupleSet);
2015
2016       analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(), condTupleNode);
2017       analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(), condTupleNode);
2018
2019     }
2020
2021   }
2022
2023   private void analyzeFlowIfStatementNode(MethodDescriptor md, SymbolTable nametable,
2024       IfStatementNode isn, NodeTupleSet implicitFlowTupleSet) {
2025
2026     NodeTupleSet condTupleNode = new NodeTupleSet();
2027     analyzeFlowExpressionNode(md, nametable, isn.getCondition(), condTupleNode, null,
2028         implicitFlowTupleSet, false);
2029
2030     // add edges from condNodeTupleSet to all nodes of conditional nodes
2031     condTupleNode.addTupleSet(implicitFlowTupleSet);
2032     analyzeFlowBlockNode(md, nametable, isn.getTrueBlock(), condTupleNode);
2033
2034     if (isn.getFalseBlock() != null) {
2035       analyzeFlowBlockNode(md, nametable, isn.getFalseBlock(), condTupleNode);
2036     }
2037
2038   }
2039
2040   private void analyzeFlowDeclarationNode(MethodDescriptor md, SymbolTable nametable,
2041       DeclarationNode dn, NodeTupleSet implicitFlowTupleSet) {
2042
2043     VarDescriptor vd = dn.getVarDescriptor();
2044     mapDescToDefinitionLine.put(vd, dn.getNumLine());
2045     NTuple<Descriptor> tupleLHS = new NTuple<Descriptor>();
2046     tupleLHS.add(vd);
2047     FlowNode fn = getFlowGraph(md).createNewFlowNode(tupleLHS);
2048     fn.setDeclarationNode();
2049
2050     if (dn.getExpression() != null) {
2051
2052       NodeTupleSet tupleSetRHS = new NodeTupleSet();
2053       analyzeFlowExpressionNode(md, nametable, dn.getExpression(), tupleSetRHS, null,
2054           implicitFlowTupleSet, false);
2055
2056       // add a new flow edge from rhs to lhs
2057       for (Iterator<NTuple<Descriptor>> iter = tupleSetRHS.iterator(); iter.hasNext();) {
2058         NTuple<Descriptor> from = iter.next();
2059         addFlowGraphEdge(md, from, tupleLHS);
2060       }
2061
2062     }
2063
2064   }
2065
2066   private void analyzeBlockExpressionNode(MethodDescriptor md, SymbolTable nametable,
2067       BlockExpressionNode ben, NodeTupleSet implicitFlowTupleSet) {
2068     analyzeFlowExpressionNode(md, nametable, ben.getExpression(), null, null, implicitFlowTupleSet,
2069         false);
2070   }
2071
2072   private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
2073       ExpressionNode en, NodeTupleSet nodeSet, boolean isLHS) {
2074     return analyzeFlowExpressionNode(md, nametable, en, nodeSet, null, new NodeTupleSet(), isLHS);
2075   }
2076
2077   private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
2078       ExpressionNode en, NodeTupleSet nodeSet, NTuple<Descriptor> base,
2079       NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
2080
2081     // note that expression node can create more than one flow node
2082     // nodeSet contains of flow nodes
2083     // base is always assigned to null except the case of a name node!
2084
2085     NTuple<Descriptor> flowTuple;
2086
2087     switch (en.kind()) {
2088
2089     case Kind.AssignmentNode:
2090       analyzeFlowAssignmentNode(md, nametable, (AssignmentNode) en, nodeSet, base,
2091           implicitFlowTupleSet);
2092       break;
2093
2094     case Kind.FieldAccessNode:
2095       flowTuple =
2096           analyzeFlowFieldAccessNode(md, nametable, (FieldAccessNode) en, nodeSet, base,
2097               implicitFlowTupleSet, isLHS);
2098       if (flowTuple != null) {
2099         nodeSet.addTuple(flowTuple);
2100       }
2101       return flowTuple;
2102
2103     case Kind.NameNode:
2104       NodeTupleSet nameNodeSet = new NodeTupleSet();
2105       flowTuple =
2106           analyzeFlowNameNode(md, nametable, (NameNode) en, nameNodeSet, base, implicitFlowTupleSet);
2107       if (flowTuple != null) {
2108         nodeSet.addTuple(flowTuple);
2109       }
2110       return flowTuple;
2111
2112     case Kind.OpNode:
2113       analyzeFlowOpNode(md, nametable, (OpNode) en, nodeSet, implicitFlowTupleSet);
2114       break;
2115
2116     case Kind.CreateObjectNode:
2117       analyzeCreateObjectNode(md, nametable, (CreateObjectNode) en);
2118       break;
2119
2120     case Kind.ArrayAccessNode:
2121       analyzeFlowArrayAccessNode(md, nametable, (ArrayAccessNode) en, nodeSet, isLHS);
2122       break;
2123
2124     case Kind.LiteralNode:
2125       analyzeLiteralNode(md, nametable, (LiteralNode) en);
2126       break;
2127
2128     case Kind.MethodInvokeNode:
2129       analyzeFlowMethodInvokeNode(md, nametable, (MethodInvokeNode) en, nodeSet,
2130           implicitFlowTupleSet);
2131       break;
2132
2133     case Kind.TertiaryNode:
2134       analyzeFlowTertiaryNode(md, nametable, (TertiaryNode) en, nodeSet, implicitFlowTupleSet);
2135       break;
2136
2137     case Kind.CastNode:
2138       analyzeFlowCastNode(md, nametable, (CastNode) en, nodeSet, base, implicitFlowTupleSet);
2139       break;
2140     // case Kind.InstanceOfNode:
2141     // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
2142     // return null;
2143
2144     // case Kind.ArrayInitializerNode:
2145     // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
2146     // td);
2147     // return null;
2148
2149     // case Kind.ClassTypeNode:
2150     // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
2151     // return null;
2152
2153     // case Kind.OffsetNode:
2154     // checkOffsetNode(md, nametable, (OffsetNode)en, td);
2155     // return null;
2156
2157     }
2158     return null;
2159
2160   }
2161
2162   private void analyzeFlowCastNode(MethodDescriptor md, SymbolTable nametable, CastNode cn,
2163       NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
2164
2165     analyzeFlowExpressionNode(md, nametable, cn.getExpression(), nodeSet, base,
2166         implicitFlowTupleSet, false);
2167
2168   }
2169
2170   private void analyzeFlowTertiaryNode(MethodDescriptor md, SymbolTable nametable, TertiaryNode tn,
2171       NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
2172
2173     NodeTupleSet tertiaryTupleNode = new NodeTupleSet();
2174     analyzeFlowExpressionNode(md, nametable, tn.getCond(), tertiaryTupleNode, null,
2175         implicitFlowTupleSet, false);
2176
2177     // add edges from tertiaryTupleNode to all nodes of conditional nodes
2178     tertiaryTupleNode.addTupleSet(implicitFlowTupleSet);
2179     analyzeFlowExpressionNode(md, nametable, tn.getTrueExpr(), tertiaryTupleNode, null,
2180         implicitFlowTupleSet, false);
2181
2182     analyzeFlowExpressionNode(md, nametable, tn.getFalseExpr(), tertiaryTupleNode, null,
2183         implicitFlowTupleSet, false);
2184
2185     nodeSet.addTupleSet(tertiaryTupleNode);
2186
2187   }
2188
2189   private void addMapCallerMethodDescToMethodInvokeNodeSet(MethodDescriptor caller,
2190       MethodInvokeNode min) {
2191     Set<MethodInvokeNode> set = mapMethodDescriptorToMethodInvokeNodeSet.get(caller);
2192     if (set == null) {
2193       set = new HashSet<MethodInvokeNode>();
2194       mapMethodDescriptorToMethodInvokeNodeSet.put(caller, set);
2195     }
2196     set.add(min);
2197   }
2198
2199   private void addParamNodeFlowingToReturnValue(MethodDescriptor md, FlowNode fn) {
2200
2201     if (!mapMethodDescToParamNodeFlowsToReturnValue.containsKey(md)) {
2202       mapMethodDescToParamNodeFlowsToReturnValue.put(md, new HashSet<FlowNode>());
2203     }
2204     mapMethodDescToParamNodeFlowsToReturnValue.get(md).add(fn);
2205   }
2206
2207   private Set<FlowNode> getParamNodeFlowingToReturnValue(MethodDescriptor md) {
2208     return mapMethodDescToParamNodeFlowsToReturnValue.get(md);
2209   }
2210
2211   private void analyzeFlowMethodInvokeNode(MethodDescriptor md, SymbolTable nametable,
2212       MethodInvokeNode min, NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
2213
2214     if (nodeSet == null) {
2215       nodeSet = new NodeTupleSet();
2216     }
2217
2218     addMapCallerMethodDescToMethodInvokeNodeSet(md, min);
2219
2220     MethodDescriptor calleeMethodDesc = min.getMethod();
2221
2222     NameDescriptor baseName = min.getBaseName();
2223     boolean isSystemout = false;
2224     if (baseName != null) {
2225       isSystemout = baseName.getSymbol().equals("System.out");
2226     }
2227
2228     if (!ssjava.isSSJavaUtil(calleeMethodDesc.getClassDesc())
2229         && !ssjava.isTrustMethod(calleeMethodDesc) && !calleeMethodDesc.getModifiers().isNative()
2230         && !isSystemout) {
2231
2232       FlowGraph calleeFlowGraph = getFlowGraph(calleeMethodDesc);
2233       Set<FlowNode> calleeReturnSet = calleeFlowGraph.getReturnNodeSet();
2234
2235       if (min.getExpression() != null) {
2236
2237         NodeTupleSet baseNodeSet = new NodeTupleSet();
2238         analyzeFlowExpressionNode(md, nametable, min.getExpression(), baseNodeSet, null,
2239             implicitFlowTupleSet, false);
2240
2241         if (!min.getMethod().isStatic()) {
2242           addArgIdxMap(min, 0, baseNodeSet);
2243
2244           for (Iterator iterator = calleeReturnSet.iterator(); iterator.hasNext();) {
2245             FlowNode returnNode = (FlowNode) iterator.next();
2246             NTuple<Descriptor> returnDescTuple = returnNode.getDescTuple();
2247             if (returnDescTuple.startsWith(calleeMethodDesc.getThis())) {
2248               // the location type of the return value is started with 'this'
2249               // reference
2250               for (Iterator<NTuple<Descriptor>> baseIter = baseNodeSet.iterator(); baseIter
2251                   .hasNext();) {
2252                 NTuple<Descriptor> baseTuple = baseIter.next();
2253                 NTuple<Descriptor> inFlowTuple = new NTuple<Descriptor>(baseTuple.getList());
2254                 inFlowTuple.addAll(returnDescTuple.subList(1, returnDescTuple.size()));
2255                 nodeSet.addTuple(inFlowTuple);
2256               }
2257             } else {
2258               Set<FlowNode> inFlowSet = calleeFlowGraph.getIncomingFlowNodeSet(returnNode);
2259               for (Iterator iterator2 = inFlowSet.iterator(); iterator2.hasNext();) {
2260                 FlowNode inFlowNode = (FlowNode) iterator2.next();
2261                 if (inFlowNode.getDescTuple().startsWith(calleeMethodDesc.getThis())) {
2262                   nodeSet.addTupleSet(baseNodeSet);
2263                 }
2264               }
2265             }
2266           }
2267         }
2268       }
2269
2270       // analyze parameter flows
2271
2272       if (min.numArgs() > 0) {
2273
2274         int offset;
2275         if (min.getMethod().isStatic()) {
2276           offset = 0;
2277         } else {
2278           offset = 1;
2279         }
2280
2281         for (int i = 0; i < min.numArgs(); i++) {
2282           ExpressionNode en = min.getArg(i);
2283           int idx = i + offset;
2284           NodeTupleSet argTupleSet = new NodeTupleSet();
2285           analyzeFlowExpressionNode(md, nametable, en, argTupleSet, false);
2286           // if argument is liternal node, argTuple is set to NULL.
2287           addArgIdxMap(min, idx, argTupleSet);
2288           FlowNode paramNode = calleeFlowGraph.getParamFlowNode(idx);
2289           if (hasInFlowTo(calleeFlowGraph, paramNode, calleeReturnSet)) {
2290             addParamNodeFlowingToReturnValue(calleeMethodDesc, paramNode);
2291             nodeSet.addTupleSet(argTupleSet);
2292           }
2293         }
2294
2295       }
2296
2297     }
2298
2299   }
2300
2301   private boolean hasInFlowTo(FlowGraph fg, FlowNode inNode, Set<FlowNode> nodeSet) {
2302     // return true if inNode has in-flows to nodeSet
2303     Set<FlowNode> reachableSet = fg.getReachableFlowNodeSet(inNode);
2304     for (Iterator iterator = reachableSet.iterator(); iterator.hasNext();) {
2305       FlowNode fn = (FlowNode) iterator.next();
2306       if (nodeSet.contains(fn)) {
2307         return true;
2308       }
2309     }
2310     return false;
2311   }
2312
2313   private NodeTupleSet getNodeTupleSetByArgIdx(MethodInvokeNode min, int idx) {
2314     return mapMethodInvokeNodeToArgIdxMap.get(min).get(new Integer(idx));
2315   }
2316
2317   private void addArgIdxMap(MethodInvokeNode min, int idx, NodeTupleSet tupleSet) {
2318     Map<Integer, NodeTupleSet> mapIdxToTupleSet = mapMethodInvokeNodeToArgIdxMap.get(min);
2319     if (mapIdxToTupleSet == null) {
2320       mapIdxToTupleSet = new HashMap<Integer, NodeTupleSet>();
2321       mapMethodInvokeNodeToArgIdxMap.put(min, mapIdxToTupleSet);
2322     }
2323     mapIdxToTupleSet.put(new Integer(idx), tupleSet);
2324   }
2325
2326   private void analyzeFlowMethodParameters(MethodDescriptor callermd, SymbolTable nametable,
2327       MethodInvokeNode min, NodeTupleSet nodeSet) {
2328
2329     if (min.numArgs() > 0) {
2330
2331       int offset;
2332       if (min.getMethod().isStatic()) {
2333         offset = 0;
2334       } else {
2335         offset = 1;
2336         // NTuple<Descriptor> thisArgTuple = new NTuple<Descriptor>();
2337         // thisArgTuple.add(callermd.getThis());
2338         // NodeTupleSet argTupleSet = new NodeTupleSet();
2339         // argTupleSet.addTuple(thisArgTuple);
2340         // addArgIdxMap(min, 0, argTupleSet);
2341         // nodeSet.addTuple(thisArgTuple);
2342       }
2343
2344       for (int i = 0; i < min.numArgs(); i++) {
2345         ExpressionNode en = min.getArg(i);
2346         NodeTupleSet argTupleSet = new NodeTupleSet();
2347         analyzeFlowExpressionNode(callermd, nametable, en, argTupleSet, false);
2348         // if argument is liternal node, argTuple is set to NULL.
2349         addArgIdxMap(min, i + offset, argTupleSet);
2350         nodeSet.addTupleSet(argTupleSet);
2351       }
2352
2353     }
2354
2355   }
2356
2357   private void analyzeLiteralNode(MethodDescriptor md, SymbolTable nametable, LiteralNode en) {
2358
2359   }
2360
2361   private void analyzeFlowArrayAccessNode(MethodDescriptor md, SymbolTable nametable,
2362       ArrayAccessNode aan, NodeTupleSet nodeSet, boolean isLHS) {
2363
2364     NodeTupleSet expNodeTupleSet = new NodeTupleSet();
2365     analyzeFlowExpressionNode(md, nametable, aan.getExpression(), expNodeTupleSet, isLHS);
2366
2367     NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
2368     analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, isLHS);
2369
2370     if (isLHS) {
2371       // need to create an edge from idx to array
2372       for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
2373         NTuple<Descriptor> idxTuple = idxIter.next();
2374         for (Iterator<NTuple<Descriptor>> arrIter = expNodeTupleSet.iterator(); arrIter.hasNext();) {
2375           NTuple<Descriptor> arrTuple = arrIter.next();
2376           getFlowGraph(md).addValueFlowEdge(idxTuple, arrTuple);
2377         }
2378       }
2379
2380       nodeSet.addTupleSet(expNodeTupleSet);
2381     } else {
2382       nodeSet.addTupleSet(expNodeTupleSet);
2383       nodeSet.addTupleSet(idxNodeTupleSet);
2384     }
2385   }
2386
2387   private void analyzeCreateObjectNode(MethodDescriptor md, SymbolTable nametable,
2388       CreateObjectNode en) {
2389     // TODO Auto-generated method stub
2390
2391   }
2392
2393   private void analyzeFlowOpNode(MethodDescriptor md, SymbolTable nametable, OpNode on,
2394       NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
2395
2396     NodeTupleSet leftOpSet = new NodeTupleSet();
2397     NodeTupleSet rightOpSet = new NodeTupleSet();
2398
2399     // left operand
2400     analyzeFlowExpressionNode(md, nametable, on.getLeft(), leftOpSet, null, implicitFlowTupleSet,
2401         false);
2402
2403     if (on.getRight() != null) {
2404       // right operand
2405       analyzeFlowExpressionNode(md, nametable, on.getRight(), rightOpSet, null,
2406           implicitFlowTupleSet, false);
2407     }
2408
2409     Operation op = on.getOp();
2410
2411     switch (op.getOp()) {
2412
2413     case Operation.UNARYPLUS:
2414     case Operation.UNARYMINUS:
2415     case Operation.LOGIC_NOT:
2416       // single operand
2417       nodeSet.addTupleSet(leftOpSet);
2418       break;
2419
2420     case Operation.LOGIC_OR:
2421     case Operation.LOGIC_AND:
2422     case Operation.COMP:
2423     case Operation.BIT_OR:
2424     case Operation.BIT_XOR:
2425     case Operation.BIT_AND:
2426     case Operation.ISAVAILABLE:
2427     case Operation.EQUAL:
2428     case Operation.NOTEQUAL:
2429     case Operation.LT:
2430     case Operation.GT:
2431     case Operation.LTE:
2432     case Operation.GTE:
2433     case Operation.ADD:
2434     case Operation.SUB:
2435     case Operation.MULT:
2436     case Operation.DIV:
2437     case Operation.MOD:
2438     case Operation.LEFTSHIFT:
2439     case Operation.RIGHTSHIFT:
2440     case Operation.URIGHTSHIFT:
2441
2442       // there are two operands
2443       nodeSet.addTupleSet(leftOpSet);
2444       nodeSet.addTupleSet(rightOpSet);
2445       break;
2446
2447     default:
2448       throw new Error(op.toString());
2449     }
2450
2451   }
2452
2453   private NTuple<Descriptor> analyzeFlowNameNode(MethodDescriptor md, SymbolTable nametable,
2454       NameNode nn, NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
2455
2456     if (base == null) {
2457       base = new NTuple<Descriptor>();
2458     }
2459
2460     NameDescriptor nd = nn.getName();
2461
2462     if (nd.getBase() != null) {
2463       base =
2464           analyzeFlowExpressionNode(md, nametable, nn.getExpression(), nodeSet, base,
2465               implicitFlowTupleSet, false);
2466       if (base == null) {
2467         // base node has the top location
2468         return base;
2469       }
2470     } else {
2471       String varname = nd.toString();
2472       if (varname.equals("this")) {
2473         // 'this' itself!
2474         base.add(md.getThis());
2475         return base;
2476       }
2477
2478       Descriptor d = (Descriptor) nametable.get(varname);
2479
2480       if (d instanceof VarDescriptor) {
2481         VarDescriptor vd = (VarDescriptor) d;
2482         base.add(vd);
2483       } else if (d instanceof FieldDescriptor) {
2484         // the type of field descriptor has a location!
2485         FieldDescriptor fd = (FieldDescriptor) d;
2486         if (fd.isStatic()) {
2487           if (fd.isFinal()) {
2488             // if it is 'static final', no need to have flow node for the TOP
2489             // location
2490             return null;
2491           } else {
2492             // if 'static', assign the default GLOBAL LOCATION to the first
2493             // element of the tuple
2494             base.add(GLOBALDESC);
2495           }
2496         } else {
2497           // the location of field access starts from this, followed by field
2498           // location
2499           base.add(md.getThis());
2500         }
2501
2502         base.add(fd);
2503       } else if (d == null) {
2504         // access static field
2505         base.add(GLOBALDESC);
2506         // base.add(nn.getField());
2507         return base;
2508
2509         // FieldDescriptor fd = nn.getField();addFlowGraphEdge
2510         //
2511         // MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
2512         // String globalLocId = localLattice.getGlobalLoc();
2513         // if (globalLocId == null) {
2514         // throw new
2515         // Error("Method lattice does not define global variable location at "
2516         // + generateErrorMessage(md.getClassDesc(), nn));
2517         // }
2518         // loc.addLocation(new Location(md, globalLocId));
2519         //
2520         // Location fieldLoc = (Location) fd.getType().getExtension();
2521         // loc.addLocation(fieldLoc);
2522         //
2523         // return loc;
2524
2525       }
2526     }
2527     getFlowGraph(md).createNewFlowNode(base);
2528
2529     return base;
2530
2531   }
2532
2533   private NTuple<Descriptor> analyzeFlowFieldAccessNode(MethodDescriptor md, SymbolTable nametable,
2534       FieldAccessNode fan, NodeTupleSet nodeSet, NTuple<Descriptor> base,
2535       NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
2536
2537     ExpressionNode left = fan.getExpression();
2538     TypeDescriptor ltd = left.getType();
2539     FieldDescriptor fd = fan.getField();
2540
2541     String varName = null;
2542     if (left.kind() == Kind.NameNode) {
2543       NameDescriptor nd = ((NameNode) left).getName();
2544       varName = nd.toString();
2545     }
2546
2547     if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
2548       // using a class name directly or access using this
2549       if (fd.isStatic() && fd.isFinal()) {
2550         return null;
2551       }
2552     }
2553
2554     NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
2555     if (left instanceof ArrayAccessNode) {
2556
2557       ArrayAccessNode aan = (ArrayAccessNode) left;
2558       left = aan.getExpression();
2559       analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, base,
2560           implicitFlowTupleSet, isLHS);
2561       nodeSet.addTupleSet(idxNodeTupleSet);
2562     }
2563     base =
2564         analyzeFlowExpressionNode(md, nametable, left, nodeSet, base, implicitFlowTupleSet, isLHS);
2565
2566     if (base == null) {
2567       // in this case, field is TOP location
2568       return null;
2569     } else {
2570
2571       NTuple<Descriptor> flowFieldTuple = new NTuple<Descriptor>(base.toList());
2572
2573       if (!left.getType().isPrimitive()) {
2574
2575         if (!fd.getSymbol().equals("length")) {
2576           // array.length access, just have the location of the array
2577           flowFieldTuple.add(fd);
2578           nodeSet.removeTuple(base);
2579         }
2580
2581       }
2582       getFlowGraph(md).createNewFlowNode(flowFieldTuple);
2583
2584       if (isLHS) {
2585         for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
2586           NTuple<Descriptor> idxTuple = idxIter.next();
2587           getFlowGraph(md).addValueFlowEdge(idxTuple, flowFieldTuple);
2588         }
2589       }
2590
2591       return flowFieldTuple;
2592
2593     }
2594
2595   }
2596
2597   private void debug_printTreeNode(TreeNode tn) {
2598
2599     System.out.println("DEBUG: " + tn.printNode(0) + "                line#=" + tn.getNumLine());
2600
2601   }
2602
2603   private void analyzeFlowAssignmentNode(MethodDescriptor md, SymbolTable nametable,
2604       AssignmentNode an, NodeTupleSet nodeSet, NTuple<Descriptor> base,
2605       NodeTupleSet implicitFlowTupleSet) {
2606
2607     NodeTupleSet nodeSetRHS = new NodeTupleSet();
2608     NodeTupleSet nodeSetLHS = new NodeTupleSet();
2609
2610     boolean postinc = true;
2611     if (an.getOperation().getBaseOp() == null
2612         || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
2613             .getBaseOp().getOp() != Operation.POSTDEC)) {
2614       postinc = false;
2615     }
2616     // if LHS is array access node, need to capture value flows between an array
2617     // and its index value
2618     analyzeFlowExpressionNode(md, nametable, an.getDest(), nodeSetLHS, null, implicitFlowTupleSet,
2619         true);
2620
2621     if (!postinc) {
2622       // analyze value flows of rhs expression
2623       analyzeFlowExpressionNode(md, nametable, an.getSrc(), nodeSetRHS, null, implicitFlowTupleSet,
2624           false);
2625
2626       // System.out.println("-analyzeFlowAssignmentNode=" + an.printNode(0));
2627       // System.out.println("-nodeSetLHS=" + nodeSetLHS);
2628       // System.out.println("-nodeSetRHS=" + nodeSetRHS);
2629       // System.out.println("-implicitFlowTupleSet=" + implicitFlowTupleSet);
2630       // System.out.println("-");
2631
2632       if (an.getOperation().getOp() >= 2 && an.getOperation().getOp() <= 12) {
2633         // if assignment contains OP+EQ operator, creates edges from LHS to LHS
2634         for (Iterator<NTuple<Descriptor>> iter = nodeSetLHS.iterator(); iter.hasNext();) {
2635           NTuple<Descriptor> fromTuple = iter.next();
2636           for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
2637             NTuple<Descriptor> toTuple = iter2.next();
2638             addFlowGraphEdge(md, fromTuple, toTuple);
2639           }
2640         }
2641       }
2642
2643       // creates edges from RHS to LHS
2644       for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
2645         NTuple<Descriptor> fromTuple = iter.next();
2646         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
2647           NTuple<Descriptor> toTuple = iter2.next();
2648           addFlowGraphEdge(md, fromTuple, toTuple);
2649         }
2650       }
2651
2652       // creates edges from implicitFlowTupleSet to LHS
2653       for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
2654         NTuple<Descriptor> fromTuple = iter.next();
2655         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
2656           NTuple<Descriptor> toTuple = iter2.next();
2657           addFlowGraphEdge(md, fromTuple, toTuple);
2658         }
2659       }
2660
2661     } else {
2662       // postinc case
2663       for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
2664         NTuple<Descriptor> tuple = iter2.next();
2665         addFlowGraphEdge(md, tuple, tuple);
2666       }
2667
2668       // creates edges from implicitFlowTupleSet to LHS
2669       for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
2670         NTuple<Descriptor> fromTuple = iter.next();
2671         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
2672           NTuple<Descriptor> toTuple = iter2.next();
2673           addFlowGraphEdge(md, fromTuple, toTuple);
2674         }
2675       }
2676
2677     }
2678
2679     if (nodeSet != null) {
2680       nodeSet.addTupleSet(nodeSetLHS);
2681     }
2682   }
2683
2684   public FlowGraph getFlowGraph(MethodDescriptor md) {
2685     return mapMethodDescriptorToFlowGraph.get(md);
2686   }
2687
2688   private boolean addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
2689       NTuple<Descriptor> to) {
2690     // TODO
2691     // return true if it adds a new edge
2692     FlowGraph graph = getFlowGraph(md);
2693     graph.addValueFlowEdge(from, to);
2694     return true;
2695   }
2696
2697   public void _debug_printGraph() {
2698     Set<MethodDescriptor> keySet = mapMethodDescriptorToFlowGraph.keySet();
2699
2700     for (Iterator<MethodDescriptor> iterator = keySet.iterator(); iterator.hasNext();) {
2701       MethodDescriptor md = (MethodDescriptor) iterator.next();
2702       FlowGraph fg = mapMethodDescriptorToFlowGraph.get(md);
2703       try {
2704         fg.writeGraph();
2705       } catch (IOException e) {
2706         e.printStackTrace();
2707       }
2708     }
2709
2710   }
2711
2712 }
2713
2714 class CyclicFlowException extends Exception {
2715
2716 }