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