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