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