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