changes.
[IRC.git] / Robust / src / Analysis / SSJava / LocationInference.java
1 package Analysis.SSJava;
2
3 import java.io.IOException;
4 import java.util.ArrayList;
5 import java.util.Collection;
6 import java.util.Collections;
7 import java.util.Comparator;
8 import java.util.HashMap;
9 import java.util.HashSet;
10 import java.util.Iterator;
11 import java.util.LinkedList;
12 import java.util.List;
13 import java.util.Map;
14 import java.util.Set;
15 import java.util.Stack;
16
17 import IR.ClassDescriptor;
18 import IR.Descriptor;
19 import IR.FieldDescriptor;
20 import IR.MethodDescriptor;
21 import IR.NameDescriptor;
22 import IR.Operation;
23 import IR.State;
24 import IR.SymbolTable;
25 import IR.TypeDescriptor;
26 import IR.VarDescriptor;
27 import IR.Tree.ArrayAccessNode;
28 import IR.Tree.AssignmentNode;
29 import IR.Tree.BlockExpressionNode;
30 import IR.Tree.BlockNode;
31 import IR.Tree.BlockStatementNode;
32 import IR.Tree.CastNode;
33 import IR.Tree.CreateObjectNode;
34 import IR.Tree.DeclarationNode;
35 import IR.Tree.ExpressionNode;
36 import IR.Tree.FieldAccessNode;
37 import IR.Tree.IfStatementNode;
38 import IR.Tree.Kind;
39 import IR.Tree.LiteralNode;
40 import IR.Tree.LoopNode;
41 import IR.Tree.MethodInvokeNode;
42 import IR.Tree.NameNode;
43 import IR.Tree.OpNode;
44 import IR.Tree.ReturnNode;
45 import IR.Tree.SubBlockNode;
46 import IR.Tree.SwitchStatementNode;
47 import IR.Tree.TertiaryNode;
48 import IR.Tree.TreeNode;
49 import Util.Pair;
50
51 public class LocationInference {
52
53   State state;
54   SSJavaAnalysis ssjava;
55
56   List<ClassDescriptor> toanalyzeList;
57   List<MethodDescriptor> toanalyzeMethodList;
58   Map<MethodDescriptor, FlowGraph> mapMethodDescriptorToFlowGraph;
59
60   // map a method descriptor to its set of parameter descriptors
61   Map<MethodDescriptor, Set<Descriptor>> mapMethodDescriptorToParamDescSet;
62
63   // keep current descriptors to visit in fixed-point interprocedural analysis,
64   private Stack<MethodDescriptor> methodDescriptorsToVisitStack;
65
66   // map a class descriptor to a field lattice
67   private Map<ClassDescriptor, SSJavaLattice<String>> cd2lattice;
68
69   // map a method descriptor to a method lattice
70   private Map<MethodDescriptor, SSJavaLattice<String>> md2lattice;
71
72   // map a method descriptor to the set of method invocation nodes which are
73   // invoked by the method descriptor
74   private Map<MethodDescriptor, Set<MethodInvokeNode>> mapMethodDescriptorToMethodInvokeNodeSet;
75
76   private Map<MethodInvokeNode, Map<Integer, NodeTupleSet>> mapMethodInvokeNodeToArgIdxMap;
77
78   private Map<MethodDescriptor, MethodLocationInfo> mapMethodDescToMethodLocationInfo;
79
80   private Map<ClassDescriptor, LocationInfo> mapClassToLocationInfo;
81
82   private Map<MethodDescriptor, Set<MethodDescriptor>> mapMethodToCalleeSet;
83
84   public static final String GLOBALLOC = "GLOBALLOC";
85
86   public static final String TOPLOC = "TOPLOC";
87
88   public static final Descriptor GLOBALDESC = new NameDescriptor(GLOBALLOC);
89
90   public static final Descriptor TOPDESC = new NameDescriptor(TOPLOC);
91
92   LocationInfo curMethodInfo;
93
94   boolean debug = true;
95
96   public LocationInference(SSJavaAnalysis ssjava, State state) {
97     this.ssjava = ssjava;
98     this.state = state;
99     this.toanalyzeList = new ArrayList<ClassDescriptor>();
100     this.toanalyzeMethodList = new ArrayList<MethodDescriptor>();
101     this.mapMethodDescriptorToFlowGraph = new HashMap<MethodDescriptor, FlowGraph>();
102     this.cd2lattice = new HashMap<ClassDescriptor, SSJavaLattice<String>>();
103     this.md2lattice = new HashMap<MethodDescriptor, SSJavaLattice<String>>();
104     this.methodDescriptorsToVisitStack = new Stack<MethodDescriptor>();
105     this.mapMethodDescriptorToMethodInvokeNodeSet =
106         new HashMap<MethodDescriptor, Set<MethodInvokeNode>>();
107     this.mapMethodInvokeNodeToArgIdxMap =
108         new HashMap<MethodInvokeNode, Map<Integer, NodeTupleSet>>();
109     this.mapMethodDescToMethodLocationInfo = new HashMap<MethodDescriptor, MethodLocationInfo>();
110     this.mapMethodToCalleeSet = new HashMap<MethodDescriptor, Set<MethodDescriptor>>();
111     this.mapClassToLocationInfo = new HashMap<ClassDescriptor, LocationInfo>();
112   }
113
114   public void setupToAnalyze() {
115     SymbolTable classtable = state.getClassSymbolTable();
116     toanalyzeList.clear();
117     toanalyzeList.addAll(classtable.getValueSet());
118     Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
119       public int compare(ClassDescriptor o1, ClassDescriptor o2) {
120         return o1.getClassName().compareToIgnoreCase(o2.getClassName());
121       }
122     });
123   }
124
125   public void setupToAnalazeMethod(ClassDescriptor cd) {
126
127     SymbolTable methodtable = cd.getMethodTable();
128     toanalyzeMethodList.clear();
129     toanalyzeMethodList.addAll(methodtable.getValueSet());
130     Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
131       public int compare(MethodDescriptor o1, MethodDescriptor o2) {
132         return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
133       }
134     });
135   }
136
137   public boolean toAnalyzeMethodIsEmpty() {
138     return toanalyzeMethodList.isEmpty();
139   }
140
141   public boolean toAnalyzeIsEmpty() {
142     return toanalyzeList.isEmpty();
143   }
144
145   public ClassDescriptor toAnalyzeNext() {
146     return toanalyzeList.remove(0);
147   }
148
149   public MethodDescriptor toAnalyzeMethodNext() {
150     return toanalyzeMethodList.remove(0);
151   }
152
153   public void inference() {
154
155     // 1) construct value flow graph
156     constructFlowGraph();
157
158     // 2) construct lattices
159     inferLattices();
160
161     simplifyLattices();
162
163     debug_writeLatticeDotFile();
164
165     // 3) check properties
166     checkLattices();
167
168   }
169
170   private void simplifyLattices() {
171
172     // generate lattice dot file
173     setupToAnalyze();
174
175     while (!toAnalyzeIsEmpty()) {
176       ClassDescriptor cd = toAnalyzeNext();
177
178       setupToAnalazeMethod(cd);
179
180       SSJavaLattice<String> classLattice = cd2lattice.get(cd);
181       if (classLattice != null) {
182         classLattice.removeRedundantEdges();
183       }
184
185       while (!toAnalyzeMethodIsEmpty()) {
186         MethodDescriptor md = toAnalyzeMethodNext();
187         if (ssjava.needTobeAnnotated(md)) {
188           SSJavaLattice<String> methodLattice = md2lattice.get(md);
189           if (methodLattice != null) {
190             methodLattice.removeRedundantEdges();
191           }
192         }
193       }
194     }
195
196   }
197
198   private void checkLattices() {
199
200     LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
201
202     // current descriptors to visit in fixed-point interprocedural analysis,
203     // prioritized by
204     // dependency in the call graph
205     methodDescriptorsToVisitStack.clear();
206
207     descriptorListToAnalyze.removeFirst();
208
209     Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
210     methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
211
212     while (!descriptorListToAnalyze.isEmpty()) {
213       MethodDescriptor md = descriptorListToAnalyze.removeFirst();
214       checkLatticesOfVirtualMethods(md);
215     }
216
217   }
218
219   private void debug_writeLatticeDotFile() {
220     // generate lattice dot file
221
222     setupToAnalyze();
223
224     while (!toAnalyzeIsEmpty()) {
225       ClassDescriptor cd = toAnalyzeNext();
226
227       setupToAnalazeMethod(cd);
228
229       SSJavaLattice<String> classLattice = cd2lattice.get(cd);
230       if (classLattice != null) {
231         ssjava.writeLatticeDotFile(cd, null, classLattice);
232         debug_printDescriptorToLocNameMapping(cd);
233       }
234
235       while (!toAnalyzeMethodIsEmpty()) {
236         MethodDescriptor md = toAnalyzeMethodNext();
237         if (ssjava.needTobeAnnotated(md)) {
238           SSJavaLattice<String> methodLattice = md2lattice.get(md);
239           if (methodLattice != null) {
240             ssjava.writeLatticeDotFile(cd, md, methodLattice);
241             debug_printDescriptorToLocNameMapping(md);
242           }
243         }
244       }
245     }
246
247   }
248
249   private void debug_printDescriptorToLocNameMapping(Descriptor desc) {
250
251     LocationInfo info = getLocationInfo(desc);
252     System.out.println("## " + desc + " ##");
253     System.out.println(info.getMapDescToInferLocation());
254     LocationInfo locInfo = getLocationInfo(desc);
255     System.out.println("mapping=" + locInfo.getMapLocSymbolToDescSet());
256     System.out.println("###################");
257
258   }
259
260   private void inferLattices() {
261
262     // do fixed-point analysis
263
264     LinkedList<MethodDescriptor> descriptorListToAnalyze = ssjava.getSortedDescriptors();
265
266     Collections.sort(descriptorListToAnalyze, new Comparator<MethodDescriptor>() {
267       public int compare(MethodDescriptor o1, MethodDescriptor o2) {
268         return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
269       }
270     });
271
272     // current descriptors to visit in fixed-point interprocedural analysis,
273     // prioritized by
274     // dependency in the call graph
275     methodDescriptorsToVisitStack.clear();
276
277     // descriptorListToAnalyze.removeFirst();
278
279     Set<MethodDescriptor> methodDescriptorToVistSet = new HashSet<MethodDescriptor>();
280     methodDescriptorToVistSet.addAll(descriptorListToAnalyze);
281
282     while (!descriptorListToAnalyze.isEmpty()) {
283       MethodDescriptor md = descriptorListToAnalyze.removeFirst();
284       methodDescriptorsToVisitStack.add(md);
285     }
286
287     // analyze scheduled methods until there are no more to visit
288     while (!methodDescriptorsToVisitStack.isEmpty()) {
289       // start to analyze leaf node
290       MethodDescriptor md = methodDescriptorsToVisitStack.pop();
291
292       SSJavaLattice<String> methodLattice =
293           new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM);
294
295       MethodLocationInfo methodInfo = new MethodLocationInfo(md);
296       curMethodInfo = methodInfo;
297
298       System.out.println();
299       System.out.println("SSJAVA: Inferencing the lattice from " + md);
300
301       try {
302         analyzeMethodLattice(md, methodLattice, methodInfo);
303       } catch (CyclicFlowException e) {
304         throw new Error("Fail to generate the method lattice for " + md);
305       }
306
307       SSJavaLattice<String> prevMethodLattice = getMethodLattice(md);
308       MethodLocationInfo prevMethodInfo = getMethodLocationInfo(md);
309
310       if ((!methodLattice.equals(prevMethodLattice)) || (!methodInfo.equals(prevMethodInfo))) {
311
312         setMethodLattice(md, methodLattice);
313         setMethodLocInfo(md, methodInfo);
314
315         // results for callee changed, so enqueue dependents caller for
316         // further analysis
317         Iterator<MethodDescriptor> depsItr = ssjava.getDependents(md).iterator();
318         while (depsItr.hasNext()) {
319           MethodDescriptor methodNext = depsItr.next();
320           if (!methodDescriptorsToVisitStack.contains(methodNext)
321               && methodDescriptorToVistSet.contains(methodNext)) {
322             methodDescriptorsToVisitStack.add(methodNext);
323           }
324         }
325
326       }
327
328     }
329   }
330
331   private void setMethodLocInfo(MethodDescriptor md, MethodLocationInfo methodInfo) {
332     mapMethodDescToMethodLocationInfo.put(md, methodInfo);
333   }
334
335   private void checkLatticesOfVirtualMethods(MethodDescriptor md) {
336
337     if (!md.isStatic()) {
338       Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
339       setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
340
341       for (Iterator iterator = setPossibleCallees.iterator(); iterator.hasNext();) {
342         MethodDescriptor mdCallee = (MethodDescriptor) iterator.next();
343         if (!md.equals(mdCallee)) {
344           checkConsistency(md, mdCallee);
345         }
346       }
347
348     }
349
350   }
351
352   private void checkConsistency(MethodDescriptor md1, MethodDescriptor md2) {
353
354     // check that two lattice have the same relations between parameters(+PC
355     // LOC, GLOBAL_LOC RETURN LOC)
356
357     List<CompositeLocation> list1 = new ArrayList<CompositeLocation>();
358     List<CompositeLocation> list2 = new ArrayList<CompositeLocation>();
359
360     MethodLocationInfo locInfo1 = getMethodLocationInfo(md1);
361     MethodLocationInfo locInfo2 = getMethodLocationInfo(md2);
362
363     Map<Integer, CompositeLocation> paramMap1 = locInfo1.getMapParamIdxToInferLoc();
364     Map<Integer, CompositeLocation> paramMap2 = locInfo2.getMapParamIdxToInferLoc();
365
366     int numParam = locInfo1.getMapParamIdxToInferLoc().keySet().size();
367
368     // add location types of paramters
369     for (int idx = 0; idx < numParam; idx++) {
370       list1.add(paramMap1.get(Integer.valueOf(idx)));
371       list2.add(paramMap2.get(Integer.valueOf(idx)));
372     }
373
374     // add program counter location
375     list1.add(locInfo1.getPCLoc());
376     list2.add(locInfo2.getPCLoc());
377
378     if (!md1.getReturnType().isVoid()) {
379       // add return value location
380       CompositeLocation rtrLoc1 =
381           new CompositeLocation(new Location(md1, locInfo1.getReturnLocName()));
382       CompositeLocation rtrLoc2 =
383           new CompositeLocation(new Location(md2, locInfo2.getReturnLocName()));
384       list1.add(rtrLoc1);
385       list2.add(rtrLoc2);
386     }
387
388     // add global location type
389     if (md1.isStatic()) {
390       CompositeLocation globalLoc1 =
391           new CompositeLocation(new Location(md1, locInfo1.getGlobalLocName()));
392       CompositeLocation globalLoc2 =
393           new CompositeLocation(new Location(md2, locInfo2.getGlobalLocName()));
394       list1.add(globalLoc1);
395       list2.add(globalLoc2);
396     }
397
398     for (int i = 0; i < list1.size(); i++) {
399       CompositeLocation locA1 = list1.get(i);
400       CompositeLocation locA2 = list2.get(i);
401       for (int k = 0; k < list1.size(); k++) {
402         if (i != k) {
403           CompositeLocation locB1 = list1.get(k);
404           CompositeLocation locB2 = list2.get(k);
405           boolean r1 = isGreaterThan(getLattice(md1), locA1, locB1);
406
407           boolean r2 = isGreaterThan(getLattice(md1), locA2, locB2);
408
409           if (r1 != r2) {
410             throw new Error("The method " + md1 + " is not consistent with the method " + md2
411                 + ".:: They have a different ordering relation between locations (" + locA1 + ","
412                 + locB1 + ") and (" + locA2 + "," + locB2 + ").");
413           }
414         }
415       }
416     }
417
418   }
419
420   private String getSymbol(int idx, FlowNode node) {
421     Descriptor desc = node.getDescTuple().get(idx);
422     return desc.getSymbol();
423   }
424
425   private Descriptor getDescriptor(int idx, FlowNode node) {
426     Descriptor desc = node.getDescTuple().get(idx);
427     return desc;
428   }
429
430   private void analyzeMethodLattice(MethodDescriptor md, SSJavaLattice<String> methodLattice,
431       MethodLocationInfo methodInfo) throws CyclicFlowException {
432
433     // first take a look at method invocation nodes to newly added relations
434     // from the callee
435     analyzeLatticeMethodInvocationNode(md, methodLattice, methodInfo);
436
437     if (!md.isStatic()) {
438       // set the this location
439       String thisLocSymbol = md.getThis().getSymbol();
440       methodInfo.setThisLocName(thisLocSymbol);
441     }
442
443     // set the global location
444     methodInfo.setGlobalLocName(LocationInference.GLOBALLOC);
445     methodInfo.mapDescriptorToLocation(GLOBALDESC, new CompositeLocation(
446         new Location(md, GLOBALLOC)));
447
448     // visit each node of method flow graph
449     FlowGraph fg = getFlowGraph(md);
450     Set<FlowNode> nodeSet = fg.getNodeSet();
451
452     // for the method lattice, we need to look at the first element of
453     // NTuple<Descriptor>
454     for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
455       FlowNode srcNode = (FlowNode) iterator.next();
456
457       Set<FlowEdge> outEdgeSet = srcNode.getOutEdgeSet();
458       for (Iterator iterator2 = outEdgeSet.iterator(); iterator2.hasNext();) {
459         FlowEdge outEdge = (FlowEdge) iterator2.next();
460         FlowNode dstNode = outEdge.getDst();
461
462         NTuple<Descriptor> srcNodeTuple = srcNode.getDescTuple();
463         NTuple<Descriptor> dstNodeTuple = dstNode.getDescTuple();
464
465         if (outEdge.getInitTuple().equals(srcNodeTuple)
466             && outEdge.getEndTuple().equals(dstNodeTuple)) {
467
468           if ((srcNodeTuple.size() > 1 && dstNodeTuple.size() > 1)
469               && srcNodeTuple.get(0).equals(dstNodeTuple.get(0))) {
470
471             // value flows between fields
472             Descriptor desc = srcNodeTuple.get(0);
473             ClassDescriptor classDesc;
474
475             if (desc.equals(GLOBALDESC)) {
476               classDesc = md.getClassDesc();
477             } else {
478               VarDescriptor varDesc = (VarDescriptor) srcNodeTuple.get(0);
479               classDesc = varDesc.getType().getClassDesc();
480             }
481
482             extractRelationFromFieldFlows(classDesc, srcNode, dstNode, 1);
483
484           } else if (srcNodeTuple.size() == 1 || dstNodeTuple.size() == 1) {
485             // for the method lattice, we need to look at the first element of
486             // NTuple<Descriptor>
487             // in this case, take a look at connected nodes at the local level
488             addRelationToLattice(md, methodLattice, methodInfo, srcNode, dstNode);
489           } else {
490
491             if (!srcNode.getDescTuple().get(0).equals(dstNode.getDescTuple().get(0))) {
492               // in this case, take a look at connected nodes at the local level
493               addRelationToLattice(md, methodLattice, methodInfo, srcNode, dstNode);
494             } else {
495               Descriptor srcDesc = srcNode.getDescTuple().get(0);
496               Descriptor dstDesc = dstNode.getDescTuple().get(0);
497               recursivelyAddCompositeRelation(md, fg, methodInfo, srcNode, dstNode, srcDesc,
498                   dstDesc);
499               // recursiveAddRelationToLattice(1, md, srcNode, dstNode);
500             }
501           }
502
503         }
504       }
505     }
506
507     // create mapping from param idx to inferred composite location
508
509     int offset;
510     if (!md.isStatic()) {
511       // add 'this' reference location
512       offset = 1;
513       methodInfo.addMapParamIdxToInferLoc(0, methodInfo.getInferLocation(md.getThis()));
514     } else {
515       offset = 0;
516     }
517
518     for (int idx = 0; idx < md.numParameters(); idx++) {
519       Descriptor paramDesc = md.getParameter(idx);
520       CompositeLocation inferParamLoc = methodInfo.getInferLocation(paramDesc);
521       methodInfo.addMapParamIdxToInferLoc(idx + offset, inferParamLoc);
522     }
523
524     // calculate the initial program counter location
525     // PC location is higher than location types of all parameters
526     String pcLocSymbol = "PCLOC";
527     Map<Integer, CompositeLocation> mapParamToLoc = methodInfo.getMapParamIdxToInferLoc();
528     Set<Integer> keySet = mapParamToLoc.keySet();
529     for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
530       Integer paramIdx = (Integer) iterator.next();
531       CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
532       String paramLocLocalSymbol = inferLoc.get(0).getLocIdentifier();
533       if (!methodLattice.isGreaterThan(pcLocSymbol, paramLocLocalSymbol)) {
534         addRelationHigherToLower(methodLattice, methodInfo, pcLocSymbol, paramLocLocalSymbol);
535       }
536     }
537
538     // calculate a return location
539     // the return location type is lower than all parameters
540     if (!md.getReturnType().isVoid()) {
541
542       String returnLocSymbol = "RETURNLOC";
543
544       for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
545         Integer paramIdx = (Integer) iterator.next();
546         CompositeLocation inferLoc = mapParamToLoc.get(paramIdx);
547         String paramLocLocalSymbol = inferLoc.get(0).getLocIdentifier();
548         if (!methodLattice.isGreaterThan(paramLocLocalSymbol, returnLocSymbol)) {
549           addRelationHigherToLower(methodLattice, methodInfo, paramLocLocalSymbol, returnLocSymbol);
550         }
551       }
552     }
553
554   }
555
556   private boolean isGreaterThan(SSJavaLattice<String> methodLattice, CompositeLocation comp1,
557       CompositeLocation comp2) {
558
559     int size = comp1.getSize() >= comp2.getSize() ? comp2.getSize() : comp1.getSize();
560
561     for (int idx = 0; idx < size; idx++) {
562       Location loc1 = comp1.get(idx);
563       Location loc2 = comp2.get(idx);
564
565       Descriptor desc1 = loc1.getDescriptor();
566       Descriptor desc2 = loc2.getDescriptor();
567
568       if (!desc1.equals(desc2)) {
569         throw new Error("Fail to compare " + comp1 + " and " + comp2);
570       }
571
572       String symbol1 = loc1.getLocIdentifier();
573       String symbol2 = loc2.getLocIdentifier();
574
575       SSJavaLattice<String> lattice;
576       if (idx == 0) {
577         lattice = methodLattice;
578       } else {
579         lattice = getLattice(desc1);
580       }
581       if (symbol1.equals(symbol2)) {
582         continue;
583       } else if (lattice.isGreaterThan(symbol1, symbol2)) {
584         return true;
585       } else {
586         return false;
587       }
588
589     }
590
591     return false;
592   }
593
594   private void recursiveAddRelationToLattice(int idx, MethodDescriptor md,
595       CompositeLocation srcInferLoc, CompositeLocation dstInferLoc) throws CyclicFlowException {
596
597     String srcLocSymbol = srcInferLoc.get(idx).getLocIdentifier();
598     String dstLocSymbol = dstInferLoc.get(idx).getLocIdentifier();
599
600     if (srcLocSymbol.equals(dstLocSymbol)) {
601       recursiveAddRelationToLattice(idx + 1, md, srcInferLoc, dstInferLoc);
602     } else {
603
604       Descriptor parentDesc = srcInferLoc.get(idx).getDescriptor();
605       LocationInfo locInfo = getLocationInfo(parentDesc);
606
607       addRelationHigherToLower(getLattice(parentDesc), getLocationInfo(parentDesc), srcLocSymbol,
608           dstLocSymbol);
609     }
610
611   }
612
613   private void analyzeLatticeMethodInvocationNode(MethodDescriptor mdCaller,
614       SSJavaLattice<String> methodLattice, MethodLocationInfo methodInfo)
615       throws CyclicFlowException {
616
617     // the transformation for a call site propagates all relations between
618     // parameters from the callee
619     // if the method is virtual, it also grab all relations from any possible
620     // callees
621
622     Set<MethodInvokeNode> setMethodInvokeNode =
623         mapMethodDescriptorToMethodInvokeNodeSet.get(mdCaller);
624
625     if (setMethodInvokeNode != null) {
626
627       for (Iterator iterator = setMethodInvokeNode.iterator(); iterator.hasNext();) {
628         MethodInvokeNode min = (MethodInvokeNode) iterator.next();
629         MethodDescriptor mdCallee = min.getMethod();
630         Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
631         if (mdCallee.isStatic()) {
632           setPossibleCallees.add(mdCallee);
633         } else {
634           Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getMethods(mdCallee);
635           // removes method descriptors that are not invoked by the caller
636           calleeSet.retainAll(mapMethodToCalleeSet.get(mdCaller));
637           setPossibleCallees.addAll(calleeSet);
638         }
639
640         for (Iterator iterator2 = setPossibleCallees.iterator(); iterator2.hasNext();) {
641           MethodDescriptor possibleMdCallee = (MethodDescriptor) iterator2.next();
642           propagateRelationToCaller(min, mdCaller, possibleMdCallee, methodLattice, methodInfo);
643         }
644
645       }
646     }
647
648   }
649
650   private void propagateRelationToCaller(MethodInvokeNode min, MethodDescriptor mdCaller,
651       MethodDescriptor possibleMdCallee, SSJavaLattice<String> methodLattice,
652       MethodLocationInfo methodInfo) throws CyclicFlowException {
653
654     SSJavaLattice<String> calleeLattice = getMethodLattice(possibleMdCallee);
655     MethodLocationInfo calleeLocInfo = getMethodLocationInfo(possibleMdCallee);
656     FlowGraph calleeFlowGraph = getFlowGraph(possibleMdCallee);
657
658     int numParam = calleeLocInfo.getNumParam();
659     for (int i = 0; i < numParam; i++) {
660       CompositeLocation param1 = calleeLocInfo.getParamCompositeLocation(i);
661       for (int k = 0; k < numParam; k++) {
662         if (i != k) {
663           CompositeLocation param2 = calleeLocInfo.getParamCompositeLocation(k);
664           if (isGreaterThan(getLattice(possibleMdCallee), param1, param2)) {
665             NodeTupleSet argDescTupleSet1 = getNodeTupleSetByArgIdx(min, i);
666             NodeTupleSet argDescTupleSet2 = getNodeTupleSetByArgIdx(min, k);
667
668             // the callee has the relation in which param1 is higher than param2
669             // therefore, the caller has to have the relation in which arg1 is
670             // higher than arg2
671
672             for (Iterator<NTuple<Descriptor>> iterator = argDescTupleSet1.iterator(); iterator
673                 .hasNext();) {
674               NTuple<Descriptor> argDescTuple1 = iterator.next();
675
676               for (Iterator<NTuple<Descriptor>> iterator2 = argDescTupleSet2.iterator(); iterator2
677                   .hasNext();) {
678                 NTuple<Descriptor> argDescTuple2 = iterator2.next();
679
680                 // retreive inferred location by the local var descriptor
681
682                 NTuple<Location> tuple1 = getFlowGraph(mdCaller).getLocationTuple(argDescTuple1);
683                 NTuple<Location> tuple2 = getFlowGraph(mdCaller).getLocationTuple(argDescTuple2);
684
685                 // CompositeLocation higherInferLoc =
686                 // methodInfo.getInferLocation(argTuple1.get(0));
687                 // CompositeLocation lowerInferLoc =
688                 // methodInfo.getInferLocation(argTuple2.get(0));
689
690                 CompositeLocation inferLoc1 = generateInferredCompositeLocation(methodInfo, tuple1);
691                 CompositeLocation inferLoc2 = generateInferredCompositeLocation(methodInfo, tuple2);
692
693                 // addRelation(methodLattice, methodInfo, inferLoc1, inferLoc2);
694
695                 addFlowGraphEdge(mdCaller, argDescTuple1, argDescTuple2);
696
697               }
698
699             }
700
701           }
702         }
703       }
704     }
705
706   }
707
708   private CompositeLocation generateInferredCompositeLocation(MethodLocationInfo methodInfo,
709       NTuple<Location> tuple) {
710
711     // System.out.println("@@@@@generateInferredCompositeLocation=" + tuple);
712     // System.out.println("generateInferredCompositeLocation=" + tuple + "   0="
713     // + tuple.get(0).getLocDescriptor());
714     // first, retrieve inferred location by the local var descriptor
715     CompositeLocation inferLoc = new CompositeLocation();
716
717     CompositeLocation localVarInferLoc =
718         methodInfo.getInferLocation(tuple.get(0).getLocDescriptor());
719
720     localVarInferLoc.get(0).setLocDescriptor(tuple.get(0).getLocDescriptor());
721
722     for (int i = 0; i < localVarInferLoc.getSize(); i++) {
723       inferLoc.addLocation(localVarInferLoc.get(i));
724     }
725     // System.out.println("@@@@@localVarInferLoc=" + localVarInferLoc);
726
727     for (int i = 1; i < tuple.size(); i++) {
728       Location cur = tuple.get(i);
729       Descriptor enclosingDesc = cur.getDescriptor();
730       Descriptor curDesc = cur.getLocDescriptor();
731
732       Location inferLocElement;
733       if (curDesc == null) {
734         // in this case, we have a newly generated location.
735         // System.out.println("!!! generated location=" +
736         // cur.getLocIdentifier());
737         inferLocElement = new Location(enclosingDesc, cur.getLocIdentifier());
738       } else {
739         String fieldLocSymbol =
740             getLocationInfo(enclosingDesc).getInferLocation(curDesc).get(0).getLocIdentifier();
741         inferLocElement = new Location(enclosingDesc, fieldLocSymbol);
742         inferLocElement.setLocDescriptor(curDesc);
743       }
744
745       inferLoc.addLocation(inferLocElement);
746
747     }
748     // System.out.println("@@@@@inferLoc=" + inferLoc);
749     return inferLoc;
750   }
751
752   private void addRelation(SSJavaLattice<String> methodLattice, MethodLocationInfo methodInfo,
753       CompositeLocation srcInferLoc, CompositeLocation dstInferLoc) throws CyclicFlowException {
754
755     System.out.println("addRelation --- srcInferLoc=" + srcInferLoc + "  dstInferLoc="
756         + dstInferLoc);
757     String srcLocalLocSymbol = srcInferLoc.get(0).getLocIdentifier();
758     String dstLocalLocSymbol = dstInferLoc.get(0).getLocIdentifier();
759
760     if (srcInferLoc.getSize() == 1 && dstInferLoc.getSize() == 1) {
761       // add a new relation to the local lattice
762       addRelationHigherToLower(methodLattice, methodInfo, srcLocalLocSymbol, dstLocalLocSymbol);
763     } else if (srcInferLoc.getSize() > 1 && dstInferLoc.getSize() > 1) {
764       // both src and dst have assigned to a composite location
765
766       if (!srcLocalLocSymbol.equals(dstLocalLocSymbol)) {
767         addRelationHigherToLower(methodLattice, methodInfo, srcLocalLocSymbol, dstLocalLocSymbol);
768       } else {
769         recursivelyAddRelation(1, srcInferLoc, dstInferLoc);
770       }
771     } else {
772       // either src or dst has assigned to a composite location
773       if (!srcLocalLocSymbol.equals(dstLocalLocSymbol)) {
774         addRelationHigherToLower(methodLattice, methodInfo, srcLocalLocSymbol, dstLocalLocSymbol);
775       }
776     }
777
778     System.out.println();
779
780   }
781
782   public LocationInfo getLocationInfo(Descriptor d) {
783     if (d instanceof MethodDescriptor) {
784       return getMethodLocationInfo((MethodDescriptor) d);
785     } else {
786       return getFieldLocationInfo((ClassDescriptor) d);
787     }
788   }
789
790   private MethodLocationInfo getMethodLocationInfo(MethodDescriptor md) {
791
792     if (!mapMethodDescToMethodLocationInfo.containsKey(md)) {
793       mapMethodDescToMethodLocationInfo.put(md, new MethodLocationInfo(md));
794     }
795
796     return mapMethodDescToMethodLocationInfo.get(md);
797
798   }
799
800   private LocationInfo getFieldLocationInfo(ClassDescriptor cd) {
801
802     if (!mapClassToLocationInfo.containsKey(cd)) {
803       mapClassToLocationInfo.put(cd, new LocationInfo(cd));
804     }
805
806     return mapClassToLocationInfo.get(cd);
807
808   }
809
810   private void addRelationToLattice(MethodDescriptor md, SSJavaLattice<String> methodLattice,
811       MethodLocationInfo methodInfo, FlowNode srcNode, FlowNode dstNode) throws CyclicFlowException {
812
813     System.out.println();
814     System.out.println("### addRelationToLattice src=" + srcNode + " dst=" + dstNode);
815
816     // add a new binary relation of dstNode < srcNode
817     FlowGraph flowGraph = getFlowGraph(md);
818     try {
819       System.out.println("***** src composite case::");
820       calculateCompositeLocation(flowGraph, methodLattice, methodInfo, srcNode);
821
822       CompositeLocation srcInferLoc =
823           generateInferredCompositeLocation(methodInfo, flowGraph.getLocationTuple(srcNode));
824       CompositeLocation dstInferLoc =
825           generateInferredCompositeLocation(methodInfo, flowGraph.getLocationTuple(dstNode));
826
827       addRelation(methodLattice, methodInfo, srcInferLoc, dstInferLoc);
828     } catch (CyclicFlowException e) {
829       // there is a cyclic value flow... try to calculate a composite location
830       // for the destination node
831       System.out.println("***** dst composite case::");
832       calculateCompositeLocation(flowGraph, methodLattice, methodInfo, dstNode);
833       CompositeLocation srcInferLoc =
834           generateInferredCompositeLocation(methodInfo, flowGraph.getLocationTuple(srcNode));
835       CompositeLocation dstInferLoc =
836           generateInferredCompositeLocation(methodInfo, flowGraph.getLocationTuple(dstNode));
837       try {
838         addRelation(methodLattice, methodInfo, srcInferLoc, dstInferLoc);
839       } catch (CyclicFlowException e1) {
840         throw new Error("Failed to merge cyclic value flows into a shared location.");
841       }
842     }
843
844   }
845
846   private void recursivelyAddRelation(int idx, CompositeLocation srcInferLoc,
847       CompositeLocation dstInferLoc) throws CyclicFlowException {
848
849     String srcLocSymbol = srcInferLoc.get(idx).getLocIdentifier();
850     String dstLocSymbol = dstInferLoc.get(idx).getLocIdentifier();
851
852     Descriptor parentDesc = srcInferLoc.get(idx).getDescriptor();
853
854     if (srcLocSymbol.equals(dstLocSymbol)) {
855       // check if it is the case of shared location
856       if (srcInferLoc.getSize() == (idx + 1) && dstInferLoc.getSize() == (idx + 1)) {
857         Location inferLocElement = srcInferLoc.get(idx);
858         System.out.println("SET SHARED LOCATION=" + inferLocElement);
859         getLattice(inferLocElement.getDescriptor())
860             .addSharedLoc(inferLocElement.getLocIdentifier());
861       } else if (srcInferLoc.getSize() > (idx + 1) && dstInferLoc.getSize() > (idx + 1)) {
862         recursivelyAddRelation(idx + 1, srcInferLoc, dstInferLoc);
863       }
864     } else {
865       addRelationHigherToLower(getLattice(parentDesc), getLocationInfo(parentDesc), srcLocSymbol,
866           dstLocSymbol);
867     }
868   }
869
870   private void recursivelyAddCompositeRelation(MethodDescriptor md, FlowGraph flowGraph,
871       MethodLocationInfo methodInfo, FlowNode srcNode, FlowNode dstNode, Descriptor srcDesc,
872       Descriptor dstDesc) throws CyclicFlowException {
873
874     CompositeLocation inferSrcLoc;
875     CompositeLocation inferDstLoc = methodInfo.getInferLocation(dstDesc);
876
877     if (srcNode.getDescTuple().size() > 1) {
878       // field access
879       inferSrcLoc = new CompositeLocation();
880
881       NTuple<Location> locTuple = flowGraph.getLocationTuple(srcNode);
882       for (int i = 0; i < locTuple.size(); i++) {
883         inferSrcLoc.addLocation(locTuple.get(i));
884       }
885
886     } else {
887       inferSrcLoc = methodInfo.getInferLocation(srcDesc);
888     }
889
890     if (dstNode.getDescTuple().size() > 1) {
891       // field access
892       inferDstLoc = new CompositeLocation();
893
894       NTuple<Location> locTuple = flowGraph.getLocationTuple(dstNode);
895       for (int i = 0; i < locTuple.size(); i++) {
896         inferDstLoc.addLocation(locTuple.get(i));
897       }
898
899     } else {
900       inferDstLoc = methodInfo.getInferLocation(dstDesc);
901     }
902
903     recursiveAddRelationToLattice(1, md, inferSrcLoc, inferDstLoc);
904   }
905
906   private void addPrefixMapping(Map<NTuple<Location>, Set<NTuple<Location>>> map,
907       NTuple<Location> prefix, NTuple<Location> element) {
908
909     if (!map.containsKey(prefix)) {
910       map.put(prefix, new HashSet<NTuple<Location>>());
911     }
912     map.get(prefix).add(element);
913   }
914
915   private boolean calculateCompositeLocation(FlowGraph flowGraph,
916       SSJavaLattice<String> methodLattice, MethodLocationInfo methodInfo, FlowNode flowNode)
917       throws CyclicFlowException {
918
919     Descriptor localVarDesc = flowNode.getDescTuple().get(0);
920
921     if (localVarDesc.equals(methodInfo.getMethodDesc())) {
922       return false;
923     }
924
925     Set<FlowNode> inNodeSet = flowGraph.getIncomingFlowNodeSet(flowNode);
926     Set<FlowNode> reachableNodeSet = flowGraph.getReachableFlowNodeSet(flowNode);
927
928     Map<NTuple<Location>, Set<NTuple<Location>>> mapPrefixToIncomingLocTupleSet =
929         new HashMap<NTuple<Location>, Set<NTuple<Location>>>();
930
931     Set<FlowNode> localInNodeSet = new HashSet<FlowNode>();
932     Set<FlowNode> localOutNodeSet = new HashSet<FlowNode>();
933
934     CompositeLocation flowNodeInferLoc =
935         generateInferredCompositeLocation(methodInfo, flowGraph.getLocationTuple(flowNode));
936
937     List<NTuple<Location>> prefixList = new ArrayList<NTuple<Location>>();
938
939     for (Iterator iterator = inNodeSet.iterator(); iterator.hasNext();) {
940       FlowNode inNode = (FlowNode) iterator.next();
941       NTuple<Location> inNodeTuple = flowGraph.getLocationTuple(inNode);
942
943       CompositeLocation inNodeInferredLoc =
944           generateInferredCompositeLocation(methodInfo, inNodeTuple);
945
946       NTuple<Location> inNodeInferredLocTuple = inNodeInferredLoc.getTuple();
947
948       if (inNodeTuple.size() > 1) {
949         for (int i = 1; i < inNodeInferredLocTuple.size(); i++) {
950           NTuple<Location> prefix = inNodeInferredLocTuple.subList(0, i);
951           if (!prefixList.contains(prefix)) {
952             prefixList.add(prefix);
953           }
954           addPrefixMapping(mapPrefixToIncomingLocTupleSet, prefix, inNodeInferredLocTuple);
955         }
956       } else {
957         localInNodeSet.add(inNode);
958       }
959     }
960
961     Collections.sort(prefixList, new Comparator<NTuple<Location>>() {
962       public int compare(NTuple<Location> arg0, NTuple<Location> arg1) {
963         int s0 = arg0.size();
964         int s1 = arg1.size();
965         if (s0 > s1) {
966           return -1;
967         } else if (s0 == s1) {
968           return 0;
969         } else {
970           return 1;
971         }
972       }
973     });
974
975     for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
976       FlowNode reachableNode = (FlowNode) iterator2.next();
977       if (reachableNode.getDescTuple().size() == 1) {
978         localOutNodeSet.add(reachableNode);
979       }
980     }
981
982     // find out reachable nodes that have the longest common prefix
983     for (int i = 0; i < prefixList.size(); i++) {
984       NTuple<Location> curPrefix = prefixList.get(i);
985       Set<NTuple<Location>> reachableCommonPrefixSet = new HashSet<NTuple<Location>>();
986
987       for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
988         FlowNode reachableNode = (FlowNode) iterator2.next();
989         NTuple<Location> reachLocTuple = flowGraph.getLocationTuple(reachableNode);
990         CompositeLocation reachLocInferLoc =
991             generateInferredCompositeLocation(methodInfo, reachLocTuple);
992         if (reachLocInferLoc.getTuple().startsWith(curPrefix)) {
993           reachableCommonPrefixSet.add(reachLocTuple);
994         }
995       }
996
997       // check if the lattice has the relation in which higher prefix is
998       // actually lower than the current node
999       CompositeLocation prefixInferLoc = generateInferredCompositeLocation(methodInfo, curPrefix);
1000       if (isGreaterThan(methodLattice, flowNodeInferLoc, prefixInferLoc)) {
1001         reachableCommonPrefixSet.add(curPrefix);
1002       }
1003
1004       if (!reachableCommonPrefixSet.isEmpty()) {
1005         // found reachable nodes that start with the prefix curPrefix
1006         // need to assign a composite location
1007
1008         // first, check if there are more than one the set of locations that has
1009         // the same length of the longest reachable prefix, no way to assign
1010         // a composite location to the input local var
1011         prefixSanityCheck(prefixList, i, flowGraph, reachableNodeSet);
1012
1013         Set<NTuple<Location>> incomingCommonPrefixSet =
1014             mapPrefixToIncomingLocTupleSet.get(curPrefix);
1015
1016         int idx = curPrefix.size();
1017         NTuple<Location> element = incomingCommonPrefixSet.iterator().next();
1018         Descriptor desc = element.get(idx).getDescriptor();
1019
1020         SSJavaLattice<String> lattice = getLattice(desc);
1021         LocationInfo locInfo = getLocationInfo(desc);
1022
1023         CompositeLocation inferLocation = methodInfo.getInferLocation(localVarDesc);
1024         CompositeLocation newInferLocation = new CompositeLocation();
1025
1026         if (inferLocation.getTuple().startsWith(curPrefix)) {
1027           // the same infer location is already existed. no need to do
1028           // anything
1029           return true;
1030         } else {
1031           // assign a new composite location
1032
1033           // String oldMethodLocationSymbol =
1034           // inferLocation.get(0).getLocIdentifier();
1035           String newLocSymbol = "Loc" + (SSJavaLattice.seed++);
1036           for (int locIdx = 0; locIdx < curPrefix.size(); locIdx++) {
1037             newInferLocation.addLocation(curPrefix.get(locIdx));
1038           }
1039           Location fieldLoc = new Location(desc, newLocSymbol);
1040           newInferLocation.addLocation(fieldLoc);
1041
1042           if (flowNode.getDescTuple().size() == 1) {
1043             // maps local variable to location types of the common prefix
1044             methodInfo.mapDescriptorToLocation(localVarDesc, newInferLocation.clone());
1045           }
1046
1047           // methodInfo.mapDescriptorToLocation(localVarDesc, newInferLocation);
1048           addMapLocSymbolToInferredLocation(methodInfo.getMethodDesc(), localVarDesc,
1049               newInferLocation);
1050           methodInfo.removeMaplocalVarToLocSet(localVarDesc);
1051
1052           // add the field/var descriptor to the set of the location symbol
1053           int flowNodeTupleSize = flowNode.getDescTuple().size();
1054           Descriptor lastFlowNodeDesc = flowNode.getDescTuple().get(flowNodeTupleSize - 1);
1055           int inferLocSize = newInferLocation.getSize();
1056           Location lastLoc = newInferLocation.get(inferLocSize - 1);
1057           Descriptor enclosingDesc = lastLoc.getDescriptor();
1058           getLocationInfo(enclosingDesc).addMapLocSymbolToDescSet(lastLoc.getLocIdentifier(),
1059               lastFlowNodeDesc);
1060
1061           // clean up the previous location
1062           // Location prevInferLocElement =
1063           // inferLocation.get(inferLocation.getSize() - 1);
1064           // Descriptor prevEnclosingDesc = prevInferLocElement.getDescriptor();
1065           //
1066           // SSJavaLattice<String> targetLattice;
1067           // LocationInfo targetInfo;
1068           // if (prevEnclosingDesc.equals(methodInfo.getMethodDesc())) {
1069           // targetLattice = methodLattice;
1070           // targetInfo = methodInfo;
1071           // } else {
1072           // targetLattice = getLattice(prevInferLocElement.getDescriptor());
1073           // targetInfo = getLocationInfo(prevInferLocElement.getDescriptor());
1074           // }
1075           //
1076           // Set<Pair<Descriptor, Descriptor>> associstedDescSet =
1077           // targetInfo.getRelatedInferLocSet(prevInferLocElement.getLocIdentifier());
1078           //
1079           // if (associstedDescSet.size() == 1) {
1080           // targetLattice.remove(prevInferLocElement.getLocIdentifier());
1081           // } else {
1082           // associstedDescSet.remove(lastFlowNodeDesc);
1083           // }
1084
1085         }
1086
1087         System.out.println("ASSIGN NEW COMPOSITE LOCATION =" + newInferLocation + "    to "
1088             + flowNode);
1089
1090         String newlyInsertedLocName =
1091             newInferLocation.get(newInferLocation.getSize() - 1).getLocIdentifier();
1092
1093         System.out.println("-- add in-flow");
1094         for (Iterator iterator = incomingCommonPrefixSet.iterator(); iterator.hasNext();) {
1095           NTuple<Location> tuple = (NTuple<Location>) iterator.next();
1096           System.out.println("--in-flow tuple=" + tuple);
1097           Location loc = tuple.get(idx);
1098           String higher = locInfo.getFieldInferLocation(loc.getLocDescriptor()).getLocIdentifier();
1099           addRelationHigherToLower(lattice, locInfo, higher, newlyInsertedLocName);
1100         }
1101
1102         System.out.println("-- add local in-flow");
1103         for (Iterator iterator = localInNodeSet.iterator(); iterator.hasNext();) {
1104           FlowNode localNode = (FlowNode) iterator.next();
1105
1106           if (localNode.equals(flowNode)) {
1107             continue;
1108           }
1109
1110           CompositeLocation inNodeInferLoc =
1111               generateInferredCompositeLocation(methodInfo, flowGraph.getLocationTuple(localNode));
1112
1113           if (isCompositeLocation(inNodeInferLoc)) {
1114             // need to make sure that newLocSymbol is lower than the infernode
1115             // location in the field lattice
1116             System.out.println("----srcNode=" + localNode + "  dstNode=" + flowNode);
1117             addRelationToLattice(methodInfo.getMethodDesc(), methodLattice, methodInfo, localNode,
1118                 flowNode);
1119
1120           }
1121
1122         }
1123
1124         System.out.println("-- add out flow");
1125         for (Iterator iterator = reachableCommonPrefixSet.iterator(); iterator.hasNext();) {
1126           NTuple<Location> tuple = (NTuple<Location>) iterator.next();
1127           if (tuple.size() > idx) {
1128             Location loc = tuple.get(idx);
1129             String lower = locInfo.getFieldInferLocation(loc.getLocDescriptor()).getLocIdentifier();
1130             addRelationHigherToLower(lattice, locInfo, newlyInsertedLocName, lower);
1131           }
1132         }
1133
1134         System.out.println("-- add local out flow");
1135         for (Iterator iterator = localOutNodeSet.iterator(); iterator.hasNext();) {
1136           FlowNode localOutNode = (FlowNode) iterator.next();
1137
1138           if (localOutNode.equals(flowNode)) {
1139             continue;
1140           }
1141
1142           CompositeLocation outNodeInferLoc =
1143               generateInferredCompositeLocation(methodInfo,
1144                   flowGraph.getLocationTuple(localOutNode));
1145
1146           if (isCompositeLocation(outNodeInferLoc)) {
1147             // need to make sure that newLocSymbol is higher than the infernode
1148             // location
1149             System.out.println("--- srcNode=" + flowNode + "  dstNode=" + localOutNode);
1150             addRelationToLattice(methodInfo.getMethodDesc(), methodLattice, methodInfo, flowNode,
1151                 localOutNode);
1152
1153           }
1154         }
1155         System.out.println("-- end of add local out flow");
1156
1157         return true;
1158       }
1159
1160     }
1161
1162     return false;
1163
1164   }
1165
1166   private void addMapLocSymbolToInferredLocation(MethodDescriptor md, Descriptor localVar,
1167       CompositeLocation inferLoc) {
1168
1169     Location locElement = inferLoc.get((inferLoc.getSize() - 1));
1170     Descriptor enclosingDesc = locElement.getDescriptor();
1171     LocationInfo locInfo = getLocationInfo(enclosingDesc);
1172     locInfo.addMapLocSymbolToRelatedInferLoc(locElement.getLocIdentifier(), md, localVar);
1173   }
1174
1175   private boolean isCompositeLocation(CompositeLocation cl) {
1176     return cl.getSize() > 1;
1177   }
1178
1179   private boolean containsNonPrimitiveElement(Set<Descriptor> descSet) {
1180     for (Iterator iterator = descSet.iterator(); iterator.hasNext();) {
1181       Descriptor desc = (Descriptor) iterator.next();
1182
1183       if (desc.equals(LocationInference.GLOBALDESC)) {
1184         return true;
1185       } else if (desc instanceof VarDescriptor) {
1186         if (!((VarDescriptor) desc).getType().isPrimitive()) {
1187           return true;
1188         }
1189       } else if (desc instanceof FieldDescriptor) {
1190         if (!((FieldDescriptor) desc).getType().isPrimitive()) {
1191           return true;
1192         }
1193       }
1194
1195     }
1196     return false;
1197   }
1198
1199   private void addRelationHigherToLower(SSJavaLattice<String> lattice, LocationInfo locInfo,
1200       String higher, String lower) throws CyclicFlowException {
1201
1202     System.out.println("---addRelationHigherToLower " + higher + " -> " + lower
1203         + " to the lattice of " + locInfo.getDescIdentifier());
1204     // if (higher.equals(lower) && lattice.isSharedLoc(higher)) {
1205     // return;
1206     // }
1207     Set<String> cycleElementSet = lattice.getPossibleCycleElements(higher, lower);
1208
1209     boolean hasNonPrimitiveElement = false;
1210     for (Iterator iterator = cycleElementSet.iterator(); iterator.hasNext();) {
1211       String cycleElementLocSymbol = (String) iterator.next();
1212
1213       Set<Descriptor> descSet = locInfo.getDescSet(cycleElementLocSymbol);
1214       if (containsNonPrimitiveElement(descSet)) {
1215         hasNonPrimitiveElement = true;
1216         break;
1217       }
1218     }
1219
1220     if (hasNonPrimitiveElement) {
1221       System.out.println("#Check cycle= " + lower + " < " + higher + "     cycleElementSet="
1222           + cycleElementSet);
1223       // if there is non-primitive element in the cycle, no way to merge cyclic
1224       // elements into the shared location
1225       throw new CyclicFlowException();
1226     }
1227
1228     if (cycleElementSet.size() > 0) {
1229
1230       String newSharedLoc = "SharedLoc" + (SSJavaLattice.seed++);
1231
1232       System.out.println("---ASSIGN NEW SHARED LOC=" + newSharedLoc + "   to  " + cycleElementSet);
1233       lattice.mergeIntoSharedLocation(cycleElementSet, newSharedLoc);
1234
1235       for (Iterator iterator = cycleElementSet.iterator(); iterator.hasNext();) {
1236         String oldLocSymbol = (String) iterator.next();
1237
1238         Set<Pair<Descriptor, Descriptor>> inferLocSet = locInfo.getRelatedInferLocSet(oldLocSymbol);
1239         System.out.println("---update related locations=" + inferLocSet);
1240         for (Iterator iterator2 = inferLocSet.iterator(); iterator2.hasNext();) {
1241           Pair<Descriptor, Descriptor> pair = (Pair<Descriptor, Descriptor>) iterator2.next();
1242           Descriptor enclosingDesc = pair.getFirst();
1243           Descriptor desc = pair.getSecond();
1244
1245           CompositeLocation inferLoc;
1246           if (curMethodInfo.md.equals(enclosingDesc)) {
1247             inferLoc = curMethodInfo.getInferLocation(desc);
1248           } else {
1249             inferLoc = getLocationInfo(enclosingDesc).getInferLocation(desc);
1250           }
1251
1252           Location locElement = inferLoc.get(inferLoc.getSize() - 1);
1253
1254           locElement.setLocIdentifier(newSharedLoc);
1255           locInfo.addMapLocSymbolToRelatedInferLoc(newSharedLoc, enclosingDesc, desc);
1256
1257           if (curMethodInfo.md.equals(enclosingDesc)) {
1258             inferLoc = curMethodInfo.getInferLocation(desc);
1259           } else {
1260             inferLoc = getLocationInfo(enclosingDesc).getInferLocation(desc);
1261           }
1262           System.out.println("---New Infer Loc=" + inferLoc);
1263
1264         }
1265         locInfo.removeRelatedInferLocSet(oldLocSymbol, newSharedLoc);
1266
1267       }
1268
1269       lattice.addSharedLoc(newSharedLoc);
1270
1271     } else if (!lattice.isGreaterThan(higher, lower)) {
1272       lattice.addRelationHigherToLower(higher, lower);
1273     }
1274   }
1275
1276   private void replaceOldLocWithNewLoc(SSJavaLattice<String> methodLattice, String oldLocSymbol,
1277       String newLocSymbol) {
1278
1279     if (methodLattice.containsKey(oldLocSymbol)) {
1280       methodLattice.substituteLocation(oldLocSymbol, newLocSymbol);
1281     }
1282
1283   }
1284
1285   private void prefixSanityCheck(List<NTuple<Location>> prefixList, int curIdx,
1286       FlowGraph flowGraph, Set<FlowNode> reachableNodeSet) {
1287
1288     NTuple<Location> curPrefix = prefixList.get(curIdx);
1289
1290     for (int i = curIdx + 1; i < prefixList.size(); i++) {
1291       NTuple<Location> prefixTuple = prefixList.get(i);
1292
1293       if (curPrefix.startsWith(prefixTuple)) {
1294         continue;
1295       }
1296
1297       for (Iterator iterator2 = reachableNodeSet.iterator(); iterator2.hasNext();) {
1298         FlowNode reachableNode = (FlowNode) iterator2.next();
1299         NTuple<Location> reachLocTuple = flowGraph.getLocationTuple(reachableNode);
1300         if (reachLocTuple.startsWith(prefixTuple)) {
1301           // TODO
1302           throw new Error("Failed to generate a composite location");
1303         }
1304       }
1305     }
1306   }
1307
1308   public boolean isPrimitiveLocalVariable(FlowNode node) {
1309     VarDescriptor varDesc = (VarDescriptor) node.getDescTuple().get(0);
1310     return varDesc.getType().isPrimitive();
1311   }
1312
1313   private SSJavaLattice<String> getLattice(Descriptor d) {
1314     if (d instanceof MethodDescriptor) {
1315       return getMethodLattice((MethodDescriptor) d);
1316     } else {
1317       return getFieldLattice((ClassDescriptor) d);
1318     }
1319   }
1320
1321   private SSJavaLattice<String> getMethodLattice(MethodDescriptor md) {
1322     if (!md2lattice.containsKey(md)) {
1323       md2lattice.put(md, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
1324     }
1325     return md2lattice.get(md);
1326   }
1327
1328   private void setMethodLattice(MethodDescriptor md, SSJavaLattice<String> lattice) {
1329     md2lattice.put(md, lattice);
1330   }
1331
1332   private void extractRelationFromFieldFlows(ClassDescriptor cd, FlowNode srcNode,
1333       FlowNode dstNode, int idx) throws CyclicFlowException {
1334
1335     if (srcNode.getDescTuple().get(idx).equals(dstNode.getDescTuple().get(idx))
1336         && srcNode.getDescTuple().size() > (idx + 1) && dstNode.getDescTuple().size() > (idx + 1)) {
1337       // value flow between fields: we don't need to add a binary relation
1338       // for this case
1339
1340       Descriptor desc = srcNode.getDescTuple().get(idx);
1341       ClassDescriptor classDesc;
1342
1343       if (idx == 0) {
1344         classDesc = ((VarDescriptor) desc).getType().getClassDesc();
1345       } else {
1346         classDesc = ((FieldDescriptor) desc).getType().getClassDesc();
1347       }
1348
1349       extractRelationFromFieldFlows(classDesc, srcNode, dstNode, idx + 1);
1350
1351     } else {
1352
1353       Descriptor srcFieldDesc = srcNode.getDescTuple().get(idx);
1354       Descriptor dstFieldDesc = dstNode.getDescTuple().get(idx);
1355
1356       // add a new binary relation of dstNode < srcNode
1357       SSJavaLattice<String> fieldLattice = getFieldLattice(cd);
1358       LocationInfo fieldInfo = getFieldLocationInfo(cd);
1359
1360       String srcSymbol = fieldInfo.getFieldInferLocation(srcFieldDesc).getLocIdentifier();
1361       String dstSymbol = fieldInfo.getFieldInferLocation(dstFieldDesc).getLocIdentifier();
1362
1363       addRelationHigherToLower(fieldLattice, fieldInfo, srcSymbol, dstSymbol);
1364
1365     }
1366
1367   }
1368
1369   public SSJavaLattice<String> getFieldLattice(ClassDescriptor cd) {
1370     if (!cd2lattice.containsKey(cd)) {
1371       cd2lattice.put(cd, new SSJavaLattice<String>(SSJavaAnalysis.TOP, SSJavaAnalysis.BOTTOM));
1372     }
1373     return cd2lattice.get(cd);
1374   }
1375
1376   public void constructFlowGraph() {
1377
1378     setupToAnalyze();
1379
1380     Set<MethodDescriptor> visited = new HashSet<MethodDescriptor>();
1381     Set<MethodDescriptor> reachableCallee = new HashSet<MethodDescriptor>();
1382
1383     while (!toAnalyzeIsEmpty()) {
1384       ClassDescriptor cd = toAnalyzeNext();
1385
1386       setupToAnalazeMethod(cd);
1387       toanalyzeMethodList.removeAll(visited);
1388
1389       while (!toAnalyzeMethodIsEmpty()) {
1390         MethodDescriptor md = toAnalyzeMethodNext();
1391         if ((!visited.contains(md))
1392             && (ssjava.needTobeAnnotated(md) || reachableCallee.contains(md))) {
1393           if (state.SSJAVADEBUG) {
1394             System.out.println();
1395             System.out.println("SSJAVA: Constructing a flow graph: " + md);
1396           }
1397
1398           // creates a mapping from a method descriptor to virtual methods
1399           Set<MethodDescriptor> setPossibleCallees = new HashSet<MethodDescriptor>();
1400           if (md.isStatic()) {
1401             setPossibleCallees.add(md);
1402           } else {
1403             setPossibleCallees.addAll(ssjava.getCallGraph().getMethods(md));
1404           }
1405
1406           Set<MethodDescriptor> calleeSet = ssjava.getCallGraph().getCalleeSet(md);
1407           Set<MethodDescriptor> needToAnalyzeCalleeSet = new HashSet<MethodDescriptor>();
1408
1409           for (Iterator iterator = calleeSet.iterator(); iterator.hasNext();) {
1410             MethodDescriptor calleemd = (MethodDescriptor) iterator.next();
1411             if ((!ssjava.isTrustMethod(calleemd))
1412                 && (!ssjava.isSSJavaUtil(calleemd.getClassDesc()))) {
1413               if (!visited.contains(calleemd)) {
1414                 toanalyzeMethodList.add(calleemd);
1415               }
1416               reachableCallee.add(calleemd);
1417               needToAnalyzeCalleeSet.add(calleemd);
1418             }
1419           }
1420
1421           mapMethodToCalleeSet.put(md, needToAnalyzeCalleeSet);
1422
1423           // creates a mapping from a parameter descriptor to its index
1424           Map<Descriptor, Integer> mapParamDescToIdx = new HashMap<Descriptor, Integer>();
1425           int offset = md.isStatic() ? 0 : 1;
1426           for (int i = 0; i < md.numParameters(); i++) {
1427             Descriptor paramDesc = (Descriptor) md.getParameter(i);
1428             mapParamDescToIdx.put(paramDesc, new Integer(i + offset));
1429           }
1430
1431           FlowGraph fg = new FlowGraph(md, mapParamDescToIdx);
1432           mapMethodDescriptorToFlowGraph.put(md, fg);
1433
1434           visited.add(md);
1435           analyzeMethodBody(cd, md);
1436
1437         }
1438       }
1439     }
1440
1441     _debug_printGraph();
1442   }
1443
1444   private void analyzeMethodBody(ClassDescriptor cd, MethodDescriptor md) {
1445     BlockNode bn = state.getMethodBody(md);
1446     NodeTupleSet implicitFlowTupleSet = new NodeTupleSet();
1447     analyzeFlowBlockNode(md, md.getParameterTable(), bn, implicitFlowTupleSet);
1448   }
1449
1450   private void analyzeFlowBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn,
1451       NodeTupleSet implicitFlowTupleSet) {
1452
1453     bn.getVarTable().setParent(nametable);
1454     for (int i = 0; i < bn.size(); i++) {
1455       BlockStatementNode bsn = bn.get(i);
1456       analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
1457     }
1458
1459   }
1460
1461   private void analyzeBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
1462       BlockStatementNode bsn, NodeTupleSet implicitFlowTupleSet) {
1463
1464     switch (bsn.kind()) {
1465     case Kind.BlockExpressionNode:
1466       analyzeBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, implicitFlowTupleSet);
1467       break;
1468
1469     case Kind.DeclarationNode:
1470       analyzeFlowDeclarationNode(md, nametable, (DeclarationNode) bsn, implicitFlowTupleSet);
1471       break;
1472
1473     case Kind.IfStatementNode:
1474       analyzeFlowIfStatementNode(md, nametable, (IfStatementNode) bsn, implicitFlowTupleSet);
1475       break;
1476
1477     case Kind.LoopNode:
1478       analyzeFlowLoopNode(md, nametable, (LoopNode) bsn, implicitFlowTupleSet);
1479       break;
1480
1481     case Kind.ReturnNode:
1482       analyzeFlowReturnNode(md, nametable, (ReturnNode) bsn, implicitFlowTupleSet);
1483       break;
1484
1485     case Kind.SubBlockNode:
1486       analyzeFlowSubBlockNode(md, nametable, (SubBlockNode) bsn, implicitFlowTupleSet);
1487       break;
1488
1489     case Kind.ContinueBreakNode:
1490       break;
1491
1492     case Kind.SwitchStatementNode:
1493       analyzeSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
1494       break;
1495
1496     }
1497
1498   }
1499
1500   private void analyzeSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
1501       SwitchStatementNode bsn) {
1502     // TODO Auto-generated method stub
1503   }
1504
1505   private void analyzeFlowSubBlockNode(MethodDescriptor md, SymbolTable nametable,
1506       SubBlockNode sbn, NodeTupleSet implicitFlowTupleSet) {
1507     analyzeFlowBlockNode(md, nametable, sbn.getBlockNode(), implicitFlowTupleSet);
1508   }
1509
1510   private void analyzeFlowReturnNode(MethodDescriptor md, SymbolTable nametable, ReturnNode rn,
1511       NodeTupleSet implicitFlowTupleSet) {
1512
1513     ExpressionNode returnExp = rn.getReturnExpression();
1514
1515     if (returnExp != null) {
1516       NodeTupleSet nodeSet = new NodeTupleSet();
1517       analyzeFlowExpressionNode(md, nametable, returnExp, nodeSet, false);
1518
1519       FlowGraph fg = getFlowGraph(md);
1520
1521       // annotate the elements of the node set as the return location
1522       for (Iterator iterator = nodeSet.iterator(); iterator.hasNext();) {
1523         NTuple<Descriptor> returnDescTuple = (NTuple<Descriptor>) iterator.next();
1524         fg.setReturnFlowNode(returnDescTuple);
1525         for (Iterator iterator2 = implicitFlowTupleSet.iterator(); iterator2.hasNext();) {
1526           NTuple<Descriptor> implicitFlowDescTuple = (NTuple<Descriptor>) iterator2.next();
1527           fg.addValueFlowEdge(implicitFlowDescTuple, returnDescTuple);
1528         }
1529       }
1530     }
1531
1532   }
1533
1534   private void analyzeFlowLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln,
1535       NodeTupleSet implicitFlowTupleSet) {
1536
1537     if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
1538
1539       NodeTupleSet condTupleNode = new NodeTupleSet();
1540       analyzeFlowExpressionNode(md, nametable, ln.getCondition(), condTupleNode, null,
1541           implicitFlowTupleSet, false);
1542       condTupleNode.addTupleSet(implicitFlowTupleSet);
1543
1544       // add edges from condNodeTupleSet to all nodes of conditional nodes
1545       analyzeFlowBlockNode(md, nametable, ln.getBody(), condTupleNode);
1546
1547     } else {
1548       // check 'for loop' case
1549       BlockNode bn = ln.getInitializer();
1550       bn.getVarTable().setParent(nametable);
1551       for (int i = 0; i < bn.size(); i++) {
1552         BlockStatementNode bsn = bn.get(i);
1553         analyzeBlockStatementNode(md, bn.getVarTable(), bsn, implicitFlowTupleSet);
1554       }
1555
1556       NodeTupleSet condTupleNode = new NodeTupleSet();
1557       analyzeFlowExpressionNode(md, bn.getVarTable(), ln.getCondition(), condTupleNode, null,
1558           implicitFlowTupleSet, false);
1559       condTupleNode.addTupleSet(implicitFlowTupleSet);
1560
1561       analyzeFlowBlockNode(md, bn.getVarTable(), ln.getUpdate(), condTupleNode);
1562       analyzeFlowBlockNode(md, bn.getVarTable(), ln.getBody(), condTupleNode);
1563
1564     }
1565
1566   }
1567
1568   private void analyzeFlowIfStatementNode(MethodDescriptor md, SymbolTable nametable,
1569       IfStatementNode isn, NodeTupleSet implicitFlowTupleSet) {
1570
1571     NodeTupleSet condTupleNode = new NodeTupleSet();
1572     analyzeFlowExpressionNode(md, nametable, isn.getCondition(), condTupleNode, null,
1573         implicitFlowTupleSet, false);
1574
1575     // add edges from condNodeTupleSet to all nodes of conditional nodes
1576     condTupleNode.addTupleSet(implicitFlowTupleSet);
1577     analyzeFlowBlockNode(md, nametable, isn.getTrueBlock(), condTupleNode);
1578
1579     if (isn.getFalseBlock() != null) {
1580       analyzeFlowBlockNode(md, nametable, isn.getFalseBlock(), condTupleNode);
1581     }
1582
1583   }
1584
1585   private void analyzeFlowDeclarationNode(MethodDescriptor md, SymbolTable nametable,
1586       DeclarationNode dn, NodeTupleSet implicitFlowTupleSet) {
1587
1588     VarDescriptor vd = dn.getVarDescriptor();
1589     NTuple<Descriptor> tupleLHS = new NTuple<Descriptor>();
1590     tupleLHS.add(vd);
1591     getFlowGraph(md).createNewFlowNode(tupleLHS);
1592
1593     if (dn.getExpression() != null) {
1594
1595       NodeTupleSet tupleSetRHS = new NodeTupleSet();
1596       analyzeFlowExpressionNode(md, nametable, dn.getExpression(), tupleSetRHS, null,
1597           implicitFlowTupleSet, false);
1598
1599       // add a new flow edge from rhs to lhs
1600       for (Iterator<NTuple<Descriptor>> iter = tupleSetRHS.iterator(); iter.hasNext();) {
1601         NTuple<Descriptor> from = iter.next();
1602         addFlowGraphEdge(md, from, tupleLHS);
1603       }
1604
1605     }
1606
1607   }
1608
1609   private void analyzeBlockExpressionNode(MethodDescriptor md, SymbolTable nametable,
1610       BlockExpressionNode ben, NodeTupleSet implicitFlowTupleSet) {
1611     analyzeFlowExpressionNode(md, nametable, ben.getExpression(), null, null, implicitFlowTupleSet,
1612         false);
1613   }
1614
1615   private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
1616       ExpressionNode en, NodeTupleSet nodeSet, boolean isLHS) {
1617     return analyzeFlowExpressionNode(md, nametable, en, nodeSet, null, new NodeTupleSet(), isLHS);
1618   }
1619
1620   private NTuple<Descriptor> analyzeFlowExpressionNode(MethodDescriptor md, SymbolTable nametable,
1621       ExpressionNode en, NodeTupleSet nodeSet, NTuple<Descriptor> base,
1622       NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
1623
1624     // note that expression node can create more than one flow node
1625     // nodeSet contains of flow nodes
1626     // base is always assigned to null except the case of a name node!
1627
1628     NTuple<Descriptor> flowTuple;
1629
1630     switch (en.kind()) {
1631
1632     case Kind.AssignmentNode:
1633       analyzeFlowAssignmentNode(md, nametable, (AssignmentNode) en, nodeSet, base,
1634           implicitFlowTupleSet);
1635       break;
1636
1637     case Kind.FieldAccessNode:
1638       flowTuple =
1639           analyzeFlowFieldAccessNode(md, nametable, (FieldAccessNode) en, nodeSet, base,
1640               implicitFlowTupleSet, isLHS);
1641       if (flowTuple != null) {
1642         nodeSet.addTuple(flowTuple);
1643       }
1644       return flowTuple;
1645
1646     case Kind.NameNode:
1647       NodeTupleSet nameNodeSet = new NodeTupleSet();
1648       flowTuple =
1649           analyzeFlowNameNode(md, nametable, (NameNode) en, nameNodeSet, base, implicitFlowTupleSet);
1650       if (flowTuple != null) {
1651         nodeSet.addTuple(flowTuple);
1652       }
1653       return flowTuple;
1654
1655     case Kind.OpNode:
1656       analyzeFlowOpNode(md, nametable, (OpNode) en, nodeSet, implicitFlowTupleSet);
1657       break;
1658
1659     case Kind.CreateObjectNode:
1660       analyzeCreateObjectNode(md, nametable, (CreateObjectNode) en);
1661       break;
1662
1663     case Kind.ArrayAccessNode:
1664       analyzeFlowArrayAccessNode(md, nametable, (ArrayAccessNode) en, nodeSet, isLHS);
1665       break;
1666
1667     case Kind.LiteralNode:
1668       analyzeLiteralNode(md, nametable, (LiteralNode) en);
1669       break;
1670
1671     case Kind.MethodInvokeNode:
1672       analyzeFlowMethodInvokeNode(md, nametable, (MethodInvokeNode) en, implicitFlowTupleSet);
1673       break;
1674
1675     case Kind.TertiaryNode:
1676       analyzeFlowTertiaryNode(md, nametable, (TertiaryNode) en, nodeSet, implicitFlowTupleSet);
1677       break;
1678
1679     case Kind.CastNode:
1680       analyzeFlowCastNode(md, nametable, (CastNode) en, nodeSet, base, implicitFlowTupleSet);
1681       break;
1682     // case Kind.InstanceOfNode:
1683     // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
1684     // return null;
1685
1686     // case Kind.ArrayInitializerNode:
1687     // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
1688     // td);
1689     // return null;
1690
1691     // case Kind.ClassTypeNode:
1692     // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
1693     // return null;
1694
1695     // case Kind.OffsetNode:
1696     // checkOffsetNode(md, nametable, (OffsetNode)en, td);
1697     // return null;
1698
1699     }
1700     return null;
1701
1702   }
1703
1704   private void analyzeFlowCastNode(MethodDescriptor md, SymbolTable nametable, CastNode cn,
1705       NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
1706
1707     analyzeFlowExpressionNode(md, nametable, cn.getExpression(), nodeSet, base,
1708         implicitFlowTupleSet, false);
1709
1710   }
1711
1712   private void analyzeFlowTertiaryNode(MethodDescriptor md, SymbolTable nametable, TertiaryNode tn,
1713       NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
1714
1715     NodeTupleSet tertiaryTupleNode = new NodeTupleSet();
1716     analyzeFlowExpressionNode(md, nametable, tn.getCond(), tertiaryTupleNode, null,
1717         implicitFlowTupleSet, false);
1718
1719     // add edges from tertiaryTupleNode to all nodes of conditional nodes
1720     tertiaryTupleNode.addTupleSet(implicitFlowTupleSet);
1721     analyzeFlowExpressionNode(md, nametable, tn.getTrueExpr(), tertiaryTupleNode, null,
1722         implicitFlowTupleSet, false);
1723
1724     analyzeFlowExpressionNode(md, nametable, tn.getFalseExpr(), tertiaryTupleNode, null,
1725         implicitFlowTupleSet, false);
1726
1727     nodeSet.addTupleSet(tertiaryTupleNode);
1728
1729   }
1730
1731   private void addMapCallerMethodDescToMethodInvokeNodeSet(MethodDescriptor caller,
1732       MethodInvokeNode min) {
1733     Set<MethodInvokeNode> set = mapMethodDescriptorToMethodInvokeNodeSet.get(caller);
1734     if (set == null) {
1735       set = new HashSet<MethodInvokeNode>();
1736       mapMethodDescriptorToMethodInvokeNodeSet.put(caller, set);
1737     }
1738     set.add(min);
1739   }
1740
1741   private void analyzeFlowMethodInvokeNode(MethodDescriptor md, SymbolTable nametable,
1742       MethodInvokeNode min, NodeTupleSet implicitFlowTupleSet) {
1743
1744     addMapCallerMethodDescToMethodInvokeNodeSet(md, min);
1745
1746     MethodDescriptor calleeMD = min.getMethod();
1747
1748     NameDescriptor baseName = min.getBaseName();
1749     boolean isSystemout = false;
1750     if (baseName != null) {
1751       isSystemout = baseName.getSymbol().equals("System.out");
1752     }
1753
1754     if (!ssjava.isSSJavaUtil(calleeMD.getClassDesc()) && !ssjava.isTrustMethod(calleeMD)
1755         && !calleeMD.getModifiers().isNative() && !isSystemout) {
1756
1757       // CompositeLocation baseLocation = null;
1758       if (min.getExpression() != null) {
1759
1760         NodeTupleSet baseNodeSet = new NodeTupleSet();
1761         analyzeFlowExpressionNode(md, nametable, min.getExpression(), baseNodeSet, null,
1762             implicitFlowTupleSet, false);
1763
1764       } else {
1765         if (min.getMethod().isStatic()) {
1766           // String globalLocId = ssjava.getMethodLattice(md).getGlobalLoc();
1767           // if (globalLocId == null) {
1768           // throw new
1769           // Error("Method lattice does not define global variable location at "
1770           // + generateErrorMessage(md.getClassDesc(), min));
1771           // }
1772           // baseLocation = new CompositeLocation(new Location(md,
1773           // globalLocId));
1774         } else {
1775           // 'this' var case
1776           // String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
1777           // baseLocation = new CompositeLocation(new Location(md, thisLocId));
1778         }
1779       }
1780
1781       // constraint case:
1782       // if (constraint != null) {
1783       // int compareResult =
1784       // CompositeLattice.compare(constraint, baseLocation, true,
1785       // generateErrorMessage(cd, min));
1786       // if (compareResult != ComparisonResult.GREATER) {
1787       // // if the current constraint is higher than method's THIS location
1788       // // no need to check constraints!
1789       // CompositeLocation calleeConstraint =
1790       // translateCallerLocToCalleeLoc(calleeMD, baseLocation, constraint);
1791       // // System.out.println("check method body for constraint:" + calleeMD +
1792       // // " calleeConstraint="
1793       // // + calleeConstraint);
1794       // checkMethodBody(calleeMD.getClassDesc(), calleeMD, calleeConstraint);
1795       // }
1796       // }
1797
1798       analyzeFlowMethodParameters(md, nametable, min);
1799
1800       // checkCalleeConstraints(md, nametable, min, baseLocation, constraint);
1801
1802       // checkCallerArgumentLocationConstraints(md, nametable, min,
1803       // baseLocation, constraint);
1804
1805       if (min.getMethod().getReturnType() != null && !min.getMethod().getReturnType().isVoid()) {
1806         // If method has a return value, compute the highest possible return
1807         // location in the caller's perspective
1808         // CompositeLocation ceilingLoc =
1809         // computeCeilingLocationForCaller(md, nametable, min, baseLocation,
1810         // constraint);
1811         // return ceilingLoc;
1812       }
1813     }
1814
1815     // return new CompositeLocation(Location.createTopLocation(md));
1816
1817   }
1818
1819   private NodeTupleSet getNodeTupleSetByArgIdx(MethodInvokeNode min, int idx) {
1820     return mapMethodInvokeNodeToArgIdxMap.get(min).get(new Integer(idx));
1821   }
1822
1823   private void addArgIdxMap(MethodInvokeNode min, int idx, NodeTupleSet tupleSet) {
1824     Map<Integer, NodeTupleSet> mapIdxToTupleSet = mapMethodInvokeNodeToArgIdxMap.get(min);
1825     if (mapIdxToTupleSet == null) {
1826       mapIdxToTupleSet = new HashMap<Integer, NodeTupleSet>();
1827       mapMethodInvokeNodeToArgIdxMap.put(min, mapIdxToTupleSet);
1828     }
1829     mapIdxToTupleSet.put(new Integer(idx), tupleSet);
1830   }
1831
1832   private void analyzeFlowMethodParameters(MethodDescriptor callermd, SymbolTable nametable,
1833       MethodInvokeNode min) {
1834
1835     if (min.numArgs() > 0) {
1836
1837       int offset;
1838       if (min.getMethod().isStatic()) {
1839         offset = 0;
1840       } else {
1841         offset = 1;
1842         NTuple<Descriptor> thisArgTuple = new NTuple<Descriptor>();
1843         thisArgTuple.add(callermd.getThis());
1844         NodeTupleSet argTupleSet = new NodeTupleSet();
1845         argTupleSet.addTuple(thisArgTuple);
1846         addArgIdxMap(min, 0, argTupleSet);
1847       }
1848
1849       for (int i = 0; i < min.numArgs(); i++) {
1850         ExpressionNode en = min.getArg(i);
1851         NodeTupleSet argTupleSet = new NodeTupleSet();
1852         analyzeFlowExpressionNode(callermd, nametable, en, argTupleSet, false);
1853         // if argument is liternal node, argTuple is set to NULL.
1854         addArgIdxMap(min, i + offset, argTupleSet);
1855       }
1856
1857     }
1858
1859   }
1860
1861   private void analyzeLiteralNode(MethodDescriptor md, SymbolTable nametable, LiteralNode en) {
1862
1863   }
1864
1865   private void analyzeFlowArrayAccessNode(MethodDescriptor md, SymbolTable nametable,
1866       ArrayAccessNode aan, NodeTupleSet nodeSet, boolean isLHS) {
1867
1868     NodeTupleSet expNodeTupleSet = new NodeTupleSet();
1869     analyzeFlowExpressionNode(md, nametable, aan.getExpression(), expNodeTupleSet, isLHS);
1870
1871     NodeTupleSet idxNodeTupleSet = new NodeTupleSet();
1872     analyzeFlowExpressionNode(md, nametable, aan.getIndex(), idxNodeTupleSet, isLHS);
1873
1874     if (isLHS) {
1875       // need to create an edge from idx to array
1876
1877       for (Iterator<NTuple<Descriptor>> idxIter = idxNodeTupleSet.iterator(); idxIter.hasNext();) {
1878         NTuple<Descriptor> idxTuple = idxIter.next();
1879         for (Iterator<NTuple<Descriptor>> arrIter = expNodeTupleSet.iterator(); arrIter.hasNext();) {
1880           NTuple<Descriptor> arrTuple = arrIter.next();
1881           getFlowGraph(md).addValueFlowEdge(idxTuple, arrTuple);
1882         }
1883       }
1884
1885       nodeSet.addTupleSet(expNodeTupleSet);
1886     } else {
1887       nodeSet.addTupleSet(expNodeTupleSet);
1888       nodeSet.addTupleSet(idxNodeTupleSet);
1889     }
1890   }
1891
1892   private void analyzeCreateObjectNode(MethodDescriptor md, SymbolTable nametable,
1893       CreateObjectNode en) {
1894     // TODO Auto-generated method stub
1895
1896   }
1897
1898   private void analyzeFlowOpNode(MethodDescriptor md, SymbolTable nametable, OpNode on,
1899       NodeTupleSet nodeSet, NodeTupleSet implicitFlowTupleSet) {
1900
1901     NodeTupleSet leftOpSet = new NodeTupleSet();
1902     NodeTupleSet rightOpSet = new NodeTupleSet();
1903
1904     // left operand
1905     analyzeFlowExpressionNode(md, nametable, on.getLeft(), leftOpSet, null, implicitFlowTupleSet,
1906         false);
1907
1908     if (on.getRight() != null) {
1909       // right operand
1910       analyzeFlowExpressionNode(md, nametable, on.getRight(), rightOpSet, null,
1911           implicitFlowTupleSet, false);
1912     }
1913
1914     Operation op = on.getOp();
1915
1916     switch (op.getOp()) {
1917
1918     case Operation.UNARYPLUS:
1919     case Operation.UNARYMINUS:
1920     case Operation.LOGIC_NOT:
1921       // single operand
1922       nodeSet.addTupleSet(leftOpSet);
1923       break;
1924
1925     case Operation.LOGIC_OR:
1926     case Operation.LOGIC_AND:
1927     case Operation.COMP:
1928     case Operation.BIT_OR:
1929     case Operation.BIT_XOR:
1930     case Operation.BIT_AND:
1931     case Operation.ISAVAILABLE:
1932     case Operation.EQUAL:
1933     case Operation.NOTEQUAL:
1934     case Operation.LT:
1935     case Operation.GT:
1936     case Operation.LTE:
1937     case Operation.GTE:
1938     case Operation.ADD:
1939     case Operation.SUB:
1940     case Operation.MULT:
1941     case Operation.DIV:
1942     case Operation.MOD:
1943     case Operation.LEFTSHIFT:
1944     case Operation.RIGHTSHIFT:
1945     case Operation.URIGHTSHIFT:
1946
1947       // there are two operands
1948       nodeSet.addTupleSet(leftOpSet);
1949       nodeSet.addTupleSet(rightOpSet);
1950       break;
1951
1952     default:
1953       throw new Error(op.toString());
1954     }
1955
1956   }
1957
1958   private NTuple<Descriptor> analyzeFlowNameNode(MethodDescriptor md, SymbolTable nametable,
1959       NameNode nn, NodeTupleSet nodeSet, NTuple<Descriptor> base, NodeTupleSet implicitFlowTupleSet) {
1960
1961     if (base == null) {
1962       base = new NTuple<Descriptor>();
1963     }
1964
1965     NameDescriptor nd = nn.getName();
1966
1967     if (nd.getBase() != null) {
1968       base =
1969           analyzeFlowExpressionNode(md, nametable, nn.getExpression(), nodeSet, base,
1970               implicitFlowTupleSet, false);
1971       if (base == null) {
1972         // base node has the top location
1973         return base;
1974       }
1975     } else {
1976       String varname = nd.toString();
1977       if (varname.equals("this")) {
1978         // 'this' itself!
1979         base.add(md.getThis());
1980         return base;
1981       }
1982
1983       Descriptor d = (Descriptor) nametable.get(varname);
1984
1985       if (d instanceof VarDescriptor) {
1986         VarDescriptor vd = (VarDescriptor) d;
1987         base.add(vd);
1988       } else if (d instanceof FieldDescriptor) {
1989         // the type of field descriptor has a location!
1990         FieldDescriptor fd = (FieldDescriptor) d;
1991         if (fd.isStatic()) {
1992           if (fd.isFinal()) {
1993             // if it is 'static final', no need to have flow node for the TOP
1994             // location
1995             return null;
1996           } else {
1997             // if 'static', assign the default GLOBAL LOCATION to the first
1998             // element of the tuple
1999             base.add(GLOBALDESC);
2000           }
2001         } else {
2002           // the location of field access starts from this, followed by field
2003           // location
2004           base.add(md.getThis());
2005         }
2006
2007         base.add(fd);
2008       } else if (d == null) {
2009         // access static field
2010         base.add(GLOBALDESC);
2011         // base.add(nn.getField());
2012         return base;
2013
2014         // FieldDescriptor fd = nn.getField();addFlowGraphEdge
2015         //
2016         // MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
2017         // String globalLocId = localLattice.getGlobalLoc();
2018         // if (globalLocId == null) {
2019         // throw new
2020         // Error("Method lattice does not define global variable location at "
2021         // + generateErrorMessage(md.getClassDesc(), nn));
2022         // }
2023         // loc.addLocation(new Location(md, globalLocId));
2024         //
2025         // Location fieldLoc = (Location) fd.getType().getExtension();
2026         // loc.addLocation(fieldLoc);
2027         //
2028         // return loc;
2029
2030       }
2031     }
2032
2033     getFlowGraph(md).createNewFlowNode(base);
2034
2035     return base;
2036
2037   }
2038
2039   private NTuple<Descriptor> analyzeFlowFieldAccessNode(MethodDescriptor md, SymbolTable nametable,
2040       FieldAccessNode fan, NodeTupleSet nodeSet, NTuple<Descriptor> base,
2041       NodeTupleSet implicitFlowTupleSet, boolean isLHS) {
2042
2043     ExpressionNode left = fan.getExpression();
2044     TypeDescriptor ltd = left.getType();
2045     FieldDescriptor fd = fan.getField();
2046
2047     String varName = null;
2048     if (left.kind() == Kind.NameNode) {
2049       NameDescriptor nd = ((NameNode) left).getName();
2050       varName = nd.toString();
2051     }
2052
2053     if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
2054       // using a class name directly or access using this
2055       if (fd.isStatic() && fd.isFinal()) {
2056         return null;
2057       }
2058     }
2059
2060     if (left instanceof ArrayAccessNode) {
2061
2062       ArrayAccessNode aan = (ArrayAccessNode) left;
2063       left = aan.getExpression();
2064       analyzeFlowExpressionNode(md, nametable, aan.getIndex(), nodeSet, base, implicitFlowTupleSet,
2065           isLHS);
2066     }
2067     // fanNodeSet
2068     base =
2069         analyzeFlowExpressionNode(md, nametable, left, nodeSet, base, implicitFlowTupleSet, isLHS);
2070     if (base == null) {
2071       // in this case, field is TOP location
2072       return null;
2073     } else {
2074
2075       if (!left.getType().isPrimitive()) {
2076
2077         if (!fd.getSymbol().equals("length")) {
2078           // array.length access, just have the location of the array
2079           base.add(fd);
2080         }
2081
2082       }
2083
2084       getFlowGraph(md).createNewFlowNode(base);
2085       return base;
2086
2087     }
2088
2089   }
2090
2091   private void debug_printTreeNode(TreeNode tn) {
2092
2093     System.out.println("DEBUG: " + tn.printNode(0) + "                line#=" + tn.getNumLine());
2094
2095   }
2096
2097   private void analyzeFlowAssignmentNode(MethodDescriptor md, SymbolTable nametable,
2098       AssignmentNode an, NodeTupleSet nodeSet, NTuple<Descriptor> base,
2099       NodeTupleSet implicitFlowTupleSet) {
2100
2101     NodeTupleSet nodeSetRHS = new NodeTupleSet();
2102     NodeTupleSet nodeSetLHS = new NodeTupleSet();
2103
2104     boolean postinc = true;
2105     if (an.getOperation().getBaseOp() == null
2106         || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
2107             .getBaseOp().getOp() != Operation.POSTDEC)) {
2108       postinc = false;
2109     }
2110     // if LHS is array access node, need to capture value flows between an array
2111     // and its index value
2112     analyzeFlowExpressionNode(md, nametable, an.getDest(), nodeSetLHS, null, implicitFlowTupleSet,
2113         true);
2114
2115     if (!postinc) {
2116       // analyze value flows of rhs expression
2117       analyzeFlowExpressionNode(md, nametable, an.getSrc(), nodeSetRHS, null, implicitFlowTupleSet,
2118           false);
2119
2120       // System.out.println("-analyzeFlowAssignmentNode=" + an.printNode(0));
2121       // System.out.println("-nodeSetLHS=" + nodeSetLHS);
2122       // System.out.println("-nodeSetRHS=" + nodeSetRHS);
2123       // System.out.println("-implicitFlowTupleSet=" + implicitFlowTupleSet);
2124       // System.out.println("-");
2125
2126       if (an.getOperation().getOp() >= 2 && an.getOperation().getOp() <= 12) {
2127         // if assignment contains OP+EQ operator, creates edges from LHS to LHS
2128         for (Iterator<NTuple<Descriptor>> iter = nodeSetLHS.iterator(); iter.hasNext();) {
2129           NTuple<Descriptor> fromTuple = iter.next();
2130           for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
2131             NTuple<Descriptor> toTuple = iter2.next();
2132             addFlowGraphEdge(md, fromTuple, toTuple);
2133           }
2134         }
2135       }
2136
2137       // creates edges from RHS to LHS
2138       for (Iterator<NTuple<Descriptor>> iter = nodeSetRHS.iterator(); iter.hasNext();) {
2139         NTuple<Descriptor> fromTuple = iter.next();
2140         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
2141           NTuple<Descriptor> toTuple = iter2.next();
2142           addFlowGraphEdge(md, fromTuple, toTuple);
2143         }
2144       }
2145
2146       // creates edges from implicitFlowTupleSet to LHS
2147       for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
2148         NTuple<Descriptor> fromTuple = iter.next();
2149         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
2150           NTuple<Descriptor> toTuple = iter2.next();
2151           addFlowGraphEdge(md, fromTuple, toTuple);
2152         }
2153       }
2154
2155     } else {
2156       // postinc case
2157       for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
2158         NTuple<Descriptor> tuple = iter2.next();
2159         addFlowGraphEdge(md, tuple, tuple);
2160       }
2161
2162       // creates edges from implicitFlowTupleSet to LHS
2163       for (Iterator<NTuple<Descriptor>> iter = implicitFlowTupleSet.iterator(); iter.hasNext();) {
2164         NTuple<Descriptor> fromTuple = iter.next();
2165         for (Iterator<NTuple<Descriptor>> iter2 = nodeSetLHS.iterator(); iter2.hasNext();) {
2166           NTuple<Descriptor> toTuple = iter2.next();
2167           addFlowGraphEdge(md, fromTuple, toTuple);
2168         }
2169       }
2170
2171     }
2172
2173     if (nodeSet != null) {
2174       nodeSet.addTupleSet(nodeSetLHS);
2175     }
2176   }
2177
2178   public FlowGraph getFlowGraph(MethodDescriptor md) {
2179     return mapMethodDescriptorToFlowGraph.get(md);
2180   }
2181
2182   private boolean addFlowGraphEdge(MethodDescriptor md, NTuple<Descriptor> from,
2183       NTuple<Descriptor> to) {
2184     // TODO
2185     // return true if it adds a new edge
2186     FlowGraph graph = getFlowGraph(md);
2187     graph.addValueFlowEdge(from, to);
2188     return true;
2189   }
2190
2191   public void _debug_printGraph() {
2192     Set<MethodDescriptor> keySet = mapMethodDescriptorToFlowGraph.keySet();
2193
2194     for (Iterator<MethodDescriptor> iterator = keySet.iterator(); iterator.hasNext();) {
2195       MethodDescriptor md = (MethodDescriptor) iterator.next();
2196       FlowGraph fg = mapMethodDescriptorToFlowGraph.get(md);
2197       try {
2198         fg.writeGraph();
2199       } catch (IOException e) {
2200         e.printStackTrace();
2201       }
2202     }
2203
2204   }
2205
2206 }
2207
2208 class CyclicFlowException extends Exception {
2209
2210 }