changes.
[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.TypeUtil;
31 import IR.VarDescriptor;
32 import IR.Tree.ArrayAccessNode;
33 import IR.Tree.AssignmentNode;
34 import IR.Tree.BlockExpressionNode;
35 import IR.Tree.BlockNode;
36 import IR.Tree.BlockStatementNode;
37 import IR.Tree.CastNode;
38 import IR.Tree.CreateObjectNode;
39 import IR.Tree.DeclarationNode;
40 import IR.Tree.ExpressionNode;
41 import IR.Tree.FieldAccessNode;
42 import IR.Tree.IfStatementNode;
43 import IR.Tree.Kind;
44 import IR.Tree.LiteralNode;
45 import IR.Tree.LoopNode;
46 import IR.Tree.MethodInvokeNode;
47 import IR.Tree.NameNode;
48 import IR.Tree.OpNode;
49 import IR.Tree.ReturnNode;
50 import IR.Tree.SubBlockNode;
51 import IR.Tree.SwitchBlockNode;
52 import IR.Tree.SwitchStatementNode;
53 import IR.Tree.TertiaryNode;
54 import IR.Tree.TreeNode;
55 import Util.Pair;
56
57 public class LocationInference {
58
59   static int COUNT = 0;
60
61   State state;
62   SSJavaAnalysis ssjava;
63   TypeUtil tu;
64
65   List<ClassDescriptor> temp_toanalyzeList;
66   List<MethodDescriptor> temp_toanalyzeMethodList;
67   Map<MethodDescriptor, FlowGraph> mapMethodDescriptorToFlowGraph;
68
69   LinkedList<MethodDescriptor> toanalyze_methodDescList;
70   Set<ClassDescriptor> toanalyze_classDescSet;
71
72   // InheritanceTree<ClassDescriptor> inheritanceTree;
73
74   // map a method descriptor to its set of parameter descriptors
75   Map<MethodDescriptor, Set<Descriptor>> mapMethodDescriptorToParamDescSet;
76
77   // keep current descriptors to visit in fixed-point interprocedural analysis,
78   private Stack<MethodDescriptor> methodDescriptorsToVisitStack;
79
80   // map a descriptor to a naive lattice
81   private Map<Descriptor, SSJavaLattice<String>> desc2naiveLattice;
82
83   // map a class descriptor to a field lattice
84   private Map<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
85
86   // map a method descriptor to a method lattice
87   private Map<MethodDescriptor, SSJavaLattice<String>> md2lattice;
88
89   // map a method/class descriptor to a hierarchy graph
90   private Map<Descriptor, HierarchyGraph> mapDescriptorToHierarchyGraph;
91
92   // map a method/class descriptor to a skeleton hierarchy graph
93   private Map<Descriptor, HierarchyGraph> mapDescriptorToSkeletonHierarchyGraph;
94
95   private Map<Descriptor, HierarchyGraph> mapDescriptorToSimpleHierarchyGraph;
96
97   // map a method/class descriptor to a skeleton hierarchy graph with combination nodes
98   private Map<Descriptor, HierarchyGraph> mapDescriptorToCombineSkeletonHierarchyGraph;
99
100   // map a descriptor to a skeleton lattice
101   private Map<Descriptor, SSJavaLattice<String>> mapDescriptorToSkeletonLattice;
102
103   // map a method descriptor to the set of method invocation nodes which are
104   // invoked by the method descriptor
105   private Map<MethodDescriptor, Set<MethodInvokeNode>> mapMethodDescriptorToMethodInvokeNodeSet;
106
107   private Map<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>> mapMethodInvokeNodeToArgIdxMap;
108
109   private Map<MethodInvokeNode, NTuple<Descriptor>> mapMethodInvokeNodeToBaseTuple;
110
111   private Map<MethodInvokeNode, Set<NTuple<Location>>> mapMethodInvokeNodeToPCLocTupleSet;
112
113   private Map<MethodDescriptor, MethodLocationInfo> mapMethodDescToMethodLocationInfo;
114
115   private Map<ClassDescriptor, LocationInfo> mapClassToLocationInfo;
116
117   private Map<MethodDescriptor, Set<MethodDescriptor>> mapMethodToCalleeSet;
118
119   private Map<MethodDescriptor, Set<FlowNode>> mapMethodDescToParamNodeFlowsToReturnValue;
120
121   private Map<String, Vector<String>> mapFileNameToLineVector;
122
123   private Map<Descriptor, Integer> mapDescToDefinitionLine;
124
125   private Map<Descriptor, LocationSummary> mapDescToLocationSummary;
126
127   private Map<MethodDescriptor, Set<MethodInvokeNode>> mapMethodDescToMethodInvokeNodeSet;
128
129   // maps a method descriptor to a sub global flow graph that captures all value flows caused by the
130   // set of callees reachable from the method
131   private Map<MethodDescriptor, GlobalFlowGraph> mapMethodDescriptorToSubGlobalFlowGraph;
132
133   private Map<MethodInvokeNode, Map<NTuple<Descriptor>, NTuple<Descriptor>>> mapMethodInvokeNodeToMapCallerArgToCalleeArg;
134
135   private Map<MethodDescriptor, Boolean> mapMethodDescriptorToCompositeReturnCase;
136
137   private Map<MethodDescriptor, MethodDescriptor> mapMethodDescToHighestOverriddenMethodDesc;
138
139   private Map<MethodDescriptor, Set<MethodDescriptor>> mapHighestOverriddenMethodDescToMethodDescSet;
140
141   private Map<MethodDescriptor, NTuple<Descriptor>> mapHighestOverriddenMethodDescToReturnLocTuple;
142
143   private Map<MethodDescriptor, NTuple<Descriptor>> mapHighestOverriddenMethodDescToPCLocTuple;
144
145   private Map<MethodDescriptor, Set<NTuple<Descriptor>>> mapHighestOverriddenMethodDescToSetLowerThanPCLoc;
146
147   private Map<MethodDescriptor, Set<NTuple<Descriptor>>> mapHighestOverriddenMethodDescToSetHigherThanRETURNLoc;
148
149   public static final String GLOBALLOC = "GLOBALLOC";
150
151   public static final String INTERLOC = "INTERLOC";
152
153   public static final String PCLOC = "_PCLOC_";
154
155   public static final String RLOC = "_RLOC_";
156
157   public static final Descriptor GLOBALDESC = new NameDescriptor(GLOBALLOC);
158
159   public static final Descriptor TOPDESC = new NameDescriptor(SSJavaAnalysis.TOP);
160
161   public static final Descriptor BOTTOMDESC = new NameDescriptor(SSJavaAnalysis.BOTTOM);
162
163   public static final Descriptor RETURNLOC = new NameDescriptor(RLOC);
164
165   public static final Descriptor LITERALDESC = new NameDescriptor("LITERAL");
166
167   public static final HNode TOPHNODE = new HNode(TOPDESC);
168
169   public static final HNode BOTTOMHNODE = new HNode(BOTTOMDESC);
170
171   public static String newline = System.getProperty("line.separator");
172
173   LocationInfo curMethodInfo;
174
175   private boolean hasChanges = false;
176
177   boolean debug = true;
178
179   public static int locSeed = 0;
180
181   private Stack<String> arrayAccessNodeStack;
182
183   private ClassDescriptor rootClassDescriptor;
184
185   private BuildLattice buildLattice;
186
187   public static int numLocationsSInfer = 0;
188   public static int numLocationsNaive = 0;
189
190   public LocationInference(SSJavaAnalysis ssjava, State state, TypeUtil tu) {
191     this.ssjava = ssjava;
192     this.state = state;
193     this.tu = tu;
194     this.toanalyze_classDescSet = new HashSet<ClassDescriptor>();
195     this.temp_toanalyzeList = new ArrayList<ClassDescriptor>();
196     this.temp_toanalyzeMethodList = new ArrayList<MethodDescriptor>();
197     this.mapMethodDescriptorToFlowGraph = new HashMap<MethodDescriptor, FlowGraph>();
198     this.cd2lattice = new HashMap<ClassDescriptor, SSJavaLattice<String>>();
199     this.md2lattice = new HashMap<MethodDescriptor, SSJavaLattice<String>>();
200     this.desc2naiveLattice = new HashMap<Descriptor, SSJavaLattice<String>>();
201
202     this.methodDescriptorsToVisitStack = new Stack<MethodDescriptor>();
203     this.mapMethodDescriptorToMethodInvokeNodeSet =
204         new HashMap<MethodDescriptor, Set<MethodInvokeNode>>();
205     this.mapMethodInvokeNodeToArgIdxMap =
206         new HashMap<MethodInvokeNode, Map<Integer, NTuple<Descriptor>>>();
207     this.mapMethodDescToMethodLocationInfo = new HashMap<MethodDescriptor, MethodLocationInfo>();
208     this.mapMethodToCalleeSet = new HashMap<MethodDescriptor, Set<MethodDescriptor>>();
209     this.mapClassToLocationInfo = new HashMap<ClassDescriptor, LocationInfo>();
210
211     this.mapFileNameToLineVector = new HashMap<String, Vector<String>>();
212     this.mapDescToDefinitionLine = new HashMap<Descriptor, Integer>();
213     this.mapMethodDescToParamNodeFlowsToReturnValue =
214         new HashMap<MethodDescriptor, Set<FlowNode>>();
215
216     this.mapDescriptorToHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
217     this.mapMethodInvokeNodeToBaseTuple = new HashMap<MethodInvokeNode, NTuple<Descriptor>>();
218
219     this.mapDescriptorToSkeletonHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
220     this.mapDescriptorToCombineSkeletonHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
221     this.mapDescriptorToSimpleHierarchyGraph = new HashMap<Descriptor, HierarchyGraph>();
222
223     this.mapDescriptorToSkeletonLattice = new HashMap<Descriptor, SSJavaLattice<String>>();
224
225     this.mapDescToLocationSummary = new HashMap<Descriptor, LocationSummary>();
226
227     this.mapMethodDescriptorToSubGlobalFlowGraph = new HashMap<MethodDescriptor, GlobalFlowGraph>();
228
229     this.mapMethodInvokeNodeToMapCallerArgToCalleeArg =
230         new HashMap<MethodInvokeNode, Map<NTuple<Descriptor>, NTuple<Descriptor>>>();
231
232     this.mapMethodInvokeNodeToPCLocTupleSet =
233         new HashMap<MethodInvokeNode, Set<NTuple<Location>>>();
234
235     this.arrayAccessNodeStack = new Stack<String>();
236
237     this.mapMethodDescToMethodInvokeNodeSet =
238         new HashMap<MethodDescriptor, Set<MethodInvokeNode>>();
239
240     this.mapMethodDescriptorToCompositeReturnCase = new HashMap<MethodDescriptor, Boolean>();
241
242     mapMethodDescToHighestOverriddenMethodDesc = new HashMap<MethodDescriptor, MethodDescriptor>();
243
244     mapHighestOverriddenMethodDescToSetLowerThanPCLoc =
245         new HashMap<MethodDescriptor, Set<NTuple<Descriptor>>>();
246
247     mapHighestOverriddenMethodDescToMethodDescSet =
248         new HashMap<MethodDescriptor, Set<MethodDescriptor>>();
249
250     mapHighestOverriddenMethodDescToReturnLocTuple =
251         new HashMap<MethodDescriptor, NTuple<Descriptor>>();
252
253     mapHighestOverriddenMethodDescToPCLocTuple =
254         new HashMap<MethodDescriptor, NTuple<Descriptor>>();
255
256     mapHighestOverriddenMethodDescToSetHigherThanRETURNLoc =
257         new HashMap<MethodDescriptor, Set<NTuple<Descriptor>>>();
258
259     this.buildLattice = new BuildLattice(this);
260
261   }
262
263   public void setupToAnalyze() {
264     SymbolTable classtable = state.getClassSymbolTable();
265     temp_toanalyzeList.clear();
266     temp_toanalyzeList.addAll(classtable.getValueSet());
267     // Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
268     // public int compare(ClassDescriptor o1, ClassDescriptor o2) {
269     // return o1.getClassName().compareToIgnoreCase(o2.getClassName());
270     // }
271     // });
272   }
273
274   public void setupToAnalazeMethod(ClassDescriptor cd) {
275
276     SymbolTable methodtable = cd.getMethodTable();
277     temp_toanalyzeMethodList.clear();
278     temp_toanalyzeMethodList.addAll(methodtable.getValueSet());
279     Collections.sort(temp_toanalyzeMethodList, new Comparator<MethodDescriptor>() {
280       public int compare(MethodDescriptor o1, MethodDescriptor o2) {
281         return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
282       }
283     });
284   }
285
286   public boolean toAnalyzeMethodIsEmpty() {
287     return temp_toanalyzeMethodList.isEmpty();
288   }
289
290   public boolean toAnalyzeIsEmpty() {
291     return temp_toanalyzeList.isEmpty();
292   }
293
294   public ClassDescriptor toAnalyzeNext() {
295     return temp_toanalyzeList.remove(0);
296   }
297
298   public MethodDescriptor toAnalyzeMethodNext() {
299     return temp_toanalyzeMethodList.remove(0);
300   }
301
302   public void inference() {
303
304     ssjava.init();
305
306     // construct value flow graph
307     constructFlowGraph();
308
309     constructGlobalFlowGraph();
310
311     checkReturnNodes();
312
313     assignCompositeLocation();
314     updateFlowGraph();
315     calculateExtraLocations();
316     addAdditionalOrderingConstraints();
317
318     _debug_writeFlowGraph();
319
320     buildInheritanceTree();
321     calculateReturnPCLocInheritance();
322
323     constructHierarchyGraph();
324
325     addInheritanceConstraintsToHierarchyGraph();
326
327     debug_writeHierarchyDotFiles();
328
329     simplifyHierarchyGraph();
330
331     debug_writeSimpleHierarchyDotFiles();
332
333     constructSkeletonHierarchyGraph();
334
335     debug_writeSkeletonHierarchyDotFiles();
336
337     insertCombinationNodes();
338
339     debug_writeSkeletonCombinationHierarchyDotFiles();
340
341     buildLatticeInheritanceTree();
342     // buildLattice();
343
344     debug_writeLattices();
345
346     updateCompositeLocationAssignments();
347
348     generateMethodSummary();
349
350     generateAnnoatedCode();
351
352     for (Iterator iterator = cd2lattice.keySet().iterator(); iterator.hasNext();) {
353       ClassDescriptor cd = (ClassDescriptor) iterator.next();
354       SSJavaLattice<String> lattice = getLattice(cd);
355       HierarchyGraph hg = mapDescriptorToHierarchyGraph.get(cd);
356       // System.out.println("~~~\t" + cd + "\t" + lattice.getKeySet().size() + "\t"
357       // + hg.getNodeSet().size());
358     }
359
360     for (Iterator iterator = md2lattice.keySet().iterator(); iterator.hasNext();) {
361       MethodDescriptor md = (MethodDescriptor) iterator.next();
362       SSJavaLattice<String> locOrder = getLattice(md);
363       // writeLatticeDotFile(md.getClassDesc(), md, getMethodLattice(md));
364       HierarchyGraph hg = mapDescriptorToHierarchyGraph.get(md);
365       // System.out.println("~~~\t" + md.getClassDesc() + "_" + md + "\t"
366       // + locOrder.getKeySet().size() + "\t" + hg.getNodeSet().size());
367     }
368
369     if (state.SSJAVA_INFER_NAIVE_WRITEDOTS) {
370       System.out.println("The number of elements: Naive=" + numLocationsNaive);
371     }
372     System.out.println("The number of elements: SInfer=" + numLocationsSInfer);
373
374     System.exit(0);
375
376   }
377
378   private void calculateReturnPCLocInheritance() {
379     calculateHighestPCLocInheritance();
380     calculateLowestReturnLocInheritance();
381     updateFlowGraphPCReturnLocInheritance();
382   }
383
384   private void updateFlowGraphPCReturnLocInheritance() {
385
386     Set<MethodDescriptor> keySet = mapHighestOverriddenMethodDescToMethodDescSet.keySet();
387     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
388       MethodDescriptor highestMethodDesc = (MethodDescriptor) iterator.next();
389
390       if (mapHighestOverriddenMethodDescToMethodDescSet.get(highestMethodDesc).size() == 1) {
391         continue;
392       }
393
394       Set<MethodDescriptor> methodDescSet =
395           mapHighestOverriddenMethodDescToMethodDescSet.get(highestMethodDesc);
396
397       NTuple<Descriptor> highestPCLocDescTuple =
398           mapHighestOverriddenMethodDescToPCLocTuple.get(highestMethodDesc);
399
400       NTuple<Descriptor> highestRETURNLocDescTuple =
401           mapHighestOverriddenMethodDescToReturnLocTuple.get(highestMethodDesc);
402
403       // System.out.println("\n$$$$$$$$$$$$$$$$updateFlowGraphPCReturnLocInheritance="
404       // + highestMethodDesc);
405       // System.out.println("-----highestPCLoc=" + highestPCLocDescTuple);
406       // System.out.println("-----highestRETURNLoc=" + highestRETURNLocDescTuple);
407
408       for (Iterator iterator2 = methodDescSet.iterator(); iterator2.hasNext();) {
409         MethodDescriptor md = (MethodDescriptor) iterator2.next();
410         // System.out.println("\n --------MD=" + md);
411         FlowGraph flowGraph = getFlowGraph(md);
412
413         MethodSummary summary = getMethodSummary(md);
414         CompositeLocation curPCLoc = summary.getPCLoc();
415         NTuple<Descriptor> curPCDescTuple = translateToDescTuple(curPCLoc.getTuple());
416         // System.out.println("md=" + md + "  curPCLoc=" + curPCLoc);
417         // System.out.println("highestPCLoc=" + highestPCLocDescTuple);
418
419         if (highestPCLocDescTuple == null) {
420           // this case: PCLOC is top
421           // System.out.println("###SET PCLOC AS TOP");
422           if (curPCDescTuple != null && !curPCLoc.get(0).isTop()) {
423             FlowNode pcFlowNode = flowGraph.getFlowNode(curPCDescTuple);
424             flowGraph.removeNode(pcFlowNode);
425           }
426           summary.setPCLoc(new CompositeLocation(new Location(md, Location.TOP)));
427         } else {
428           NTuple<Descriptor> newPCDescTuple = new NTuple<Descriptor>();
429           if (highestPCLocDescTuple.size() == 1) {
430             newPCDescTuple.add(highestPCLocDescTuple.get(0));
431           } else {
432             newPCDescTuple.add(md.getThis());
433             newPCDescTuple.add(highestPCLocDescTuple.get(1));
434           }
435           if (!curPCDescTuple.equals(newPCDescTuple)) {
436             FlowNode pcFlowNode = flowGraph.getFlowNode(curPCDescTuple);
437             flowGraph.updateTuple(pcFlowNode, newPCDescTuple);
438             // flowGraph.removeNode(pcFlowNode);
439             Set<NTuple<Descriptor>> descSetLowerThanPCLoc =
440                 mapHighestOverriddenMethodDescToSetLowerThanPCLoc.get(highestMethodDesc);
441             for (Iterator iterator3 = descSetLowerThanPCLoc.iterator(); iterator3.hasNext();) {
442               NTuple<Descriptor> lowerNTuple = (NTuple<Descriptor>) iterator3.next();
443               flowGraph.addValueFlowEdge(newPCDescTuple, lowerNTuple);
444             }
445             CompositeLocation newPCCompLoc =
446                 new CompositeLocation(translateToLocTuple(md, newPCDescTuple));
447             summary.setPCLoc(newPCCompLoc);
448           }
449
450         }
451
452         // update return loc
453         if (highestRETURNLocDescTuple != null) {
454           CompositeLocation curRETURNLoc = summary.getRETURNLoc();
455           NTuple<Descriptor> curReturnDescTuple = translateToDescTuple(curRETURNLoc.getTuple());
456
457           if (!curReturnDescTuple.equals(highestRETURNLocDescTuple)) {
458             // handle the case that RETURNLOC is started with 'this'...
459             NTuple<Descriptor> newRETURNLocDescTuple = new NTuple<Descriptor>();
460             if (highestRETURNLocDescTuple.size() == 1) {
461               newRETURNLocDescTuple.add(highestRETURNLocDescTuple.get(0));
462             } else {
463               newRETURNLocDescTuple.add(md.getThis());
464               newRETURNLocDescTuple.add(highestRETURNLocDescTuple.get(1));
465             }
466
467             FlowNode returnFlowNode = flowGraph.getFlowNode(curReturnDescTuple);
468             flowGraph.updateTuple(returnFlowNode, newRETURNLocDescTuple);
469
470             Set<NTuple<Descriptor>> descSetHigherThanRETURNLoc =
471                 mapHighestOverriddenMethodDescToSetHigherThanRETURNLoc.get(highestMethodDesc);
472             for (Iterator iterator3 = descSetHigherThanRETURNLoc.iterator(); iterator3.hasNext();) {
473               NTuple<Descriptor> higherNTuple = (NTuple<Descriptor>) iterator3.next();
474               flowGraph.addValueFlowEdge(higherNTuple, newRETURNLocDescTuple);
475             }
476
477             CompositeLocation newRETURNLocCompLoc =
478                 new CompositeLocation(translateToLocTuple(md, newRETURNLocDescTuple));
479             summary.setRETURNLoc(newRETURNLocCompLoc);
480           }
481         }
482       }
483     }
484   }
485
486   private void calculateHighestPCLocInheritance() {
487
488     Set<MethodDescriptor> keySet = mapHighestOverriddenMethodDescToMethodDescSet.keySet();
489
490     Map<MethodDescriptor, Integer> mapMethodDescToParamCount =
491         new HashMap<MethodDescriptor, Integer>();
492
493     next: for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
494       MethodDescriptor highestMethodDesc = (MethodDescriptor) iterator.next();
495
496       NTuple<Descriptor> tempTuple = null;
497
498       if (getMethodSummary(highestMethodDesc).getPCLoc() != null) {
499
500         Set<MethodDescriptor> methodDescSet =
501             mapHighestOverriddenMethodDescToMethodDescSet.get(highestMethodDesc);
502
503         if (methodDescSet.size() > 1) {
504           // System.out.println("---method desc set=" + methodDescSet + "  from=" +
505           // highestMethodDesc);
506         } else {
507           continue next;
508         }
509
510         for (Iterator iterator2 = methodDescSet.iterator(); iterator2.hasNext();) {
511           MethodDescriptor md = (MethodDescriptor) iterator2.next();
512
513           FlowGraph flowGraph = getFlowGraph(md);
514           if (flowGraph == null) {
515             continue;
516           }
517           Set<FlowNode> paramNodeSet = flowGraph.getParamFlowNodeSet();
518           // System.out.println("###md=" + md + "   paramNodeSet=" + paramNodeSet);
519
520           CompositeLocation pcLOC = getMethodSummary(md).getPCLoc();
521           // System.out.println("---pcLOC=" + pcLOC);
522
523           if (md.equals(highestMethodDesc)) {
524             mapHighestOverriddenMethodDescToPCLocTuple.put(highestMethodDesc,
525                 translateToDescTuple(pcLOC.getTuple()));
526           }
527
528           if (!pcLOC.get(0).isTop()) {
529
530             FlowNode pcFlowNode = flowGraph.getFlowNode(translateToDescTuple(pcLOC.getTuple()));
531
532             int count = 0;
533             for (Iterator iterator3 = paramNodeSet.iterator(); iterator3.hasNext();) {
534               FlowNode paramNode = (FlowNode) iterator3.next();
535               if (flowGraph.getReachableSetFrom(pcFlowNode.getCurrentDescTuple().subList(0, 1))
536                   .contains(paramNode)) {
537                 count++;
538               }
539             }
540             mapMethodDescToParamCount.put(md, count);
541
542           } else {
543
544             // the PC location is top
545             // if one of pcloc among the method inheritance chain has the TOP,
546             // all methods in the same chain should have the TOP.
547             mapHighestOverriddenMethodDescToPCLocTuple.remove(highestMethodDesc);
548             // System.out.println("highest=" + highestMethodDesc + "  HIGHEST PCLOC="
549             // + mapHighestOverriddenMethodDescToPCLocTuple.get(highestMethodDesc));
550
551             Set<NTuple<Descriptor>> descTupleSetLowerThanPC = new HashSet<NTuple<Descriptor>>();
552             for (Iterator iterator3 = paramNodeSet.iterator(); iterator3.hasNext();) {
553               FlowNode flowNode = (FlowNode) iterator3.next();
554               descTupleSetLowerThanPC.add(flowNode.getCurrentDescTuple());
555             }
556             mapHighestOverriddenMethodDescToSetLowerThanPCLoc.put(highestMethodDesc,
557                 descTupleSetLowerThanPC);
558
559             continue next;
560           }
561         }
562
563         // identify which method in the inheritance chain has the highest PCLOC
564         // basically, finds a method that has the highest count or TOP location
565         int highestCount = -1;
566         MethodDescriptor methodDescHighestCount = null;
567         for (Iterator iterator2 = methodDescSet.iterator(); iterator2.hasNext();) {
568           MethodDescriptor methodDesc = (MethodDescriptor) iterator2.next();
569           if (mapMethodDescToParamCount.containsKey(methodDesc)) {
570             int curCount = mapMethodDescToParamCount.get(methodDesc).intValue();
571             if (highestCount < curCount) {
572               highestCount = curCount;
573               methodDescHighestCount = methodDesc;
574             }
575           }
576         }
577
578         if (methodDescHighestCount != null) {
579           FlowGraph flowGraph = getFlowGraph(methodDescHighestCount);
580           CompositeLocation pcLOC = getMethodSummary(methodDescHighestCount).getPCLoc();
581           FlowNode pcFlowNode = flowGraph.getFlowNode(translateToDescTuple(pcLOC.getTuple()));
582           Set<FlowNode> reachableSet =
583               flowGraph.getReachableSetFrom(pcFlowNode.getCurrentDescTuple().subList(0, 1));
584
585           Set<FlowNode> reachableParamNodeSet = new HashSet<FlowNode>();
586           for (Iterator iterator3 = reachableSet.iterator(); iterator3.hasNext();) {
587             FlowNode flowNode = (FlowNode) iterator3.next();
588             if (flowGraph.isParameter(flowNode.getCurrentDescTuple())) {
589               reachableParamNodeSet.add(flowNode);
590             }
591
592           }
593
594           Set<NTuple<Descriptor>> descTupleSetLowerThanPC = new HashSet<NTuple<Descriptor>>();
595           for (Iterator iterator2 = reachableParamNodeSet.iterator(); iterator2.hasNext();) {
596             FlowNode flowNode = (FlowNode) iterator2.next();
597             descTupleSetLowerThanPC.add(flowNode.getCurrentDescTuple());
598           }
599
600           // mapHighestOverriddenMethodDescToPCLocTuple.remove(highestMethodDesc);
601           mapHighestOverriddenMethodDescToSetLowerThanPCLoc.put(highestMethodDesc,
602               descTupleSetLowerThanPC);
603         }
604
605       }
606
607       // System.out.println("####################################");
608       // System.out.println("  highest=" + highestMethodDesc + "  HIGHEST PCLOC="
609       // + mapHighestOverriddenMethodDescToPCLocTuple.get(highestMethodDesc));
610       // System.out.println("  setLowerThanPCLoc="
611       // + mapHighestOverriddenMethodDescToSetLowerThanPCLoc.get(highestMethodDesc));
612     }
613
614   }
615
616   private void calculateLowestReturnLocInheritance() {
617
618     Set<MethodDescriptor> keySet = mapHighestOverriddenMethodDescToMethodDescSet.keySet();
619
620     Map<MethodDescriptor, Integer> mapMethodDescToParamCount =
621         new HashMap<MethodDescriptor, Integer>();
622
623     next: for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
624       MethodDescriptor highestMethodDesc = (MethodDescriptor) iterator.next();
625
626       Set<MethodDescriptor> methodDescSet =
627           mapHighestOverriddenMethodDescToMethodDescSet.get(highestMethodDesc);
628
629       if (methodDescSet.size() > 1 && getMethodSummary(highestMethodDesc).getRETURNLoc() != null) {
630       } else {
631         continue next;
632       }
633
634       for (Iterator iterator2 = methodDescSet.iterator(); iterator2.hasNext();) {
635         MethodDescriptor md = (MethodDescriptor) iterator2.next();
636
637         FlowGraph flowGraph = getFlowGraph(md);
638         Set<FlowNode> paramNodeSet = flowGraph.getParamFlowNodeSet();
639
640         CompositeLocation returnLoc = getMethodSummary(md).getRETURNLoc();
641
642         FlowNode returnFlowNode = flowGraph.getFlowNode(translateToDescTuple(returnLoc.getTuple()));
643
644         int count = 0;
645         for (Iterator iterator3 = paramNodeSet.iterator(); iterator3.hasNext();) {
646           FlowNode paramNode = (FlowNode) iterator3.next();
647           if (flowGraph.getReachableSetFrom(paramNode.getCurrentDescTuple().subList(0, 1))
648               .contains(returnFlowNode)) {
649             count++;
650           }
651         }
652         mapMethodDescToParamCount.put(md, count);
653         // System.out.println("###returnLoc=" + returnLoc + "    count higher=" + count);
654       }
655
656       // identify which method in the inheritance chain has the highest PCLOC
657       // basically, finds a method that has the highest count or TOP location
658       int highestCount = -1;
659       MethodDescriptor methodDescHighestCount = null;
660       for (Iterator iterator2 = methodDescSet.iterator(); iterator2.hasNext();) {
661         MethodDescriptor methodDesc = (MethodDescriptor) iterator2.next();
662         int curCount = mapMethodDescToParamCount.get(methodDesc).intValue();
663         if (highestCount < curCount) {
664           highestCount = curCount;
665           methodDescHighestCount = methodDesc;
666         }
667       }
668
669       if (methodDescHighestCount != null) {
670         FlowGraph flowGraph = getFlowGraph(methodDescHighestCount);
671         CompositeLocation returnLOC = getMethodSummary(methodDescHighestCount).getRETURNLoc();
672         NTuple<Descriptor> returnLocTuple = translateToDescTuple(returnLOC.getTuple());
673         FlowNode returnFlowNode = flowGraph.getFlowNode(returnLocTuple);
674
675         Set<FlowNode> curMethodParamNodeSet = flowGraph.getParamFlowNodeSet();
676         Set<NTuple<Descriptor>> descTupleSetHigherThanPC = new HashSet<NTuple<Descriptor>>();
677         for (Iterator iterator3 = curMethodParamNodeSet.iterator(); iterator3.hasNext();) {
678           FlowNode paramNode = (FlowNode) iterator3.next();
679           if (flowGraph.getReachableSetFrom(paramNode.getCurrentDescTuple().subList(0, 1))
680               .contains(returnFlowNode)) {
681             descTupleSetHigherThanPC.add(paramNode.getCurrentDescTuple());
682           }
683         }
684
685         mapHighestOverriddenMethodDescToReturnLocTuple.put(highestMethodDesc, returnLocTuple);
686         mapHighestOverriddenMethodDescToSetHigherThanRETURNLoc.put(highestMethodDesc,
687             descTupleSetHigherThanPC);
688
689       }
690
691       // System.out.println("####################################");
692       // System.out.println("  highest=" + highestMethodDesc + "  LOWEST RETURNLOC="
693       // + mapHighestOverriddenMethodDescToReturnLocTuple.get(highestMethodDesc));
694       // System.out.println("  setHigherThanReturnLoc="
695       // + mapHighestOverriddenMethodDescToSetHigherThanRETURNLoc.get(highestMethodDesc));
696
697     }
698
699   }
700
701   private void addMapHighestMethodDescToMethodDesc(MethodDescriptor highest, MethodDescriptor md) {
702     if (!mapHighestOverriddenMethodDescToMethodDescSet.containsKey(highest)) {
703       mapHighestOverriddenMethodDescToMethodDescSet.put(highest, new HashSet<MethodDescriptor>());
704     }
705     mapHighestOverriddenMethodDescToMethodDescSet.get(highest).add(md);
706   }
707
708   private void DFSInheritanceTreeCalculatingHighestOverriddenMethod(ClassDescriptor cd) {
709
710     // ClassDescriptor cd = node.getData();
711
712     for (Iterator iterator = cd.getMethods(); iterator.hasNext();) {
713       MethodDescriptor md = (MethodDescriptor) iterator.next();
714       MethodDescriptor highestMethodDesc = getHighestOverriddenMethod(md.getClassDesc(), md);
715       mapMethodDescToHighestOverriddenMethodDesc.put(md, highestMethodDesc);
716       addMapHighestMethodDescToMethodDesc(highestMethodDesc, md);
717
718     }
719
720     // traverse children
721     Set<ClassDescriptor> children = getDirectSubClasses(cd);
722     for (Iterator iterator = children.iterator(); iterator.hasNext();) {
723       ClassDescriptor child = (ClassDescriptor) iterator.next();
724       DFSInheritanceTreeCalculatingHighestOverriddenMethod(child);
725     }
726
727   }
728
729   private MethodDescriptor getHighestOverriddenMethod(ClassDescriptor curClassDesc,
730       MethodDescriptor curMethodDesc) {
731
732     // Node<ClassDescriptor> curNode = inheritanceTree.getTreeNode(curClassDesc);
733     // Node<ClassDescriptor> parentNode = curNode.getParent();
734     ClassDescriptor parentClassDesc = curClassDesc.getSuperDesc();
735
736     if (parentClassDesc != null) {
737       if (parentClassDesc.getMethodTable().contains(curMethodDesc.getSymbol())) {
738         Set<MethodDescriptor> methodDescSet =
739             parentClassDesc.getMethodTable().getSet(curMethodDesc.getSymbol());
740         for (Iterator iterator = methodDescSet.iterator(); iterator.hasNext();) {
741           MethodDescriptor md = (MethodDescriptor) iterator.next();
742           if (md.matches(curMethodDesc)) {
743             return getHighestOverriddenMethod(parentClassDesc, md);
744           }
745         }
746       }
747       // traverse to the parent!
748       return getHighestOverriddenMethod(parentClassDesc, curMethodDesc);
749     }
750     return curMethodDesc;
751   }
752
753   private void buildInheritanceTree() {
754
755     DFSInheritanceTreeCalculatingHighestOverriddenMethod(rootClassDescriptor);
756
757   }
758
759   private void addInheritanceConstraintsToHierarchyGraph() {
760
761     // DFS the inheritance tree and propagates nodes/edges of parent to child
762
763     // Node<ClassDescriptor> rootNode = inheritanceTree.getRootNode();
764     DFSInheritanceTree(rootClassDescriptor);
765
766   }
767
768   private void DFSInheritanceTree(ClassDescriptor parentClassDescriptor) {
769
770     // ClassDescriptor parentClassDescriptor = parentNode.getData();
771
772     Set<ClassDescriptor> children = getDirectSubClasses(parentClassDescriptor);
773     for (Iterator iterator = children.iterator(); iterator.hasNext();) {
774       ClassDescriptor childClassDescriptor = (ClassDescriptor) iterator.next();
775
776       HierarchyGraph parentGraph = getHierarchyGraph(parentClassDescriptor);
777       HierarchyGraph childGraph = getHierarchyGraph(childClassDescriptor);
778
779       Set<HNode> parentNodeSet = parentGraph.getNodeSet();
780       for (Iterator iterator2 = parentNodeSet.iterator(); iterator2.hasNext();) {
781         HNode hNode = (HNode) iterator2.next();
782         childGraph.addNode(hNode);
783       }
784
785       // copies extra information from the parent hierarchy graph
786       Map<HNode, Set<HNode>> parentMergeNodeMap = parentGraph.getMapHNodetoMergeSet();
787       Map<HNode, Set<HNode>> childMergeNodeMap = childGraph.getMapHNodetoMergeSet();
788
789       Set<HNode> keySet = parentMergeNodeMap.keySet();
790       for (Iterator iterator2 = keySet.iterator(); iterator2.hasNext();) {
791         HNode parentKey = (HNode) iterator2.next();
792         if (!childMergeNodeMap.containsKey(parentKey)) {
793           childMergeNodeMap.put(parentKey, new HashSet<HNode>());
794         }
795         childMergeNodeMap.get(parentKey).addAll(parentMergeNodeMap.get(parentKey));
796       }
797
798       // copies nodes/edges from the parent class...
799       for (Iterator iterator2 = parentNodeSet.iterator(); iterator2.hasNext();) {
800         HNode parentHNode = (HNode) iterator2.next();
801
802         Set<HNode> parentIncomingHNode = parentGraph.getIncomingNodeSet(parentHNode);
803         Set<HNode> parentOutgoingHNode = parentGraph.getOutgoingNodeSet(parentHNode);
804
805         for (Iterator iterator3 = parentIncomingHNode.iterator(); iterator3.hasNext();) {
806           HNode inHNode = (HNode) iterator3.next();
807           childGraph.addEdge(inHNode.getDescriptor(), parentHNode.getDescriptor());
808         }
809
810         for (Iterator iterator3 = parentOutgoingHNode.iterator(); iterator3.hasNext();) {
811           HNode outHNode = (HNode) iterator3.next();
812           childGraph.addEdge(parentHNode.getDescriptor(), outHNode.getDescriptor());
813         }
814
815       }
816
817       // copies nodes/edges from parent methods to overridden methods
818
819       for (Iterator iterator3 = childClassDescriptor.getMethods(); iterator3.hasNext();) {
820         MethodDescriptor childMethodDescriptor = (MethodDescriptor) iterator3.next();
821
822         MethodDescriptor parentMethodDesc =
823             getParentMethodDesc(childMethodDescriptor.getClassDesc(), childMethodDescriptor);
824
825         if (parentMethodDesc != null) {
826
827           HierarchyGraph parentMethodGraph = getHierarchyGraph(parentMethodDesc);
828           HierarchyGraph childMethodGraph = getHierarchyGraph(childMethodDescriptor);
829
830           Set<HNode> parentMethodNodeSet = parentMethodGraph.getNodeSet();
831           for (Iterator iterator2 = parentMethodNodeSet.iterator(); iterator2.hasNext();) {
832             HNode hNode = (HNode) iterator2.next();
833             childMethodGraph.addNode(hNode);
834           }
835
836           // copies extra information from the parent hierarchy graph
837           Map<HNode, Set<HNode>> parentMethodMergeNodeMap =
838               parentMethodGraph.getMapHNodetoMergeSet();
839           Map<HNode, Set<HNode>> childMethodMergeNodeMap = childMethodGraph.getMapHNodetoMergeSet();
840
841           Set<HNode> methodKeySet = parentMethodMergeNodeMap.keySet();
842           for (Iterator iterator2 = methodKeySet.iterator(); iterator2.hasNext();) {
843             HNode parentKey = (HNode) iterator2.next();
844             if (!childMethodMergeNodeMap.containsKey(parentKey)) {
845               childMethodMergeNodeMap.put(parentKey, new HashSet<HNode>());
846             }
847             childMethodMergeNodeMap.get(parentKey).addAll(parentMethodMergeNodeMap.get(parentKey));
848           }
849
850           // copies nodes/edges from the parent method...
851           for (Iterator iterator2 = parentMethodGraph.getNodeSet().iterator(); iterator2.hasNext();) {
852             HNode parentHNode = (HNode) iterator2.next();
853
854             Set<HNode> parentIncomingHNode = parentMethodGraph.getIncomingNodeSet(parentHNode);
855             Set<HNode> parentOutgoingHNode = parentMethodGraph.getOutgoingNodeSet(parentHNode);
856
857             for (Iterator iterator4 = parentIncomingHNode.iterator(); iterator4.hasNext();) {
858               HNode inHNode = (HNode) iterator4.next();
859               childMethodGraph.addEdge(inHNode, parentHNode);
860             }
861
862             for (Iterator iterator4 = parentOutgoingHNode.iterator(); iterator4.hasNext();) {
863               HNode outHNode = (HNode) iterator4.next();
864               childMethodGraph.addEdge(parentHNode, outHNode);
865             }
866
867           }
868
869         }
870
871       }
872
873       DFSInheritanceTree(childClassDescriptor);
874     }
875
876   }
877
878   public MethodDescriptor getParentMethodDesc(ClassDescriptor classDesc, MethodDescriptor methodDesc) {
879
880     // Node<ClassDescriptor> childNode = inheritanceTree.getTreeNode(classDesc);
881     ClassDescriptor parentClassDesc = classDesc.getSuperDesc();
882     // Node<ClassDescriptor> parentNode = childNode.getParent();
883
884     if (parentClassDesc != null) {
885       // ClassDescriptor parentClassDesc = parentNode.getData();
886       if (parentClassDesc.getMethodTable().contains(methodDesc.getSymbol())) {
887         Set<MethodDescriptor> methodDescSet =
888             parentClassDesc.getMethodTable().getSet(methodDesc.getSymbol());
889         for (Iterator iterator = methodDescSet.iterator(); iterator.hasNext();) {
890           MethodDescriptor md = (MethodDescriptor) iterator.next();
891           if (md.matches(methodDesc)) {
892             return md;
893           }
894         }
895       }
896
897       // traverse to the parent!
898       getParentMethodDesc(parentClassDesc, methodDesc);
899
900     }
901
902     return null;
903   }
904
905   private void checkReturnNodes() {
906     LinkedList<MethodDescriptor> methodDescList =
907         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
908
909     while (!methodDescList.isEmpty()) {
910       MethodDescriptor md = methodDescList.removeLast();
911
912       if (md.getReturnType() != null && !md.getReturnType().isVoid()) {
913         checkFlowNodeReturnThisField(md);
914       }
915       // // in this case, this method will return the composite location that starts with 'this'
916       // FlowGraph flowGraph = getFlowGraph(md);
917       // Set<FlowNode> returnNodeSet = flowGraph.getReturnNodeSet();
918       // }
919
920     }
921
922   }
923
924   private void addSuperClasses(ClassDescriptor cd) {
925     ClassDescriptor parentClassDesc = cd.getSuperDesc();
926     if (parentClassDesc != null) {
927       toanalyze_classDescSet.add(parentClassDesc);
928       addSuperClasses(parentClassDesc);
929     }
930   }
931
932   private void updateFlowGraph() {
933
934     LinkedList<MethodDescriptor> methodDescList =
935         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
936
937     while (!methodDescList.isEmpty()) {
938       MethodDescriptor md = methodDescList.removeLast();
939       if (state.SSJAVADEBUG) {
940         System.out.println();
941         System.out.println("SSJAVA: Updating a flow graph: " + md);
942         propagateFlowsFromCalleesWithNoCompositeLocation(md);
943       }
944
945       Set<FlowNode> nodeSet = getFlowGraph(md).getNodeSet();
946       for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
947         FlowNode flowNode = (FlowNode) iterator.next();
948         NTuple<Descriptor> descTuple = flowNode.getCurrentDescTuple();
949         NTuple<Location> locTuple = translateToLocTuple(md, descTuple);
950         for (int i = 0; i < locTuple.size(); i++) {
951           Location loc = locTuple.get(i);
952           if (loc.getDescriptor() instanceof ClassDescriptor) {
953             ClassDescriptor classDesc = (ClassDescriptor) loc.getDescriptor();
954             toanalyze_classDescSet.add(classDesc);
955             addSuperClasses(classDesc);
956           } else if (loc.getDescriptor() instanceof MethodDescriptor) {
957             toanalyze_classDescSet.add(((MethodDescriptor) loc.getDescriptor()).getClassDesc());
958           }
959         }
960
961       }
962
963     }
964   }
965
966   public Map<NTuple<Descriptor>, NTuple<Descriptor>> getMapCallerArgToCalleeParam(
967       MethodInvokeNode min) {
968
969     if (!mapMethodInvokeNodeToMapCallerArgToCalleeArg.containsKey(min)) {
970       mapMethodInvokeNodeToMapCallerArgToCalleeArg.put(min,
971           new HashMap<NTuple<Descriptor>, NTuple<Descriptor>>());
972     }
973
974     return mapMethodInvokeNodeToMapCallerArgToCalleeArg.get(min);
975   }
976
977   public void addMapCallerArgToCalleeParam(MethodInvokeNode min, NTuple<Descriptor> callerArg,
978       NTuple<Descriptor> calleeParam) {
979     getMapCallerArgToCalleeParam(min).put(callerArg, calleeParam);
980   }
981
982   private void assignCompositeLocation() {
983     calculateGlobalValueFlowCompositeLocation();
984     translateCompositeLocationAssignmentToFlowGraph();
985   }
986
987   private void translateCompositeLocationAssignmentToFlowGraph() {
988     System.out.println("\nSSJAVA: Translate composite location assignments to flow graphs:");
989     MethodDescriptor methodEventLoopDesc = ssjava.getMethodContainingSSJavaLoop();
990     translateCompositeLocationAssignmentToFlowGraph(methodEventLoopDesc);
991   }
992
993   private void translateCompositeLocationAssignmentToFlowGraph2() {
994     System.out.println("\nSSJAVA: Translate composite location assignments to flow graphs:");
995     MethodDescriptor methodEventLoopDesc = ssjava.getMethodContainingSSJavaLoop();
996     translateCompositeLocationAssignmentToFlowGraph(methodEventLoopDesc);
997   }
998
999   private void addAdditionalOrderingConstraints() {
1000     System.out.println("\nSSJAVA: Add addtional ordering constriants:");
1001     MethodDescriptor methodEventLoopDesc = ssjava.getMethodContainingSSJavaLoop();
1002     addAddtionalOrderingConstraints(methodEventLoopDesc);
1003     // calculateReturnHolderLocation();
1004   }
1005
1006   private void calculateReturnHolderLocation() {
1007     LinkedList<MethodDescriptor> methodDescList =
1008         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
1009
1010     while (!methodDescList.isEmpty()) {
1011       MethodDescriptor md = methodDescList.removeLast();
1012
1013       FlowGraph fg = getFlowGraph(md);
1014       Set<FlowNode> nodeSet = fg.getNodeSet();
1015       for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1016         FlowNode flowNode = (FlowNode) iterator.next();
1017         if (flowNode.isFromHolder()) {
1018           calculateCompositeLocationFromFlowGraph(md, flowNode);
1019         }
1020       }
1021
1022     }
1023   }
1024
1025   private void updateCompositeLocationAssignments() {
1026
1027     LinkedList<MethodDescriptor> methodDescList =
1028         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
1029
1030     while (!methodDescList.isEmpty()) {
1031       MethodDescriptor md = methodDescList.removeLast();
1032
1033       System.out.println("\n#updateCompositeLocationAssignments=" + md);
1034
1035       FlowGraph flowGraph = getFlowGraph(md);
1036
1037       MethodSummary methodSummary = getMethodSummary(md);
1038
1039       Set<FlowNode> nodeSet = flowGraph.getNodeSet();
1040       for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1041         FlowNode node = (FlowNode) iterator.next();
1042         System.out.println("-node=" + node + "   node.getDescTuple=" + node.getDescTuple());
1043         if (node.getCompositeLocation() != null) {
1044           CompositeLocation compLoc = node.getCompositeLocation();
1045           CompositeLocation updatedCompLoc = updateCompositeLocation(compLoc);
1046           node.setCompositeLocation(updatedCompLoc);
1047           System.out.println("---updatedCompLoc1=" + updatedCompLoc);
1048         } else {
1049           NTuple<Descriptor> descTuple = node.getDescTuple();
1050           // System.out.println("update desc=" + descTuple);
1051           CompositeLocation compLoc = convertToCompositeLocation(md, descTuple);
1052           compLoc = updateCompositeLocation(compLoc);
1053           node.setCompositeLocation(compLoc);
1054           // System.out.println("---updatedCompLoc2=" + compLoc);
1055         }
1056
1057         if (node.isDeclaratonNode()) {
1058           Descriptor localVarDesc = node.getDescTuple().get(0);
1059           CompositeLocation compLoc = updateCompositeLocation(node.getCompositeLocation());
1060           methodSummary.addMapVarNameToInferCompLoc(localVarDesc, compLoc);
1061         }
1062       }
1063
1064       // update PCLOC and RETURNLOC if they have a composite location assignment
1065       if (methodSummary.getRETURNLoc() != null) {
1066         methodSummary.setRETURNLoc(updateCompositeLocation(methodSummary.getRETURNLoc()));
1067       }
1068       if (methodSummary.getPCLoc() != null) {
1069         methodSummary.setPCLoc(updateCompositeLocation(methodSummary.getPCLoc()));
1070       }
1071
1072     }
1073
1074   }
1075
1076   private CompositeLocation updateCompositeLocation(CompositeLocation compLoc) {
1077     CompositeLocation updatedCompLoc = new CompositeLocation();
1078     for (int i = 0; i < compLoc.getSize(); i++) {
1079       Location loc = compLoc.get(i);
1080       String nodeIdentifier = loc.getLocIdentifier();
1081       Descriptor enclosingDesc = loc.getDescriptor();
1082       String locName;
1083       if (!enclosingDesc.equals(GLOBALDESC)) {
1084         LocationSummary locSummary = getLocationSummary(enclosingDesc);
1085         // HierarchyGraph scGraph = getSkeletonCombinationHierarchyGraph(enclosingDesc);
1086         HierarchyGraph scGraph = getSimpleHierarchyGraph(enclosingDesc);
1087         if (scGraph != null) {
1088           HNode curNode = scGraph.getCurrentHNode(nodeIdentifier);
1089           System.out.println("     nodeID=" + nodeIdentifier + " curNode=" + curNode
1090               + "  enclosingDesc=" + enclosingDesc);
1091           if (curNode != null) {
1092             nodeIdentifier = curNode.getName();
1093           }
1094         }
1095         locName = locSummary.getLocationName(nodeIdentifier);
1096       } else {
1097         locName = nodeIdentifier;
1098       }
1099       Location updatedLoc = new Location(enclosingDesc, locName);
1100       updatedCompLoc.addLocation(updatedLoc);
1101     }
1102
1103     return updatedCompLoc;
1104   }
1105
1106   private void translateCompositeLocationAssignmentToFlowGraph(MethodDescriptor mdCaller) {
1107
1108     // System.out.println("\n\n###translateCompositeLocationAssignmentToFlowGraph mdCaller="
1109     // + mdCaller);
1110
1111     // First, assign a composite location to a node in the flow graph
1112     GlobalFlowGraph callerGlobalFlowGraph = getSubGlobalFlowGraph(mdCaller);
1113
1114     FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
1115     Map<Location, CompositeLocation> callerMapLocToCompLoc =
1116         callerGlobalFlowGraph.getMapLocationToInferCompositeLocation();
1117
1118     Set<Location> methodLocSet = callerMapLocToCompLoc.keySet();
1119     for (Iterator iterator = methodLocSet.iterator(); iterator.hasNext();) {
1120       Location methodLoc = (Location) iterator.next();
1121       if (methodLoc.getDescriptor().equals(mdCaller)) {
1122         CompositeLocation inferCompLoc = callerMapLocToCompLoc.get(methodLoc);
1123         assignCompositeLocationToFlowGraph(callerFlowGraph, methodLoc, inferCompLoc);
1124       }
1125     }
1126
1127     Set<MethodInvokeNode> minSet = mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
1128
1129     Set<MethodDescriptor> calleeSet = new HashSet<MethodDescriptor>();
1130     for (Iterator iterator = minSet.iterator(); iterator.hasNext();) {
1131       MethodInvokeNode min = (MethodInvokeNode) iterator.next();
1132       // need to translate a composite location that is started with the base
1133       // tuple of 'min'.
1134       translateMapLocationToInferCompositeLocationToCalleeGraph(callerGlobalFlowGraph, min);
1135       MethodDescriptor mdCallee = min.getMethod();
1136       calleeSet.add(mdCallee);
1137
1138     }
1139
1140     for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
1141       MethodDescriptor callee = (MethodDescriptor) iterator.next();
1142       translateCompositeLocationAssignmentToFlowGraph(callee);
1143     }
1144
1145   }
1146
1147   private void addAddtionalOrderingConstraints(MethodDescriptor mdCaller) {
1148
1149     // First, assign a composite location to a node in the flow graph
1150     GlobalFlowGraph callerGlobalFlowGraph = getSubGlobalFlowGraph(mdCaller);
1151
1152     FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
1153     Map<Location, CompositeLocation> callerMapLocToCompLoc =
1154         callerGlobalFlowGraph.getMapLocationToInferCompositeLocation();
1155     Set<Location> methodLocSet = callerMapLocToCompLoc.keySet();
1156
1157     Set<MethodInvokeNode> minSet = mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
1158
1159     Set<MethodDescriptor> calleeSet = new HashSet<MethodDescriptor>();
1160     for (Iterator iterator = minSet.iterator(); iterator.hasNext();) {
1161       MethodInvokeNode min = (MethodInvokeNode) iterator.next();
1162       MethodDescriptor mdCallee = min.getMethod();
1163       calleeSet.add(mdCallee);
1164
1165       //
1166       // add an additional ordering constraint
1167       // if the first element of a parameter composite location matches 'this' reference,
1168       // the corresponding argument in the caller is required to be higher than the translated
1169       // parameter location in the caller lattice
1170       // TODO
1171       // addOrderingConstraintFromCompLocParamToArg(mdCaller, min);
1172
1173       //
1174       // update return flow nodes in the caller
1175       CompositeLocation returnLoc = getMethodSummary(mdCallee).getRETURNLoc();
1176       // System.out.println("### min=" + min.printNode(0) + "  returnLoc=" + returnLoc);
1177       if (returnLoc != null && returnLoc.get(0).getLocDescriptor().equals(mdCallee.getThis())
1178           && returnLoc.getSize() > 1) {
1179         // System.out.println("###RETURN COMP LOC=" + returnLoc);
1180         NTuple<Location> returnLocTuple = returnLoc.getTuple();
1181         NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
1182         // System.out.println("###basetuple=" + baseTuple);
1183         NTuple<Descriptor> newReturnTuple = baseTuple.clone();
1184         for (int i = 1; i < returnLocTuple.size(); i++) {
1185           newReturnTuple.add(returnLocTuple.get(i).getLocDescriptor());
1186         }
1187         // System.out.println("###NEW RETURN TUPLE FOR CALLER=" + newReturnTuple);
1188
1189         FlowReturnNode holderNode = callerFlowGraph.getFlowReturnNode(min);
1190         NodeTupleSet holderTupleSet =
1191             getNodeTupleSetFromReturnNode(getFlowGraph(mdCaller), holderNode);
1192
1193         callerFlowGraph.getFlowReturnNode(min).setNewTuple(newReturnTuple);
1194
1195         // then need to remove old constraints
1196         // TODO SAT
1197         // System.out.println("###REMOVE OLD CONSTRAINTS=" + holderNode);
1198         for (Iterator<NTuple<Descriptor>> iter = holderTupleSet.iterator(); iter.hasNext();) {
1199           NTuple<Descriptor> tupleFromHolder = iter.next();
1200           Set<FlowEdge> holderOutEdge = callerFlowGraph.getOutEdgeSet(holderNode);
1201           for (Iterator iterator2 = holderOutEdge.iterator(); iterator2.hasNext();) {
1202             FlowEdge outEdge = (FlowEdge) iterator2.next();
1203             NTuple<Descriptor> toberemovedTuple = outEdge.getEndTuple();
1204             // System.out.println("---remove " + tupleFromHolder + " -> " + toberemovedTuple);
1205             callerFlowGraph.removeEdge(tupleFromHolder, toberemovedTuple);
1206           }
1207         }
1208
1209       } else {
1210         // if the return loc set was empty and later pcloc was connected to the return loc
1211         // need to make sure that return loc reflects to this changes.
1212         FlowReturnNode flowReturnNode = callerFlowGraph.getFlowReturnNode(min);
1213         if (flowReturnNode != null && flowReturnNode.getReturnTupleSet().isEmpty()) {
1214
1215           if (needToUpdateReturnLocHolder(min.getMethod(), flowReturnNode)) {
1216             NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
1217             NTuple<Descriptor> newReturnTuple = baseTuple.clone();
1218             flowReturnNode.addTuple(newReturnTuple);
1219           }
1220
1221         }
1222
1223       }
1224
1225     }
1226
1227     for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
1228       MethodDescriptor callee = (MethodDescriptor) iterator.next();
1229       addAddtionalOrderingConstraints(callee);
1230     }
1231
1232   }
1233
1234   private boolean needToUpdateReturnLocHolder(MethodDescriptor mdCallee,
1235       FlowReturnNode flowReturnNode) {
1236     FlowGraph fg = getFlowGraph(mdCallee);
1237     MethodSummary summary = getMethodSummary(mdCallee);
1238     CompositeLocation returnCompLoc = summary.getRETURNLoc();
1239     NTuple<Descriptor> returnDescTuple = translateToDescTuple(returnCompLoc.getTuple());
1240     Set<FlowNode> incomingNodeToReturnNode =
1241         fg.getIncomingFlowNodeSet(fg.getFlowNode(returnDescTuple));
1242     for (Iterator iterator = incomingNodeToReturnNode.iterator(); iterator.hasNext();) {
1243       FlowNode inNode = (FlowNode) iterator.next();
1244       if (inNode.getDescTuple().get(0).equals(mdCallee.getThis())) {
1245         return true;
1246       }
1247     }
1248     return false;
1249   }
1250
1251   private void addMapMethodDescToMethodInvokeNodeSet(MethodInvokeNode min) {
1252     MethodDescriptor md = min.getMethod();
1253     if (!mapMethodDescToMethodInvokeNodeSet.containsKey(md)) {
1254       mapMethodDescToMethodInvokeNodeSet.put(md, new HashSet<MethodInvokeNode>());
1255     }
1256     mapMethodDescToMethodInvokeNodeSet.get(md).add(min);
1257   }
1258
1259   private Set<MethodInvokeNode> getMethodInvokeNodeSetByMethodDesc(MethodDescriptor md) {
1260     if (!mapMethodDescToMethodInvokeNodeSet.containsKey(md)) {
1261       mapMethodDescToMethodInvokeNodeSet.put(md, new HashSet<MethodInvokeNode>());
1262     }
1263     return mapMethodDescToMethodInvokeNodeSet.get(md);
1264   }
1265
1266   public void assignCompositeLocationToFlowGraph(FlowGraph flowGraph, Location loc,
1267       CompositeLocation inferCompLoc) {
1268     Descriptor localDesc = loc.getLocDescriptor();
1269
1270     Set<FlowNode> nodeSet = flowGraph.getNodeSet();
1271     for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1272       FlowNode node = (FlowNode) iterator.next();
1273       if (node.getDescTuple().startsWith(localDesc)
1274           && !node.getDescTuple().get(0).equals(LITERALDESC)) {
1275         // need to assign the inferred composite location to this node
1276         CompositeLocation newCompLoc = generateCompositeLocation(node.getDescTuple(), inferCompLoc);
1277         node.setCompositeLocation(newCompLoc);
1278         // System.out.println("SET Node=" + node + "  inferCompLoc=" + newCompLoc);
1279       }
1280     }
1281   }
1282
1283   private CompositeLocation generateCompositeLocation(NTuple<Descriptor> nodeDescTuple,
1284       CompositeLocation inferCompLoc) {
1285
1286     // System.out.println("generateCompositeLocation=" + nodeDescTuple + " with inferCompLoc="
1287     // + inferCompLoc);
1288
1289     MethodDescriptor md = (MethodDescriptor) inferCompLoc.get(0).getDescriptor();
1290
1291     CompositeLocation newCompLoc = new CompositeLocation();
1292     for (int i = 0; i < inferCompLoc.getSize(); i++) {
1293       newCompLoc.addLocation(inferCompLoc.get(i));
1294     }
1295
1296     Descriptor lastDescOfPrefix = nodeDescTuple.get(0);
1297     Descriptor enclosingDescriptor;
1298     if (lastDescOfPrefix instanceof InterDescriptor) {
1299       enclosingDescriptor = getFlowGraph(md).getEnclosingDescriptor(lastDescOfPrefix);
1300     } else {
1301       enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
1302     }
1303
1304     for (int i = 1; i < nodeDescTuple.size(); i++) {
1305       Descriptor desc = nodeDescTuple.get(i);
1306       Location locElement = new Location(enclosingDescriptor, desc);
1307       newCompLoc.addLocation(locElement);
1308
1309       enclosingDescriptor = ((FieldDescriptor) desc).getClassDescriptor();
1310     }
1311
1312     return newCompLoc;
1313   }
1314
1315   private void translateMapLocationToInferCompositeLocationToCalleeGraph(
1316       GlobalFlowGraph callerGraph, MethodInvokeNode min) {
1317
1318     MethodDescriptor mdCallee = min.getMethod();
1319     MethodDescriptor mdCaller = callerGraph.getMethodDescriptor();
1320     Map<Location, CompositeLocation> callerMapLocToCompLoc =
1321         callerGraph.getMapLocationToInferCompositeLocation();
1322
1323     Map<Integer, NTuple<Descriptor>> mapIdxToArgTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
1324
1325     FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
1326     GlobalFlowGraph calleeGlobalGraph = getSubGlobalFlowGraph(mdCallee);
1327
1328     NTuple<Location> baseLocTuple = null;
1329     if (mapMethodInvokeNodeToBaseTuple.containsKey(min)) {
1330       baseLocTuple = translateToLocTuple(mdCaller, mapMethodInvokeNodeToBaseTuple.get(min));
1331     }
1332
1333     // System.out.println("\n-#translate caller=" + mdCaller + " infer composite loc to callee="
1334     // + mdCallee + " baseLocTuple=" + baseLocTuple);
1335
1336     Set<Location> keySet = callerMapLocToCompLoc.keySet();
1337     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1338       Location key = (Location) iterator.next();
1339       CompositeLocation callerCompLoc = callerMapLocToCompLoc.get(key);
1340
1341       if (!key.getDescriptor().equals(mdCaller)) {
1342
1343         CompositeLocation newCalleeCompLoc;
1344         if (baseLocTuple != null && callerCompLoc.getTuple().startsWith(baseLocTuple)) {
1345           // System.out.println("-----need to translate callerCompLoc=" + callerCompLoc
1346           // + " with baseTuple=" + baseLocTuple);
1347           newCalleeCompLoc =
1348               translateCompositeLocationToCallee(callerCompLoc, baseLocTuple, mdCallee);
1349
1350           calleeGlobalGraph.addMapLocationToInferCompositeLocation(key, newCalleeCompLoc);
1351           // System.out.println("1---key=" + key + "  callerCompLoc=" + callerCompLoc
1352           // + "  newCalleeCompLoc=" + newCalleeCompLoc);
1353           // System.out.println("-----caller=" + mdCaller + "    callee=" + mdCallee);
1354           if (!newCalleeCompLoc.get(0).getDescriptor().equals(mdCallee)) {
1355             System.exit(0);
1356           }
1357
1358           // System.out.println("-----baseLoctuple=" + baseLocTuple);
1359         } else {
1360           // check if it is the global access
1361           Location compLocFirstElement = callerCompLoc.getTuple().get(0);
1362           if (compLocFirstElement.getDescriptor().equals(mdCallee)
1363               && compLocFirstElement.getLocDescriptor().equals(GLOBALDESC)) {
1364
1365             newCalleeCompLoc = new CompositeLocation();
1366             Location newMethodLoc = new Location(mdCallee, GLOBALDESC);
1367
1368             newCalleeCompLoc.addLocation(newMethodLoc);
1369             for (int i = 1; i < callerCompLoc.getSize(); i++) {
1370               newCalleeCompLoc.addLocation(callerCompLoc.get(i));
1371             }
1372             calleeGlobalGraph.addMapLocationToInferCompositeLocation(key, newCalleeCompLoc);
1373             // System.out.println("2---key=" + key + "  callerCompLoc=" + callerCompLoc
1374             // + "  newCalleeCompLoc=" + newCalleeCompLoc);
1375             // System.out.println("-----caller=" + mdCaller + "    callee=" + mdCallee);
1376
1377           } else {
1378             int paramIdx = getParamIdx(callerCompLoc, mapIdxToArgTuple);
1379             if (paramIdx == -1) {
1380               // here, the first element of the current composite location comes from the current
1381               // callee
1382               // so transfer the same composite location to the callee
1383               if (!calleeGlobalGraph.contrainsInferCompositeLocationMapKey(key)) {
1384                 if (callerCompLoc.get(0).getDescriptor().equals(mdCallee)) {
1385                   // System.out.println("3---key=" + key + "  callerCompLoc=" + callerCompLoc
1386                   // + "  newCalleeCompLoc=" + callerCompLoc);
1387                   // System.out.println("-----caller=" + mdCaller + "    callee=" + mdCallee);
1388                   calleeGlobalGraph.addMapLocationToInferCompositeLocation(key, callerCompLoc);
1389                 } else {
1390                   // System.out.println("3---SKIP key=" + key + " callerCompLoc=" + callerCompLoc);
1391                 }
1392               }
1393               continue;
1394             }
1395
1396             // It is the case where two parameters have relative orderings between them by having
1397             // composite locations
1398             // if we found the param idx, it means that the first part of the caller composite
1399             // location corresponds to the one of arguments.
1400             // for example, if the caller argument is <<caller.this>,<Decoder.br>>
1401             // and the current caller composite location mapping
1402             // <<caller.this>,<Decoder.br>,<Br.value>>
1403             // and the parameter which matches with the caller argument is 'Br brParam'
1404             // then, the translated callee composite location will be <<callee.brParam>,<Br.value>>
1405             NTuple<Descriptor> argTuple = mapIdxToArgTuple.get(paramIdx);
1406
1407             FlowNode paramFlowNode = calleeFlowGraph.getParamFlowNode(paramIdx);
1408             NTuple<Location> paramLocTuple =
1409                 translateToLocTuple(mdCallee, paramFlowNode.getDescTuple());
1410             newCalleeCompLoc = new CompositeLocation();
1411             for (int i = 0; i < paramLocTuple.size(); i++) {
1412               newCalleeCompLoc.addLocation(paramLocTuple.get(i));
1413             }
1414             for (int i = argTuple.size(); i < callerCompLoc.getSize(); i++) {
1415               newCalleeCompLoc.addLocation(callerCompLoc.get(i));
1416             }
1417             calleeGlobalGraph.addMapLocationToInferCompositeLocation(key, newCalleeCompLoc);
1418             // System.out.println("4---key=" + key + "  callerCompLoc=" + callerCompLoc
1419             // + "  newCalleeCompLoc=" + newCalleeCompLoc);
1420             // System.out.println("-----caller=" + mdCaller + "    callee=" + mdCallee);
1421
1422           }
1423
1424         }
1425
1426       }
1427     }
1428
1429     // System.out.println("#ASSIGN COMP LOC TO CALLEE PARAMS: callee=" + mdCallee + "  caller="
1430     // + mdCaller);
1431     // If the location of an argument has a composite location
1432     // need to assign a proper composite location to the corresponding callee parameter
1433     Set<Integer> idxSet = mapIdxToArgTuple.keySet();
1434     for (Iterator iterator = idxSet.iterator(); iterator.hasNext();) {
1435       Integer idx = (Integer) iterator.next();
1436
1437       if (idx == 0 && !min.getMethod().isStatic()) {
1438         continue;
1439       }
1440
1441       NTuple<Descriptor> argTuple = mapIdxToArgTuple.get(idx);
1442       // System.out.println("-argTuple=" + argTuple + "   idx=" + idx);
1443       if (argTuple.size() > 0) {
1444         // check if an arg tuple has been already assigned to a composite location
1445         NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argTuple);
1446         Location argLocalLoc = argLocTuple.get(0);
1447
1448         // if (!isPrimitiveType(argTuple)) {
1449         if (callerMapLocToCompLoc.containsKey(argLocalLoc)) {
1450
1451           CompositeLocation callerCompLoc = callerMapLocToCompLoc.get(argLocalLoc);
1452           for (int i = 1; i < argLocTuple.size(); i++) {
1453             callerCompLoc.addLocation(argLocTuple.get(i));
1454           }
1455
1456           // System.out.println("---callerCompLoc=" + callerCompLoc);
1457
1458           // if (baseLocTuple != null && callerCompLoc.getTuple().startsWith(baseLocTuple)) {
1459
1460           FlowNode calleeParamFlowNode = calleeFlowGraph.getParamFlowNode(idx);
1461
1462           NTuple<Descriptor> calleeParamDescTuple = calleeParamFlowNode.getDescTuple();
1463           NTuple<Location> calleeParamLocTuple =
1464               translateToLocTuple(mdCallee, calleeParamDescTuple);
1465
1466           int refParamIdx = getParamIdx(callerCompLoc, mapIdxToArgTuple);
1467           // System.out.println("-----paramIdx=" + refParamIdx);
1468           if (refParamIdx == 0 && !mdCallee.isStatic()) {
1469
1470             // System.out.println("-------need to translate callerCompLoc=" + callerCompLoc
1471             // + " with baseTuple=" + baseLocTuple + "   calleeParamLocTuple="
1472             // + calleeParamLocTuple);
1473
1474             CompositeLocation newCalleeCompLoc =
1475                 translateCompositeLocationToCallee(callerCompLoc, baseLocTuple, mdCallee);
1476
1477             calleeGlobalGraph.addMapLocationToInferCompositeLocation(calleeParamLocTuple.get(0),
1478                 newCalleeCompLoc);
1479
1480             // System.out.println("---------key=" + calleeParamLocTuple.get(0) + "  callerCompLoc="
1481             // + callerCompLoc + "  newCalleeCompLoc=" + newCalleeCompLoc);
1482
1483           } else if (refParamIdx != -1) {
1484             // the first element of an argument composite location matches with one of paramtere
1485             // composite locations
1486
1487             // System.out.println("-------param match case=");
1488
1489             NTuple<Descriptor> argTupleRef = mapIdxToArgTuple.get(refParamIdx);
1490             FlowNode refParamFlowNode = calleeFlowGraph.getParamFlowNode(refParamIdx);
1491             NTuple<Location> refParamLocTuple =
1492                 translateToLocTuple(mdCallee, refParamFlowNode.getDescTuple());
1493
1494             // System.out.println("---------refParamLocTuple=" + refParamLocTuple
1495             // + "  from argTupleRef=" + argTupleRef);
1496
1497             CompositeLocation newCalleeCompLoc = new CompositeLocation();
1498             for (int i = 0; i < refParamLocTuple.size(); i++) {
1499               newCalleeCompLoc.addLocation(refParamLocTuple.get(i));
1500             }
1501             for (int i = argTupleRef.size(); i < callerCompLoc.getSize(); i++) {
1502               newCalleeCompLoc.addLocation(callerCompLoc.get(i));
1503             }
1504
1505             calleeGlobalGraph.addMapLocationToInferCompositeLocation(calleeParamLocTuple.get(0),
1506                 newCalleeCompLoc);
1507
1508             calleeParamFlowNode.setCompositeLocation(newCalleeCompLoc);
1509             // System.out.println("-----------key=" + calleeParamLocTuple.get(0) +
1510             // "  callerCompLoc="
1511             // + callerCompLoc + "  newCalleeCompLoc=" + newCalleeCompLoc);
1512
1513           } else {
1514             CompositeLocation newCalleeCompLoc =
1515                 calculateCompositeLocationFromSubGlobalGraph(mdCallee, calleeParamFlowNode);
1516             if (newCalleeCompLoc != null) {
1517               calleeGlobalGraph.addMapLocationToInferCompositeLocation(calleeParamLocTuple.get(0),
1518                   newCalleeCompLoc);
1519               calleeParamFlowNode.setCompositeLocation(newCalleeCompLoc);
1520             }
1521           }
1522
1523           // System.out.println("-----------------calleeParamFlowNode="
1524           // + calleeParamFlowNode.getCompositeLocation());
1525
1526           // }
1527
1528         }
1529       }
1530
1531     }
1532
1533   }
1534
1535   private CompositeLocation calculateCompositeLocationFromSubGlobalGraph(MethodDescriptor md,
1536       FlowNode paramNode) {
1537
1538     // System.out.println("#############################################################");
1539     // System.out.println("calculateCompositeLocationFromSubGlobalGraph=" + paramNode);
1540
1541     GlobalFlowGraph subGlobalFlowGraph = getSubGlobalFlowGraph(md);
1542     NTuple<Location> paramLocTuple = translateToLocTuple(md, paramNode.getDescTuple());
1543     GlobalFlowNode paramGlobalNode = subGlobalFlowGraph.getFlowNode(paramLocTuple);
1544
1545     List<NTuple<Location>> prefixList = calculatePrefixList(subGlobalFlowGraph, paramGlobalNode);
1546
1547     Location prefixLoc = paramLocTuple.get(0);
1548
1549     Set<GlobalFlowNode> reachableNodeSet =
1550         subGlobalFlowGraph.getReachableNodeSetByPrefix(paramGlobalNode.getLocTuple().get(0));
1551     // Set<GlobalFlowNode> reachNodeSet = globalFlowGraph.getReachableNodeSetFrom(node);
1552
1553     // System.out.println("node=" + node + "    prefixList=" + prefixList);
1554
1555     for (int i = 0; i < prefixList.size(); i++) {
1556       NTuple<Location> curPrefix = prefixList.get(i);
1557       Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
1558
1559       for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
1560         GlobalFlowNode reachNode = (GlobalFlowNode) iterator2.next();
1561         if (reachNode.getLocTuple().startsWith(curPrefix)) {
1562           reachableCommonPrefixSet.add(reachNode.getLocTuple());
1563         }
1564       }
1565       // System.out.println("reachableCommonPrefixSet=" + reachableCommonPrefixSet);
1566
1567       if (!reachableCommonPrefixSet.isEmpty()) {
1568
1569         MethodDescriptor curPrefixFirstElementMethodDesc =
1570             (MethodDescriptor) curPrefix.get(0).getDescriptor();
1571
1572         MethodDescriptor nodePrefixLocFirstElementMethodDesc =
1573             (MethodDescriptor) prefixLoc.getDescriptor();
1574
1575         // System.out.println("curPrefixFirstElementMethodDesc=" +
1576         // curPrefixFirstElementMethodDesc);
1577         // System.out.println("nodePrefixLocFirstElementMethodDesc="
1578         // + nodePrefixLocFirstElementMethodDesc);
1579
1580         if (curPrefixFirstElementMethodDesc.equals(nodePrefixLocFirstElementMethodDesc)
1581             || isTransitivelyCalledFrom(nodePrefixLocFirstElementMethodDesc,
1582                 curPrefixFirstElementMethodDesc)) {
1583
1584           // TODO
1585           // if (!node.getLocTuple().startsWith(curPrefix.get(0))) {
1586
1587           Location curPrefixLocalLoc = curPrefix.get(0);
1588           if (subGlobalFlowGraph.mapLocationToInferCompositeLocation.containsKey(curPrefixLocalLoc)) {
1589             // in this case, the local variable of the current prefix has already got a composite
1590             // location
1591             // so we just ignore the current composite location.
1592
1593             // System.out.println("HERE WE DO NOT ASSIGN A COMPOSITE LOCATION TO =" + node
1594             // + " DUE TO " + curPrefix);
1595             return null;
1596           }
1597
1598           if (!needToGenerateCompositeLocation(paramGlobalNode, curPrefix)) {
1599             // System.out.println("NO NEED TO GENERATE COMP LOC to " + paramGlobalNode
1600             // + " with prefix=" + curPrefix);
1601             return null;
1602           }
1603
1604           Location targetLocalLoc = paramGlobalNode.getLocTuple().get(0);
1605           CompositeLocation newCompLoc = generateCompositeLocation(curPrefix);
1606           // System.out.println("NEED TO ASSIGN COMP LOC TO " + paramGlobalNode + " with prefix="
1607           // + curPrefix);
1608           // System.out.println("-targetLocalLoc=" + targetLocalLoc + "   - newCompLoc=" +
1609           // newCompLoc);
1610
1611           // makes sure that a newly generated location appears in the hierarchy graph
1612           for (int compIdx = 0; compIdx < newCompLoc.getSize(); compIdx++) {
1613             Location curLoc = newCompLoc.get(compIdx);
1614             getHierarchyGraph(curLoc.getDescriptor()).getHNode(curLoc.getLocDescriptor());
1615           }
1616
1617           subGlobalFlowGraph.addMapLocationToInferCompositeLocation(targetLocalLoc, newCompLoc);
1618
1619           return newCompLoc;
1620
1621         }
1622
1623       }
1624
1625     }
1626     return null;
1627   }
1628
1629   private int getParamIdx(CompositeLocation compLoc,
1630       Map<Integer, NTuple<Descriptor>> mapIdxToArgTuple) {
1631
1632     // if the composite location is started with the argument descriptor
1633     // return the argument's index. o.t. return -1
1634
1635     Set<Integer> keySet = mapIdxToArgTuple.keySet();
1636     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
1637       Integer key = (Integer) iterator.next();
1638       NTuple<Descriptor> argTuple = mapIdxToArgTuple.get(key);
1639       if (argTuple.size() > 0 && translateToDescTuple(compLoc.getTuple()).startsWith(argTuple)) {
1640         // System.out.println("compLoc.getTuple=" + compLoc + " is started with " + argTuple);
1641         return key.intValue();
1642       }
1643     }
1644
1645     return -1;
1646   }
1647
1648   private boolean isPrimitiveType(NTuple<Descriptor> argTuple) {
1649
1650     Descriptor lastDesc = argTuple.get(argTuple.size() - 1);
1651
1652     if (lastDesc instanceof FieldDescriptor) {
1653       return ((FieldDescriptor) lastDesc).getType().isPrimitive();
1654     } else if (lastDesc instanceof VarDescriptor) {
1655       return ((VarDescriptor) lastDesc).getType().isPrimitive();
1656     } else if (lastDesc instanceof InterDescriptor) {
1657       return true;
1658     }
1659
1660     return false;
1661   }
1662
1663   private CompositeLocation translateCompositeLocationToCallee(CompositeLocation callerCompLoc,
1664       NTuple<Location> baseLocTuple, MethodDescriptor mdCallee) {
1665
1666     CompositeLocation newCalleeCompLoc = new CompositeLocation();
1667
1668     Location calleeThisLoc = new Location(mdCallee, mdCallee.getThis());
1669     newCalleeCompLoc.addLocation(calleeThisLoc);
1670
1671     // remove the base tuple from the caller
1672     // ex; In the method invoation foo.bar.methodA(), the callee will have the composite location
1673     // ,which is relative to the 'this' variable, <THIS,...>
1674     for (int i = baseLocTuple.size(); i < callerCompLoc.getSize(); i++) {
1675       newCalleeCompLoc.addLocation(callerCompLoc.get(i));
1676     }
1677
1678     return newCalleeCompLoc;
1679
1680   }
1681
1682   private void calculateGlobalValueFlowCompositeLocation() {
1683
1684     System.out.println("SSJAVA: Calculate composite locations in the global value flow graph");
1685     MethodDescriptor methodDescEventLoop = ssjava.getMethodContainingSSJavaLoop();
1686     GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(methodDescEventLoop);
1687
1688     Set<Location> calculatedPrefixSet = new HashSet<Location>();
1689
1690     Set<GlobalFlowNode> nodeSet = globalFlowGraph.getNodeSet();
1691
1692     next: for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1693       GlobalFlowNode node = (GlobalFlowNode) iterator.next();
1694
1695       Location prefixLoc = node.getLocTuple().get(0);
1696
1697       if (calculatedPrefixSet.contains(prefixLoc)) {
1698         // the prefix loc has been already assigned to a composite location
1699         continue;
1700       }
1701
1702       calculatedPrefixSet.add(prefixLoc);
1703
1704       // Set<GlobalFlowNode> incomingNodeSet = globalFlowGraph.getIncomingNodeSet(node);
1705       List<NTuple<Location>> prefixList = calculatePrefixList(globalFlowGraph, node);
1706
1707       Set<GlobalFlowNode> reachableNodeSet =
1708           globalFlowGraph.getReachableNodeSetByPrefix(node.getLocTuple().get(0));
1709       // Set<GlobalFlowNode> reachNodeSet = globalFlowGraph.getReachableNodeSetFrom(node);
1710
1711       // System.out.println("node=" + node + "    prefixList=" + prefixList);
1712       // System.out.println("---prefixList=" + prefixList);
1713
1714       nextprefix: for (int i = 0; i < prefixList.size(); i++) {
1715         NTuple<Location> curPrefix = prefixList.get(i);
1716         // System.out.println("---curPrefix=" + curPrefix);
1717         Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
1718
1719         for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
1720           GlobalFlowNode reachNode = (GlobalFlowNode) iterator2.next();
1721           if (reachNode.getLocTuple().startsWith(curPrefix)) {
1722             reachableCommonPrefixSet.add(reachNode.getLocTuple());
1723           }
1724         }
1725         // System.out.println("reachableCommonPrefixSet=" + reachableCommonPrefixSet);
1726
1727         if (!reachableCommonPrefixSet.isEmpty()) {
1728
1729           MethodDescriptor curPrefixFirstElementMethodDesc =
1730               (MethodDescriptor) curPrefix.get(0).getDescriptor();
1731
1732           MethodDescriptor nodePrefixLocFirstElementMethodDesc =
1733               (MethodDescriptor) prefixLoc.getDescriptor();
1734
1735           // System.out.println("curPrefixFirstElementMethodDesc=" +
1736           // curPrefixFirstElementMethodDesc);
1737           // System.out.println("nodePrefixLocFirstElementMethodDesc="
1738           // + nodePrefixLocFirstElementMethodDesc);
1739
1740           if (curPrefixFirstElementMethodDesc.equals(nodePrefixLocFirstElementMethodDesc)
1741               || isTransitivelyCalledFrom(nodePrefixLocFirstElementMethodDesc,
1742                   curPrefixFirstElementMethodDesc)) {
1743
1744             // TODO
1745             // if (!node.getLocTuple().startsWith(curPrefix.get(0))) {
1746
1747             Location curPrefixLocalLoc = curPrefix.get(0);
1748             if (globalFlowGraph.mapLocationToInferCompositeLocation.containsKey(curPrefixLocalLoc)) {
1749               // in this case, the local variable of the current prefix has already got a composite
1750               // location
1751               // so we just ignore the current composite location.
1752
1753               // System.out.println("HERE WE DO NOT ASSIGN A COMPOSITE LOCATION TO =" + node
1754               // + " DUE TO " + curPrefix);
1755
1756               continue next;
1757             }
1758
1759             if (!needToGenerateCompositeLocation(node, curPrefix)) {
1760               // System.out.println("NO NEED TO GENERATE COMP LOC to " + node + " with prefix="
1761               // + curPrefix);
1762               // System.out.println("prefixList=" + prefixList);
1763               // System.out.println("reachableNodeSet=" + reachableNodeSet);
1764               continue nextprefix;
1765             }
1766
1767             Location targetLocalLoc = node.getLocTuple().get(0);
1768             CompositeLocation newCompLoc = generateCompositeLocation(curPrefix);
1769             // System.out.println("NEED TO ASSIGN COMP LOC TO " + node + " with prefix=" +
1770             // curPrefix);
1771             // System.out.println("-targetLocalLoc=" + targetLocalLoc + "   - newCompLoc="
1772             // + newCompLoc);
1773             globalFlowGraph.addMapLocationToInferCompositeLocation(targetLocalLoc, newCompLoc);
1774             // }
1775
1776             continue next;
1777             // }
1778
1779           }
1780
1781         }
1782
1783       }
1784
1785     }
1786   }
1787
1788   private boolean checkFlowNodeReturnThisField(MethodDescriptor md) {
1789
1790     MethodDescriptor methodDescEventLoop = ssjava.getMethodContainingSSJavaLoop();
1791     GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(methodDescEventLoop);
1792
1793     FlowGraph flowGraph = getFlowGraph(md);
1794
1795     ClassDescriptor enclosingDesc = getClassTypeDescriptor(md.getThis());
1796     if (enclosingDesc == null) {
1797       return false;
1798     }
1799
1800     int count = 0;
1801     Set<FlowNode> returnNodeSet = flowGraph.getReturnNodeSet();
1802     Set<GlobalFlowNode> globalReturnNodeSet = new HashSet<GlobalFlowNode>();
1803     for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
1804       FlowNode flowNode = (FlowNode) iterator.next();
1805       NTuple<Location> locTuple = translateToLocTuple(md, flowNode.getDescTuple());
1806       GlobalFlowNode globalReturnNode = globalFlowGraph.getFlowNode(locTuple);
1807       globalReturnNodeSet.add(globalReturnNode);
1808
1809       List<NTuple<Location>> prefixList = calculatePrefixList(globalFlowGraph, globalReturnNode);
1810       for (int i = 0; i < prefixList.size(); i++) {
1811         NTuple<Location> curPrefix = prefixList.get(i);
1812         ClassDescriptor cd =
1813             getClassTypeDescriptor(curPrefix.get(curPrefix.size() - 1).getLocDescriptor());
1814         if (cd != null && cd.equals(enclosingDesc)) {
1815           count++;
1816           break;
1817         }
1818       }
1819
1820     }
1821
1822     if (count == returnNodeSet.size()) {
1823       // in this case, all return nodes in the method returns values coming from a location that
1824       // starts with "this"
1825
1826       // System.out.println("$$$SET RETURN LOC TRUE=" + md);
1827       mapMethodDescriptorToCompositeReturnCase.put(md, Boolean.TRUE);
1828
1829       // NameDescriptor returnLocDesc = new NameDescriptor("RLOC" + (locSeed++));
1830       // NTuple<Descriptor> rDescTuple = new NTuple<Descriptor>();
1831       // rDescTuple.add(md.getThis());
1832       // rDescTuple.add(returnLocDesc);
1833       //
1834       // for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
1835       // FlowNode rnode = (FlowNode) iterator.next();
1836       // flowGraph.addValueFlowEdge(rnode.getDescTuple(), rDescTuple);
1837       // }
1838       //
1839       // getMethodSummary(md).setRETURNLoc(new CompositeLocation(translateToLocTuple(md,
1840       // rDescTuple)));
1841
1842     } else {
1843       mapMethodDescriptorToCompositeReturnCase.put(md, Boolean.FALSE);
1844     }
1845
1846     return mapMethodDescriptorToCompositeReturnCase.get(md).booleanValue();
1847
1848   }
1849
1850   private boolean needToGenerateCompositeLocation(GlobalFlowNode node, NTuple<Location> curPrefix) {
1851     // return true if there is a path between a node to which we want to give a composite location
1852     // and nodes which start with curPrefix
1853
1854     // System.out.println("---needToGenerateCompositeLocation curPrefix=" + curPrefix);
1855
1856     Location targetLocalLoc = node.getLocTuple().get(0);
1857
1858     MethodDescriptor md = (MethodDescriptor) targetLocalLoc.getDescriptor();
1859     FlowGraph flowGraph = getFlowGraph(md);
1860
1861     FlowNode flowNode = flowGraph.getFlowNode(node.getDescTuple());
1862     Set<FlowNode> reachableSet = flowGraph.getReachFlowNodeSetFrom(flowNode);
1863
1864     Set<FlowNode> paramNodeSet = flowGraph.getParamFlowNodeSet();
1865     for (Iterator iterator = paramNodeSet.iterator(); iterator.hasNext();) {
1866       FlowNode paramFlowNode = (FlowNode) iterator.next();
1867       if (curPrefix.startsWith(translateToLocTuple(md, paramFlowNode.getDescTuple()))) {
1868         return true;
1869       }
1870     }
1871
1872     if (targetLocalLoc.getLocDescriptor() instanceof InterDescriptor) {
1873       Pair<MethodInvokeNode, Integer> pair =
1874           ((InterDescriptor) targetLocalLoc.getLocDescriptor()).getMethodArgIdxPair();
1875
1876       if (pair != null) {
1877         // System.out.println("$$$TARGETLOCALLOC HOLDER=" + targetLocalLoc);
1878
1879         MethodInvokeNode min = pair.getFirst();
1880         Integer paramIdx = pair.getSecond();
1881         MethodDescriptor mdCallee = min.getMethod();
1882
1883         FlowNode paramNode = getFlowGraph(mdCallee).getParamFlowNode(paramIdx);
1884         if (checkNodeReachToReturnNode(mdCallee, paramNode)) {
1885           return true;
1886         }
1887
1888       }
1889
1890     }
1891
1892     GlobalFlowGraph subGlobalFlowGraph = getSubGlobalFlowGraph(md);
1893     Set<GlobalFlowNode> subGlobalReachableSet = subGlobalFlowGraph.getReachableNodeSetFrom(node);
1894
1895     if (!md.isStatic()) {
1896       ClassDescriptor currentMethodThisType = getClassTypeDescriptor(md.getThis());
1897       for (int i = 0; i < curPrefix.size(); i++) {
1898         ClassDescriptor prefixType = getClassTypeDescriptor(curPrefix.get(i).getLocDescriptor());
1899         if (prefixType != null && prefixType.equals(currentMethodThisType)) {
1900           // System.out.println("PREFIX TYPE MATCHES WITH=" + currentMethodThisType);
1901
1902           if (mapMethodDescriptorToCompositeReturnCase.containsKey(md)) {
1903             boolean hasCompReturnLocWithThis =
1904                 mapMethodDescriptorToCompositeReturnCase.get(md).booleanValue();
1905             if (hasCompReturnLocWithThis) {
1906               if (checkNodeReachToReturnNode(md, flowNode)) {
1907                 return true;
1908               }
1909             }
1910           }
1911
1912           for (Iterator iterator3 = subGlobalReachableSet.iterator(); iterator3.hasNext();) {
1913             GlobalFlowNode subGlobalReachalbeNode = (GlobalFlowNode) iterator3.next();
1914             if (subGlobalReachalbeNode.getLocTuple().get(0).getLocDescriptor().equals(md.getThis())) {
1915               // System.out.println("PREFIX FOUND=" + subGlobalReachalbeNode);
1916               return true;
1917             }
1918           }
1919         }
1920       }
1921     }
1922
1923     Location lastLocationOfPrefix = curPrefix.get(curPrefix.size() - 1);
1924     // check whether prefix appears in the list of parameters
1925     Set<MethodInvokeNode> minSet = mapMethodDescToMethodInvokeNodeSet.get(md);
1926     // System.out.println("$$$md=" + md + "   minSet=" + minSet);
1927     if (minSet == null) {
1928       return false;
1929     }
1930     found: for (Iterator iterator = minSet.iterator(); iterator.hasNext();) {
1931       MethodInvokeNode min = (MethodInvokeNode) iterator.next();
1932       Map<Integer, NTuple<Descriptor>> map = mapMethodInvokeNodeToArgIdxMap.get(min);
1933       Set<Integer> keySet = map.keySet();
1934       // System.out.println("min=" + min.printNode(0));
1935
1936       for (Iterator iterator2 = keySet.iterator(); iterator2.hasNext();) {
1937         Integer argIdx = (Integer) iterator2.next();
1938         NTuple<Descriptor> argTuple = map.get(argIdx);
1939
1940         if (!(!md.isStatic() && argIdx == 0)) {
1941           // if the argTuple is empty, we don't need to do with anything(LITERAL CASE).
1942           if (argTuple.size() > 0
1943               && argTuple.get(argTuple.size() - 1).equals(lastLocationOfPrefix.getLocDescriptor())) {
1944             NTuple<Location> locTuple =
1945                 translateToLocTuple(md, flowGraph.getParamFlowNode(argIdx).getDescTuple());
1946             lastLocationOfPrefix = locTuple.get(0);
1947             // System.out.println("ARG CASE=" + locTuple);
1948             for (Iterator iterator3 = subGlobalReachableSet.iterator(); iterator3.hasNext();) {
1949               GlobalFlowNode subGlobalReachalbeNode = (GlobalFlowNode) iterator3.next();
1950               // NTuple<Location> locTuple = translateToLocTuple(md, reachalbeNode.getDescTuple());
1951               NTuple<Location> globalReachlocTuple = subGlobalReachalbeNode.getLocTuple();
1952               for (int i = 0; i < globalReachlocTuple.size(); i++) {
1953                 if (globalReachlocTuple.get(i).equals(lastLocationOfPrefix)) {
1954                   // System.out.println("ARG  " + argTuple + "  IS MATCHED WITH="
1955                   // + lastLocationOfPrefix);
1956                   return true;
1957                 }
1958               }
1959             }
1960           }
1961         }
1962       }
1963     }
1964
1965     return false;
1966   }
1967
1968   private boolean checkNodeReachToReturnNode(MethodDescriptor md, FlowNode node) {
1969
1970     FlowGraph flowGraph = getFlowGraph(md);
1971     Set<FlowNode> reachableSet = flowGraph.getReachFlowNodeSetFrom(node);
1972     if (mapMethodDescriptorToCompositeReturnCase.containsKey(md)) {
1973       boolean hasCompReturnLocWithThis =
1974           mapMethodDescriptorToCompositeReturnCase.get(md).booleanValue();
1975
1976       if (hasCompReturnLocWithThis) {
1977         for (Iterator iterator = flowGraph.getReturnNodeSet().iterator(); iterator.hasNext();) {
1978           FlowNode returnFlowNode = (FlowNode) iterator.next();
1979           if (reachableSet.contains(returnFlowNode)) {
1980             return true;
1981           }
1982         }
1983       }
1984     }
1985     return false;
1986   }
1987
1988   private void assignCompositeLocation(CompositeLocation compLocPrefix, GlobalFlowNode node) {
1989     CompositeLocation newCompLoc = compLocPrefix.clone();
1990     NTuple<Location> locTuple = node.getLocTuple();
1991     for (int i = 1; i < locTuple.size(); i++) {
1992       newCompLoc.addLocation(locTuple.get(i));
1993     }
1994     node.setInferCompositeLocation(newCompLoc);
1995   }
1996
1997   private List<NTuple<Location>> calculatePrefixList(GlobalFlowGraph graph, GlobalFlowNode node) {
1998
1999     // System.out.println("\n##### calculatePrefixList node=" + node);
2000
2001     Set<GlobalFlowNode> incomingNodeSetPrefix =
2002         graph.getIncomingNodeSetByPrefix(node.getLocTuple().get(0));
2003     // System.out.println("---incomingNodeSetPrefix=" + incomingNodeSetPrefix);
2004
2005     Set<GlobalFlowNode> reachableNodeSetPrefix =
2006         graph.getReachableNodeSetByPrefix(node.getLocTuple().get(0));
2007     // System.out.println("---reachableNodeSetPrefix=" + reachableNodeSetPrefix);
2008
2009     List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
2010
2011     for (Iterator iterator = incomingNodeSetPrefix.iterator(); iterator.hasNext();) {
2012       GlobalFlowNode inNode = (GlobalFlowNode) iterator.next();
2013       NTuple<Location> inNodeTuple = inNode.getLocTuple();
2014
2015       if (inNodeTuple.get(0).getLocDescriptor() instanceof InterDescriptor
2016           || inNodeTuple.get(0).getLocDescriptor().equals(GLOBALDESC)) {
2017         continue;
2018       }
2019
2020       for (int i = 1; i < inNodeTuple.size(); i++) {
2021         NTuple<Location> prefix = inNodeTuple.subList(0, i);
2022         if (!prefixList.contains(prefix)) {
2023           prefixList.add(prefix);
2024         }
2025       }
2026     }
2027
2028     Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
2029       public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
2030         int s0 = arg0.size();
2031         int s1 = arg1.size();
2032         if (s0 > s1) {
2033           return -1;
2034         } else if (s0 == s1) {
2035           return 0;
2036         } else {
2037           return 1;
2038         }
2039       }
2040     });
2041
2042     return prefixList;
2043
2044   }
2045
2046   private CompositeLocation calculateCompositeLocationFromFlowGraph(MethodDescriptor md,
2047       FlowNode node) {
2048
2049     // System.out.println("#############################################################");
2050     // System.out.println("calculateCompositeLocationFromFlowGraph=" + node);
2051
2052     FlowGraph flowGraph = getFlowGraph(md);
2053     // NTuple<Location> paramLocTuple = translateToLocTuple(md, paramNode.getDescTuple());
2054     // GlobalFlowNode paramGlobalNode = subGlobalFlowGraph.getFlowNode(paramLocTuple);
2055
2056     List<NTuple<Location>> prefixList = calculatePrefixListFlowGraph(flowGraph, node);
2057
2058     // Set<GlobalFlowNode> reachableNodeSet =
2059     // subGlobalFlowGraph.getReachableNodeSetByPrefix(paramGlobalNode.getLocTuple().get(0));
2060     //
2061     Set<FlowNode> reachableNodeSet =
2062         flowGraph.getReachableSetFrom(node.getDescTuple().subList(0, 1));
2063
2064     // Set<GlobalFlowNode> reachNodeSet = globalFlowGraph.getReachableNodeSetFrom(node);
2065
2066     // System.out.println("node=" + node + "    prefixList=" + prefixList);
2067
2068     for (int i = 0; i < prefixList.size(); i++) {
2069       NTuple<Location> curPrefix = prefixList.get(i);
2070       Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
2071
2072       for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
2073         FlowNode reachNode = (FlowNode) iterator2.next();
2074         NTuple<Location> reachLocTuple = translateToLocTuple(md, reachNode.getCurrentDescTuple());
2075         if (reachLocTuple.startsWith(curPrefix)) {
2076           reachableCommonPrefixSet.add(reachLocTuple);
2077         }
2078       }
2079       // System.out.println("reachableCommonPrefixSet=" + reachableCommonPrefixSet);
2080
2081       if (!reachableCommonPrefixSet.isEmpty()) {
2082
2083         MethodDescriptor curPrefixFirstElementMethodDesc =
2084             (MethodDescriptor) curPrefix.get(0).getDescriptor();
2085
2086         Location curPrefixLocalLoc = curPrefix.get(0);
2087
2088         Location targetLocalLoc = new Location(md, node.getDescTuple().get(0));
2089         // Location targetLocalLoc = paramGlobalNode.getLocTuple().get(0);
2090
2091         CompositeLocation newCompLoc = generateCompositeLocation(curPrefix);
2092         // System.out.println("NEED2ASSIGN COMP LOC TO " + node + " with prefix=" + curPrefix);
2093         // System.out.println("-targetLocalLoc=" + targetLocalLoc + "   - newCompLoc=" +
2094         // newCompLoc);
2095
2096         node.setCompositeLocation(newCompLoc);
2097
2098         return newCompLoc;
2099
2100       }
2101
2102     }
2103     return null;
2104   }
2105
2106   private List<NTuple<Location>> calculatePrefixListFlowGraph(FlowGraph graph, FlowNode node) {
2107
2108     // System.out.println("\n##### calculatePrefixList node=" + node);
2109
2110     MethodDescriptor md = graph.getMethodDescriptor();
2111     Set<FlowNode> incomingNodeSetPrefix =
2112         graph.getIncomingNodeSetByPrefix(node.getDescTuple().get(0));
2113     // System.out.println("---incomingNodeSetPrefix=" + incomingNodeSetPrefix);
2114
2115     Set<FlowNode> reachableNodeSetPrefix =
2116         graph.getReachableSetFrom(node.getDescTuple().subList(0, 1));
2117     // System.out.println("---reachableNodeSetPrefix=" + reachableNodeSetPrefix);
2118
2119     List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
2120
2121     for (Iterator iterator = incomingNodeSetPrefix.iterator(); iterator.hasNext();) {
2122       FlowNode inNode = (FlowNode) iterator.next();
2123       NTuple<Location> inNodeTuple = translateToLocTuple(md, inNode.getCurrentDescTuple());
2124
2125       // if (inNodeTuple.get(0).getLocDescriptor() instanceof InterDescriptor
2126       // || inNodeTuple.get(0).getLocDescriptor().equals(GLOBALDESC)) {
2127       // continue;
2128       // }
2129
2130       for (int i = 1; i < inNodeTuple.size(); i++) {
2131         NTuple<Location> prefix = inNodeTuple.subList(0, i);
2132         if (!prefixList.contains(prefix)) {
2133           prefixList.add(prefix);
2134         }
2135       }
2136     }
2137
2138     Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
2139       public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
2140         int s0 = arg0.size();
2141         int s1 = arg1.size();
2142         if (s0 > s1) {
2143           return -1;
2144         } else if (s0 == s1) {
2145           return 0;
2146         } else {
2147           return 1;
2148         }
2149       }
2150     });
2151
2152     return prefixList;
2153
2154   }
2155
2156   private GlobalFlowGraph constructSubGlobalFlowGraph(FlowGraph flowGraph) {
2157
2158     MethodDescriptor md = flowGraph.getMethodDescriptor();
2159
2160     GlobalFlowGraph globalGraph = getSubGlobalFlowGraph(md);
2161
2162     // Set<FlowNode> nodeSet = flowGraph.getNodeSet();
2163     Set<FlowEdge> edgeSet = flowGraph.getEdgeSet();
2164
2165     for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
2166
2167       FlowEdge edge = (FlowEdge) iterator.next();
2168       NTuple<Descriptor> srcDescTuple = edge.getInitTuple();
2169       NTuple<Descriptor> dstDescTuple = edge.getEndTuple();
2170
2171       if (flowGraph.getFlowNode(srcDescTuple) instanceof FlowReturnNode
2172           || flowGraph.getFlowNode(dstDescTuple) instanceof FlowReturnNode) {
2173         continue;
2174       }
2175
2176       // here only keep the first element(method location) of the descriptor
2177       // tuple
2178       NTuple<Location> srcLocTuple = translateToLocTuple(md, srcDescTuple);
2179       NTuple<Location> dstLocTuple = translateToLocTuple(md, dstDescTuple);
2180
2181       globalGraph.addValueFlowEdge(srcLocTuple, dstLocTuple);
2182
2183     }
2184
2185     return globalGraph;
2186   }
2187
2188   private NTuple<Location> translateToLocTuple(MethodDescriptor md, NTuple<Descriptor> descTuple) {
2189
2190     NTuple<Location> locTuple = new NTuple<Location>();
2191
2192     Descriptor enclosingDesc = md;
2193     for (int i = 0; i < descTuple.size(); i++) {
2194       Descriptor desc = descTuple.get(i);
2195
2196       Location loc = new Location(enclosingDesc, desc);
2197       locTuple.add(loc);
2198
2199       if (desc instanceof VarDescriptor) {
2200         enclosingDesc = ((VarDescriptor) desc).getType().getClassDesc();
2201       } else if (desc instanceof FieldDescriptor) {
2202         enclosingDesc = ((FieldDescriptor) desc).getType().getClassDesc();
2203       } else {
2204         enclosingDesc = desc;
2205       }
2206
2207     }
2208
2209     return locTuple;
2210
2211   }
2212
2213   private void addValueFlowsFromCalleeSubGlobalFlowGraph(MethodDescriptor mdCaller) {
2214
2215     // the transformation for a call site propagates flows through parameters
2216     // if the method is virtual, it also grab all relations from any possible
2217     // callees
2218
2219     Set<MethodInvokeNode> setMethodInvokeNode = getMethodInvokeNodeSet(mdCaller);
2220
2221     for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
2222       MethodInvokeNode min = (MethodInvokeNode) iterator.next();
2223       MethodDescriptor mdCallee = min.getMethod();
2224       Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
2225       if (mdCallee.isStatic()) {
2226         setPossibleCallees.add(mdCallee);
2227       } else {
2228         Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
2229         // removes method descriptors that are not invoked by the caller
2230         calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
2231         setPossibleCallees.addAll(calleeSet);
2232       }
2233
2234       for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
2235         MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
2236         propagateValueFlowsToCallerFromSubGlobalFlowGraph(min, mdCaller, possibleMdCallee);
2237       }
2238
2239     }
2240
2241   }
2242
2243   private void propagateValueFlowsToCallerFromSubGlobalFlowGraph(MethodInvokeNode min,
2244       MethodDescriptor mdCaller, MethodDescriptor possibleMdCallee) {
2245
2246     // System.out.println("---propagate from " + min.printNode(0) + " to caller=" + mdCaller);
2247     FlowGraph calleeFlowGraph = getFlowGraph(possibleMdCallee);
2248     Map<Integer, NTuple<Descriptor>> mapIdxToArg = mapMethodInvokeNodeToArgIdxMap.get(min);
2249
2250     // System.out.println("-----mapMethodInvokeNodeToArgIdxMap.get(min)="
2251     // + mapMethodInvokeNodeToArgIdxMap.get(min));
2252
2253     Set<Integer> keySet = mapIdxToArg.keySet();
2254     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2255       Integer idx = (Integer) iterator.next();
2256       NTuple<Descriptor> argDescTuple = mapIdxToArg.get(idx);
2257       if (argDescTuple.size() > 0) {
2258         NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argDescTuple);
2259         NTuple<Descriptor> paramDescTuple = calleeFlowGraph.getParamFlowNode(idx).getDescTuple();
2260         NTuple<Location> paramLocTuple = translateToLocTuple(possibleMdCallee, paramDescTuple);
2261         // System.out.println("-------paramDescTuple=" + paramDescTuple + "->argDescTuple="
2262         // + argDescTuple);
2263         addMapCallerArgToCalleeParam(min, argDescTuple, paramDescTuple);
2264       }
2265     }
2266
2267     // addValueFlowBetweenParametersToCaller(min, mdCaller, possibleMdCallee);
2268
2269     NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
2270     GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(possibleMdCallee);
2271     Set<GlobalFlowNode> calleeNodeSet = calleeSubGlobalGraph.getNodeSet();
2272     for (Iterator iterator = calleeNodeSet.iterator(); iterator.hasNext();) {
2273       GlobalFlowNode calleeNode = (GlobalFlowNode) iterator.next();
2274       addValueFlowFromCalleeNode(min, mdCaller, possibleMdCallee, calleeNode);
2275     }
2276
2277     // System.out.println("$$$GLOBAL PC LOC ADD=" + mdCaller);
2278     Set<NTuple<Location>> pcLocTupleSet = mapMethodInvokeNodeToPCLocTupleSet.get(min);
2279     // System.out.println("---pcLocTupleSet=" + pcLocTupleSet);
2280     GlobalFlowGraph callerSubGlobalGraph = getSubGlobalFlowGraph(mdCaller);
2281     for (Iterator iterator = calleeNodeSet.iterator(); iterator.hasNext();) {
2282       GlobalFlowNode calleeNode = (GlobalFlowNode) iterator.next();
2283       if (calleeNode.isParamNodeWithIncomingFlows()) {
2284         // System.out.println("calleeNode.getLocTuple()" + calleeNode.getLocTuple());
2285         NTuple<Location> callerSrcNodeLocTuple =
2286             translateToCallerLocTuple(min, possibleMdCallee, mdCaller, calleeNode.getLocTuple());
2287         // System.out.println("---callerSrcNodeLocTuple=" + callerSrcNodeLocTuple);
2288         if (callerSrcNodeLocTuple != null && callerSrcNodeLocTuple.size() > 0) {
2289           for (Iterator iterator2 = pcLocTupleSet.iterator(); iterator2.hasNext();) {
2290             NTuple<Location> pcLocTuple = (NTuple<Location>) iterator2.next();
2291
2292             callerSubGlobalGraph.addValueFlowEdge(pcLocTuple, callerSrcNodeLocTuple);
2293           }
2294         }
2295       }
2296
2297     }
2298
2299   }
2300
2301   private void addValueFlowFromCalleeNode(MethodInvokeNode min, MethodDescriptor mdCaller,
2302       MethodDescriptor mdCallee, GlobalFlowNode calleeSrcNode) {
2303
2304     GlobalFlowGraph calleeSubGlobalGraph = getSubGlobalFlowGraph(mdCallee);
2305     GlobalFlowGraph callerSubGlobalGraph = getSubGlobalFlowGraph(mdCaller);
2306
2307     // System.out.println("$addValueFlowFromCalleeNode calleeSrcNode=" + calleeSrcNode);
2308
2309     NTuple<Location> callerSrcNodeLocTuple =
2310         translateToCallerLocTuple(min, mdCallee, mdCaller, calleeSrcNode.getLocTuple());
2311     // System.out.println("---callerSrcNodeLocTuple=" + callerSrcNodeLocTuple);
2312
2313     if (callerSrcNodeLocTuple != null && callerSrcNodeLocTuple.size() > 0) {
2314
2315       Set<GlobalFlowNode> outNodeSet = calleeSubGlobalGraph.getOutNodeSet(calleeSrcNode);
2316
2317       for (Iterator iterator = outNodeSet.iterator(); iterator.hasNext();) {
2318         GlobalFlowNode outNode = (GlobalFlowNode) iterator.next();
2319         NTuple<Location> callerDstNodeLocTuple =
2320             translateToCallerLocTuple(min, mdCallee, mdCaller, outNode.getLocTuple());
2321         // System.out.println("outNode=" + outNode + "   callerDstNodeLocTuple="
2322         // + callerDstNodeLocTuple);
2323         if (callerSrcNodeLocTuple != null && callerDstNodeLocTuple != null
2324             && callerSrcNodeLocTuple.size() > 0 && callerDstNodeLocTuple.size() > 0) {
2325           callerSubGlobalGraph.addValueFlowEdge(callerSrcNodeLocTuple, callerDstNodeLocTuple);
2326         }
2327       }
2328     }
2329
2330   }
2331
2332   private NTuple<Location> translateToCallerLocTuple(MethodInvokeNode min,
2333       MethodDescriptor mdCallee, MethodDescriptor mdCaller, NTuple<Location> nodeLocTuple) {
2334     // this method will return the same nodeLocTuple if the corresponding argument is literal
2335     // value.
2336
2337     // System.out.println("translateToCallerLocTuple=" + nodeLocTuple);
2338
2339     FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
2340     NTuple<Descriptor> nodeDescTuple = translateToDescTuple(nodeLocTuple);
2341     if (calleeFlowGraph.isParameter(nodeDescTuple)) {
2342       int paramIdx = calleeFlowGraph.getParamIdx(nodeDescTuple);
2343       NTuple<Descriptor> argDescTuple = mapMethodInvokeNodeToArgIdxMap.get(min).get(paramIdx);
2344
2345       // if (isPrimitive(nodeLocTuple.get(0).getLocDescriptor())) {
2346       // // the type of argument is primitive.
2347       // return nodeLocTuple.clone();
2348       // }
2349       // System.out.println("paramIdx=" + paramIdx + "  argDescTuple=" + argDescTuple + " from min="
2350       // + min.printNode(0));
2351       NTuple<Location> argLocTuple = translateToLocTuple(mdCaller, argDescTuple);
2352
2353       NTuple<Location> callerLocTuple = new NTuple<Location>();
2354
2355       callerLocTuple.addAll(argLocTuple);
2356       for (int i = 1; i < nodeLocTuple.size(); i++) {
2357         callerLocTuple.add(nodeLocTuple.get(i));
2358       }
2359       return callerLocTuple;
2360     } else {
2361       return nodeLocTuple.clone();
2362     }
2363
2364   }
2365
2366   public static boolean isPrimitive(Descriptor desc) {
2367
2368     if (desc instanceof FieldDescriptor) {
2369       return ((FieldDescriptor) desc).getType().isPrimitive();
2370     } else if (desc instanceof VarDescriptor) {
2371       return ((VarDescriptor) desc).getType().isPrimitive();
2372     } else if (desc instanceof InterDescriptor) {
2373       return true;
2374     }
2375
2376     return false;
2377   }
2378
2379   public static boolean isReference(Descriptor desc) {
2380
2381     if (desc instanceof FieldDescriptor) {
2382
2383       TypeDescriptor type = ((FieldDescriptor) desc).getType();
2384       if (type.isArray()) {
2385         return !type.isPrimitive();
2386       } else {
2387         return type.isPtr();
2388       }
2389
2390     } else if (desc instanceof VarDescriptor) {
2391       TypeDescriptor type = ((VarDescriptor) desc).getType();
2392       if (type.isArray()) {
2393         return !type.isPrimitive();
2394       } else {
2395         return type.isPtr();
2396       }
2397     }
2398
2399     return false;
2400   }
2401
2402   private NTuple<Descriptor> translateToDescTuple(NTuple<Location> locTuple) {
2403
2404     NTuple<Descriptor> descTuple = new NTuple<Descriptor>();
2405     for (int i = 0; i < locTuple.size(); i++) {
2406       descTuple.add(locTuple.get(i).getLocDescriptor());
2407     }
2408     return descTuple;
2409
2410   }
2411
2412   public LocationSummary getLocationSummary(Descriptor d) {
2413     if (!mapDescToLocationSummary.containsKey(d)) {
2414       if (d instanceof MethodDescriptor) {
2415         mapDescToLocationSummary.put(d, new MethodSummary((MethodDescriptor) d));
2416       } else if (d instanceof ClassDescriptor) {
2417         mapDescToLocationSummary.put(d, new FieldSummary());
2418       }
2419     }
2420     return mapDescToLocationSummary.get(d);
2421   }
2422
2423   private void generateMethodSummary() {
2424
2425     Set<MethodDescriptor> keySet = md2lattice.keySet();
2426     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2427       MethodDescriptor md = (MethodDescriptor) iterator.next();
2428
2429       System.out.println("\nSSJAVA: generate method summary: " + md);
2430
2431       FlowGraph flowGraph = getFlowGraph(md);
2432       if (flowGraph == null) {
2433         continue;
2434       }
2435       MethodSummary methodSummary = getMethodSummary(md);
2436
2437       HierarchyGraph scGraph = getSkeletonCombinationHierarchyGraph(md);
2438
2439       // set the 'this' reference location
2440       if (!md.isStatic()) {
2441         // System.out.println("setThisLocName=" + scGraph.getHNode(md.getThis()).getName());
2442         methodSummary.setThisLocName(scGraph.getHNode(md.getThis()).getName());
2443       }
2444
2445       // set the 'global' reference location if needed
2446       if (methodSummary.hasGlobalAccess()) {
2447         methodSummary.setGlobalLocName(scGraph.getHNode(GLOBALDESC).getName());
2448       }
2449
2450       // construct a parameter mapping that maps a parameter descriptor to an
2451       // inferred composite location
2452       for (int paramIdx = 0; paramIdx < flowGraph.getNumParameters(); paramIdx++) {
2453         FlowNode flowNode = flowGraph.getParamFlowNode(paramIdx);
2454         CompositeLocation inferredCompLoc =
2455             updateCompositeLocation(flowNode.getCompositeLocation());
2456         // System.out.println("-paramIdx=" + paramIdx + "   infer=" + inferredCompLoc + " original="
2457         // + flowNode.getCompositeLocation());
2458
2459         Descriptor localVarDesc = flowNode.getDescTuple().get(0);
2460         methodSummary.addMapVarNameToInferCompLoc(localVarDesc, inferredCompLoc);
2461         methodSummary.addMapParamIdxToInferLoc(paramIdx, inferredCompLoc);
2462       }
2463
2464     }
2465
2466   }
2467
2468   private boolean hasOrderingRelation(NTuple<Location> locTuple1, NTuple<Location> locTuple2) {
2469
2470     int size = locTuple1.size() >= locTuple2.size() ? locTuple2.size() : locTuple1.size();
2471
2472     for (int idx = 0; idx < size; idx++) {
2473       Location loc1 = locTuple1.get(idx);
2474       Location loc2 = locTuple2.get(idx);
2475
2476       Descriptor desc1 = loc1.getDescriptor();
2477       Descriptor desc2 = loc2.getDescriptor();
2478
2479       if (!desc1.equals(desc2)) {
2480         throw new Error("Fail to compare " + locTuple1 + " and " + locTuple2);
2481       }
2482
2483       Descriptor locDesc1 = loc1.getLocDescriptor();
2484       Descriptor locDesc2 = loc2.getLocDescriptor();
2485
2486       HierarchyGraph hierarchyGraph = getHierarchyGraph(desc1);
2487
2488       HNode node1 = hierarchyGraph.getHNode(locDesc1);
2489       HNode node2 = hierarchyGraph.getHNode(locDesc2);
2490
2491       // System.out.println("---node1=" + node1 + "  node2=" + node2);
2492       // System.out.println("---hierarchyGraph.getIncomingNodeSet(node2)="
2493       // + hierarchyGraph.getIncomingNodeSet(node2));
2494
2495       if (locDesc1.equals(locDesc2)) {
2496         continue;
2497       } else if (!hierarchyGraph.getIncomingNodeSet(node2).contains(node1)
2498           && !hierarchyGraph.getIncomingNodeSet(node1).contains(node2)) {
2499         return false;
2500       } else {
2501         return true;
2502       }
2503
2504     }
2505
2506     return false;
2507
2508   }
2509
2510   private boolean isHigherThan(NTuple<Location> locTuple1, NTuple<Location> locTuple2) {
2511
2512     int size = locTuple1.size() >= locTuple2.size() ? locTuple2.size() : locTuple1.size();
2513
2514     for (int idx = 0; idx < size; idx++) {
2515       Location loc1 = locTuple1.get(idx);
2516       Location loc2 = locTuple2.get(idx);
2517
2518       Descriptor desc1 = loc1.getDescriptor();
2519       Descriptor desc2 = loc2.getDescriptor();
2520
2521       if (!desc1.equals(desc2)) {
2522         throw new Error("Fail to compare " + locTuple1 + " and " + locTuple2);
2523       }
2524
2525       Descriptor locDesc1 = loc1.getLocDescriptor();
2526       Descriptor locDesc2 = loc2.getLocDescriptor();
2527
2528       HierarchyGraph hierarchyGraph = getHierarchyGraph(desc1);
2529
2530       HNode node1 = hierarchyGraph.getHNode(locDesc1);
2531       HNode node2 = hierarchyGraph.getHNode(locDesc2);
2532
2533       // System.out.println("---node1=" + node1 + "  node2=" + node2);
2534       // System.out.println("---hierarchyGraph.getIncomingNodeSet(node2)="
2535       // + hierarchyGraph.getIncomingNodeSet(node2));
2536
2537       if (locDesc1.equals(locDesc2)) {
2538         continue;
2539       } else if (hierarchyGraph.getIncomingNodeSet(node2).contains(node1)) {
2540         return true;
2541       } else {
2542         return false;
2543       }
2544
2545     }
2546
2547     return false;
2548   }
2549
2550   private void debug_writeLattices() {
2551
2552     Set<Descriptor> keySet = mapDescriptorToSkeletonLattice.keySet();
2553     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2554       Descriptor key = (Descriptor) iterator.next();
2555       SSJavaLattice<String> skeletonLattice = mapDescriptorToSkeletonLattice.get(key);
2556       // HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(key);
2557       HierarchyGraph scHierarchyGraph = getSkeletonCombinationHierarchyGraph(key);
2558       if (key instanceof ClassDescriptor) {
2559         writeInferredLatticeDotFile((ClassDescriptor) key, skeletonLattice, "_SKELETON");
2560       } else if (key instanceof MethodDescriptor) {
2561         MethodDescriptor md = (MethodDescriptor) key;
2562         writeInferredLatticeDotFile(md.getClassDesc(), md, skeletonLattice, "_SKELETON");
2563       }
2564
2565       LocationSummary ls = getLocationSummary(key);
2566       // System.out.println("####LOC SUMMARY=" + key + "\n" + ls.getMapHNodeNameToLocationName());
2567     }
2568
2569     Set<ClassDescriptor> cdKeySet = cd2lattice.keySet();
2570     for (Iterator iterator = cdKeySet.iterator(); iterator.hasNext();) {
2571       ClassDescriptor cd = (ClassDescriptor) iterator.next();
2572       // System.out.println("########cd=" + cd);
2573       writeInferredLatticeDotFile((ClassDescriptor) cd, cd2lattice.get(cd), "");
2574       COUNT += cd2lattice.get(cd).getKeySet().size();
2575     }
2576
2577     Set<MethodDescriptor> mdKeySet = md2lattice.keySet();
2578     for (Iterator iterator = mdKeySet.iterator(); iterator.hasNext();) {
2579       MethodDescriptor md = (MethodDescriptor) iterator.next();
2580       writeInferredLatticeDotFile(md.getClassDesc(), md, md2lattice.get(md), "");
2581       COUNT += md2lattice.get(md).getKeySet().size();
2582     }
2583     System.out.println("###COUNT=" + COUNT);
2584
2585     Set<Descriptor> descKeySet = desc2naiveLattice.keySet();
2586     for (Iterator iterator = descKeySet.iterator(); iterator.hasNext();) {
2587       Descriptor desc = (Descriptor) iterator.next();
2588       // System.out.println("########cd=" + cd);
2589
2590       ClassDescriptor cd_naive;
2591       MethodDescriptor md_naive;
2592       if (desc instanceof ClassDescriptor) {
2593         cd_naive = (ClassDescriptor) desc;
2594         md_naive = null;
2595       } else {
2596         md_naive = (MethodDescriptor) desc;
2597         cd_naive = md_naive.getClassDesc();
2598       }
2599
2600       writeInferredLatticeDotFile(cd_naive, md_naive, desc2naiveLattice.get(desc), "_naive");
2601     }
2602   }
2603
2604   private void buildLattice(Descriptor desc) {
2605     // System.out.println("buildLattice=" + desc);
2606     SSJavaLattice<String> skeletonLattice = buildLattice.buildLattice(desc);
2607
2608     addMapDescToSkeletonLattice(desc, skeletonLattice);
2609
2610     // write a dot file before everything is done
2611     if (desc instanceof ClassDescriptor) {
2612       writeInferredLatticeDotFile((ClassDescriptor) desc, null, skeletonLattice, "_SC");
2613     } else {
2614       MethodDescriptor md = (MethodDescriptor) desc;
2615       writeInferredLatticeDotFile(md.getClassDesc(), md, skeletonLattice, "_SC");
2616     }
2617
2618     HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
2619
2620     // System.out.println("\n## insertIntermediateNodesToStraightLine:"
2621     // + simpleHierarchyGraph.getName());
2622     SSJavaLattice<String> lattice =
2623         buildLattice.insertIntermediateNodesToStraightLine(desc, skeletonLattice);
2624
2625     if (lattice == null) {
2626       return;
2627     }
2628     lattice.removeRedundantEdges();
2629
2630     LocationInference.numLocationsSInfer += lattice.getKeySet().size();
2631
2632     if (desc instanceof ClassDescriptor) {
2633       // field lattice
2634       cd2lattice.put((ClassDescriptor) desc, lattice);
2635       ssjava.writeLatticeDotFile((ClassDescriptor) desc, null, lattice);
2636     } else if (desc instanceof MethodDescriptor) {
2637       // method lattice
2638       md2lattice.put((MethodDescriptor) desc, lattice);
2639       MethodDescriptor md = (MethodDescriptor) desc;
2640       ClassDescriptor cd = md.getClassDesc();
2641       ssjava.writeLatticeDotFile(cd, md, lattice);
2642     }
2643
2644   }
2645
2646   // deprecated: it builds method/class lattices without considering class inheritance
2647   private void buildLattice() {
2648
2649     Set<Descriptor> keySet = mapDescriptorToCombineSkeletonHierarchyGraph.keySet();
2650     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2651       Descriptor desc = (Descriptor) iterator.next();
2652
2653       SSJavaLattice<String> simpleLattice = buildLattice.buildLattice(desc);
2654
2655       addMapDescToSkeletonLattice(desc, simpleLattice);
2656
2657       HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
2658       System.out.println("\n## insertIntermediateNodesToStraightLine:"
2659           + simpleHierarchyGraph.getName());
2660       SSJavaLattice<String> lattice =
2661           buildLattice.insertIntermediateNodesToStraightLine(desc, simpleLattice);
2662       lattice.removeRedundantEdges();
2663
2664       LocationInference.numLocationsSInfer += lattice.getKeySet().size();
2665
2666       if (desc instanceof ClassDescriptor) {
2667         // field lattice
2668         cd2lattice.put((ClassDescriptor) desc, lattice);
2669         // ssjava.writeLatticeDotFile((ClassDescriptor) desc, null, lattice);
2670       } else if (desc instanceof MethodDescriptor) {
2671         // method lattice
2672         md2lattice.put((MethodDescriptor) desc, lattice);
2673         MethodDescriptor md = (MethodDescriptor) desc;
2674         ClassDescriptor cd = md.getClassDesc();
2675         // ssjava.writeLatticeDotFile(cd, md, lattice);
2676       }
2677
2678     }
2679
2680   }
2681
2682   private void buildLatticeInheritanceTree() {
2683     // DFS the inheritance tree and propagates lattice nodes/edges from the parent to children
2684     // Node<ClassDescriptor> rootNode = inheritanceTree.getRootNode();
2685     DFSBuildLatticeInheritanceTree(rootClassDescriptor);
2686   }
2687
2688   public Set<ClassDescriptor> getDirectSubClasses(ClassDescriptor parent) {
2689
2690     Set<ClassDescriptor> result = new HashSet<ClassDescriptor>();
2691
2692     Set<ClassDescriptor> children = tu.getDirectSubClasses(parent);
2693     if (children == null) {
2694       children = new HashSet<ClassDescriptor>();
2695     }
2696
2697     for (Iterator iterator = children.iterator(); iterator.hasNext();) {
2698       ClassDescriptor child = (ClassDescriptor) iterator.next();
2699       if (toanalyze_classDescSet.contains(child)) {
2700         result.add(child);
2701       }
2702     }
2703
2704     return result;
2705   }
2706
2707   private void DFSBuildLatticeInheritanceTree(ClassDescriptor cd) {
2708     // ClassDescriptor cd = node.getData();
2709
2710     ClassDescriptor parentClassDesc = cd.getSuperDesc();
2711     if (parentClassDesc != null) {
2712       Map<TripleItem, String> parentMap = buildLattice.getIntermediateLocMap(parentClassDesc);
2713       buildLattice.setIntermediateLocMap(cd, parentMap);
2714     }
2715
2716     buildLattice(cd);
2717
2718     for (Iterator iterator = cd.getMethods(); iterator.hasNext();) {
2719       MethodDescriptor md = (MethodDescriptor) iterator.next();
2720       if (toanalyze_methodDescList.contains(md)) {
2721         MethodDescriptor parentMethodDesc = getParentMethodDesc(md.getClassDesc(), md);
2722         if (parentMethodDesc != null) {
2723           Map<TripleItem, String> parentMap = buildLattice.getIntermediateLocMap(parentMethodDesc);
2724           Map<TripleItem, String> childMap = new HashMap<TripleItem, String>();
2725           Set<TripleItem> keySet = parentMap.keySet();
2726           for (Iterator iterator2 = keySet.iterator(); iterator2.hasNext();) {
2727             TripleItem key = (TripleItem) iterator2.next();
2728             childMap.put(key, parentMap.get(key));
2729           }
2730           buildLattice.setIntermediateLocMap(md, childMap);
2731         }
2732         buildLattice(md);
2733       }
2734     }
2735
2736     // traverse children
2737     Set<ClassDescriptor> children = tu.getDirectSubClasses(cd);
2738     if (children != null) {
2739       for (Iterator iterator = children.iterator(); iterator.hasNext();) {
2740         ClassDescriptor classDescriptor = (ClassDescriptor) iterator.next();
2741         if (toanalyze_classDescSet.contains(classDescriptor)) {
2742           DFSBuildLatticeInheritanceTree(classDescriptor);
2743         } else {
2744           if (classDescriptor.isAbstract()) {
2745             DFSBuildLatticeInheritanceTree(classDescriptor);
2746           }
2747         }
2748       }
2749     }
2750
2751   }
2752
2753   public void addMapDescToSkeletonLattice(Descriptor desc, SSJavaLattice<String> lattice) {
2754     mapDescriptorToSkeletonLattice.put(desc, lattice);
2755   }
2756
2757   public SSJavaLattice<String> getSkeletonLattice(Descriptor desc) {
2758     return mapDescriptorToSkeletonLattice.get(desc);
2759   }
2760
2761   private void simplifyHierarchyGraph() {
2762     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
2763     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2764       Descriptor desc = (Descriptor) iterator.next();
2765       // System.out.println("SSJAVA: remove redundant edges: " + desc);
2766       HierarchyGraph simpleHierarchyGraph = getHierarchyGraph(desc).clone();
2767       simpleHierarchyGraph.setName(desc + "_SIMPLE");
2768       simpleHierarchyGraph.removeRedundantEdges();
2769       mapDescriptorToSimpleHierarchyGraph.put(desc, simpleHierarchyGraph);
2770     }
2771   }
2772
2773   private void insertCombinationNodes() {
2774     Set<Descriptor> keySet = mapDescriptorToSkeletonHierarchyGraph.keySet();
2775     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2776       Descriptor desc = (Descriptor) iterator.next();
2777       System.out.println("\nSSJAVA: Inserting Combination Nodes:" + desc);
2778       HierarchyGraph skeletonGraph = getSkeletonHierarchyGraph(desc);
2779       HierarchyGraph skeletonGraphWithCombinationNode = skeletonGraph.clone();
2780       skeletonGraphWithCombinationNode.setSCGraph(true);
2781       skeletonGraphWithCombinationNode.setName(desc + "_SC");
2782
2783       HierarchyGraph simpleHierarchyGraph = getSimpleHierarchyGraph(desc);
2784       skeletonGraphWithCombinationNode.insertCombinationNodesToGraph(simpleHierarchyGraph);
2785       // skeletonGraphWithCombinationNode.insertCombinationNodesToGraph(simpleHierarchyGraph,
2786       // skeletonGraph);
2787       // skeletonGraphWithCombinationNode.simplifySkeletonCombinationHierarchyGraph();
2788       skeletonGraphWithCombinationNode.removeRedundantEdges();
2789       mapDescriptorToCombineSkeletonHierarchyGraph.put(desc, skeletonGraphWithCombinationNode);
2790     }
2791   }
2792
2793   private void constructSkeletonHierarchyGraph() {
2794     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
2795     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2796       Descriptor desc = (Descriptor) iterator.next();
2797       System.out.println("SSJAVA: Constructing Skeleton Hierarchy Graph: " + desc);
2798       HierarchyGraph simpleGraph = getSimpleHierarchyGraph(desc);
2799       HierarchyGraph skeletonGraph = simpleGraph.generateSkeletonGraph();
2800       skeletonGraph.setMapDescToHNode(simpleGraph.getMapDescToHNode());
2801       skeletonGraph.setMapHNodeToDescSet(simpleGraph.getMapHNodeToDescSet());
2802       skeletonGraph.simplifyHierarchyGraph(this);
2803       mapDescriptorToSkeletonHierarchyGraph.put(desc, skeletonGraph);
2804     }
2805   }
2806
2807   private void recurUpAccumulateInheritanceDesc(Descriptor curDesc, Set<Descriptor> set) {
2808
2809     if (curDesc instanceof ClassDescriptor) {
2810       ClassDescriptor cd = (ClassDescriptor) curDesc;
2811       ClassDescriptor parentClassDesc = cd.getSuperDesc();
2812       if (parentClassDesc != null && !parentClassDesc.equals(rootClassDescriptor)) {
2813         set.add(parentClassDesc);
2814         recurUpAccumulateInheritanceDesc(parentClassDesc, set);
2815       }
2816     } else {
2817       MethodDescriptor md = (MethodDescriptor) curDesc;
2818       ClassDescriptor cd = md.getClassDesc();
2819
2820       // traverse up
2821       ClassDescriptor parentClassDesc = cd.getSuperDesc();
2822       if (parentClassDesc != null && !parentClassDesc.equals(rootClassDescriptor)) {
2823
2824         Set<MethodDescriptor> methodDescSet =
2825             parentClassDesc.getMethodTable().getSet(md.getSymbol());
2826         for (Iterator iterator = methodDescSet.iterator(); iterator.hasNext();) {
2827           MethodDescriptor parentMethodDesc = (MethodDescriptor) iterator.next();
2828           if (parentMethodDesc.matches(md)) {
2829             set.add(parentMethodDesc);
2830             recurUpAccumulateInheritanceDesc(parentMethodDesc, set);
2831           }
2832         }
2833       }
2834
2835     }
2836
2837   }
2838
2839   private void recurDownAccumulateInheritanceDesc(Descriptor curDesc, Set<Descriptor> set) {
2840
2841     if (curDesc instanceof ClassDescriptor) {
2842       ClassDescriptor cd = (ClassDescriptor) curDesc;
2843       ClassDescriptor parentClassDesc = cd.getSuperDesc();
2844       Set<ClassDescriptor> directSubClasses = tu.getDirectSubClasses(cd);
2845       for (Iterator iterator = directSubClasses.iterator(); iterator.hasNext();) {
2846         ClassDescriptor child = (ClassDescriptor) iterator.next();
2847         recurDownAccumulateInheritanceDesc(child, set);
2848       }
2849     } else {
2850       MethodDescriptor md = (MethodDescriptor) curDesc;
2851       ClassDescriptor cd = md.getClassDesc();
2852
2853       // traverse down
2854       Set<ClassDescriptor> directSubClasses = tu.getDirectSubClasses(cd);
2855       for (Iterator iterator = directSubClasses.iterator(); iterator.hasNext();) {
2856         ClassDescriptor child = (ClassDescriptor) iterator.next();
2857
2858         Set<MethodDescriptor> methodDescSet = child.getMethodTable().getSet(md.getSymbol());
2859         for (Iterator iterator2 = methodDescSet.iterator(); iterator2.hasNext();) {
2860           MethodDescriptor childMethodDesc = (MethodDescriptor) iterator2.next();
2861           if (childMethodDesc.matches(md)) {
2862             set.add(childMethodDesc);
2863             recurDownAccumulateInheritanceDesc(childMethodDesc, set);
2864           }
2865         }
2866       }
2867
2868     }
2869
2870   }
2871
2872   private void accumulateInheritanceDesc(Descriptor curDesc, Set<Descriptor> set) {
2873
2874     recurUpAccumulateInheritanceDesc(curDesc, set);
2875     recurDownAccumulateInheritanceDesc(curDesc, set);
2876
2877   }
2878
2879   public boolean isValidMergeInheritanceCheck(Descriptor desc, Set<HNode> mergeSet) {
2880
2881     // set up inheritance chain set...
2882     Set<Descriptor> inheritanceDescSet = new HashSet<Descriptor>();
2883     recurUpAccumulateInheritanceDesc(desc, inheritanceDescSet);
2884
2885     nextgraph: for (Iterator iterator = inheritanceDescSet.iterator(); iterator.hasNext();) {
2886       Descriptor inheritDesc = (Descriptor) iterator.next();
2887
2888       if (!desc.equals(inheritDesc)) {
2889         HierarchyGraph graph = getSkeletonCombinationHierarchyGraph(inheritDesc);
2890
2891         // first check whether this graph includes all elements of the merge set
2892         for (Iterator iterator2 = mergeSet.iterator(); iterator2.hasNext();) {
2893           HNode node = (HNode) iterator2.next();
2894           if (!graph.contains(node)) {
2895             continue nextgraph;
2896           }
2897         }
2898
2899         HNode firstNode = mergeSet.iterator().next();
2900
2901         Set<HNode> incomingNode = graph.getIncomingNodeSet(firstNode);
2902         Set<HNode> outgoingNode = graph.getOutgoingNodeSet(firstNode);
2903
2904         for (Iterator iterator2 = mergeSet.iterator(); iterator2.hasNext();) {
2905           HNode node = (HNode) iterator2.next();
2906
2907           if (!graph.getIncomingNodeSet(node).equals(incomingNode)
2908               || !graph.getOutgoingNodeSet(node).equals(outgoingNode)) {
2909             return false;
2910           }
2911
2912         }
2913       }
2914
2915     }
2916
2917     return true;
2918   }
2919
2920   private void debug_writeHierarchyDotFiles() {
2921
2922     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
2923     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2924       Descriptor desc = (Descriptor) iterator.next();
2925       getHierarchyGraph(desc).writeGraph();
2926     }
2927
2928   }
2929
2930   private void debug_writeSimpleHierarchyDotFiles() {
2931
2932     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
2933     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2934       Descriptor desc = (Descriptor) iterator.next();
2935       getHierarchyGraph(desc).writeGraph();
2936       getSimpleHierarchyGraph(desc).writeGraph();
2937       getSimpleHierarchyGraph(desc).writeGraph(true);
2938     }
2939
2940   }
2941
2942   private void debug_writeSkeletonHierarchyDotFiles() {
2943
2944     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
2945     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2946       Descriptor desc = (Descriptor) iterator.next();
2947       getSkeletonHierarchyGraph(desc).writeGraph();
2948     }
2949
2950   }
2951
2952   private void debug_writeSkeletonCombinationHierarchyDotFiles() {
2953
2954     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
2955     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
2956       Descriptor desc = (Descriptor) iterator.next();
2957       getSkeletonCombinationHierarchyGraph(desc).writeGraph();
2958     }
2959
2960   }
2961
2962   public HierarchyGraph getSimpleHierarchyGraph(Descriptor d) {
2963     return mapDescriptorToSimpleHierarchyGraph.get(d);
2964   }
2965
2966   private HierarchyGraph getSkeletonHierarchyGraph(Descriptor d) {
2967     if (!mapDescriptorToSkeletonHierarchyGraph.containsKey(d)) {
2968       mapDescriptorToSkeletonHierarchyGraph.put(d, new HierarchyGraph(d));
2969     }
2970     return mapDescriptorToSkeletonHierarchyGraph.get(d);
2971   }
2972
2973   public HierarchyGraph getSkeletonCombinationHierarchyGraph(Descriptor d) {
2974     if (!mapDescriptorToCombineSkeletonHierarchyGraph.containsKey(d)) {
2975       mapDescriptorToCombineSkeletonHierarchyGraph.put(d, new HierarchyGraph(d));
2976     }
2977     return mapDescriptorToCombineSkeletonHierarchyGraph.get(d);
2978   }
2979
2980   private void constructHierarchyGraph() {
2981
2982     LinkedList<MethodDescriptor> methodDescList =
2983         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
2984
2985     while (!methodDescList.isEmpty()) {
2986       MethodDescriptor md = methodDescList.removeLast();
2987       if (state.SSJAVADEBUG) {
2988         HierarchyGraph hierarchyGraph = new HierarchyGraph(md);
2989         System.out.println();
2990         System.out.println("SSJAVA: Construcing the hierarchy graph from " + md);
2991         constructHierarchyGraph(md, hierarchyGraph);
2992         mapDescriptorToHierarchyGraph.put(md, hierarchyGraph);
2993
2994       }
2995     }
2996
2997     setupToAnalyze();
2998     while (!toAnalyzeIsEmpty()) {
2999       ClassDescriptor cd = toAnalyzeNext();
3000       HierarchyGraph graph = getHierarchyGraph(cd);
3001       for (Iterator iter = cd.getFields(); iter.hasNext();) {
3002         FieldDescriptor fieldDesc = (FieldDescriptor) iter.next();
3003         if (!(fieldDesc.isStatic() && fieldDesc.isFinal())) {
3004           graph.getHNode(fieldDesc);
3005         }
3006       }
3007     }
3008
3009     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
3010     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
3011       Descriptor key = (Descriptor) iterator.next();
3012       HierarchyGraph graph = getHierarchyGraph(key);
3013
3014       Set<HNode> nodeToBeConnected = new HashSet<HNode>();
3015       for (Iterator iterator2 = graph.getNodeSet().iterator(); iterator2.hasNext();) {
3016         HNode node = (HNode) iterator2.next();
3017         if (!node.isSkeleton() && !node.isCombinationNode()) {
3018           if (graph.getIncomingNodeSet(node).size() == 0) {
3019             nodeToBeConnected.add(node);
3020           }
3021         }
3022       }
3023
3024       for (Iterator iterator2 = nodeToBeConnected.iterator(); iterator2.hasNext();) {
3025         HNode node = (HNode) iterator2.next();
3026         // System.out.println("NEED TO BE CONNECTED TO TOP=" + node);
3027         graph.addEdge(graph.getHNode(TOPDESC), node);
3028       }
3029
3030     }
3031
3032   }
3033
3034   private void constructHierarchyGraph2() {
3035
3036     // do fixed-point analysis
3037
3038     LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
3039
3040     // Collections.sort(descriptorListToAnalyze, new
3041     // Comparator<MethodDescriptor>() {
3042     // public int compare(MethodDescriptor o1, MethodDescriptor o2) {
3043     // return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
3044     // }
3045     // });
3046
3047     // current descriptors to visit in fixed-point interprocedural analysis,
3048     // prioritized by dependency in the call graph
3049     methodDescriptorsToVisitStack.clear();
3050
3051     Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
3052     methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
3053
3054     while (!descriptorListToAnalyze.isEmpty()) {
3055       MethodDescriptor md = descriptorListToAnalyze.removeFirst();
3056       methodDescriptorsToVisitStack.add(md);
3057     }
3058
3059     // analyze scheduled methods until there are no more to visit
3060     while (!methodDescriptorsToVisitStack.isEmpty()) {
3061       // start to analyze leaf node
3062       MethodDescriptor md = methodDescriptorsToVisitStack.pop();
3063
3064       HierarchyGraph hierarchyGraph = new HierarchyGraph(md);
3065       // MethodSummary methodSummary = new MethodSummary(md);
3066
3067       // MethodLocationInfo methodInfo = new MethodLocationInfo(md);
3068       // curMethodInfo = methodInfo;
3069
3070       System.out.println();
3071       System.out.println("SSJAVA: Construcing the hierarchy graph from " + md);
3072
3073       constructHierarchyGraph(md, hierarchyGraph);
3074
3075       HierarchyGraph prevHierarchyGraph = getHierarchyGraph(md);
3076       // MethodSummary prevMethodSummary = getMethodSummary(md);
3077
3078       if (!hierarchyGraph.equals(prevHierarchyGraph)) {
3079
3080         mapDescriptorToHierarchyGraph.put(md, hierarchyGraph);
3081         // mapDescToLocationSummary.put(md, methodSummary);
3082
3083         // results for callee changed, so enqueue dependents caller for
3084         // further analysis
3085         Iterator<MethodDescriptor> depsItr = ssjava.getDependents(md).iterator();
3086         while (depsItr.hasNext()) {
3087           MethodDescriptor methodNext = depsItr.next();
3088           if (!methodDescriptorsToVisitStack.contains(methodNext)
3089               && methodDescriptorToVistSet.contains(methodNext)) {
3090             methodDescriptorsToVisitStack.add(methodNext);
3091           }
3092         }
3093
3094       }
3095
3096     }
3097
3098     setupToAnalyze();
3099     while (!toAnalyzeIsEmpty()) {
3100       ClassDescriptor cd = toAnalyzeNext();
3101       HierarchyGraph graph = getHierarchyGraph(cd);
3102       for (Iterator iter = cd.getFields(); iter.hasNext();) {
3103         FieldDescriptor fieldDesc = (FieldDescriptor) iter.next();
3104         if (!(fieldDesc.isStatic() && fieldDesc.isFinal())) {
3105           graph.getHNode(fieldDesc);
3106         }
3107       }
3108     }
3109
3110     Set<Descriptor> keySet = mapDescriptorToHierarchyGraph.keySet();
3111     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
3112       Descriptor key = (Descriptor) iterator.next();
3113       HierarchyGraph graph = getHierarchyGraph(key);
3114
3115       Set<HNode> nodeToBeConnected = new HashSet<HNode>();
3116       for (Iterator iterator2 = graph.getNodeSet().iterator(); iterator2.hasNext();) {
3117         HNode node = (HNode) iterator2.next();
3118         if (!node.isSkeleton() && !node.isCombinationNode()) {
3119           if (graph.getIncomingNodeSet(node).size() == 0) {
3120             nodeToBeConnected.add(node);
3121           }
3122         }
3123       }
3124
3125       for (Iterator iterator2 = nodeToBeConnected.iterator(); iterator2.hasNext();) {
3126         HNode node = (HNode) iterator2.next();
3127         // System.out.println("NEED TO BE CONNECTED TO TOP=" + node);
3128         graph.addEdge(graph.getHNode(TOPDESC), node);
3129       }
3130
3131     }
3132
3133   }
3134
3135   private HierarchyGraph getHierarchyGraph(Descriptor d) {
3136     if (!mapDescriptorToHierarchyGraph.containsKey(d)) {
3137       mapDescriptorToHierarchyGraph.put(d, new HierarchyGraph(d));
3138     }
3139     return mapDescriptorToHierarchyGraph.get(d);
3140   }
3141
3142   private void constructHierarchyGraph(MethodDescriptor md, HierarchyGraph methodGraph) {
3143
3144     // visit each node of method flow graph
3145     FlowGraph fg = getFlowGraph(md);
3146     // Set<FlowNode> nodeSet = fg.getNodeSet();
3147
3148     Set<FlowEdge> edgeSet = fg.getEdgeSet();
3149
3150     Set<Descriptor> paramDescSet = fg.getMapParamDescToIdx().keySet();
3151     for (Iterator iterator = paramDescSet.iterator(); iterator.hasNext();) {
3152       Descriptor desc = (Descriptor) iterator.next();
3153       methodGraph.getHNode(desc).setSkeleton(true);
3154     }
3155
3156     // for the method lattice, we need to look at the first element of
3157     // NTuple<Descriptor>
3158     boolean hasGlobalAccess = false;
3159     // for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
3160     // FlowNode originalSrcNode = (FlowNode) iterator.next();
3161     for (Iterator iterator = edgeSet.iterator(); iterator.hasNext();) {
3162       FlowEdge edge = (FlowEdge) iterator.next();
3163
3164       FlowNode originalSrcNode = fg.getFlowNode(edge.getInitTuple());
3165       Set<FlowNode> sourceNodeSet = new HashSet<FlowNode>();
3166       if (originalSrcNode instanceof FlowReturnNode) {
3167         FlowReturnNode rnode = (FlowReturnNode) originalSrcNode;
3168         // System.out.println("rnode=" + rnode);
3169         Set<NTuple<Descriptor>> tupleSet = rnode.getReturnTupleSet();
3170         for (Iterator iterator2 = tupleSet.iterator(); iterator2.hasNext();) {
3171           NTuple<Descriptor> nTuple = (NTuple<Descriptor>) iterator2.next();
3172           sourceNodeSet.add(fg.getFlowNode(nTuple));
3173           // System.out.println("&&&SOURCE fg.getFlowNode(nTuple)=" + fg.getFlowNode(nTuple));
3174         }
3175       } else {
3176         sourceNodeSet.add(originalSrcNode);
3177       }
3178
3179       // System.out.println("---sourceNodeSet=" + sourceNodeSet + "  from originalSrcNode="
3180       // + originalSrcNode);
3181
3182       for (Iterator iterator3 = sourceNodeSet.iterator(); iterator3.hasNext();) {
3183         FlowNode srcNode = (FlowNode) iterator3.next();
3184
3185         NTuple<Descriptor> srcNodeTuple = srcNode.getDescTuple();
3186         Descriptor srcLocalDesc = srcNodeTuple.get(0);
3187
3188         if (srcLocalDesc instanceof InterDescriptor
3189             && ((InterDescriptor) srcLocalDesc).getMethodArgIdxPair() != null) {
3190
3191           if (srcNode.getCompositeLocation() == null) {
3192             continue;
3193           }
3194         }
3195
3196         // if the srcNode is started with the global descriptor
3197         // need to set as a skeleton node
3198         if (!hasGlobalAccess && srcNode.getDescTuple().startsWith(GLOBALDESC)) {
3199           hasGlobalAccess = true;
3200         }
3201
3202         // Set<FlowEdge> outEdgeSet = fg.getOutEdgeSet(originalSrcNode);
3203         // for (Iterator iterator2 = outEdgeSet.iterator(); iterator2.hasNext();) {
3204         // FlowEdge outEdge = (FlowEdge) iterator2.next();
3205         // FlowNode originalDstNode = outEdge.getDst();
3206         FlowNode originalDstNode = fg.getFlowNode(edge.getEndTuple());
3207
3208         Set<FlowNode> dstNodeSet = new HashSet<FlowNode>();
3209         if (originalDstNode instanceof FlowReturnNode) {
3210           FlowReturnNode rnode = (FlowReturnNode) originalDstNode;
3211           // System.out.println("\n-returnNode=" + rnode);
3212           Set<NTuple<Descriptor>> tupleSet = rnode.getReturnTupleSet();
3213           for (Iterator iterator4 = tupleSet.iterator(); iterator4.hasNext();) {
3214             NTuple<Descriptor> nTuple = (NTuple<Descriptor>) iterator4.next();
3215             dstNodeSet.add(fg.getFlowNode(nTuple));
3216             // System.out.println("&&&DST fg.getFlowNode(nTuple)=" + fg.getFlowNode(nTuple));
3217           }
3218         } else {
3219           dstNodeSet.add(originalDstNode);
3220         }
3221         // System.out.println("---dstNodeSet=" + dstNodeSet);
3222         for (Iterator iterator4 = dstNodeSet.iterator(); iterator4.hasNext();) {
3223           FlowNode dstNode = (FlowNode) iterator4.next();
3224
3225           NTuple<Descriptor> dstNodeTuple = dstNode.getDescTuple();
3226           Descriptor dstLocalDesc = dstNodeTuple.get(0);
3227
3228           if (dstLocalDesc instanceof InterDescriptor
3229               && ((InterDescriptor) dstLocalDesc).getMethodArgIdxPair() != null) {
3230             if (dstNode.getCompositeLocation() == null) {
3231               // System.out.println("%%%%%%%%%%%%%SKIP=" + dstNode);
3232               continue;
3233             }
3234           }
3235
3236           // if (outEdge.getInitTuple().equals(srcNodeTuple)
3237           // && outEdge.getEndTuple().equals(dstNodeTuple)) {
3238
3239           NTuple<Descriptor> srcCurTuple = srcNode.getCurrentDescTuple();
3240           NTuple<Descriptor> dstCurTuple = dstNode.getCurrentDescTuple();
3241
3242           // //////////////////////////
3243           // inheritance check
3244           if (mapMethodDescToHighestOverriddenMethodDesc.containsKey(md)) {
3245
3246             MethodDescriptor highestOverriddenMethodDesc =
3247                 mapMethodDescToHighestOverriddenMethodDesc.get(md);
3248
3249             if (srcCurTuple.get(srcCurTuple.size() - 1).getSymbol().startsWith(PCLOC)) {
3250             }
3251
3252           }
3253           // //////////////////////////
3254
3255           // System.out.println("-srcCurTuple=" + srcCurTuple + "  dstCurTuple=" + dstCurTuple
3256           // + "  srcNode=" + srcNode + "   dstNode=" + dstNode);
3257
3258           // srcCurTuple = translateBaseTuple(srcNode, srcCurTuple);
3259           // dstCurTuple = translateBaseTuple(dstNode, dstCurTuple);
3260
3261           if ((srcCurTuple.size() > 1 && dstCurTuple.size() > 1)
3262               && srcCurTuple.get(0).equals(dstCurTuple.get(0))) {
3263
3264             // value flows between fields
3265             Descriptor desc = srcCurTuple.get(0);
3266             ClassDescriptor classDesc;
3267
3268             if (desc.equals(GLOBALDESC)) {
3269               classDesc = md.getClassDesc();
3270             } else {
3271               VarDescriptor varDesc = (VarDescriptor) srcCurTuple.get(0);
3272               classDesc = varDesc.getType().getClassDesc();
3273             }
3274             extractFlowsBetweenFields(classDesc, srcNode, dstNode, 1);
3275
3276           } else if ((srcCurTuple.size() == 1 && dstCurTuple.size() == 1)
3277               || ((srcCurTuple.size() > 1 || dstCurTuple.size() > 1) && !srcCurTuple.get(0).equals(
3278                   dstCurTuple.get(0)))) {
3279
3280             // value flow between a primitive local var - a primitive local var or local var -
3281             // field
3282
3283             Descriptor srcDesc = srcCurTuple.get(0);
3284             Descriptor dstDesc = dstCurTuple.get(0);
3285
3286             methodGraph.addEdge(srcDesc, dstDesc);
3287
3288             if (fg.isParamDesc(srcDesc)) {
3289               methodGraph.setParamHNode(srcDesc);
3290             }
3291             if (fg.isParamDesc(dstDesc)) {
3292               methodGraph.setParamHNode(dstDesc);
3293             }
3294
3295           }
3296
3297           // }
3298           // }
3299
3300         }
3301
3302       }
3303
3304     }
3305
3306     // If the method accesses static fields
3307     // set hasGloabalAccess true in the method summary.
3308     if (hasGlobalAccess) {
3309       getMethodSummary(md).setHasGlobalAccess();
3310     }
3311     methodGraph.getHNode(GLOBALDESC).setSkeleton(true);
3312
3313     if (ssjava.getMethodContainingSSJavaLoop().equals(md)) {
3314       // if the current method contains the event loop
3315       // we need to set all nodes of the hierarchy graph as a skeleton node
3316       Set<HNode> hnodeSet = methodGraph.getNodeSet();
3317       for (Iterator iterator = hnodeSet.iterator(); iterator.hasNext();) {
3318         HNode hnode = (HNode) iterator.next();
3319         hnode.setSkeleton(true);
3320       }
3321     }
3322
3323   }
3324
3325   private NTuple<Descriptor> translateBaseTuple(FlowNode flowNode, NTuple<Descriptor> inTuple) {
3326
3327     if (flowNode.getBaseTuple() != null) {
3328
3329       NTuple<Descriptor> translatedTuple = new NTuple<Descriptor>();
3330
3331       NTuple<Descriptor> baseTuple = flowNode.getBaseTuple();
3332
3333       for (int i = 0; i < baseTuple.size(); i++) {
3334         translatedTuple.add(baseTuple.get(i));
3335       }
3336
3337       for (int i = 1; i < inTuple.size(); i++) {
3338         translatedTuple.add(inTuple.get(i));
3339       }
3340
3341       // System.out.println("------TRANSLATED " + inTuple + " -> " + translatedTuple);
3342       return translatedTuple;
3343
3344     } else {
3345       return inTuple;
3346     }
3347
3348   }
3349
3350   private MethodSummary getMethodSummary(MethodDescriptor md) {
3351     if (!mapDescToLocationSummary.containsKey(md)) {
3352       mapDescToLocationSummary.put(md, new MethodSummary(md));
3353     }
3354     return (MethodSummary) mapDescToLocationSummary.get(md);
3355   }
3356
3357   private void addMapClassDefinitionToLineNum(ClassDescriptor cd, String strLine, int lineNum) {
3358
3359     String classSymbol = cd.getSymbol();
3360     int idx = classSymbol.lastIndexOf("$");
3361     if (idx != -1) {
3362       classSymbol = classSymbol.substring(idx + 1);
3363     }
3364
3365     String pattern = "class " + classSymbol + " ";
3366     if (strLine.indexOf(pattern) != -1) {
3367       mapDescToDefinitionLine.put(cd, lineNum);
3368     }
3369   }
3370
3371   private void addMapMethodDefinitionToLineNum(Set<MethodDescriptor> methodSet, String strLine,
3372       int lineNum) {
3373     for (Iterator iterator = methodSet.iterator(); iterator.hasNext();) {
3374       MethodDescriptor md = (MethodDescriptor) iterator.next();
3375       String pattern = md.getMethodDeclaration();
3376       if (strLine.indexOf(pattern) != -1) {
3377         mapDescToDefinitionLine.put(md, lineNum);
3378         methodSet.remove(md);
3379         return;
3380       }
3381     }
3382
3383   }
3384
3385   private void readOriginalSourceFiles() {
3386
3387     SymbolTable classtable = state.getClassSymbolTable();
3388
3389     Set<ClassDescriptor> classDescSet = new HashSet<ClassDescriptor>();
3390     classDescSet.addAll(classtable.getValueSet());
3391
3392     try {
3393       // inefficient implement. it may re-visit the same file if the file
3394       // contains more than one class definitions.
3395       for (Iterator iterator = classDescSet.iterator(); iterator.hasNext();) {
3396         ClassDescriptor cd = (ClassDescriptor) iterator.next();
3397
3398         Set<MethodDescriptor> methodSet = new HashSet<MethodDescriptor>();
3399         methodSet.addAll(cd.getMethodTable().getValueSet());
3400
3401         String sourceFileName = cd.getSourceFileName();
3402         Vector<String> lineVec = new Vector<String>();
3403
3404         mapFileNameToLineVector.put(sourceFileName, lineVec);
3405
3406         BufferedReader in = new BufferedReader(new FileReader(sourceFileName));
3407         String strLine;
3408         int lineNum = 1;
3409         lineVec.add(""); // the index is started from 1.
3410         while ((strLine = in.readLine()) != null) {
3411           lineVec.add(lineNum, strLine);
3412           addMapClassDefinitionToLineNum(cd, strLine, lineNum);
3413           addMapMethodDefinitionToLineNum(methodSet, strLine, lineNum);
3414           lineNum++;
3415         }
3416
3417       }
3418
3419     } catch (IOException e) {
3420       e.printStackTrace();
3421     }
3422
3423   }
3424
3425   private String generateLatticeDefinition(Descriptor desc) {
3426
3427     Set<String> sharedLocSet = new HashSet<String>();
3428
3429     SSJavaLattice<String> lattice = getLattice(desc);
3430     String rtr = "@LATTICE(\"";
3431
3432     Map<String, Set<String>> map = lattice.getTable();
3433     Set<String> keySet = map.keySet();
3434
3435     // System.out.println("@generateLatticeDefinition=" + desc + "      map=" + map);
3436
3437     boolean first = true;
3438     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
3439       String key = (String) iterator.next();
3440       if (!key.equals(lattice.getTopItem())) {
3441         Set<String> connectedSet = map.get(key);
3442
3443         if (connectedSet.size() == 1) {
3444           if (connectedSet.iterator().next().equals(lattice.getBottomItem())) {
3445             if (!first) {
3446               rtr += ",";
3447             } else {
3448               rtr += "LOC,";
3449               first = false;
3450             }
3451             rtr += key;
3452             if (lattice.isSharedLoc(key)) {
3453               rtr += "," + key + "*";
3454             }
3455           }
3456         }
3457
3458         for (Iterator iterator2 = connectedSet.iterator(); iterator2.hasNext();) {
3459           String loc = (String) iterator2.next();
3460           if (!loc.equals(lattice.getBottomItem())) {
3461             if (!first) {
3462               rtr += ",";
3463             } else {
3464               rtr += "LOC,";
3465               first = false;
3466             }
3467             rtr += loc + "<" + key;
3468             if (lattice.isSharedLoc(key) && (!sharedLocSet.contains(key))) {
3469               rtr += "," + key + "*";
3470               sharedLocSet.add(key);
3471             }
3472             if (lattice.isSharedLoc(loc) && (!sharedLocSet.contains(loc))) {
3473               rtr += "," + loc + "*";
3474               sharedLocSet.add(loc);
3475             }
3476
3477           }
3478         }
3479       }
3480     }
3481
3482     if (desc instanceof MethodDescriptor) {
3483       // System.out.println("#EXTRA LOC DECLARATION GEN=" + desc);
3484
3485       MethodDescriptor md = (MethodDescriptor) desc;
3486       MethodSummary methodSummary = getMethodSummary(md);
3487
3488       TypeDescriptor returnType = ((MethodDescriptor) desc).getReturnType();
3489       if (!ssjava.getMethodContainingSSJavaLoop().equals(desc) && returnType != null
3490           && (!returnType.isVoid())) {
3491         CompositeLocation returnLoc = methodSummary.getRETURNLoc();
3492         if (returnLoc.getSize() == 1) {
3493           String returnLocStr = generateLocationAnnoatation(methodSummary.getRETURNLoc());
3494           if (rtr.indexOf(returnLocStr) == -1) {
3495             rtr += "," + returnLocStr;
3496           }
3497         }
3498       }
3499       rtr += "\")";
3500
3501       if (!ssjava.getMethodContainingSSJavaLoop().equals(desc)) {
3502         if (returnType != null && (!returnType.isVoid())) {
3503           rtr +=
3504               "\n@RETURNLOC(\"" + generateLocationAnnoatation(methodSummary.getRETURNLoc()) + "\")";
3505         }
3506
3507         CompositeLocation pcLoc = methodSummary.getPCLoc();
3508         if ((pcLoc != null) && (!pcLoc.get(0).isTop())) {
3509           rtr += "\n@PCLOC(\"" + generateLocationAnnoatation(pcLoc) + "\")";
3510         }
3511       }
3512
3513       if (!md.isStatic()) {
3514         rtr += "\n@THISLOC(\"" + methodSummary.getThisLocName() + "\")";
3515       }
3516       rtr += "\n@GLOBALLOC(\"" + methodSummary.getGlobalLocName() + "\")";
3517
3518     } else {
3519       rtr += "\")";
3520     }
3521
3522     return rtr;
3523   }
3524
3525   private void generateAnnoatedCode() {
3526
3527     readOriginalSourceFiles();
3528
3529     setupToAnalyze();
3530     while (!toAnalyzeIsEmpty()) {
3531       ClassDescriptor cd = toAnalyzeNext();
3532
3533       setupToAnalazeMethod(cd);
3534
3535       String sourceFileName = cd.getSourceFileName();
3536
3537       if (cd.isInterface()) {
3538         continue;
3539       }
3540
3541       int classDefLine = mapDescToDefinitionLine.get(cd);
3542       Vector<String> sourceVec = mapFileNameToLineVector.get(sourceFileName);
3543
3544       LocationSummary fieldLocSummary = getLocationSummary(cd);
3545
3546       String fieldLatticeDefStr = generateLatticeDefinition(cd);
3547       String annoatedSrc = fieldLatticeDefStr + newline + sourceVec.get(classDefLine);
3548       sourceVec.set(classDefLine, annoatedSrc);
3549
3550       // generate annotations for field declarations
3551       // Map<Descriptor, CompositeLocation> inferLocMap = fieldLocInfo.getMapDescToInferLocation();
3552       Map<String, String> mapFieldNameToLocName = fieldLocSummary.getMapHNodeNameToLocationName();
3553
3554       for (Iterator iter = cd.getFields(); iter.hasNext();) {
3555         FieldDescriptor fd = (FieldDescriptor) iter.next();
3556
3557         String locAnnotationStr;
3558         // CompositeLocation inferLoc = inferLocMap.get(fd);
3559         String locName = mapFieldNameToLocName.get(fd.getSymbol());
3560
3561         if (locName != null) {
3562           // infer loc is null if the corresponding field is static and final
3563           // locAnnotationStr = "@LOC(\"" + generateLocationAnnoatation(inferLoc) + "\")";
3564           locAnnotationStr = "@LOC(\"" + locName + "\")";
3565           int fdLineNum = fd.getLineNum();
3566           String orgFieldDeclarationStr = sourceVec.get(fdLineNum);
3567           String fieldDeclaration = fd.toString();
3568           fieldDeclaration = fieldDeclaration.substring(0, fieldDeclaration.length() - 1);
3569           String annoatedStr = locAnnotationStr + " " + orgFieldDeclarationStr;
3570           sourceVec.set(fdLineNum, annoatedStr);
3571         }
3572
3573       }
3574
3575       while (!toAnalyzeMethodIsEmpty()) {
3576         MethodDescriptor md = toAnalyzeMethodNext();
3577
3578         if (!ssjava.needTobeAnnotated(md)) {
3579           continue;
3580         }
3581
3582         SSJavaLattice<String> methodLattice = md2lattice.get(md);
3583         // System.out.println("md=" + md + " methodLattice=" + methodLattice);
3584         if (methodLattice != null) {
3585
3586           int methodDefLine = md.getLineNum();
3587
3588           // MethodLocationInfo methodLocInfo = getMethodLocationInfo(md);
3589           // Map<Descriptor, CompositeLocation> methodInferLocMap =
3590           // methodLocInfo.getMapDescToInferLocation();
3591
3592           MethodSummary methodSummary = getMethodSummary(md);
3593
3594           Map<Descriptor, CompositeLocation> mapVarDescToInferLoc =
3595               methodSummary.getMapVarDescToInferCompositeLocation();
3596           // System.out.println("-----md=" + md + " methodDefLine=" + methodDefLine);
3597           // System.out.println("-----mapVarDescToInferLoc=" + mapVarDescToInferLoc);
3598
3599           Set<Descriptor> localVarDescSet = mapVarDescToInferLoc.keySet();
3600
3601           Set<String> localLocElementSet = methodLattice.getElementSet();
3602
3603           for (Iterator iterator = localVarDescSet.iterator(); iterator.hasNext();) {
3604             Descriptor localVarDesc = (Descriptor) iterator.next();
3605             // System.out.println("-------localVarDesc=" + localVarDesc);
3606             CompositeLocation inferLoc = mapVarDescToInferLoc.get(localVarDesc);
3607
3608             String localLocIdentifier = inferLoc.get(0).getLocIdentifier();
3609             if (!localLocElementSet.contains(localLocIdentifier)) {
3610               methodLattice.put(localLocIdentifier);
3611             }
3612
3613             String locAnnotationStr = "@LOC(\"" + generateLocationAnnoatation(inferLoc) + "\")";
3614
3615             if (!isParameter(md, localVarDesc)) {
3616               if (mapDescToDefinitionLine.containsKey(localVarDesc)) {
3617                 int varLineNum = mapDescToDefinitionLine.get(localVarDesc);
3618                 String orgSourceLine = sourceVec.get(varLineNum);
3619                 // System.out.println("varLineNum=" + varLineNum + "  org src=" + orgSourceLine);
3620                 int idx =
3621                     orgSourceLine.indexOf(generateVarDeclaration((VarDescriptor) localVarDesc));
3622                 // System.out.println("idx=" + idx
3623                 // + "  generateVarDeclaration((VarDescriptor) localVarDesc)="
3624                 // + generateVarDeclaration((VarDescriptor) localVarDesc));
3625                 assert (idx != -1);
3626                 String annoatedStr =
3627                     orgSourceLine.substring(0, idx) + locAnnotationStr + " "
3628                         + orgSourceLine.substring(idx);
3629                 sourceVec.set(varLineNum, annoatedStr);
3630               }
3631             } else {
3632               String methodDefStr = sourceVec.get(methodDefLine);
3633
3634               int idx =
3635                   getParamLocation(methodDefStr,
3636                       generateVarDeclaration((VarDescriptor) localVarDesc));
3637               // System.out.println("methodDefStr=" + methodDefStr + " localVarDesc=" + localVarDesc
3638               // + " idx=" + idx);
3639               assert (idx != -1);
3640
3641               String annoatedStr =
3642                   methodDefStr.substring(0, idx) + locAnnotationStr + " "
3643                       + methodDefStr.substring(idx);
3644               sourceVec.set(methodDefLine, annoatedStr);
3645             }
3646
3647           }
3648
3649           // check if the lattice has to have the location type for the this
3650           // reference...
3651
3652           // boolean needToAddthisRef = hasThisReference(md);
3653           // if (localLocElementSet.contains("this")) {
3654           // methodLattice.put("this");
3655           // }
3656
3657           String methodLatticeDefStr = generateLatticeDefinition(md);
3658           String annoatedStr = methodLatticeDefStr + newline + sourceVec.get(methodDefLine);
3659           sourceVec.set(methodDefLine, annoatedStr);
3660
3661         }
3662       }
3663
3664     }
3665
3666     codeGen();
3667   }
3668
3669   private boolean hasThisReference(MethodDescriptor md) {
3670
3671     FlowGraph fg = getFlowGraph(md);
3672     Set<FlowNode> nodeSet = fg.getNodeSet();
3673     for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
3674       FlowNode flowNode = (FlowNode) iterator.next();
3675       if (flowNode.getDescTuple().get(0).equals(md.getThis())) {
3676         return true;
3677       }
3678     }
3679
3680     return false;
3681   }
3682
3683   private int getParamLocation(String methodStr, String paramStr) {
3684
3685     String pattern = paramStr + ",";
3686
3687     int idx = methodStr.indexOf(pattern);
3688     if (idx != -1) {
3689       return idx;
3690     } else {
3691       pattern = paramStr + ")";
3692       return methodStr.indexOf(pattern);
3693     }
3694
3695   }
3696
3697   private String generateVarDeclaration(VarDescriptor varDesc) {
3698
3699     TypeDescriptor td = varDesc.getType();
3700     String rtr = td.toString();
3701     if (td.isArray()) {
3702       for (int i = 0; i < td.getArrayCount(); i++) {
3703         rtr += "[]";
3704       }
3705     }
3706     rtr += " " + varDesc.getName();
3707     return rtr;
3708
3709   }
3710
3711   private String generateLocationAnnoatation(CompositeLocation loc) {
3712     String rtr = "";
3713     // method location
3714     Location methodLoc = loc.get(0);
3715     rtr += methodLoc.getLocIdentifier();
3716
3717     for (int i = 1; i < loc.getSize(); i++) {
3718       Location element = loc.get(i);
3719       rtr += "," + element.getDescriptor().getSymbol() + "." + element.getLocIdentifier();
3720     }
3721
3722     return rtr;
3723   }
3724
3725   private boolean isParameter(MethodDescriptor md, Descriptor localVarDesc) {
3726     return getFlowGraph(md).isParamDesc(localVarDesc);
3727   }
3728
3729   private String extractFileName(String fileName) {
3730     int idx = fileName.lastIndexOf("/");
3731     if (idx == -1) {
3732       return fileName;
3733     } else {
3734       return fileName.substring(idx + 1);
3735     }
3736
3737   }
3738
3739   private void codeGen() {
3740
3741     Set<String> originalFileNameSet = mapFileNameToLineVector.keySet();
3742     for (Iterator iterator = originalFileNameSet.iterator(); iterator.hasNext();) {
3743       String orgFileName = (String) iterator.next();
3744       String outputFileName = extractFileName(orgFileName);
3745
3746       Vector<String> sourceVec = mapFileNameToLineVector.get(orgFileName);
3747
3748       try {
3749
3750         FileWriter fileWriter = new FileWriter("./infer/" + outputFileName);
3751         BufferedWriter out = new BufferedWriter(fileWriter);
3752
3753         for (int i = 0; i < sourceVec.size(); i++) {
3754           out.write(sourceVec.get(i));
3755           out.newLine();
3756         }
3757         out.close();
3758       } catch (IOException e) {
3759         e.printStackTrace();
3760       }
3761
3762     }
3763
3764   }
3765
3766   private void checkLattices() {
3767
3768     LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
3769
3770     // current descriptors to visit in fixed-point interprocedural analysis,
3771     // prioritized by
3772     // dependency in the call graph
3773     methodDescriptorsToVisitStack.clear();
3774
3775     // descriptorListToAnalyze.removeFirst();
3776
3777     Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
3778     methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
3779
3780     while (!descriptorListToAnalyze.isEmpty()) {
3781       MethodDescriptor md = descriptorListToAnalyze.removeFirst();
3782       checkLatticesOfVirtualMethods(md);
3783     }
3784
3785   }
3786
3787   private void debug_writeLatticeDotFile() {
3788     // generate lattice dot file
3789
3790     setupToAnalyze();
3791
3792     while (!toAnalyzeIsEmpty()) {
3793       ClassDescriptor cd = toAnalyzeNext();
3794
3795       setupToAnalazeMethod(cd);
3796
3797       SSJavaLattice<String> classLattice = cd2lattice.get(cd);
3798       if (classLattice != null) {
3799         ssjava.writeLatticeDotFile(cd, null, classLattice);
3800         // debug_printDescriptorToLocNameMapping(cd);
3801       }
3802
3803       while (!toAnalyzeMethodIsEmpty()) {
3804         MethodDescriptor md = toAnalyzeMethodNext();
3805         SSJavaLattice<String> methodLattice = md2lattice.get(md);
3806         if (methodLattice != null) {
3807           ssjava.writeLatticeDotFile(cd, md, methodLattice);
3808           // debug_printDescriptorToLocNameMapping(md);
3809         }
3810       }
3811     }
3812
3813   }
3814
3815   private void debug_printDescriptorToLocNameMapping(Descriptor desc) {
3816
3817     LocationInfo info = getLocationInfo(desc);
3818     System.out.println("## " + desc + " ##");
3819     System.out.println(info.getMapDescToInferLocation());
3820     LocationInfo locInfo = getLocationInfo(desc);
3821     System.out.println("mapping=" + locInfo.getMapLocSymbolToDescSet());
3822     System.out.println("###################");
3823
3824   }
3825
3826   private void calculateExtraLocations() {
3827
3828     // LinkedList<MethodDescriptor> methodDescList = ssjava.getSortedDescriptors();
3829     LinkedList<MethodDescriptor> methodDescList =
3830         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
3831     for (Iterator iterator = methodDescList.iterator(); iterator.hasNext();) {
3832       MethodDescriptor md = (MethodDescriptor) iterator.next();
3833       if (!ssjava.getMethodContainingSSJavaLoop().equals(md)) {
3834         calculateExtraLocations(md);
3835       }
3836     }
3837
3838   }
3839
3840   private void checkLatticesOfVirtualMethods(MethodDescriptor md) {
3841
3842     if (!md.isStatic()) {
3843       Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
3844       setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
3845
3846       for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
3847         MethodDescriptor mdCallee = (MethodDescriptor) iterator.next();
3848         if (!md.equals(mdCallee)) {
3849           checkConsistency(md, mdCallee);
3850         }
3851       }
3852
3853     }
3854
3855   }
3856
3857   private void checkConsistency(MethodDescriptor md1, MethodDescriptor md2) {
3858
3859     // check that two lattice have the same relations between parameters(+PC
3860     // LOC, GLOBAL_LOC RETURN LOC)
3861
3862     List<CompositeLocation> list1 = new ArrayList<CompositeLocation>();
3863     List<CompositeLocation> list2 = new ArrayList<CompositeLocation>();
3864
3865     MethodLocationInfo locInfo1 = getMethodLocationInfo(md1);
3866     MethodLocationInfo locInfo2 = getMethodLocationInfo(md2);
3867
3868     Map<Integer, CompositeLocation> paramMap1 = locInfo1.getMapParamIdxToInferLoc();
3869     Map<Integer, CompositeLocation> paramMap2 = locInfo2.getMapParamIdxToInferLoc();
3870
3871     int numParam = locInfo1.getMapParamIdxToInferLoc().keySet().size();
3872
3873     // add location types of paramters
3874     for (int idx = 0; idx < numParam; idx++) {
3875       list1.add(paramMap1.get(Integer.valueOf(idx)));
3876       list2.add(paramMap2.get(Integer.valueOf(idx)));
3877     }
3878
3879     // add program counter location
3880     list1.add(locInfo1.getPCLoc());
3881     list2.add(locInfo2.getPCLoc());
3882
3883     if (!md1.getReturnType().isVoid()) {
3884       // add return value location
3885       CompositeLocation rtrLoc1 = getMethodLocationInfo(md1).getReturnLoc();
3886       CompositeLocation rtrLoc2 = getMethodLocationInfo(md2).getReturnLoc();
3887       list1.add(rtrLoc1);
3888       list2.add(rtrLoc2);
3889     }
3890
3891     // add global location type
3892     if (md1.isStatic()) {
3893       CompositeLocation globalLoc1 =
3894           new CompositeLocation(new Location(md1, locInfo1.getGlobalLocName()));
3895       CompositeLocation globalLoc2 =
3896           new CompositeLocation(new Location(md2, locInfo2.getGlobalLocName()));
3897       list1.add(globalLoc1);
3898       list2.add(globalLoc2);
3899     }
3900
3901     for (int i = 0; i < list1.size(); i++) {
3902       CompositeLocation locA1 = list1.get(i);
3903       CompositeLocation locA2 = list2.get(i);
3904       for (int k = 0; k < list1.size(); k++) {
3905         if (i != k) {
3906           CompositeLocation locB1 = list1.get(k);
3907           CompositeLocation locB2 = list2.get(k);
3908           boolean r1 = isGreaterThan(getLattice(md1), locA1, locB1);
3909
3910           boolean r2 = isGreaterThan(getLattice(md1), locA2, locB2);
3911
3912           if (r1 != r2) {
3913             throw new Error("The method " + md1 + " is not consistent with the method " + md2
3914                 + ".:: They have a different ordering relation between locations (" + locA1 + ","
3915                 + locB1 + ") and (" + locA2 + "," + locB2 + ").");
3916           }
3917         }
3918       }
3919     }
3920
3921   }
3922
3923   private String getSymbol(int idx, FlowNode node) {
3924     Descriptor desc = node.getDescTuple().get(idx);
3925     return desc.getSymbol();
3926   }
3927
3928   private Descriptor getDescriptor(int idx, FlowNode node) {
3929     Descriptor desc = node.getDescTuple().get(idx);
3930     return desc;
3931   }
3932
3933   private void calculatePCLOC(MethodDescriptor md) {
3934
3935     // System.out.println("#CalculatePCLOC");
3936     MethodSummary methodSummary = getMethodSummary(md);
3937     FlowGraph fg = getFlowGraph(md);
3938     Map<Integer, CompositeLocation> mapParamToLoc = methodSummary.getMapParamIdxToInferLoc();
3939
3940     // calculate the initial program counter location
3941     // PC location is higher than location types of parameters which has incoming flows.
3942
3943     Set<NTuple<Location>> paramLocTupleHavingInFlowSet = new HashSet<NTuple<Location>>();
3944     Set<Descriptor> paramDescNOTHavingInFlowSet = new HashSet<Descriptor>();
3945     // Set<FlowNode> paramNodeNOThavingInFlowSet = new HashSet<FlowNode>();
3946
3947     int numParams = fg.getNumParameters();
3948     for (int i = 0; i < numParams; i++) {
3949       FlowNode paramFlowNode = fg.getParamFlowNode(i);
3950       Descriptor prefix = paramFlowNode.getDescTuple().get(0);
3951       NTuple<Descriptor> paramDescTuple = paramFlowNode.getCurrentDescTuple();
3952       NTuple<Location> paramLocTuple = translateToLocTuple(md, paramDescTuple);
3953
3954       Set<FlowNode> inNodeToParamSet = fg.getIncomingNodeSetByPrefix(prefix);
3955       if (inNodeToParamSet.size() > 0) {
3956         // parameter has in-value flows
3957
3958         for (Iterator iterator = inNodeToParamSet.iterator(); iterator.hasNext();) {
3959           FlowNode inNode = (FlowNode) iterator.next();
3960           Set<FlowEdge> outEdgeSet = fg.getOutEdgeSet(inNode);
3961           for (Iterator iterator2 = outEdgeSet.iterator(); iterator2.hasNext();) {
3962             FlowEdge flowEdge = (FlowEdge) iterator2.next();
3963             if (flowEdge.getEndTuple().startsWith(prefix)) {
3964               NTuple<Location> paramLocTupleWithIncomingFlow =
3965                   translateToLocTuple(md, flowEdge.getEndTuple());
3966               paramLocTupleHavingInFlowSet.add(paramLocTupleWithIncomingFlow);
3967             }
3968           }
3969         }
3970
3971         // paramLocTupleHavingInFlowSet.add(paramLocTuple);
3972       } else {
3973         // paramNodeNOThavingInFlowSet.add(fg.getFlowNode(paramDescTuple));
3974         paramDescNOTHavingInFlowSet.add(prefix);
3975       }
3976     }
3977
3978     // System.out.println("paramLocTupleHavingInFlowSet=" + paramLocTupleHavingInFlowSet);
3979
3980     if (paramLocTupleHavingInFlowSet.size() > 0
3981         && !coversAllParamters(md, fg, paramLocTupleHavingInFlowSet)) {
3982
3983       // Here, generates a location in the method lattice that is higher than the
3984       // paramLocTupleHavingInFlowSet
3985       NTuple<Location> pcLocTuple =
3986           generateLocTupleRelativeTo(md, paramLocTupleHavingInFlowSet, PCLOC);
3987
3988       NTuple<Descriptor> pcDescTuple = translateToDescTuple(pcLocTuple);
3989
3990       // System.out.println("pcLoc=" + pcLocTuple);
3991
3992       CompositeLocation curPCLoc = methodSummary.getPCLoc();
3993       if (curPCLoc.get(0).isTop() || pcLocTuple.size() > curPCLoc.getSize()) {
3994         methodSummary.setPCLoc(new CompositeLocation(pcLocTuple));
3995
3996         Set<FlowNode> flowNodeLowerthanPCLocSet = new HashSet<FlowNode>();
3997         GlobalFlowGraph subGlobalFlowGraph = getSubGlobalFlowGraph(md);
3998         // add ordering relations s.t. PCLOC is higher than all flow nodes except the set of
3999         // parameters that do not have incoming flows
4000         for (Iterator iterator = fg.getNodeSet().iterator(); iterator.hasNext();) {
4001           FlowNode node = (FlowNode) iterator.next();
4002
4003           if (!(node instanceof FlowReturnNode)) {
4004             if (!paramDescNOTHavingInFlowSet.contains(node.getCurrentDescTuple().get(0))) {
4005               flowNodeLowerthanPCLocSet.add(node);
4006               fg.addValueFlowEdge(pcDescTuple, node.getDescTuple());
4007
4008               subGlobalFlowGraph.addValueFlowEdge(pcLocTuple,
4009                   translateToLocTuple(md, node.getDescTuple()));
4010             }
4011           } else {
4012             // System.out.println("***SKIP PCLOC -> RETURNLOC=" + node);
4013           }
4014
4015         }
4016         fg.getFlowNode(translateToDescTuple(pcLocTuple)).setSkeleton(true);
4017
4018         if (pcLocTuple.get(0).getLocDescriptor().equals(md.getThis())) {
4019           for (Iterator iterator = flowNodeLowerthanPCLocSet.iterator(); iterator.hasNext();) {
4020             FlowNode lowerNode = (FlowNode) iterator.next();
4021             if (lowerNode.getDescTuple().size() == 1 && lowerNode.getCompositeLocation() == null) {
4022               NTuple<Location> lowerLocTuple = translateToLocTuple(md, lowerNode.getDescTuple());
4023               CompositeLocation newComp =
4024                   calculateCompositeLocationFromSubGlobalGraph(md, lowerNode);
4025               if (newComp != null) {
4026                 subGlobalFlowGraph.addMapLocationToInferCompositeLocation(lowerLocTuple.get(0),
4027                     newComp);
4028                 lowerNode.setCompositeLocation(newComp);
4029                 // System.out.println("NEW COMP LOC=" + newComp + "    to lowerNode=" + lowerNode);
4030               }
4031
4032             }
4033
4034           }
4035         }
4036
4037       }
4038
4039     }
4040   }
4041
4042   private int countFirstDescriptorSetSize(Set<NTuple<Location>> set) {
4043
4044     Set<Descriptor> descSet = new HashSet<Descriptor>();
4045
4046     for (Iterator iterator = set.iterator(); iterator.hasNext();) {
4047       NTuple<Location> locTuple = (NTuple<Location>) iterator.next();
4048       descSet.add(locTuple.get(0).getLocDescriptor());
4049     }
4050
4051     return descSet.size();
4052   }
4053
4054   private boolean coversAllParamters(MethodDescriptor md, FlowGraph fg,
4055       Set<NTuple<Location>> paramLocTupleHavingInFlowSet) {
4056
4057     int numParam = fg.getNumParameters();
4058     // int size = paramLocTupleHavingInFlowSet.size();
4059     int size = countFirstDescriptorSetSize(paramLocTupleHavingInFlowSet);
4060
4061     // System.out.println("numParam=" + numParam + "     size=" + size);
4062
4063     // if (!md.isStatic()) {
4064     //
4065     // // if the method is not static && there is a parameter composite location &&
4066     // // it is started with 'this',
4067     // // paramLocTupleHavingInFlowSet need to have 'this' parameter.
4068     //
4069     // FlowNode thisParamNode = fg.getParamFlowNode(0);
4070     // NTuple<Location> thisParamLocTuple =
4071     // translateToLocTuple(md, thisParamNode.getCurrentDescTuple());
4072     //
4073     // if (!paramLocTupleHavingInFlowSet.contains(thisParamLocTuple)) {
4074     //
4075     // for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
4076     // NTuple<Location> paramTuple = (NTuple<Location>) iterator.next();
4077     // if (paramTuple.size() > 1 && paramTuple.get(0).getLocDescriptor().equals(md.getThis())) {
4078     // // paramLocTupleHavingInFlowSet.add(thisParamLocTuple);
4079     // // break;
4080     // size++;
4081     // }
4082     // }
4083     //
4084     // }
4085     // }
4086
4087     if (size == numParam) {
4088       return true;
4089     } else {
4090       return false;
4091     }
4092
4093   }
4094
4095   private void calculateRETURNLOC(MethodDescriptor md) {
4096
4097     // System.out.println("#calculateRETURNLOC= " + md);
4098
4099     // calculate a return location:
4100     // the return location type is lower than all parameters and the location of return values
4101     MethodSummary methodSummary = getMethodSummary(md);
4102     // if (methodSummary.getRETURNLoc() != null) {
4103     // System.out.println("$HERE?");
4104     // return;
4105     // }
4106
4107     FlowGraph fg = getFlowGraph(md);
4108     Map<Integer, CompositeLocation> mapParamToLoc = methodSummary.getMapParamIdxToInferLoc();
4109     Set<Integer> paramIdxSet = mapParamToLoc.keySet();
4110
4111     if (md.getReturnType() != null && !md.getReturnType().isVoid()) {
4112       // first, generate the set of return value location types that starts
4113       // with 'this' reference
4114
4115       Set<FlowNode> paramFlowNodeFlowingToReturnValueSet = getParamNodeFlowingToReturnValue(md);
4116       // System.out.println("paramFlowNodeFlowingToReturnValueSet="
4117       // + paramFlowNodeFlowingToReturnValueSet);
4118
4119       Set<NTuple<Location>> tupleToBeHigherThanReturnLocSet = new HashSet<NTuple<Location>>();
4120       for (Iterator iterator = paramFlowNodeFlowingToReturnValueSet.iterator(); iterator.hasNext();) {
4121         FlowNode fn = (FlowNode) iterator.next();
4122         NTuple<Descriptor> paramDescTuple = fn.getCurrentDescTuple();
4123         tupleToBeHigherThanReturnLocSet.add(translateToLocTuple(md, paramDescTuple));
4124       }
4125
4126       Set<FlowNode> returnNodeSet = fg.getReturnNodeSet();
4127       for (Iterator iterator = returnNodeSet.iterator(); iterator.hasNext();) {
4128         FlowNode returnNode = (FlowNode) iterator.next();
4129         NTuple<Descriptor> returnDescTuple = returnNode.getCurrentDescTuple();
4130         tupleToBeHigherThanReturnLocSet.add(translateToLocTuple(md, returnDescTuple));
4131       }
4132       // System.out.println("-flow graph's returnNodeSet=" + returnNodeSet);
4133       // System.out.println("tupleSetToBeHigherThanReturnLoc=" + tupleToBeHigherThanReturnLocSet);
4134
4135       // Here, generates a return location in the method lattice that is lower than the
4136       // locFlowingToReturnValueSet
4137       NTuple<Location> returnLocTuple =
4138           generateLocTupleRelativeTo(md, tupleToBeHigherThanReturnLocSet, RLOC);
4139
4140       // System.out.println("returnLocTuple=" + returnLocTuple);
4141       NTuple<Descriptor> returnDescTuple = translateToDescTuple(returnLocTuple);
4142       CompositeLocation curReturnLoc = methodSummary.getRETURNLoc();
4143       if (curReturnLoc == null || returnDescTuple.size() > curReturnLoc.getSize()) {
4144         methodSummary.setRETURNLoc(new CompositeLocation(returnLocTuple));
4145
4146         for (Iterator iterator = tupleToBeHigherThanReturnLocSet.iterator(); iterator.hasNext();) {
4147           NTuple<Location> higherTuple = (NTuple<Location>) iterator.next();
4148           fg.addValueFlowEdge(translateToDescTuple(higherTuple), returnDescTuple);
4149         }
4150         fg.getFlowNode(returnDescTuple).setSkeleton(true);
4151
4152       }
4153
4154       // makes sure that PCLOC is higher than RETURNLOC
4155       CompositeLocation pcLoc = methodSummary.getPCLoc();
4156       if (!pcLoc.get(0).isTop()) {
4157         NTuple<Descriptor> pcLocDescTuple = translateToDescTuple(pcLoc.getTuple());
4158         fg.addValueFlowEdge(pcLocDescTuple, returnDescTuple);
4159       }
4160
4161     }
4162
4163   }
4164
4165   private void calculateExtraLocations(MethodDescriptor md) {
4166     // calcualte pcloc, returnloc,...
4167
4168     System.out.println("\nSSJAVA:Calculate PCLOC/RETURNLOC locations: " + md);
4169
4170     calculatePCLOC(md);
4171     calculateRETURNLOC(md);
4172
4173   }
4174
4175   private NTuple<Location> generateLocTupleRelativeTo(MethodDescriptor md,
4176       Set<NTuple<Location>> paramLocTupleHavingInFlowSet, String locNamePrefix) {
4177
4178     // System.out.println("-generateLocTupleRelativeTo=" + paramLocTupleHavingInFlowSet);
4179
4180     NTuple<Location> higherLocTuple = new NTuple<Location>();
4181
4182     VarDescriptor thisVarDesc = md.getThis();
4183     // check if all paramter loc tuple is started with 'this' reference
4184     boolean hasParamNotStartedWithThisRef = false;
4185
4186     int minSize = 0;
4187
4188     Set<NTuple<Location>> paramLocTupleStartedWithThis = new HashSet<NTuple<Location>>();
4189
4190     next: for (Iterator iterator = paramLocTupleHavingInFlowSet.iterator(); iterator.hasNext();) {
4191       NTuple<Location> paramLocTuple = (NTuple<Location>) iterator.next();
4192       Descriptor paramLocalDesc = paramLocTuple.get(0).getLocDescriptor();
4193       if (!paramLocalDesc.equals(thisVarDesc)) {
4194
4195         Set<FlowNode> inNodeSet = getFlowGraph(md).getIncomingNodeSetByPrefix(paramLocalDesc);
4196         for (Iterator iterator2 = inNodeSet.iterator(); iterator2.hasNext();) {
4197           FlowNode flowNode = (FlowNode) iterator2.next();
4198           if (flowNode.getDescTuple().startsWith(thisVarDesc)) {
4199             // System.out.println("paramLocTuple=" + paramLocTuple + " is lower than THIS");
4200             continue next;
4201           }
4202         }
4203         hasParamNotStartedWithThisRef = true;
4204
4205       } else if (paramLocTuple.size() > 1) {
4206         paramLocTupleStartedWithThis.add(paramLocTuple);
4207         if (minSize == 0 || minSize > paramLocTuple.size()) {
4208           minSize = paramLocTuple.size();
4209         }
4210       }
4211     }
4212
4213     // System.out.println("---paramLocTupleStartedWithThis=" + paramLocTupleStartedWithThis);
4214     Descriptor enclosingDesc = md;
4215     if (hasParamNotStartedWithThisRef) {
4216       // in this case, PCLOC will be the local location
4217     } else {
4218       // all parameter is started with 'this', so PCLOC will be set relative to the composite
4219       // location started with 'this'.
4220       // for (int idx = 0; idx < minSize - 1; idx++) {
4221       for (int idx = 0; idx < 1; idx++) {
4222         Set<Descriptor> locDescSet = new HashSet<Descriptor>();
4223         Location curLoc = null;
4224         NTuple<Location> paramLocTuple = null;
4225         for (Iterator iterator = paramLocTupleStartedWithThis.iterator(); iterator.hasNext();) {
4226           paramLocTuple = (NTuple<Location>) iterator.next();
4227           // System.out.println("-----paramLocTuple=" + paramLocTuple + "  idx=" + idx);
4228           curLoc = paramLocTuple.get(idx);
4229           Descriptor locDesc = curLoc.getLocDescriptor();
4230           locDescSet.add(locDesc);
4231         }
4232         // System.out.println("-----locDescSet=" + locDescSet + " idx=" + idx);
4233         if (locDescSet.size() != 1) {
4234           break;
4235         }
4236         Location newLocElement = new Location(curLoc.getDescriptor(), curLoc.getLocDescriptor());
4237         // System.out.println("newLocElement" + newLocElement);
4238         higherLocTuple.add(newLocElement);
4239         enclosingDesc = getClassTypeDescriptor(curLoc.getLocDescriptor());
4240       }
4241
4242     }
4243
4244     String locIdentifier = locNamePrefix + (locSeed++);
4245     NameDescriptor locDesc = new NameDescriptor(locIdentifier);
4246     Location newLoc = new Location(enclosingDesc, locDesc);
4247     higherLocTuple.add(newLoc);
4248     // System.out.println("---new loc tuple=" + higherLocTuple);
4249
4250     return higherLocTuple;
4251
4252   }
4253
4254   public ClassDescriptor getClassTypeDescriptor(Descriptor in) {
4255
4256     if (in instanceof VarDescriptor) {
4257       return ((VarDescriptor) in).getType().getClassDesc();
4258     } else if (in instanceof FieldDescriptor) {
4259       return ((FieldDescriptor) in).getType().getClassDesc();
4260     }
4261     // else if (in instanceof LocationDescriptor) {
4262     // // here is the case that the descriptor 'in' is the last element of the assigned composite
4263     // // location
4264     // return ((VarDescriptor) locTuple.get(0).getLocDescriptor()).getType().getClassDesc();
4265     // }
4266     else {
4267       return null;
4268     }
4269
4270   }
4271
4272   private Set<NTuple<Location>> calculateHighestLocTupleSet(
4273       Set<NTuple<Location>> paramLocTupleHavingInFlowSet) {
4274
4275     Set<NTuple<Location>> highestSet = new HashSet<NTuple<Location>>();
4276
4277     Iterator<NTuple<Location>> iterator = paramLocTupleHavingInFlowSet.iterator();
4278     NTuple<Location> highest = iterator.next();
4279
4280     for (; iterator.hasNext();) {
4281       NTuple<Location> curLocTuple = (NTuple<Location>) iterator.next();
4282       if (isHigherThan(curLocTuple, highest)) {
4283         // System.out.println(curLocTuple + " is greater than " + highest);
4284         highest = curLocTuple;
4285       }
4286     }
4287
4288     highestSet.add(highest);
4289
4290     MethodDescriptor md = (MethodDescriptor) highest.get(0).getDescriptor();
4291     VarDescriptor thisVarDesc = md.getThis();
4292
4293     // System.out.println("highest=" + highest);
4294
4295     for (Iterator<NTuple<Location>> iter = paramLocTupleHavingInFlowSet.iterator(); iter.hasNext();) {
4296       NTuple<Location> curLocTuple = iter.next();
4297
4298       if (!curLocTuple.equals(highest) && !hasOrderingRelation(highest, curLocTuple)) {
4299
4300         // System.out.println("add it to the highest set=" + curLocTuple);
4301         highestSet.add(curLocTuple);
4302
4303       }
4304     }
4305
4306     return highestSet;
4307
4308   }
4309
4310   private Set<String> getHigherLocSymbolThan(SSJavaLattice<String> lattice, String loc) {
4311     Set<String> higherLocSet = new HashSet<String>();
4312
4313     Set<String> locSet = lattice.getTable().keySet();
4314     for (Iterator iterator = locSet.iterator(); iterator.hasNext();) {
4315       String element = (String) iterator.next();
4316       if (lattice.isGreaterThan(element, loc) && (!element.equals(lattice.getTopItem()))) {
4317         higherLocSet.add(element);
4318       }
4319     }
4320     return higherLocSet;
4321   }
4322
4323   private CompositeLocation getLowest(SSJavaLattice<String> methodLattice,
4324       Set<CompositeLocation> set) {
4325
4326     CompositeLocation lowest = set.iterator().next();
4327
4328     if (set.size() == 1) {
4329       return lowest;
4330     }
4331
4332     for (Iterator iterator = set.iterator(); iterator.hasNext();) {
4333       CompositeLocation loc = (CompositeLocation) iterator.next();
4334
4335       if ((!loc.equals(lowest)) && (!isComparable(methodLattice, lowest, loc))) {
4336         // if there is a case where composite locations are incomparable, just
4337         // return null
4338         return null;
4339       }
4340
4341       if ((!loc.equals(lowest)) && isGreaterThan(methodLattice, lowest, loc)) {
4342         lowest = loc;
4343       }
4344     }
4345     return lowest;
4346   }
4347
4348   private boolean isComparable(SSJavaLattice<String> methodLattice, CompositeLocation comp1,
4349       CompositeLocation comp2) {
4350
4351     int size = comp1.getSize() >= comp2.getSize() ? comp2.getSize() : comp1.getSize();
4352
4353     for (int idx = 0; idx < size; idx++) {
4354       Location loc1 = comp1.get(idx);
4355       Location loc2 = comp2.get(idx);
4356
4357       Descriptor desc1 = loc1.getDescriptor();
4358       Descriptor desc2 = loc2.getDescriptor();
4359
4360       if (!desc1.equals(desc2)) {
4361         throw new Error("Fail to compare " + comp1 + " and " + comp2);
4362       }
4363
4364       String symbol1 = loc1.getLocIdentifier();
4365       String symbol2 = loc2.getLocIdentifier();
4366
4367       SSJavaLattice<String> lattice;
4368       if (idx == 0) {
4369         lattice = methodLattice;
4370       } else {
4371         lattice = getLattice(desc1);
4372       }
4373
4374       if (symbol1.equals(symbol2)) {
4375         continue;
4376       } else if (!lattice.isComparable(symbol1, symbol2)) {
4377         return false;
4378       }
4379
4380     }
4381
4382     return true;
4383   }
4384
4385   private boolean isGreaterThan(SSJavaLattice<String> methodLattice, CompositeLocation comp1,
4386       CompositeLocation comp2) {
4387
4388     int size = comp1.getSize() >= comp2.getSize() ? comp2.getSize() : comp1.getSize();
4389
4390     for (int idx = 0; idx < size; idx++) {
4391       Location loc1 = comp1.get(idx);
4392       Location loc2 = comp2.get(idx);
4393
4394       Descriptor desc1 = loc1.getDescriptor();
4395       Descriptor desc2 = loc2.getDescriptor();
4396
4397       if (!desc1.equals(desc2)) {
4398         throw new Error("Fail to compare " + comp1 + " and " + comp2);
4399       }
4400
4401       String symbol1 = loc1.getLocIdentifier();
4402       String symbol2 = loc2.getLocIdentifier();
4403
4404       SSJavaLattice<String> lattice;
4405       if (idx == 0) {
4406         lattice = methodLattice;
4407       } else {
4408         lattice = getLattice(desc1);
4409       }
4410
4411       if (symbol1.equals(symbol2)) {
4412         continue;
4413       } else if (lattice.isGreaterThan(symbol1, symbol2)) {
4414         return true;
4415       } else {
4416         return false;
4417       }
4418
4419     }
4420
4421     return false;
4422   }
4423
4424   private GlobalFlowGraph getSubGlobalFlowGraph(MethodDescriptor md) {
4425
4426     if (!mapMethodDescriptorToSubGlobalFlowGraph.containsKey(md)) {
4427       mapMethodDescriptorToSubGlobalFlowGraph.put(md, new GlobalFlowGraph(md));
4428     }
4429     return mapMethodDescriptorToSubGlobalFlowGraph.get(md);
4430   }
4431
4432   private void propagateFlowsToCallerWithNoCompositeLocation(MethodInvokeNode min,
4433       MethodDescriptor mdCaller, MethodDescriptor mdCallee) {
4434
4435     // System.out.println("-propagateFlowsToCallerWithNoCompositeLocation=" + min.printNode(0));
4436     // if the parameter A reaches to the parameter B
4437     // then, add an edge the argument A -> the argument B to the caller's flow
4438     // graph
4439
4440     FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
4441     FlowGraph callerFlowGraph = getFlowGraph(mdCaller);
4442     int numParam = calleeFlowGraph.getNumParameters();
4443
4444     for (int i = 0; i < numParam; i++) {
4445       for (int k = 0; k < numParam; k++) {
4446
4447         if (i != k) {
4448
4449           FlowNode paramNode1 = calleeFlowGraph.getParamFlowNode(i);
4450           FlowNode paramNode2 = calleeFlowGraph.getParamFlowNode(k);
4451
4452           NTuple<Descriptor> arg1Tuple = getNodeTupleByArgIdx(min, i);
4453           NTuple<Descriptor> arg2Tuple = getNodeTupleByArgIdx(min, k);
4454
4455           // check if the callee propagates an ordering constraints through
4456           // parameters
4457
4458           // Set<FlowNode> localReachSet = calleeFlowGraph.getLocalReachFlowNodeSetFrom(paramNode1);
4459           Set<FlowNode> localReachSet =
4460               calleeFlowGraph.getReachableSetFrom(paramNode1.getDescTuple());
4461
4462           NTuple<Descriptor> paramDescTuple1 = paramNode1.getCurrentDescTuple();
4463           NTuple<Descriptor> paramDescTuple2 = paramNode2.getCurrentDescTuple();
4464
4465           // System.out.println("-param1CurTuple=" + paramDescTuple1 + " param2CurTuple="
4466           // + paramDescTuple2);
4467           // System.out.println("-- localReachSet from param1=" + localReachSet);
4468
4469           if (paramDescTuple1.get(0).equals(paramDescTuple2.get(0))) {
4470             // if two parameters share the same prefix
4471             // it already has been assigned to a composite location
4472             // so we don't need to add an additional ordering relation caused by these two
4473             // paramters.
4474             continue;
4475           }
4476
4477           if (arg1Tuple.size() > 0 && arg2Tuple.size() > 0
4478               && containsPrefix(paramNode2.getDescTuple().get(0), localReachSet)) {
4479             // need to propagate an ordering relation s.t. arg1 is higher
4480             // than arg2
4481             // System.out.println("-param1=" + paramNode1 + " is higher than param2=" + paramNode2);
4482
4483             // add a new flow between the corresponding arguments.
4484             callerFlowGraph.addValueFlowEdge(arg1Tuple, arg2Tuple);
4485             // System.out.println("arg1=" + arg1Tuple + "   arg2=" + arg2Tuple);
4486
4487             // System.out
4488             // .println("-arg1Tuple=" + arg1Tuple + " is higher than arg2Tuple=" + arg2Tuple);
4489
4490           }
4491
4492           // System.out.println();
4493         }
4494       }
4495     }
4496
4497     // if a parameter has a composite location and the first element of the parameter location
4498     // matches the callee's 'this'
4499     // we have a more specific constraint: the caller's corresponding argument is higher than the
4500     // parameter location which is translated into the caller
4501
4502     for (int idx = 0; idx < numParam; idx++) {
4503       FlowNode paramNode = calleeFlowGraph.getParamFlowNode(idx);
4504       CompositeLocation compLoc = paramNode.getCompositeLocation();
4505       // System.out.println("paramNode=" + paramNode + "   compLoc=" + compLoc);
4506       if (compLoc != null && compLoc.get(0).getLocDescriptor().equals(min.getMethod().getThis())) {
4507         // System.out.println("$$$COMPLOC CASE=" + compLoc + "  idx=" + idx);
4508
4509         NTuple<Descriptor> argTuple = getNodeTupleByArgIdx(min, idx);
4510         // System.out.println("--- argTuple=" + argTuple + " current compLoc="
4511         // + callerFlowGraph.getFlowNode(argTuple).getCompositeLocation());
4512
4513         NTuple<Descriptor> translatedParamTuple =
4514             translateCompositeLocationToCaller(idx, min, compLoc);
4515         // System.out.println("add a flow edge= " + argTuple + "->" + translatedParamTuple);
4516         callerFlowGraph.addValueFlowEdge(argTuple, translatedParamTuple);
4517
4518         Set<NTuple<Location>> pcLocTupleSet = getPCLocTupleSet(min);
4519         for (Iterator iterator = pcLocTupleSet.iterator(); iterator.hasNext();) {
4520           NTuple<Location> pcLocTuple = (NTuple<Location>) iterator.next();
4521           callerFlowGraph.addValueFlowEdge(translateToDescTuple(pcLocTuple), translatedParamTuple);
4522         }
4523
4524       }
4525     }
4526
4527   }
4528
4529   private boolean containsPrefix(Descriptor prefixDesc, Set<FlowNode> set) {
4530
4531     for (Iterator iterator = set.iterator(); iterator.hasNext();) {
4532       FlowNode flowNode = (FlowNode) iterator.next();
4533       if (flowNode.getDescTuple().startsWith(prefixDesc)) {
4534         // System.out.println("FOUND=" + flowNode);
4535         return true;
4536       }
4537     }
4538     return false;
4539   }
4540
4541   private NTuple<Descriptor> translateCompositeLocationToCaller(int idx, MethodInvokeNode min,
4542       CompositeLocation compLocForParam1) {
4543
4544     NTuple<Descriptor> baseTuple = mapMethodInvokeNodeToBaseTuple.get(min);
4545
4546     NTuple<Descriptor> tuple = new NTuple<Descriptor>();
4547     for (int i = 0; i < baseTuple.size(); i++) {
4548       tuple.add(baseTuple.get(i));
4549     }
4550
4551     for (int i = 1; i < compLocForParam1.getSize(); i++) {
4552       Location loc = compLocForParam1.get(i);
4553       tuple.add(loc.getLocDescriptor());
4554     }
4555
4556     return tuple;
4557   }
4558
4559   private CompositeLocation generateCompositeLocation(NTuple<Location> prefixLocTuple) {
4560
4561     // System.out.println("generateCompositeLocation=" + prefixLocTuple);
4562
4563     CompositeLocation newCompLoc = new CompositeLocation();
4564     for (int i = 0; i < prefixLocTuple.size(); i++) {
4565       newCompLoc.addLocation(prefixLocTuple.get(i));
4566     }
4567
4568     Descriptor lastDescOfPrefix = prefixLocTuple.get(prefixLocTuple.size() - 1).getLocDescriptor();
4569
4570     ClassDescriptor enclosingDescriptor;
4571     if (lastDescOfPrefix instanceof FieldDescriptor) {
4572       enclosingDescriptor = ((FieldDescriptor) lastDescOfPrefix).getType().getClassDesc();
4573       // System.out.println("enclosingDescriptor0=" + enclosingDescriptor);
4574     } else if (lastDescOfPrefix.equals(GLOBALDESC)) {
4575       MethodDescriptor currentMethodDesc = (MethodDescriptor) prefixLocTuple.get(0).getDescriptor();
4576       enclosingDescriptor = currentMethodDesc.getClassDesc();
4577     } else {
4578       // var descriptor case
4579       enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
4580     }
4581     // System.out.println("enclosingDescriptor=" + enclosingDescriptor);
4582
4583     LocationDescriptor newLocDescriptor = generateNewLocationDescriptor();
4584     newLocDescriptor.setEnclosingClassDesc(enclosingDescriptor);
4585
4586     Location newLoc = new Location(enclosingDescriptor, newLocDescriptor.getSymbol());
4587     newLoc.setLocDescriptor(newLocDescriptor);
4588     newCompLoc.addLocation(newLoc);
4589
4590     // System.out.println("--newCompLoc=" + newCompLoc);
4591     return newCompLoc;
4592   }
4593
4594   private CompositeLocation generateCompositeLocation(MethodDescriptor md,
4595       NTuple<Descriptor> paramPrefix) {
4596
4597     // System.out.println("generateCompositeLocation=" + paramPrefix);
4598
4599     CompositeLocation newCompLoc = convertToCompositeLocation(md, paramPrefix);
4600
4601     Descriptor lastDescOfPrefix = paramPrefix.get(paramPrefix.size() - 1);
4602     // System.out.println("lastDescOfPrefix=" + lastDescOfPrefix + "  kind="
4603     // + lastDescOfPrefix.getClass());
4604     ClassDescriptor enclosingDescriptor;
4605     if (lastDescOfPrefix instanceof FieldDescriptor) {
4606       enclosingDescriptor = ((FieldDescriptor) lastDescOfPrefix).getType().getClassDesc();
4607       // System.out.println("enclosingDescriptor0=" + enclosingDescriptor);
4608     } else {
4609       // var descriptor case
4610       enclosingDescriptor = ((VarDescriptor) lastDescOfPrefix).getType().getClassDesc();
4611     }
4612     // System.out.println("enclosingDescriptor=" + enclosingDescriptor);
4613
4614     LocationDescriptor newLocDescriptor = generateNewLocationDescriptor();
4615     newLocDescriptor.setEnclosingClassDesc(enclosingDescriptor);
4616
4617     Location newLoc = new Location(enclosingDescriptor, newLocDescriptor.getSymbol());
4618     newLoc.setLocDescriptor(newLocDescriptor);
4619     newCompLoc.addLocation(newLoc);
4620
4621     // System.out.println("--newCompLoc=" + newCompLoc);
4622     return newCompLoc;
4623   }
4624
4625   private List<NTuple<Descriptor>> translatePrefixListToCallee(Descriptor baseRef,
4626       MethodDescriptor mdCallee, List<NTuple<Descriptor>> callerPrefixList) {
4627
4628     List<NTuple<Descriptor>> calleePrefixList = new ArrayList<NTuple<Descriptor>>();
4629
4630     for (int i = 0; i < callerPrefixList.size(); i++) {
4631       NTuple<Descriptor> prefix = callerPrefixList.get(i);
4632       if (prefix.startsWith(baseRef)) {
4633         NTuple<Descriptor> calleePrefix = new NTuple<Descriptor>();
4634         calleePrefix.add(mdCallee.getThis());
4635         for (int k = 1; k < prefix.size(); k++) {
4636           calleePrefix.add(prefix.get(k));
4637         }
4638         calleePrefixList.add(calleePrefix);
4639       }
4640     }
4641
4642     return calleePrefixList;
4643
4644   }
4645
4646   public CompositeLocation convertToCompositeLocation(MethodDescriptor md, NTuple<Descriptor> tuple) {
4647
4648     CompositeLocation compLoc = new CompositeLocation();
4649
4650     Descriptor enclosingDescriptor = md;
4651
4652     for (int i = 0; i < tuple.size(); i++) {
4653       Descriptor curDescriptor = tuple.get(i);
4654       Location locElement = new Location(enclosingDescriptor, curDescriptor.getSymbol());
4655       locElement.setLocDescriptor(curDescriptor);
4656       compLoc.addLocation(locElement);
4657
4658       if (curDescriptor instanceof VarDescriptor) {
4659         enclosingDescriptor = md.getClassDesc();
4660       } else if (curDescriptor instanceof FieldDescriptor) {
4661         enclosingDescriptor = ((FieldDescriptor) curDescriptor).getClassDescriptor();
4662       } else if (curDescriptor instanceof NameDescriptor) {
4663         // it is "GLOBAL LOC" case!
4664         enclosingDescriptor = GLOBALDESC;
4665       } else if (curDescriptor instanceof InterDescriptor) {
4666         enclosingDescriptor = getFlowGraph(md).getEnclosingDescriptor(curDescriptor);
4667       } else {
4668         enclosingDescriptor = null;
4669       }
4670
4671     }
4672
4673     return compLoc;
4674   }
4675
4676   private LocationDescriptor generateNewLocationDescriptor() {
4677     return new LocationDescriptor("Loc" + (locSeed++));
4678   }
4679
4680   private int getPrefixIndex(NTuple<Descriptor> tuple1, NTuple<Descriptor> tuple2) {
4681
4682     // return the index where the prefix shared by tuple1 and tuple2 is ended
4683     // if there is no prefix shared by both of them, return -1
4684
4685     int minSize = tuple1.size();
4686     if (minSize > tuple2.size()) {
4687       minSize = tuple2.size();
4688     }
4689
4690     int idx = -1;
4691     for (int i = 0; i < minSize; i++) {
4692       if (!tuple1.get(i).equals(tuple2.get(i))) {
4693         break;
4694       } else {
4695         idx++;
4696       }
4697     }
4698
4699     return idx;
4700   }
4701
4702   private CompositeLocation generateInferredCompositeLocation(MethodLocationInfo methodInfo,
4703       NTuple<Location> tuple) {
4704
4705     // first, retrieve inferred location by the local var descriptor
4706     CompositeLocation inferLoc = new CompositeLocation();
4707
4708     CompositeLocation localVarInferLoc =
4709         methodInfo.getInferLocation(tuple.get(0).getLocDescriptor());
4710
4711     localVarInferLoc.get(0).setLocDescriptor(tuple.get(0).getLocDescriptor());
4712
4713     for (int i = 0; i < localVarInferLoc.getSize(); i++) {
4714       inferLoc.addLocation(localVarInferLoc.get(i));
4715     }
4716
4717     for (int i = 1; i < tuple.size(); i++) {
4718       Location cur = tuple.get(i);
4719       Descriptor enclosingDesc = cur.getDescriptor();
4720       Descriptor curDesc = cur.getLocDescriptor();
4721
4722       Location inferLocElement;
4723       if (curDesc == null) {
4724         // in this case, we have a newly generated location.
4725         inferLocElement = new Location(enclosingDesc, cur.getLocIdentifier());
4726       } else {
4727         String fieldLocSymbol =
4728             getLocationInfo(enclosingDesc).getInferLocation(curDesc).get(0).getLocIdentifier();
4729         inferLocElement = new Location(enclosingDesc, fieldLocSymbol);
4730         inferLocElement.setLocDescriptor(curDesc);
4731       }
4732
4733       inferLoc.addLocation(inferLocElement);
4734
4735     }
4736
4737     assert (inferLoc.get(0).getLocDescriptor().getSymbol() == inferLoc.get(0).getLocIdentifier());
4738     return inferLoc;
4739   }
4740
4741   public LocationInfo getLocationInfo(Descriptor d) {
4742     if (d instanceof MethodDescriptor) {
4743       return getMethodLocationInfo((MethodDescriptor) d);
4744     } else {
4745       return getFieldLocationInfo((ClassDescriptor) d);
4746     }
4747   }
4748
4749   private MethodLocationInfo getMethodLocationInfo(MethodDescriptor md) {
4750
4751     if (!mapMethodDescToMethodLocationInfo.containsKey(md)) {
4752       mapMethodDescToMethodLocationInfo.put(md, new MethodLocationInfo(md));
4753     }
4754
4755     return mapMethodDescToMethodLocationInfo.get(md);
4756
4757   }
4758
4759   private LocationInfo getFieldLocationInfo(ClassDescriptor cd) {
4760
4761     if (!mapClassToLocationInfo.containsKey(cd)) {
4762       mapClassToLocationInfo.put(cd, new LocationInfo(cd));
4763     }
4764
4765     return mapClassToLocationInfo.get(cd);
4766
4767   }
4768
4769   private void addPrefixMapping(Map<NTuple<Location>, Set<NTuple<Location>>> map,
4770       NTuple<Location> prefix, NTuple<Location> element) {
4771
4772     if (!map.containsKey(prefix)) {
4773       map.put(prefix, new HashSet<NTuple<Location>>());
4774     }
4775     map.get(prefix).add(element);
4776   }
4777
4778   private boolean containsNonPrimitiveElement(Set<Descriptor> descSet) {
4779     for (Iterator iterator = descSet.iterator(); iterator.hasNext();) {
4780       Descriptor desc = (Descriptor) iterator.next();
4781
4782       if (desc.equals(LocationInference.GLOBALDESC)) {
4783         return true;
4784       } else if (desc instanceof VarDescriptor) {
4785         if (!((VarDescriptor) desc).getType().isPrimitive()) {
4786           return true;
4787         }
4788       } else if (desc instanceof FieldDescriptor) {
4789         if (!((FieldDescriptor) desc).getType().isPrimitive()) {
4790           return true;
4791         }
4792       }
4793
4794     }
4795     return false;
4796   }
4797
4798   public SSJavaLattice<String> getLattice(Descriptor d) {
4799     if (d instanceof MethodDescriptor) {
4800       return getMethodLattice((MethodDescriptor) d);
4801     } else {
4802       return getFieldLattice((ClassDescriptor) d);
4803     }
4804   }
4805
4806   private SSJavaLattice<String> getMethodLattice(MethodDescriptor md) {
4807     if (!md2lattice.containsKey(md)) {
4808       md2lattice.put(md, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
4809     }
4810     return md2lattice.get(md);
4811   }
4812
4813   private void setMethodLattice(MethodDescriptor md, SSJavaLattice<String> lattice) {
4814     md2lattice.put(md, lattice);
4815   }
4816
4817   private void extractFlowsBetweenFields(ClassDescriptor cd, FlowNode srcNode, FlowNode dstNode,
4818       int idx) {
4819
4820     NTuple<Descriptor> srcCurTuple = srcNode.getCurrentDescTuple();
4821     NTuple<Descriptor> dstCurTuple = dstNode.getCurrentDescTuple();
4822
4823     if (srcCurTuple.get(idx).equals(dstCurTuple.get(idx)) && srcCurTuple.size() > (idx + 1)
4824         && dstCurTuple.size() > (idx + 1)) {
4825       // value flow between fields: we don't need to add a binary relation
4826       // for this case
4827
4828       Descriptor desc = srcCurTuple.get(idx);
4829       ClassDescriptor classDesc;
4830
4831       if (idx == 0) {
4832         classDesc = ((VarDescriptor) desc).getType().getClassDesc();
4833       } else {
4834         if (desc instanceof FieldDescriptor) {
4835           classDesc = ((FieldDescriptor) desc).getType().getClassDesc();
4836         } else {
4837           // this case is that the local variable has a composite location assignment
4838           // the following element after the composite location to the local variable
4839           // has the enclosing descriptor of the local variable
4840           Descriptor localDesc = srcNode.getDescTuple().get(0);
4841           classDesc = ((VarDescriptor) localDesc).getType().getClassDesc();
4842         }
4843       }
4844       extractFlowsBetweenFields(classDesc, srcNode, dstNode, idx + 1);
4845
4846     } else {
4847
4848       Descriptor srcFieldDesc = srcCurTuple.get(idx);
4849       Descriptor dstFieldDesc = dstCurTuple.get(idx);
4850
4851       // System.out.println("srcFieldDesc=" + srcFieldDesc + "  dstFieldDesc=" + dstFieldDesc
4852       // + "   idx=" + idx);
4853       if (!srcFieldDesc.equals(dstFieldDesc)) {
4854         // add a new edge
4855         // System.out.println("-ADD EDGE");
4856         getHierarchyGraph(cd).addEdge(srcFieldDesc, dstFieldDesc);
4857       } else if (!isReference(srcFieldDesc) && !isReference(dstFieldDesc)) {
4858         // System.out.println("-ADD EDGE");
4859         getHierarchyGraph(cd).addEdge(srcFieldDesc, dstFieldDesc);
4860       }
4861
4862     }
4863
4864   }
4865
4866   public SSJavaLattice<String> getFieldLattice(ClassDescriptor cd) {
4867     if (!cd2lattice.containsKey(cd)) {
4868       cd2lattice.put(cd, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
4869     }
4870     return cd2lattice.get(cd);
4871   }
4872
4873   public LinkedList<MethodDescriptor> computeMethodList() {
4874
4875     Set<MethodDescriptor> toSort = new HashSet<MethodDescriptor>();
4876
4877     setupToAnalyze();
4878
4879     Set<MethodDescriptor> visited = new HashSet<MethodDescriptor>();
4880     Set<MethodDescriptor> reachableCallee = new HashSet<MethodDescriptor>();
4881
4882     while (!toAnalyzeIsEmpty()) {
4883       ClassDescriptor cd = toAnalyzeNext();
4884
4885       if (cd.getClassName().equals("Object")) {
4886         rootClassDescriptor = cd;
4887         // inheritanceTree = new InheritanceTree<ClassDescriptor>(cd);
4888       }
4889
4890       setupToAnalazeMethod(cd);
4891       temp_toanalyzeMethodList.removeAll(visited);
4892
4893       while (!toAnalyzeMethodIsEmpty()) {
4894         MethodDescriptor md = toAnalyzeMethodNext();
4895         if ((!visited.contains(md))
4896             && (ssjava.needTobeAnnotated(md) || reachableCallee.contains(md))) {
4897
4898           // creates a mapping from a method descriptor to virtual methods
4899           Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
4900           if (md.isStatic()) {
4901             setPossibleCallees.add(md);
4902           } else {
4903             setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
4904           }
4905
4906           Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getCalleeSet(md);
4907           Set<MethodDescriptor> needToAnalyzeCalleeSet = new HashSet<MethodDescriptor>();
4908
4909           for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
4910             MethodDescriptor calleemd = (MethodDescriptor) iterator.next();
4911             if ((!ssjava.isTrustMethod(calleemd))
4912                 && (!ssjava.isSSJavaUtil(calleemd.getClassDesc()))
4913                 && (!calleemd.getModifiers().isNative())) {
4914               if (!visited.contains(calleemd)) {
4915                 temp_toanalyzeMethodList.add(calleemd);
4916               }
4917               reachableCallee.add(calleemd);
4918               needToAnalyzeCalleeSet.add(calleemd);
4919             }
4920           }
4921
4922           mapMethodToCalleeSet.put(md, needToAnalyzeCalleeSet);
4923
4924           visited.add(md);
4925
4926           toSort.add(md);
4927         }
4928       }
4929     }
4930
4931     return ssjava.topologicalSort(toSort);
4932
4933   }
4934
4935   public boolean isTransitivelyCalledFrom(MethodDescriptor callee, MethodDescriptor caller) {
4936     // if the callee is transitively invoked from the caller
4937     // return true;
4938
4939     int callerIdx = toanalyze_methodDescList.indexOf(caller);
4940     int calleeIdx = toanalyze_methodDescList.indexOf(callee);
4941
4942     if (callerIdx < calleeIdx) {
4943       return true;
4944     }
4945
4946     return false;
4947
4948   }
4949
4950   public void constructFlowGraph() {
4951
4952     System.out.println("");
4953     toanalyze_methodDescList = computeMethodList();
4954
4955     // hack... it seems that there is a problem with topological sorting.
4956     // so String.toString(Object o) is appeared too higher in the call chain.
4957     MethodDescriptor mdToString1 = null;
4958     MethodDescriptor mdToString2 = null;
4959     for (Iterator iterator = toanalyze_methodDescList.iterator(); iterator.hasNext();) {
4960       MethodDescriptor md = (MethodDescriptor) iterator.next();
4961       if (md.toString().equals("public static String String.valueOf(Object o)")) {
4962         mdToString1 = md;
4963       }
4964       if (md.toString().equals("public String Object.toString()")) {
4965         mdToString2 = md;
4966       }
4967     }
4968
4969     if (mdToString1 != null) {
4970       toanalyze_methodDescList.remove(mdToString1);
4971       toanalyze_methodDescList.addLast(mdToString1);
4972     }
4973     if (mdToString2 != null) {
4974       toanalyze_methodDescList.remove(mdToString2);
4975       toanalyze_methodDescList.addLast(mdToString2);
4976     }
4977
4978     LinkedList<MethodDescriptor> methodDescList =
4979         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
4980
4981     // System.out.println("@@@methodDescList=" + methodDescList);
4982     // System.exit(0);
4983
4984     while (!methodDescList.isEmpty()) {
4985       MethodDescriptor md = methodDescList.removeLast();
4986       if (state.SSJAVADEBUG) {
4987         System.out.println();
4988         System.out.println("SSJAVA: Constructing a flow graph: " + md);
4989
4990         // creates a mapping from a parameter descriptor to its index
4991         Map<Descriptor, Integer> mapParamDescToIdx = new HashMap<Descriptor, Integer>();
4992         int offset = 0;
4993         if (!md.isStatic()) {
4994           offset = 1;
4995           mapParamDescToIdx.put(md.getThis(), 0);
4996         }
4997
4998         for (int i = 0; i < md.numParameters(); i++) {
4999           Descriptor paramDesc = (Descriptor) md.getParameter(i);
5000           mapParamDescToIdx.put(paramDesc, new Integer(i + offset));
5001         }
5002
5003         FlowGraph fg = new FlowGraph(md, mapParamDescToIdx);
5004         mapMethodDescriptorToFlowGraph.put(md, fg);
5005
5006         analyzeMethodBody(md.getClassDesc(), md);
5007
5008         // System.out.println("##constructSubGlobalFlowGraph");
5009         // GlobalFlowGraph subGlobalFlowGraph = constructSubGlobalFlowGraph(fg);
5010         // mapMethodDescriptorToSubGlobalFlowGraph.put(md, subGlobalFlowGraph);
5011         //
5012         // // TODO
5013         // System.out.println("##addValueFlowsFromCalleeSubGlobalFlowGraph");
5014         // addValueFlowsFromCalleeSubGlobalFlowGraph(md, subGlobalFlowGraph);
5015         // subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
5016         //
5017         // propagateFlowsFromCalleesWithNoCompositeLocation(md);
5018       }
5019     }
5020     // _debug_printGraph();
5021
5022   }
5023
5024   private void constructGlobalFlowGraph() {
5025     LinkedList<MethodDescriptor> methodDescList =
5026         (LinkedList<MethodDescriptor>) toanalyze_methodDescList.clone();
5027
5028     while (!methodDescList.isEmpty()) {
5029       MethodDescriptor md = methodDescList.removeLast();
5030       if (state.SSJAVADEBUG) {
5031         System.out.println();
5032         System.out.println("SSJAVA: Constructing a sub global flow graph: " + md);
5033
5034         constructSubGlobalFlowGraph(getFlowGraph(md));
5035
5036         // TODO
5037         // System.out.println("-add Value Flows From CalleeSubGlobalFlowGraph");
5038         addValueFlowsFromCalleeSubGlobalFlowGraph(md);
5039         // subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
5040
5041         // System.out.println("-propagate Flows From Callees With No CompositeLocation");
5042         // propagateFlowsFromCalleesWithNoCompositeLocation(md);
5043
5044         // mark if a parameter has incoming flows
5045         checkParamNodesInSubGlobalFlowGraph(md);
5046
5047       }
5048     }
5049   }
5050
5051   private void checkParamNodesInSubGlobalFlowGraph(MethodDescriptor md) {
5052     GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
5053     FlowGraph flowGraph = getFlowGraph(md);
5054
5055     Set<FlowNode> paramFlowNodeSet = flowGraph.getParamFlowNodeSet();
5056     for (Iterator iterator = paramFlowNodeSet.iterator(); iterator.hasNext();) {
5057       FlowNode paramFlowNode = (FlowNode) iterator.next();
5058       // System.out.println("paramFlowNode=" + paramFlowNode);
5059       NTuple<Descriptor> paramDescTuple = paramFlowNode.getDescTuple();
5060       NTuple<Location> paramLocTuple = translateToLocTuple(md, paramDescTuple);
5061       GlobalFlowNode paramGlobalNode = globalFlowGraph.getFlowNode(paramLocTuple);
5062
5063       Set<GlobalFlowNode> incomingNodeSet =
5064           globalFlowGraph.getIncomingNodeSetByPrefix(paramLocTuple.get(0));
5065
5066       if (incomingNodeSet.size() > 0) {
5067         paramGlobalNode.setParamNodeWithIncomingFlows(true);
5068       }
5069
5070     }
5071   }
5072
5073   private Set<MethodInvokeNode> getMethodInvokeNodeSet(MethodDescriptor md) {
5074     if (!mapMethodDescriptorToMethodInvokeNodeSet.containsKey(md)) {
5075       mapMethodDescriptorToMethodInvokeNodeSet.put(md, new HashSet<MethodInvokeNode>());
5076     }
5077     return mapMethodDescriptorToMethodInvokeNodeSet.get(md);
5078   }
5079
5080   private void propagateFlowsFromCalleesWithNoCompositeLocation(MethodDescriptor mdCaller) {
5081
5082     // the transformation for a call site propagates flows through parameters
5083     // if the method is virtual, it also grab all relations from any possible
5084     // callees
5085
5086     Set<MethodInvokeNode> setMethodInvokeNode =
5087         mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
5088
5089     if (setMethodInvokeNode != null) {
5090
5091       for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
5092         MethodInvokeNode min = (MethodInvokeNode) iterator.next();
5093         MethodDescriptor mdCallee = min.getMethod();
5094         Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
5095         if (mdCallee.isStatic()) {
5096           setPossibleCallees.add(mdCallee);
5097         } else {
5098           Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
5099           // removes method descriptors that are not invoked by the caller
5100           calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
5101           setPossibleCallees.addAll(calleeSet);
5102         }
5103
5104         for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
5105           MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
5106           propagateFlowsToCallerWithNoCompositeLocation(min, mdCaller, possibleMdCallee);
5107         }
5108
5109       }
5110     }
5111
5112   }
5113
5114   private void analyzeMethodBody(ClassDescriptor cd, MethodDescriptor md) {
5115     BlockNode bn = state.getMethodBody(md);
5116     NodeTupleSet implicitFlowTupleSet = new NodeTupleSet();
5117     analyzeFlowBlockNode(md, md.getParameterTable(), bn, implicitFlowTupleSet);
5118   }
5119
5120   private void analyzeFlowBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn,
5121       NodeTupleSet implicitFlowTupleSet) {
5122
5123     bn.getVarTable().setParent(nametable);
5124     for (int i = 0; i < bn.size(); i++) {
5125       BlockStatementNode bsn = bn.get(i);
5126       analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
5127     }
5128
5129   }
5130
5131   private void analyzeBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
5132       BlockStatementNode bsn, NodeTupleSet implicitFlowTupleSet) {
5133
5134     switch (bsn.kind()) {
5135     case Kind.BlockExpressionNode:
5136       analyzeBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, implicitFlowTupleSet);
5137       break;
5138
5139     case Kind.DeclarationNode:
5140       analyzeFlowDeclarationNode(md, nametable, (DeclarationNode) bsn, implicitFlowTupleSet);
5141       break;
5142
5143     case Kind.IfStatementNode:
5144       analyzeFlowIfStatementNode(md, nametable, (IfStatementNode) bsn, implicitFlowTupleSet);
5145       break;
5146
5147     case Kind.LoopNode:
5148       analyzeFlowLoopNode(md, nametable, (LoopNode) bsn, implicitFlowTupleSet);
5149       break;
5150
5151     case Kind.ReturnNode:
5152       analyzeFlowReturnNode(md, nametable, (ReturnNode) bsn, implicitFlowTupleSet);
5153       break;
5154
5155     case Kind.SubBlockNode:
5156       analyzeFlowSubBlockNode(md, nametable, (SubBlockNode) bsn, implicitFlowTupleSet);
5157       break;
5158
5159     case Kind.ContinueBreakNode:
5160       break;
5161
5162     case Kind.SwitchStatementNode:
5163       analyzeSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, implicitFlowTupleSet);
5164       break;
5165
5166     }
5167
5168   }
5169
5170   private void analyzeSwitchBlockNode(MethodDescriptor md, SymbolTable nametable,
5171       SwitchBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
5172
5173     analyzeFlowBlockNode(md, nametable, sbn.getSwitchBlockStatement(), implicitFlowTupleSet);
5174
5175   }
5176
5177   private void analyzeSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
5178       SwitchStatementNode ssn, NodeTupleSet implicitFlowTupleSet) {
5179
5180     NodeTupleSet condTupleNode = new NodeTupleSet();
5181     analyzeFlowExpressionNode(md, nametable, ssn.getCondition(), condTupleNode, null,
5182         implicitFlowTupleSet, false);
5183
5184     NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
5185
5186     newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
5187     newImplicitTupleSet.addTupleSet(condTupleNode);
5188
5189     if (needToGenerateInterLoc(newImplicitTupleSet)) {
5190       // need to create an intermediate node for the GLB of conditional
5191       // locations & implicit flows
5192
5193       NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
5194       for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter.hasNext();) {
5195         NTuple<Descriptor> tuple = idxIter.next();
5196         addFlowGraphEdge(md, tuple, interTuple);
5197       }
5198       newImplicitTupleSet.clear();
5199       newImplicitTupleSet.addTuple(interTuple);
5200     }
5201
5202     BlockNode sbn = ssn.getSwitchBody();
5203     for (int i = 0; i < sbn.size(); i++) {
5204       analyzeSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), newImplicitTupleSet);
5205     }
5206
5207   }
5208
5209   private void analyzeFlowSubBlockNode(MethodDescriptor md, SymbolTable nametable,
5210       SubBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
5211     analyzeFlowBlockNode(md, nametable, sbn.getBlockNode(), implicitFlowTupleSet);
5212   }
5213
5214   private void analyzeFlowReturnNode(MethodDescriptor md, SymbolTable nametable, ReturnNode rn,
5215       NodeTupleSet implicitFlowTupleSet) {
5216
5217     // System.out.println("-analyzeFlowReturnNode=" + rn.printNode(0));
5218     ExpressionNode returnExp = rn.getReturnExpression();
5219
5220     if (returnExp != null) {
5221       NodeTupleSet nodeSet = new NodeTupleSet();
5222       // if a return expression returns a literal value, nodeSet is empty
5223       analyzeFlowExpressionNode(md, nametable, returnExp, nodeSet, false);
5224       FlowGraph fg = getFlowGraph(md);
5225
5226       // if (implicitFlowTupleSet.size() == 1
5227       // &&
5228       // fg.getFlowNode(implicitFlowTupleSet.iterator().next()).isIntermediate())
5229       // {
5230       //
5231       // // since there is already an intermediate node for the GLB of implicit
5232       // flows
5233       // // we don't need to create another intermediate node.
5234       // // just re-use the intermediate node for implicit flows.
5235       //
5236       // FlowNode meetNode =
5237       // fg.getFlowNode(implicitFlowTupleSet.iterator().next());
5238       //
5239       // for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
5240       // NTuple<Descriptor> returnNodeTuple = (NTuple<Descriptor>)
5241       // iterator.next();
5242       // fg.addValueFlowEdge(returnNodeTuple, meetNode.getDescTuple());
5243       // }
5244       //
5245       // }
5246
5247       NodeTupleSet currentFlowTupleSet = new NodeTupleSet();
5248
5249       // add tuples from return node
5250       currentFlowTupleSet.addTupleSet(nodeSet);
5251
5252       // add tuples corresponding to the current implicit flows
5253       currentFlowTupleSet.addTupleSet(implicitFlowTupleSet);
5254
5255       // System.out.println("---currentFlowTupleSet=" + currentFlowTupleSet);
5256
5257       if (needToGenerateInterLoc(currentFlowTupleSet)) {
5258
5259         FlowNode meetNode = fg.createIntermediateNode();
5260         for (Iterator iterator = currentFlowTupleSet.iterator(); iterator.hasNext();) {
5261           NTuple<Descriptor> currentFlowTuple = (NTuple<Descriptor>) iterator.next();
5262           fg.addValueFlowEdge(currentFlowTuple, meetNode.getDescTuple());
5263         }
5264         fg.addReturnFlowNode(meetNode.getDescTuple());
5265       } else {
5266         // currentFlowTupleSet = removeLiteralTuple(currentFlowTupleSet);
5267         for (Iterator iterator = currentFlowTupleSet.iterator(); iterator.hasNext();) {
5268           NTuple<Descriptor> currentFlowTuple = (NTuple<Descriptor>) iterator.next();
5269           fg.addReturnFlowNode(currentFlowTuple);
5270         }
5271       }
5272
5273     }
5274
5275   }
5276
5277   private NodeTupleSet removeLiteralTuple(NodeTupleSet inSet) {
5278     NodeTupleSet tupleSet = new NodeTupleSet();
5279     for (Iterator<NTuple<Descriptor>> iter = inSet.iterator(); iter.hasNext();) {
5280       NTuple<Descriptor> tuple = iter.next();
5281       if (!tuple.get(0).equals(LITERALDESC)) {
5282         tupleSet.addTuple(tuple);
5283       }
5284     }
5285     return tupleSet;
5286   }
5287
5288   private boolean needToGenerateInterLoc(NodeTupleSet tupleSet) {
5289     int size = 0;
5290     for (Iterator<NTuple<Descriptor>> iter = tupleSet.iterator(); iter.hasNext();) {
5291       NTuple<Descriptor> descTuple = iter.next();
5292       if (!descTuple.get(0).equals(LITERALDESC)) {
5293         size++;
5294       }
5295     }
5296     if (size > 1) {
5297       // System.out.println("needToGenerateInterLoc=" + tupleSet + "  size=" + size);
5298       return true;
5299     } else {
5300       return false;
5301     }
5302   }
5303
5304   private void analyzeFlowLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln,
5305       NodeTupleSet implicitFlowTupleSet) {
5306
5307     if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
5308
5309       NodeTupleSet condTupleNode = new NodeTupleSet();
5310       analyzeFlowExpressionNode(md, nametable, ln.getCondition(), condTupleNode, null,
5311           implicitFlowTupleSet, false);
5312
5313       NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
5314
5315       newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
5316       newImplicitTupleSet.addTupleSet(condTupleNode);
5317
5318       newImplicitTupleSet.addGlobalFlowTupleSet(implicitFlowTupleSet.getGlobalLocTupleSet());
5319       newImplicitTupleSet.addGlobalFlowTupleSet(condTupleNode.getGlobalLocTupleSet());
5320
5321       if (needToGenerateInterLoc(newImplicitTupleSet)) {
5322         // need to create an intermediate node for the GLB of conditional
5323         // locations & implicit flows
5324
5325         NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
5326         for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter
5327             .hasNext();) {
5328           NTuple<Descriptor> tuple = idxIter.next();
5329           addFlowGraphEdge(md, tuple, interTuple);
5330         }
5331         newImplicitTupleSet.clear();
5332         newImplicitTupleSet.addTuple(interTuple);
5333
5334       }
5335
5336       // ///////////
5337       // System.out.println("condTupleNode="+condTupleNode);
5338       // NTuple<Descriptor> interTuple =
5339       // getFlowGraph(md).createIntermediateNode().getDescTuple();
5340       //
5341       // for (Iterator<NTuple<Descriptor>> idxIter = condTupleNode.iterator();
5342       // idxIter.hasNext();) {
5343       // NTuple<Descriptor> tuple = idxIter.next();
5344       // addFlowGraphEdge(md, tuple, interTuple);
5345       // }
5346
5347       // for (Iterator<NTuple<Descriptor>> idxIter =
5348       // implicitFlowTupleSet.iterator(); idxIter
5349       // .hasNext();) {
5350       // NTuple<Descriptor> tuple = idxIter.next();
5351       // addFlowGraphEdge(md, tuple, interTuple);
5352       // }
5353
5354       // NodeTupleSet newImplicitSet = new NodeTupleSet();
5355       // newImplicitSet.addTuple(interTuple);
5356       analyzeFlowBlockNode(md, nametable, ln.getBody(), newImplicitTupleSet);
5357       // ///////////
5358
5359       // condTupleNode.addTupleSet(implicitFlowTupleSet);
5360
5361       // add edges from condNodeTupleSet to all nodes of conditional nodes
5362       // analyzeFlowBlockNode(md, nametable, ln.getBody(), condTupleNode);
5363
5364     } else {
5365       // check 'for loop' case
5366       BlockNode bn = ln.getInitializer();
5367       bn.getVarTable().setParent(nametable);
5368       for (int i = 0; i < bn.size(); i++) {
5369         BlockStatementNode bsn = bn.get(i);
5370         analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
5371       }
5372
5373       NodeTupleSet condTupleNode = new NodeTupleSet();
5374       analyzeFlowExpressionNode(md, bn.getVarTable(), ln.getCondition(), condTupleNode, null,
5375           implicitFlowTupleSet, false);
5376
5377       NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
5378       newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
5379       newImplicitTupleSet.addTupleSet(condTupleNode);
5380
5381       if (needToGenerateInterLoc(newImplicitTupleSet)) {
5382         // need to create an intermediate node for the GLB of conditional
5383         // locations & implicit flows
5384
5385         NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
5386         for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter
5387             .hasNext();) {
5388           NTuple<Descriptor> tuple = idxIter.next();
5389           addFlowGraphEdge(md, tuple, interTuple);
5390         }
5391         newImplicitTupleSet.clear();
5392         newImplicitTupleSet.addTuple(interTuple);
5393
5394       }
5395
5396       // ///////////
5397       // NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
5398       //
5399       // for (Iterator<NTuple<Descriptor>> idxIter = condTupleNode.iterator(); idxIter.hasNext();) {
5400       // NTuple<Descriptor> tuple = idxIter.next();
5401       // addFlowGraphEdge(md, tuple, interTuple);
5402       // }
5403       //
5404       // for (Iterator<NTuple<Descriptor>> idxIter = implicitFlowTupleSet.iterator(); idxIter
5405       // .hasNext();) {
5406       // NTuple<Descriptor> tuple = idxIter.next();
5407       // addFlowGraphEdge(md, tuple, interTuple);
5408       // }
5409       //
5410       // NodeTupleSet newImplicitSet = new NodeTupleSet();
5411       // newImplicitSet.addTuple(interTuple);
5412       analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(), newImplicitTupleSet);
5413       analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(), newImplicitTupleSet);
5414       // ///////////
5415
5416       // condTupleNode.addTupleSet(implicitFlowTupleSet);
5417       //
5418       // analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(),
5419       // condTupleNode);
5420       // analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(),
5421       // condTupleNode);
5422
5423     }
5424
5425   }
5426
5427   private void analyzeFlowIfStatementNode(MethodDescriptor md, SymbolTable nametable,
5428       IfStatementNode isn, NodeTupleSet implicitFlowTupleSet) {
5429
5430     // System.out.println("analyzeFlowIfStatementNode=" + isn.printNode(0));
5431
5432     NodeTupleSet condTupleNode = new NodeTupleSet();
5433     analyzeFlowExpressionNode(md, nametable, isn.getCondition(), condTupleNode, null,
5434         implicitFlowTupleSet, false);
5435
5436     NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
5437
5438     newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
5439     newImplicitTupleSet.addTupleSet(condTupleNode);
5440
5441     // System.out.println("$$$GGGcondTupleNode=" + condTupleNode.getGlobalLocTupleSet());
5442     // System.out.println("-condTupleNode=" + condTupleNode);
5443     // System.out.println("-implicitFlowTupleSet=" + implicitFlowTupleSet);
5444     // System.out.println("-newImplicitTupleSet=" + newImplicitTupleSet);
5445
5446     if (needToGenerateInterLoc(newImplicitTupleSet)) {
5447
5448       // need to create an intermediate node for the GLB of conditional locations & implicit flows
5449       NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
5450       for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter.hasNext();) {
5451         NTuple<Descriptor> tuple = idxIter.next();
5452         addFlowGraphEdge(md, tuple, interTuple);
5453       }
5454       newImplicitTupleSet.clear();
5455       newImplicitTupleSet.addTuple(interTuple);
5456     }
5457
5458     // GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
5459     // for (Iterator<NTuple<Location>> iterator = condTupleNode.globalIterator();
5460     // iterator.hasNext();) {
5461     // NTuple<Location> calleeReturnLocTuple = iterator.next();
5462     // for (Iterator<NTuple<Descriptor>> iter2 = newImplicitTupleSet.iterator(); iter2.hasNext();) {
5463     // NTuple<Descriptor> callerImplicitTuple = iter2.next();
5464     // globalFlowGraph.addValueFlowEdge(calleeReturnLocTuple,
5465     // translateToLocTuple(md, callerImplicitTuple));
5466     // }
5467     // }
5468     newImplicitTupleSet.addGlobalFlowTupleSet(condTupleNode.getGlobalLocTupleSet());
5469
5470     analyzeFlowBlockNode(md, nametable, isn.getTrueBlock(), newImplicitTupleSet);
5471
5472     if (isn.getFalseBlock() != null) {
5473       analyzeFlowBlockNode(md, nametable, isn.getFalseBlock(), newImplicitTupleSet);
5474     }
5475
5476   }
5477
5478   private void analyzeFlowDeclarationNode(MethodDescriptor md, SymbolTable nametable,
5479       DeclarationNode dn, NodeTupleSet implicitFlowTupleSet) {
5480
5481     VarDescriptor vd = dn.getVarDescriptor();
5482     mapDescToDefinitionLine.put(vd, dn.getNumLine());
5483     NTuple<Descriptor> tupleLHS = new NTuple<Descriptor>();
5484     tupleLHS.add(vd);
5485     FlowNode fn = getFlowGraph(md).createNewFlowNode(tupleLHS);
5486     fn.setDeclarationNode();
5487
5488     if (dn.getExpression() != null) {
5489       // System.out.println("-analyzeFlowDeclarationNode=" + dn.printNode(0));
5490
5491       NodeTupleSet nodeSetRHS = new NodeTupleSet();
5492       analyzeFlowExpressionNode(md, nametable, dn.getExpression(), nodeSetRHS, null,
5493           implicitFlowTupleSet, false);
5494
5495       // creates edges from RHS to LHS
5496       NTuple<Descriptor> interTuple = null;
5497       if (needToGenerateInterLoc(nodeSetRHS)) {
5498         interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
5499       }
5500
5501       for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
5502         NTuple<Descriptor> fromTuple = iter.next();
5503         // System.out.println("fromTuple=" + fromTuple + "  interTuple=" + interTuple + " tupleLSH="
5504         // + tupleLHS);
5505         addFlowGraphEdge(md, fromTuple, interTuple, tupleLHS);
5506       }
5507
5508       // creates edges from implicitFlowTupleSet to LHS
5509       for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
5510         NTuple<Descriptor> implicitTuple = iter.next();
5511         addFlowGraphEdge(md, implicitTuple, tupleLHS);
5512       }
5513
5514       GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
5515       for (Iterator<NTuple<Location>> iterator = nodeSetRHS.globalIterator(); iterator.hasNext();) {
5516         NTuple<Location> calleeReturnLocTuple = iterator.next();
5517
5518         globalFlowGraph.addValueFlowEdge(calleeReturnLocTuple, translateToLocTuple(md, tupleLHS));
5519       }
5520
5521       for (Iterator<NTuple<Location>> iterator = implicitFlowTupleSet.globalIterator(); iterator
5522           .hasNext();) {
5523         NTuple<Location> implicitGlobalTuple = iterator.next();
5524
5525         globalFlowGraph.addValueFlowEdge(implicitGlobalTuple, translateToLocTuple(md, tupleLHS));
5526       }
5527
5528       // System.out.println("-nodeSetRHS=" + nodeSetRHS);
5529       // System.out.println("-implicitFlowTupleSet=" + implicitFlowTupleSet);
5530
5531     }
5532
5533   }
5534
5535   private void analyzeBlockExpressionNode(MethodDescriptor md, SymbolTable nametable,
5536       BlockExpressionNode ben, NodeTupleSet implicitFlowTupleSet) {
5537     analyzeFlowExpressionNode(md, nametable, ben.getExpression(), null, null, implicitFlowTupleSet,
5538         false);
5539   }
5540
5541   private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
5542       ExpressionNode en, NodeTupleSet nodeSet, boolean isLHS) {
5543     return analyzeFlowExpressionNode(md, nametable, en, nodeSet, null, new NodeTupleSet(), isLHS);
5544   }
5545
5546   private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
5547       ExpressionNode en, NodeTupleSet nodeSet, NTuple<Descriptor> base,
5548       NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
5549
5550     // System.out.println("en=" + en.printNode(0) + "   class=" + en.getClass());
5551
5552     // note that expression node can create more than one flow node
5553     // nodeSet contains of flow nodes
5554     // base is always assigned to null except the case of a name node!
5555     NTuple<Descriptor> flowTuple;
5556     switch (en.kind()) {
5557     case Kind.AssignmentNode:
5558       analyzeFlowAssignmentNode(md, nametable, (AssignmentNode) en, nodeSet, base,
5559           implicitFlowTupleSet);
5560       break;
5561
5562     case Kind.FieldAccessNode:
5563       flowTuple =
5564           analyzeFlowFieldAccessNode(md, nametable, (FieldAccessNode) en, nodeSet, base,
5565               implicitFlowTupleSet, isLHS);
5566       if (flowTuple != null) {
5567         nodeSet.addTuple(flowTuple);
5568       }
5569       return flowTuple;
5570
5571     case Kind.NameNode:
5572       NodeTupleSet nameNodeSet = new NodeTupleSet();
5573       flowTuple =
5574           analyzeFlowNameNode(md, nametable, (NameNode) en, nameNodeSet, base, implicitFlowTupleSet);
5575       if (flowTuple != null) {
5576         nodeSet.addTuple(flowTuple);
5577       }
5578       return flowTuple;
5579
5580     case Kind.OpNode:
5581       analyzeFlowOpNode(md, nametable, (OpNode) en, nodeSet, implicitFlowTupleSet);
5582       break;
5583
5584     case Kind.CreateObjectNode:
5585       analyzeCreateObjectNode(md, nametable, (CreateObjectNode) en, nodeSet, implicitFlowTupleSet);
5586       break;
5587
5588     case Kind.ArrayAccessNode:
5589       analyzeFlowArrayAccessNode(md, nametable, (ArrayAccessNode) en, nodeSet, isLHS);
5590       break;
5591
5592     case Kind.LiteralNode:
5593       analyzeFlowLiteralNode(md, nametable, (LiteralNode) en, nodeSet);
5594       break;
5595
5596     case Kind.MethodInvokeNode:
5597       analyzeFlowMethodInvokeNode(md, nametable, (MethodInvokeNode) en, nodeSet,
5598           implicitFlowTupleSet);
5599       break;
5600
5601     case Kind.TertiaryNode:
5602       analyzeFlowTertiaryNode(md, nametable, (TertiaryNode) en, nodeSet, implicitFlowTupleSet);
5603       break;
5604
5605     case Kind.CastNode:
5606       analyzeFlowCastNode(md, nametable, (CastNode) en, nodeSet, base, implicitFlowTupleSet);
5607       break;
5608     // case Kind.InstanceOfNode:
5609     // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
5610     // return null;
5611
5612     // case Kind.ArrayInitializerNode:
5613     // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
5614     // td);
5615     // return null;
5616
5617     // case Kind.ClassTypeNode:
5618     // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
5619     // return null;
5620
5621     // case Kind.OffsetNode:
5622     // checkOffsetNode(md, nametable, (OffsetNode)en, td);
5623     // return null;
5624
5625     }
5626
5627     return null;
5628
5629   }
5630
5631   private void analyzeFlowCastNode(MethodDescriptor md, SymbolTable nametable, CastNode cn,
5632       NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
5633
5634     analyzeFlowExpressionNode(md, nametable, cn.getExpression(), nodeSet, base,
5635         implicitFlowTupleSet, false);
5636
5637   }
5638
5639   private void analyzeFlowTertiaryNode(MethodDescriptor md, SymbolTable nametable, TertiaryNode tn,
5640       NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
5641
5642     // System.out.println("analyzeFlowTertiaryNode=" + tn.printNode(0));
5643
5644     NodeTupleSet tertiaryTupleNode = new NodeTupleSet();
5645     analyzeFlowExpressionNode(md, nametable, tn.getCond(), tertiaryTupleNode, null,
5646         implicitFlowTupleSet, false);
5647
5648     NodeTupleSet newImplicitTupleSet = new NodeTupleSet();
5649     newImplicitTupleSet.addTupleSet(implicitFlowTupleSet);
5650     newImplicitTupleSet.addTupleSet(tertiaryTupleNode);
5651
5652     // System.out.println("$$$GGGcondTupleNode=" + tertiaryTupleNode.getGlobalLocTupleSet());
5653     // System.out.println("-tertiaryTupleNode=" + tertiaryTupleNode);
5654     // System.out.println("-implicitFlowTupleSet=" + implicitFlowTupleSet);
5655     // System.out.println("-newImplicitTupleSet=" + newImplicitTupleSet);
5656
5657     if (needToGenerateInterLoc(newImplicitTupleSet)) {
5658       // need to create an intermediate node for the GLB of conditional locations & implicit flows
5659       NTuple<Descriptor> interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
5660       for (Iterator<NTuple<Descriptor>> idxIter = newImplicitTupleSet.iterator(); idxIter.hasNext();) {
5661         NTuple<Descriptor> tuple = idxIter.next();
5662         addFlowGraphEdge(md, tuple, interTuple);
5663       }
5664       newImplicitTupleSet.clear();
5665       newImplicitTupleSet.addTuple(interTuple);
5666     }
5667
5668     newImplicitTupleSet.addGlobalFlowTupleSet(tertiaryTupleNode.getGlobalLocTupleSet());
5669
5670     // System.out.println("---------newImplicitTupleSet=" + newImplicitTupleSet);
5671
5672     // add edges from tertiaryTupleNode to all nodes of conditional nodes
5673     // tertiaryTupleNode.addTupleSet(implicitFlowTupleSet);
5674     analyzeFlowExpressionNode(md, nametable, tn.getTrueExpr(), tertiaryTupleNode, null,
5675         newImplicitTupleSet, false);
5676
5677     analyzeFlowExpressionNode(md, nametable, tn.getFalseExpr(), tertiaryTupleNode, null,
5678         newImplicitTupleSet, false);
5679
5680     nodeSet.addGlobalFlowTupleSet(tertiaryTupleNode.getGlobalLocTupleSet());
5681     nodeSet.addTupleSet(tertiaryTupleNode);
5682
5683     // System.out.println("#tertiary node set=" + nodeSet);
5684   }
5685
5686   private void addMapCallerMethodDescToMethodInvokeNodeSet(MethodDescriptor caller,
5687       MethodInvokeNode min) {
5688     Set<MethodInvokeNode> set = mapMethodDescriptorToMethodInvokeNodeSet.get(caller);
5689     if (set == null) {
5690       set = new HashSet<MethodInvokeNode>();
5691       mapMethodDescriptorToMethodInvokeNodeSet.put(caller, set);
5692     }
5693     set.add(min);
5694   }
5695
5696   private void addParamNodeFlowingToReturnValue(MethodDescriptor md, FlowNode fn) {
5697
5698     if (!mapMethodDescToParamNodeFlowsToReturnValue.containsKey(md)) {
5699       mapMethodDescToParamNodeFlowsToReturnValue.put(md, new HashSet<FlowNode>());
5700     }
5701     mapMethodDescToParamNodeFlowsToReturnValue.get(md).add(fn);
5702   }
5703
5704   private Set<FlowNode> getParamNodeFlowingToReturnValue(MethodDescriptor md) {
5705
5706     if (!mapMethodDescToParamNodeFlowsToReturnValue.containsKey(md)) {
5707       mapMethodDescToParamNodeFlowsToReturnValue.put(md, new HashSet<FlowNode>());
5708     }
5709
5710     return mapMethodDescToParamNodeFlowsToReturnValue.get(md);
5711   }
5712
5713   private Set<NTuple<Location>> getPCLocTupleSet(MethodInvokeNode min) {
5714     if (!mapMethodInvokeNodeToPCLocTupleSet.containsKey(min)) {
5715       mapMethodInvokeNodeToPCLocTupleSet.put(min, new HashSet<NTuple<Location>>());
5716     }
5717     return mapMethodInvokeNodeToPCLocTupleSet.get(min);
5718   }
5719
5720   private void analyzeFlowMethodInvokeNode(MethodDescriptor mdCaller, SymbolTable nametable,
5721       MethodInvokeNode min, NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
5722
5723     // System.out.println("analyzeFlowMethodInvokeNode=" + min.printNode(0));
5724
5725     if (!toanalyze_methodDescList.contains(min.getMethod())) {
5726       return;
5727     }
5728
5729     addMapMethodDescToMethodInvokeNodeSet(min);
5730
5731     Set<NTuple<Location>> pcLocTupleSet = getPCLocTupleSet(min);
5732     for (Iterator iterator = implicitFlowTupleSet.iterator(); iterator.hasNext();) {
5733       NTuple<Descriptor> pcDescTuple = (NTuple<Descriptor>) iterator.next();
5734       if (!pcDescTuple.get(0).equals(LITERALDESC)) {
5735         // here we don't need to add the literal value as a PC location
5736         pcLocTupleSet.add(translateToLocTuple(mdCaller, pcDescTuple));
5737       }
5738     }
5739
5740     mapMethodInvokeNodeToArgIdxMap.put(min, new HashMap<Integer, NTuple<Descriptor>>());
5741
5742     if (nodeSet == null) {
5743       nodeSet = new NodeTupleSet();
5744     }
5745
5746     MethodDescriptor mdCallee = min.getMethod();
5747
5748     NameDescriptor baseName = min.getBaseName();
5749     boolean isSystemout = false;
5750     if (baseName != null) {
5751       isSystemout = baseName.getSymbol().equals("System.out");
5752     }
5753
5754     if (!ssjava.isSSJavaUtil(mdCallee.getClassDesc()) && !ssjava.isTrustMethod(mdCallee)
5755         && !isSystemout) {
5756
5757       addMapCallerMethodDescToMethodInvokeNodeSet(mdCaller, min);
5758
5759       FlowGraph calleeFlowGraph = getFlowGraph(mdCallee);
5760       // System.out.println("mdCallee=" + mdCallee + " calleeFlowGraph=" + calleeFlowGraph);
5761       Set<FlowNode> calleeReturnSet = calleeFlowGraph.getReturnNodeSet();
5762
5763       // System.out.println("---calleeReturnSet=" + calleeReturnSet);
5764
5765       NodeTupleSet tupleSet = new NodeTupleSet();
5766
5767       if (min.getExpression() != null) {
5768
5769         NodeTupleSet baseNodeSet = new NodeTupleSet();
5770         analyzeFlowExpressionNode(mdCaller, nametable, min.getExpression(), baseNodeSet, null,
5771             implicitFlowTupleSet, false);
5772         // System.out.println("baseNodeSet=" + baseNodeSet);
5773
5774         assert (baseNodeSet.size() == 1);
5775         NTuple<Descriptor> baseTuple = baseNodeSet.iterator().next();
5776         if (baseTuple.get(0) instanceof InterDescriptor) {
5777           if (baseTuple.size() > 1) {
5778             throw new Error();
5779           }
5780           FlowNode interNode = getFlowGraph(mdCaller).getFlowNode(baseTuple);
5781           baseTuple = translateBaseTuple(interNode, baseTuple);
5782         }
5783         mapMethodInvokeNodeToBaseTuple.put(min, baseTuple);
5784
5785         if (!min.getMethod().isStatic()) {
5786           addArgIdxMap(min, 0, baseTuple);
5787
5788           for (Iterator iterator = calleeReturnSet.iterator(); iterator.hasNext();) {
5789             FlowNode returnNode = (FlowNode) iterator.next();
5790             NTuple<Descriptor> returnDescTuple = returnNode.getDescTuple();
5791             if (returnDescTuple.startsWith(mdCallee.getThis())) {
5792               // the location type of the return value is started with 'this'
5793               // reference
5794               NTuple<Descriptor> inFlowTuple = new NTuple<Descriptor>(baseTuple.getList());
5795
5796               if (inFlowTuple.get(0) instanceof InterDescriptor) {
5797                 // min.getExpression()
5798               } else {
5799
5800               }
5801
5802               inFlowTuple.addAll(returnDescTuple.subList(1, returnDescTuple.size()));
5803               // nodeSet.addTuple(inFlowTuple);
5804               // System.out.println("1CREATE A NEW TUPLE=" + inFlowTuple + "  from="
5805               // + mdCallee.getThis());
5806               // tupleSet.addTuple(inFlowTuple);
5807               tupleSet.addTuple(baseTuple);
5808             } else {
5809               // TODO
5810               // System.out.println("returnNode=" + returnNode);
5811               Set<FlowNode> inFlowSet = calleeFlowGraph.getIncomingFlowNodeSet(returnNode);
5812               // System.out.println("inFlowSet=" + inFlowSet + "   from retrunNode=" + returnNode);
5813               for (Iterator iterator2 = inFlowSet.iterator(); iterator2.hasNext();) {
5814                 FlowNode inFlowNode = (FlowNode) iterator2.next();
5815                 if (inFlowNode.getDescTuple().startsWith(mdCallee.getThis())) {
5816                   // nodeSet.addTupleSet(baseNodeSet);
5817                   // System.out.println("2CREATE A NEW TUPLE=" + baseNodeSet + "  from="
5818                   // + mdCallee.getThis());
5819                   tupleSet.addTupleSet(baseNodeSet);
5820                 }
5821               }
5822             }
5823           }
5824         }
5825
5826       }
5827       // analyze parameter flows
5828
5829       if (min.numArgs() > 0) {
5830
5831         int offset;
5832         if (min.getMethod().isStatic()) {
5833           offset = 0;
5834         } else {
5835           offset = 1;
5836         }
5837
5838         for (int i = 0; i < min.numArgs(); i++) {
5839           ExpressionNode en = min.getArg(i);
5840           int idx = i + offset;
5841           NodeTupleSet argTupleSet = new NodeTupleSet();
5842           analyzeFlowExpressionNode(mdCaller, nametable, en, argTupleSet, false);
5843           // if argument is liternal node, argTuple is set to NULL
5844           // System.out.println("---arg idx=" + idx + "   argTupleSet=" + argTupleSet);
5845           NTuple<Descriptor> argTuple = generateArgTuple(mdCaller, argTupleSet);
5846
5847           // if an argument is literal value,
5848           // we need to create an itermediate node so that we could assign a composite location to
5849           // that node if needed
5850           if (argTuple.size() > 0
5851               && (argTuple.get(0).equals(GLOBALDESC) || argTuple.get(0).equals(LITERALDESC))) {
5852             /*
5853              * System.out.println("***GLOBAL ARG TUPLE CASE=" + argTuple); System.out.println("8");
5854              * 
5855              * NTuple<Descriptor> interTuple =
5856              * getFlowGraph(mdCaller).createIntermediateNode().getDescTuple(); ((InterDescriptor)
5857              * interTuple.get(0)).setMethodArgIdxPair(min, idx); addFlowGraphEdge(mdCaller,
5858              * argTuple, interTuple); argTuple = interTuple; addArgIdxMap(min, idx, argTuple);
5859              * System.out.println("new min mapping i=" + idx + "  ->" + argTuple);
5860              */
5861             argTuple = new NTuple<Descriptor>();
5862           }
5863
5864           addArgIdxMap(min, idx, argTuple);
5865
5866           FlowNode paramNode = calleeFlowGraph.getParamFlowNode(idx);
5867
5868           // check whether a param node in the callee graph has incoming flows
5869           // if it has incoming flows, the corresponding arg should be lower than the current PC
5870           // Descriptor prefix = paramNode.getDescTuple().get(0);
5871           // if (calleeFlowGraph.getIncomingNodeSetByPrefix(prefix).size() > 0) {
5872           // for (Iterator<NTuple<Descriptor>> iterator = implicitFlowTupleSet.iterator(); iterator
5873           // .hasNext();) {
5874           // NTuple<Descriptor> pcTuple = iterator.next();
5875           // System.out.println("add edge pcTuple =" + pcTuple + " -> " + argTuple);
5876           // addFlowGraphEdge(md, pcTuple, argTuple);
5877           // }
5878           // }
5879
5880           // System.out.println("paramNode=" + paramNode + "  calleeReturnSet=" + calleeReturnSet);
5881           if (hasInFlowTo(calleeFlowGraph, paramNode, calleeReturnSet)
5882               || mdCallee.getModifiers().isNative()) {
5883             addParamNodeFlowingToReturnValue(mdCallee, paramNode);
5884             // nodeSet.addTupleSet(argTupleSet);
5885             // System.out.println("3CREATE A NEW TUPLE=" + argTupleSet + "  from=" + paramNode);
5886             tupleSet.addTupleSet(argTupleSet);
5887           }
5888         }
5889
5890       }
5891
5892       if (mdCallee.getReturnType() != null && !mdCallee.getReturnType().isVoid()) {
5893         FlowReturnNode returnHolderNode = getFlowGraph(mdCaller).createReturnNode(min);
5894
5895         if (needToGenerateInterLoc(tupleSet)) {
5896           FlowGraph fg = getFlowGraph(mdCaller);
5897           FlowNode interNode = fg.createIntermediateNode();
5898           interNode.setFormHolder(true);
5899
5900           NTuple<Descriptor> interTuple = interNode.getDescTuple();
5901
5902           for (Iterator iterator = tupleSet.iterator(); iterator.hasNext();) {
5903             NTuple<Descriptor> tuple = (NTuple<Descriptor>) iterator.next();
5904
5905             Set<NTuple<Descriptor>> addSet = new HashSet<NTuple<Descriptor>>();
5906             FlowNode node = fg.getFlowNode(tuple);
5907             if (node instanceof FlowReturnNode) {
5908               addSet.addAll(fg.getReturnTupleSet(((FlowReturnNode) node).getReturnTupleSet()));
5909             } else {
5910               addSet.add(tuple);
5911             }
5912             for (Iterator iterator2 = addSet.iterator(); iterator2.hasNext();) {
5913               NTuple<Descriptor> higher = (NTuple<Descriptor>) iterator2.next();
5914               addFlowGraphEdge(mdCaller, higher, interTuple);
5915             }
5916           }
5917
5918           returnHolderNode.addTuple(interTuple);
5919
5920           nodeSet.addTuple(interTuple);
5921           // System.out.println("ADD TUPLESET=" + interTuple + " to returnnode=" +
5922           // returnHolderNode);
5923
5924         } else {
5925           returnHolderNode.addTupleSet(tupleSet);
5926           // System.out.println("ADD TUPLESET=" + tupleSet + " to returnnode=" + returnHolderNode);
5927         }
5928         // setNode.addTupleSet(tupleSet);
5929         // NodeTupleSet setFromReturnNode=new NodeTupleSet();
5930         // setFromReturnNode.addTuple(tuple);
5931
5932         NodeTupleSet holderTupleSet =
5933             getNodeTupleSetFromReturnNode(getFlowGraph(mdCaller), returnHolderNode);
5934
5935         // System.out.println("HOLDER TUPLE SET=" + holderTupleSet);
5936         nodeSet.addTupleSet(holderTupleSet);
5937
5938         nodeSet.addTuple(returnHolderNode.getDescTuple());
5939       }
5940
5941       // propagateFlowsFromCallee(min, md, min.getMethod());
5942
5943       // when generating the global flow graph,
5944       // we need to add ordering relations from the set of callee return loc tuple to LHS of the
5945       // caller assignment
5946       for (Iterator iterator = calleeReturnSet.iterator(); iterator.hasNext();) {
5947         FlowNode calleeReturnNode = (FlowNode) iterator.next();
5948         NTuple<Location> calleeReturnLocTuple =
5949             translateToLocTuple(mdCallee, calleeReturnNode.getDescTuple());
5950         // System.out.println("calleeReturnLocTuple=" + calleeReturnLocTuple);
5951         NTuple<Location> transaltedToCaller =
5952             translateToCallerLocTuple(min, mdCallee, mdCaller, calleeReturnLocTuple);
5953         // System.out.println("translateToCallerLocTuple="
5954         // + translateToCallerLocTuple(min, mdCallee, mdCaller, calleeReturnLocTuple));
5955         if (transaltedToCaller.size() > 0) {
5956           nodeSet.addGlobalFlowTuple(translateToCallerLocTuple(min, mdCallee, mdCaller,
5957               calleeReturnLocTuple));
5958         }
5959       }
5960
5961       // System.out.println("min nodeSet=" + nodeSet);
5962
5963     }
5964
5965   }
5966
5967   private NodeTupleSet getNodeTupleSetFromReturnNode(FlowGraph fg, FlowReturnNode node) {
5968     NodeTupleSet nts = new NodeTupleSet();
5969
5970     Set<NTuple<Descriptor>> returnSet = node.getReturnTupleSet();
5971
5972     for (Iterator iterator = returnSet.iterator(); iterator.hasNext();) {
5973       NTuple<Descriptor> tuple = (NTuple<Descriptor>) iterator.next();
5974       FlowNode flowNode = fg.getFlowNode(tuple);
5975       if (flowNode instanceof FlowReturnNode) {
5976         returnSet.addAll(recurGetNode(fg, (FlowReturnNode) flowNode));
5977       } else {
5978         returnSet.add(tuple);
5979       }
5980     }
5981
5982     for (Iterator iterator = returnSet.iterator(); iterator.hasNext();) {
5983       NTuple<Descriptor> nTuple = (NTuple<Descriptor>) iterator.next();
5984       nts.addTuple(nTuple);
5985     }
5986
5987     return nts;
5988
5989   }
5990
5991   private Set<NTuple<Descriptor>> recurGetNode(FlowGraph fg, FlowReturnNode rnode) {
5992
5993     Set<NTuple<Descriptor>> tupleSet = new HashSet<NTuple<Descriptor>>();
5994
5995     Set<NTuple<Descriptor>> returnSet = rnode.getReturnTupleSet();
5996     for (Iterator iterator = returnSet.iterator(); iterator.hasNext();) {
5997       NTuple<Descriptor> tuple = (NTuple<Descriptor>) iterator.next();
5998       FlowNode flowNode = fg.getFlowNode(tuple);
5999       if (flowNode instanceof FlowReturnNode) {
6000         tupleSet.addAll(recurGetNode(fg, (FlowReturnNode) flowNode));
6001       }
6002       tupleSet.add(tuple);
6003     }
6004
6005     return tupleSet;
6006   }
6007
6008   private NTuple<Descriptor> generateArgTuple(MethodDescriptor mdCaller, NodeTupleSet argTupleSet) {
6009
6010     int size = 0;
6011
6012     // if argTupleSet is empty, it comes from the top location
6013     if (argTupleSet.size() == 0) {
6014       NTuple<Descriptor> descTuple = new NTuple<Descriptor>();
6015       descTuple.add(LITERALDESC);
6016       return descTuple;
6017     }
6018
6019     Set<NTuple<Descriptor>> argTupleSetNonLiteral = new HashSet<NTuple<Descriptor>>();
6020
6021     for (Iterator<NTuple<Descriptor>> iter = argTupleSet.iterator(); iter.hasNext();) {
6022       NTuple<Descriptor> descTuple = iter.next();
6023       if (!descTuple.get(0).equals(LITERALDESC)) {
6024         argTupleSetNonLiteral.add(descTuple);
6025       }
6026     }
6027
6028     if (argTupleSetNonLiteral.size() > 1) {
6029
6030       NTuple<Descriptor> interTuple =
6031           getFlowGraph(mdCaller).createIntermediateNode().getDescTuple();
6032       for (Iterator<NTuple<Descriptor>> idxIter = argTupleSet.iterator(); idxIter.hasNext();) {
6033         NTuple<Descriptor> tuple = idxIter.next();
6034         addFlowGraphEdge(mdCaller, tuple, interTuple);
6035       }
6036       return interTuple;
6037     } else if (argTupleSetNonLiteral.size() == 1) {
6038       return argTupleSetNonLiteral.iterator().next();
6039     } else {
6040       return argTupleSet.iterator().next();
6041     }
6042
6043   }
6044
6045   private boolean hasInFlowTo(FlowGraph fg, FlowNode inNode, Set<FlowNode> nodeSet) {
6046     // return true if inNode has in-flows to nodeSet
6047
6048     if (nodeSet.contains(inNode)) {
6049       // in this case, the method directly returns a parameter variable.
6050       return true;
6051     }
6052     // Set<FlowNode> reachableSet = fg.getReachFlowNodeSetFrom(inNode);
6053     Set<FlowNode> reachableSet = fg.getReachableSetFrom(inNode.getDescTuple());
6054     // System.out.println("inNode=" + inNode + "  reachalbeSet=" + reachableSet);
6055
6056     for (Iterator iterator = reachableSet.iterator(); iterator.hasNext();) {
6057       FlowNode fn = (FlowNode) iterator.next();
6058       if (nodeSet.contains(fn)) {
6059         return true;
6060       }
6061     }
6062     return false;
6063   }
6064
6065   private NTuple<Descriptor> getNodeTupleByArgIdx(MethodInvokeNode min, int idx) {
6066     return mapMethodInvokeNodeToArgIdxMap.get(min).get(new Integer(idx));
6067   }
6068
6069   private void addArgIdxMap(MethodInvokeNode min, int idx, NTuple<Descriptor> argTuple /*
6070                                                                                         * NodeTupleSet
6071                                                                                         * tupleSet
6072                                                                                         */) {
6073     Map<Integer, NTuple<Descriptor>> mapIdxToTuple = mapMethodInvokeNodeToArgIdxMap.get(min);
6074     if (mapIdxToTuple == null) {
6075       mapIdxToTuple = new HashMap<Integer, NTuple<Descriptor>>();
6076       mapMethodInvokeNodeToArgIdxMap.put(min, mapIdxToTuple);
6077     }
6078     mapIdxToTuple.put(new Integer(idx), argTuple);
6079   }
6080
6081   private void analyzeFlowLiteralNode(MethodDescriptor md, SymbolTable nametable, LiteralNode en,
6082       NodeTupleSet nodeSet) {
6083     NTuple<Descriptor> tuple = new NTuple<Descriptor>();
6084     tuple.add(LITERALDESC);
6085     nodeSet.addTuple(tuple);
6086   }
6087
6088   private void analyzeFlowArrayAccessNode(MethodDescriptor md, SymbolTable nametable,
6089       ArrayAccessNode aan, NodeTupleSet nodeSet, boolean isLHS) {
6090
6091     // System.out.println("analyzeFlowArrayAccessNode aan=" + aan.printNode(0));
6092     String currentArrayAccessNodeExpStr = aan.printNode(0);
6093     arrayAccessNodeStack.push(aan.printNode(0));
6094
6095     NodeTupleSet expNodeTupleSet = new NodeTupleSet();
6096     NTuple<Descriptor> base =
6097         analyzeFlowExpressionNode(md, nametable, aan.getExpression(), expNodeTupleSet, isLHS);
6098     // System.out.println("-base=" + base);
6099
6100     nodeSet.setMethodInvokeBaseDescTuple(base);
6101     NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
6102     analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, isLHS);
6103
6104     arrayAccessNodeStack.pop();
6105
6106     if (isLHS) {
6107       // need to create an edge from idx to array
6108       for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
6109         NTuple<Descriptor> idxTuple = idxIter.next();
6110         for (Iterator<NTuple<Descriptor>> arrIter = expNodeTupleSet.iterator(); arrIter.hasNext();) {
6111           NTuple<Descriptor> arrTuple = arrIter.next();
6112           getFlowGraph(md).addValueFlowEdge(idxTuple, arrTuple);
6113         }
6114       }
6115
6116       GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
6117       for (Iterator<NTuple<Location>> iterator = idxNodeTupleSet.globalIterator(); iterator
6118           .hasNext();) {
6119         NTuple<Location> calleeReturnLocTuple = iterator.next();
6120         for (Iterator<NTuple<Descriptor>> arrIter = expNodeTupleSet.iterator(); arrIter.hasNext();) {
6121           NTuple<Descriptor> arrTuple = arrIter.next();
6122
6123           globalFlowGraph.addValueFlowEdge(calleeReturnLocTuple, translateToLocTuple(md, arrTuple));
6124         }
6125       }
6126
6127       nodeSet.addTupleSet(expNodeTupleSet);
6128     } else {
6129
6130       NodeTupleSet nodeSetArrayAccessExp = new NodeTupleSet();
6131
6132       nodeSetArrayAccessExp.addTupleSet(expNodeTupleSet);
6133       nodeSetArrayAccessExp.addTupleSet(idxNodeTupleSet);
6134
6135       if (arrayAccessNodeStack.isEmpty()
6136           || !arrayAccessNodeStack.peek().startsWith(currentArrayAccessNodeExpStr)) {
6137
6138         if (needToGenerateInterLoc(nodeSetArrayAccessExp)) {
6139           FlowNode interNode = getFlowGraph(md).createIntermediateNode();
6140           NTuple<Descriptor> interTuple = interNode.getDescTuple();
6141
6142           for (Iterator<NTuple<Descriptor>> iter = nodeSetArrayAccessExp.iterator(); iter.hasNext();) {
6143             NTuple<Descriptor> higherTuple = iter.next();
6144             addFlowGraphEdge(md, higherTuple, interTuple);
6145           }
6146           nodeSetArrayAccessExp.clear();
6147           nodeSetArrayAccessExp.addTuple(interTuple);
6148           FlowGraph fg = getFlowGraph(md);
6149
6150           // System.out.println("base=" + base);
6151           if (base != null) {
6152             fg.addMapInterLocNodeToEnclosingDescriptor(interTuple.get(0),
6153                 getClassTypeDescriptor(base.get(base.size() - 1)));
6154             interNode.setBaseTuple(base);
6155           }
6156         }
6157       }
6158
6159       nodeSet.addGlobalFlowTupleSet(idxNodeTupleSet.getGlobalLocTupleSet());
6160       nodeSet.addTupleSet(nodeSetArrayAccessExp);
6161
6162     }
6163
6164   }
6165
6166   private void analyzeCreateObjectNode(MethodDescriptor md, SymbolTable nametable,
6167       CreateObjectNode en, NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
6168     // System.out.println("#analyzeCreateObjectNode=" + en.printNode(0));
6169     int numArgs = en.numArgs();
6170     NodeTupleSet argSet = new NodeTupleSet();
6171
6172     for (int i = 0; i < numArgs; i++) {
6173       analyzeFlowExpressionNode(md, nametable, en.getArg(i), argSet, null, implicitFlowTupleSet,
6174           false);
6175     }
6176
6177     // System.out.println("###argSet=" + argSet);
6178     nodeSet.addTupleSet(argSet);
6179
6180   }
6181
6182   private void analyzeFlowOpNode(MethodDescriptor md, SymbolTable nametable, OpNode on,
6183       NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
6184
6185     NodeTupleSet leftOpSet = new NodeTupleSet();
6186     NodeTupleSet rightOpSet = new NodeTupleSet();
6187
6188     // System.out.println("analyzeFlowOpNode=" + on.printNode(0));
6189
6190     // left operand
6191     analyzeFlowExpressionNode(md, nametable, on.getLeft(), leftOpSet, null, implicitFlowTupleSet,
6192         false);
6193
6194     if (on.getRight() != null) {
6195       // right operand
6196       analyzeFlowExpressionNode(md, nametable, on.getRight(), rightOpSet, null,
6197           implicitFlowTupleSet, false);
6198     }
6199
6200     Operation op = on.getOp();
6201
6202     switch (op.getOp()) {
6203
6204     case Operation.UNARYPLUS:
6205     case Operation.UNARYMINUS:
6206     case Operation.LOGIC_NOT:
6207       // single operand
6208       nodeSet.addTupleSet(leftOpSet);
6209       break;
6210
6211     case Operation.LOGIC_OR:
6212     case Operation.LOGIC_AND:
6213     case Operation.COMP:
6214     case Operation.BIT_OR:
6215     case Operation.BIT_XOR:
6216     case Operation.BIT_AND:
6217     case Operation.ISAVAILABLE:
6218     case Operation.EQUAL:
6219     case Operation.NOTEQUAL:
6220     case Operation.LT:
6221     case Operation.GT:
6222     case Operation.LTE:
6223     case Operation.GTE:
6224     case Operation.ADD:
6225     case Operation.SUB:
6226     case Operation.MULT:
6227     case Operation.DIV:
6228     case Operation.MOD:
6229     case Operation.LEFTSHIFT:
6230     case Operation.RIGHTSHIFT:
6231     case Operation.URIGHTSHIFT:
6232
6233       // there are two operands
6234       nodeSet.addTupleSet(leftOpSet);
6235       nodeSet.addTupleSet(rightOpSet);
6236
6237       nodeSet.addGlobalFlowTupleSet(leftOpSet.getGlobalLocTupleSet());
6238       nodeSet.addGlobalFlowTupleSet(rightOpSet.getGlobalLocTupleSet());
6239
6240       break;
6241
6242     default:
6243       throw new Error(op.toString());
6244     }
6245
6246   }
6247
6248   private NTuple<Descriptor> analyzeFlowNameNode(MethodDescriptor md, SymbolTable nametable,
6249       NameNode nn, NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
6250
6251     if (base == null) {
6252       base = new NTuple<Descriptor>();
6253     }
6254
6255     NameDescriptor nd = nn.getName();
6256
6257     if (nd.getBase() != null) {
6258       base =
6259           analyzeFlowExpressionNode(md, nametable, nn.getExpression(), nodeSet, base,
6260               implicitFlowTupleSet, false);
6261       if (base == null) {
6262         // base node has the top location
6263         return base;
6264       }
6265     } else {
6266       String varname = nd.toString();
6267       if (varname.equals("this")) {
6268         // 'this' itself!
6269         base.add(md.getThis());
6270         return base;
6271       }
6272
6273       Descriptor d = (Descriptor) nametable.get(varname);
6274
6275       if (d instanceof VarDescriptor) {
6276         VarDescriptor vd = (VarDescriptor) d;
6277         base.add(vd);
6278       } else if (d instanceof FieldDescriptor) {
6279         // the type of field descriptor has a location!
6280         FieldDescriptor fd = (FieldDescriptor) d;
6281         if (fd.isStatic()) {
6282           if (fd.isFinal()) {
6283             // if it is 'static final', no need to have flow node for the TOP
6284             // location
6285             return null;
6286           } else {
6287             // if 'static', assign the default GLOBAL LOCATION to the first
6288             // element of the tuple
6289             base.add(GLOBALDESC);
6290           }
6291         } else {
6292           // the location of field access starts from this, followed by field
6293           // location
6294           base.add(md.getThis());
6295         }
6296
6297         base.add(fd);
6298       } else if (d == null) {
6299         // access static field
6300         base.add(GLOBALDESC);
6301         base.add(nn.getField());
6302         return base;
6303
6304         // FieldDescriptor fd = nn.getField();addFlowGraphEdge
6305         //
6306         // MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
6307         // String globalLocId = localLattice.getGlobalLoc();
6308         // if (globalLocId == null) {
6309         // throw new
6310         // Error("Method lattice does not define global variable location at "
6311         // + generateErrorMessage(md.getClassDesc(), nn));
6312         // }
6313         // loc.addLocation(new Location(md, globalLocId));
6314         //
6315         // Location fieldLoc = (Location) fd.getType().getExtension();
6316         // loc.addLocation(fieldLoc);
6317         //
6318         // return loc;
6319
6320       }
6321     }
6322     getFlowGraph(md).createNewFlowNode(base);
6323
6324     return base;
6325
6326   }
6327
6328   private NTuple<Descriptor> analyzeFlowFieldAccessNode(MethodDescriptor md, SymbolTable nametable,
6329       FieldAccessNode fan, NodeTupleSet nodeSet, NTuple<Descriptor> base,
6330       NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
6331     // System.out.println("analyzeFlowFieldAccessNode=" + fan.printNode(0));
6332
6333     String currentArrayAccessNodeExpStr = null;
6334     ExpressionNode left = fan.getExpression();
6335     TypeDescriptor ltd = left.getType();
6336     FieldDescriptor fd = fan.getField();
6337     ArrayAccessNode aan = null;
6338
6339     String varName = null;
6340     if (left.kind() == Kind.NameNode) {
6341       NameDescriptor nd = ((NameNode) left).getName();
6342       varName = nd.toString();
6343     }
6344
6345     if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
6346       // using a class name directly or access using this
6347       if (fd.isStatic() && fd.isFinal()) {
6348         return null;
6349       }
6350     }
6351
6352     NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
6353
6354     boolean isArrayCase = false;
6355     if (left instanceof ArrayAccessNode) {
6356
6357       isArrayCase = true;
6358       aan = (ArrayAccessNode) left;
6359
6360       currentArrayAccessNodeExpStr = aan.printNode(0);
6361       arrayAccessNodeStack.push(currentArrayAccessNodeExpStr);
6362
6363       left = aan.getExpression();
6364       analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, base,
6365           implicitFlowTupleSet, isLHS);
6366
6367     }
6368     base =
6369         analyzeFlowExpressionNode(md, nametable, left, nodeSet, base, implicitFlowTupleSet, isLHS);
6370
6371     if (base == null) {
6372       // in this case, field is TOP location
6373       return null;
6374     } else {
6375
6376       NTuple<Descriptor> flowFieldTuple = new NTuple<Descriptor>(base.toList());
6377
6378       if (!left.getType().isPrimitive()) {
6379         if (!fd.getSymbol().equals("length")) {
6380           // array.length access, just have the location of the array
6381           flowFieldTuple.add(fd);
6382           nodeSet.removeTuple(base);
6383         }
6384       }
6385       getFlowGraph(md).createNewFlowNode(flowFieldTuple);
6386
6387       if (isLHS) {
6388         for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
6389           NTuple<Descriptor> idxTuple = idxIter.next();
6390           getFlowGraph(md).addValueFlowEdge(idxTuple, flowFieldTuple);
6391         }
6392
6393         GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
6394         for (Iterator<NTuple<Location>> iterator = idxNodeTupleSet.globalIterator(); iterator
6395             .hasNext();) {
6396           NTuple<Location> calleeReturnLocTuple = iterator.next();
6397
6398           globalFlowGraph.addValueFlowEdge(calleeReturnLocTuple,
6399               translateToLocTuple(md, flowFieldTuple));
6400         }
6401
6402       } else {
6403         nodeSet.addTupleSet(idxNodeTupleSet);
6404
6405         // if it is the array case and not the LHS case
6406         if (isArrayCase) {
6407           arrayAccessNodeStack.pop();
6408
6409           if (arrayAccessNodeStack.isEmpty()
6410               || !arrayAccessNodeStack.peek().startsWith(currentArrayAccessNodeExpStr)) {
6411             NodeTupleSet nodeSetArrayAccessExp = new NodeTupleSet();
6412
6413             nodeSetArrayAccessExp.addTuple(flowFieldTuple);
6414             nodeSetArrayAccessExp.addTupleSet(idxNodeTupleSet);
6415             nodeSetArrayAccessExp.addTupleSet(nodeSet);
6416
6417             if (needToGenerateInterLoc(nodeSetArrayAccessExp)) {
6418               // System.out.println("nodeSetArrayAccessExp=" + nodeSetArrayAccessExp);
6419               // System.out.println("idxNodeTupleSet.getGlobalLocTupleSet()="
6420               // + idxNodeTupleSet.getGlobalLocTupleSet());
6421
6422               NTuple<Descriptor> interTuple =
6423                   getFlowGraph(md).createIntermediateNode().getDescTuple();
6424
6425               for (Iterator<NTuple<Descriptor>> iter = nodeSetArrayAccessExp.iterator(); iter
6426                   .hasNext();) {
6427                 NTuple<Descriptor> higherTuple = iter.next();
6428                 addFlowGraphEdge(md, higherTuple, interTuple);
6429               }
6430
6431               FlowGraph fg = getFlowGraph(md);
6432               fg.addMapInterLocNodeToEnclosingDescriptor(interTuple.get(0),
6433                   getClassTypeDescriptor(base.get(base.size() - 1)));
6434
6435               nodeSet.clear();
6436               flowFieldTuple = interTuple;
6437             }
6438             nodeSet.addGlobalFlowTupleSet(idxNodeTupleSet.getGlobalLocTupleSet());
6439           }
6440
6441         }
6442
6443       }
6444       return flowFieldTuple;
6445     }
6446
6447   }
6448
6449   private void debug_printTreeNode(TreeNode tn) {
6450
6451     System.out.println("DEBUG: " + tn.printNode(0) + "                line#=" + tn.getNumLine());
6452
6453   }
6454
6455   private void analyzeFlowAssignmentNode(MethodDescriptor md, SymbolTable nametable,
6456       AssignmentNode an, NodeTupleSet nodeSet, NTuple<Descriptor> base,
6457       NodeTupleSet implicitFlowTupleSet) {
6458
6459     NodeTupleSet nodeSetRHS = new NodeTupleSet();
6460     NodeTupleSet nodeSetLHS = new NodeTupleSet();
6461
6462     boolean postinc = true;
6463     if (an.getOperation().getBaseOp() == null
6464         || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
6465             .getBaseOp().getOp() != Operation.POSTDEC)) {
6466       postinc = false;
6467     }
6468     // if LHS is array access node, need to capture value flows between an array
6469     // and its index value
6470     analyzeFlowExpressionNode(md, nametable, an.getDest(), nodeSetLHS, null, implicitFlowTupleSet,
6471         true);
6472
6473     if (!postinc) {
6474       // analyze value flows of rhs expression
6475       analyzeFlowExpressionNode(md, nametable, an.getSrc(), nodeSetRHS, null, implicitFlowTupleSet,
6476           false);
6477
6478       // System.out.println("-analyzeFlowAssignmentNode=" + an.printNode(0));
6479       // System.out.println("-nodeSetLHS=" + nodeSetLHS);
6480       // System.out.println("-nodeSetRHS=" + nodeSetRHS);
6481       // System.out.println("-implicitFlowTupleSet=" + implicitFlowTupleSet);
6482       // System.out.println("-");
6483
6484       if (an.getOperation().getOp() >= 2 && an.getOperation().getOp() <= 12) {
6485         // if assignment contains OP+EQ operator, creates edges from LHS to LHS
6486
6487         for (Iterator<NTuple<Descriptor>> iter = nodeSetLHS.iterator(); iter.hasNext();) {
6488           NTuple<Descriptor> fromTuple = iter.next();
6489           for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6490             NTuple<Descriptor> toTuple = iter2.next();
6491             addFlowGraphEdge(md, fromTuple, toTuple);
6492           }
6493         }
6494       }
6495
6496       // creates edges from RHS to LHS
6497       NTuple<Descriptor> interTuple = null;
6498       if (needToGenerateInterLoc(nodeSetRHS)) {
6499         interTuple = getFlowGraph(md).createIntermediateNode().getDescTuple();
6500       }
6501
6502       for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
6503         NTuple<Descriptor> fromTuple = iter.next();
6504         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6505           NTuple<Descriptor> toTuple = iter2.next();
6506           addFlowGraphEdge(md, fromTuple, interTuple, toTuple);
6507         }
6508       }
6509
6510       // creates edges from implicitFlowTupleSet to LHS
6511       for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
6512         NTuple<Descriptor> fromTuple = iter.next();
6513         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6514           NTuple<Descriptor> toTuple = iter2.next();
6515           addFlowGraphEdge(md, fromTuple, toTuple);
6516         }
6517       }
6518
6519       // create global flow edges if the callee gives return value flows to the caller
6520       GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
6521       for (Iterator<NTuple<Location>> iterator = nodeSetRHS.globalIterator(); iterator.hasNext();) {
6522         NTuple<Location> calleeReturnLocTuple = iterator.next();
6523         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6524           NTuple<Descriptor> callerLHSTuple = iter2.next();
6525           // System.out.println("$$$ GLOBAL FLOW ADD=" + calleeReturnLocTuple + " -> "
6526           // + translateToLocTuple(md, callerLHSTuple));
6527
6528           globalFlowGraph.addValueFlowEdge(calleeReturnLocTuple,
6529               translateToLocTuple(md, callerLHSTuple));
6530         }
6531       }
6532
6533       for (Iterator<NTuple<Location>> iterator = implicitFlowTupleSet.globalIterator(); iterator
6534           .hasNext();) {
6535         NTuple<Location> calleeReturnLocTuple = iterator.next();
6536         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6537           NTuple<Descriptor> callerLHSTuple = iter2.next();
6538
6539           globalFlowGraph.addValueFlowEdge(calleeReturnLocTuple,
6540               translateToLocTuple(md, callerLHSTuple));
6541           // System.out.println("$$$ GLOBAL FLOW PCLOC ADD=" + calleeReturnLocTuple + " -> "
6542           // + translateToLocTuple(md, callerLHSTuple));
6543         }
6544       }
6545
6546     } else {
6547       // postinc case
6548
6549       for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6550         NTuple<Descriptor> tuple = iter2.next();
6551         addFlowGraphEdge(md, tuple, tuple);
6552       }
6553
6554       // creates edges from implicitFlowTupleSet to LHS
6555       for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
6556         NTuple<Descriptor> fromTuple = iter.next();
6557         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6558           NTuple<Descriptor> toTuple = iter2.next();
6559           addFlowGraphEdge(md, fromTuple, toTuple);
6560         }
6561       }
6562
6563       GlobalFlowGraph globalFlowGraph = getSubGlobalFlowGraph(md);
6564       for (Iterator<NTuple<Location>> iterator = implicitFlowTupleSet.globalIterator(); iterator
6565           .hasNext();) {
6566         NTuple<Location> calleeReturnLocTuple = iterator.next();
6567         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
6568           NTuple<Descriptor> callerLHSTuple = iter2.next();
6569           globalFlowGraph.addValueFlowEdge(calleeReturnLocTuple,
6570               translateToLocTuple(md, callerLHSTuple));
6571           // System.out.println("$$$ GLOBAL FLOW PC ADD=" + calleeReturnLocTuple + " -> "
6572           // + translateToLocTuple(md, callerLHSTuple));
6573         }
6574       }
6575
6576     }
6577
6578     if (nodeSet != null) {
6579       nodeSet.addTupleSet(nodeSetLHS);
6580       nodeSet.addGlobalFlowTupleSet(nodeSetLHS.getGlobalLocTupleSet());
6581     }
6582   }
6583
6584   public FlowGraph getFlowGraph(MethodDescriptor md) {
6585     return mapMethodDescriptorToFlowGraph.get(md);
6586   }
6587
6588   private boolean addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
6589       NTuple<Descriptor> to) {
6590     FlowGraph graph = getFlowGraph(md);
6591     graph.addValueFlowEdge(from, to);
6592     return true;
6593   }
6594
6595   private void addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
6596       NTuple<Descriptor> inter, NTuple<Descriptor> to) {
6597
6598     FlowGraph graph = getFlowGraph(md);
6599
6600     if (inter != null) {
6601       graph.addValueFlowEdge(from, inter);
6602       graph.addValueFlowEdge(inter, to);
6603     } else {
6604       graph.addValueFlowEdge(from, to);
6605     }
6606
6607   }
6608
6609   public void writeInferredLatticeDotFile(ClassDescriptor cd, SSJavaLattice<String> locOrder,
6610       String nameSuffix) {
6611     // System.out.println("@cd=" + cd);
6612     // System.out.println("@sharedLoc=" + locOrder.getSharedLocSet());
6613     writeInferredLatticeDotFile(cd, null, locOrder, nameSuffix);
6614   }
6615
6616   public void writeInferredLatticeDotFile(ClassDescriptor cd, MethodDescriptor md,
6617       SSJavaLattice<String> locOrder, String nameSuffix) {
6618
6619     String fileName = "lattice_";
6620     if (md != null) {
6621       fileName +=
6622           cd.getSymbol().replaceAll("[\\W_]", "") + "_" + md.toString().replaceAll("[\\W_]", "");
6623     } else {
6624       fileName += cd.getSymbol().replaceAll("[\\W_]", "");
6625     }
6626
6627     fileName += nameSuffix;
6628
6629     System.out.println("***lattice=" + fileName + "    setsize=" + locOrder.getKeySet().size());
6630
6631     Set<Pair<String, String>> pairSet = locOrder.getOrderingPairSet();
6632
6633     Set<String> addedLocSet = new HashSet<String>();
6634
6635     if (pairSet.size() > 0) {
6636       try {
6637         BufferedWriter bw = new BufferedWriter(new FileWriter(fileName + ".dot"));
6638
6639         bw.write("digraph " + fileName + " {\n");
6640
6641         for (Iterator iterator = pairSet.iterator(); iterator.hasNext();) {
6642           // pair is in the form of <higher, lower>
6643           Pair<String, String> pair = (Pair<String, String>) iterator.next();
6644
6645           String highLocId = pair.getFirst();
6646           String lowLocId = pair.getSecond();
6647           if (!addedLocSet.contains(highLocId)) {
6648             addedLocSet.add(highLocId);
6649             drawNode(bw, locOrder, highLocId);
6650           }
6651
6652           if (!addedLocSet.contains(lowLocId)) {
6653             addedLocSet.add(lowLocId);
6654             drawNode(bw, locOrder, lowLocId);
6655           }
6656
6657           bw.write(highLocId + " -> " + lowLocId + ";\n");
6658         }
6659         bw.write("}\n");
6660         bw.close();
6661
6662       } catch (IOException e) {
6663         e.printStackTrace();
6664       }
6665
6666     }
6667
6668   }
6669
6670   private String convertMergeSetToString(HierarchyGraph graph, Set<HNode> mergeSet) {
6671     String str = "";
6672     for (Iterator iterator = mergeSet.iterator(); iterator.hasNext();) {
6673       HNode merged = (HNode) iterator.next();
6674       if (merged.isMergeNode()) {
6675         str += convertMergeSetToString(graph, graph.getMapHNodetoMergeSet().get(merged));
6676       } else {
6677         str += " " + merged.getName();
6678       }
6679     }
6680     return str;
6681   }
6682
6683   public void addNaiveLattice(Descriptor desc, SSJavaLattice<String> lattice) {
6684     desc2naiveLattice.put(desc, lattice);
6685   }
6686
6687   private void drawNode(BufferedWriter bw, SSJavaLattice<String> lattice, String locName)
6688       throws IOException {
6689
6690     String prettyStr;
6691     if (lattice.isSharedLoc(locName)) {
6692       prettyStr = locName + "*";
6693     } else {
6694       prettyStr = locName;
6695     }
6696     // HNode node = graph.getHNode(locName);
6697     // if (node != null && node.isMergeNode()) {
6698     // Set<HNode> mergeSet = graph.getMapHNodetoMergeSet().get(node);
6699     // prettyStr += ":" + convertMergeSetToString(graph, mergeSet);
6700     // }
6701     bw.write(locName + " [label=\"" + prettyStr + "\"]" + ";\n");
6702   }
6703
6704   public void _debug_writeFlowGraph() {
6705     Set<MethodDescriptor> keySet = mapMethodDescriptorToFlowGraph.keySet();
6706
6707     for (Iterator<MethodDescriptor> iterator = keySet.iterator(); iterator.hasNext();) {
6708       MethodDescriptor md = (MethodDescriptor) iterator.next();
6709       FlowGraph fg = mapMethodDescriptorToFlowGraph.get(md);
6710       GlobalFlowGraph subGlobalFlowGraph = getSubGlobalFlowGraph(md);
6711       try {
6712         fg.writeGraph();
6713         subGlobalFlowGraph.writeGraph("_SUBGLOBAL");
6714       } catch (IOException e) {
6715         e.printStackTrace();
6716       }
6717     }
6718
6719   }
6720
6721 }
6722
6723 class CyclicFlowException extends Exception {
6724
6725 }
6726
6727 class InterDescriptor extends Descriptor {
6728
6729   Pair<MethodInvokeNode, Integer> minArgIdxPair;
6730
6731   public InterDescriptor(String name) {
6732     super(name);
6733   }
6734
6735   public void setMethodArgIdxPair(MethodInvokeNode min, int idx) {
6736     minArgIdxPair = new Pair<MethodInvokeNode, Integer>(min, new Integer(idx));
6737   }
6738
6739   public Pair<MethodInvokeNode, Integer> getMethodArgIdxPair() {
6740     return minArgIdxPair;
6741   }
6742
6743 }