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