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