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