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