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