changes: now Inference engine works fine with the EyeTracking benchmark.
[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       &n