changes.
[IRC.git] / Robust / src / Analysis / SSJava / FlowDownCheck.java
1 package Analysis.SSJava;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.Comparator;
6 import java.util.HashSet;
7 import java.util.Hashtable;
8 import java.util.Iterator;
9 import java.util.List;
10 import java.util.Set;
11 import java.util.StringTokenizer;
12 import java.util.Vector;
13
14 import Analysis.SSJava.FlowDownCheck.ComparisonResult;
15 import Analysis.SSJava.FlowDownCheck.CompositeLattice;
16 import IR.AnnotationDescriptor;
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.SwitchBlockNode;
47 import IR.Tree.SwitchStatementNode;
48 import IR.Tree.SynchronizedNode;
49 import IR.Tree.TertiaryNode;
50 import IR.Tree.TreeNode;
51 import Util.Pair;
52
53 public class FlowDownCheck {
54
55   State state;
56   static SSJavaAnalysis ssjava;
57
58   Set<ClassDescriptor> toanalyze;
59   List<ClassDescriptor> toanalyzeList;
60
61   Set<MethodDescriptor> toanalyzeMethod;
62   List<MethodDescriptor> toanalyzeMethodList;
63
64   // mapping from 'descriptor' to 'composite location'
65   Hashtable<Descriptor, CompositeLocation> d2loc;
66
67   Hashtable<MethodDescriptor, CompositeLocation> md2ReturnLoc;
68   Hashtable<MethodDescriptor, ReturnLocGenerator> md2ReturnLocGen;
69
70   // mapping from 'locID' to 'class descriptor'
71   Hashtable<String, ClassDescriptor> fieldLocName2cd;
72
73   boolean deterministic = true;
74
75   public FlowDownCheck(SSJavaAnalysis ssjava, State state) {
76     this.ssjava = ssjava;
77     this.state = state;
78     if (deterministic) {
79       this.toanalyzeList = new ArrayList<ClassDescriptor>();
80     } else {
81       this.toanalyze = new HashSet<ClassDescriptor>();
82     }
83     if (deterministic) {
84       this.toanalyzeMethodList = new ArrayList<MethodDescriptor>();
85     } else {
86       this.toanalyzeMethod = new HashSet<MethodDescriptor>();
87     }
88     this.d2loc = new Hashtable<Descriptor, CompositeLocation>();
89     this.fieldLocName2cd = new Hashtable<String, ClassDescriptor>();
90     this.md2ReturnLoc = new Hashtable<MethodDescriptor, CompositeLocation>();
91     this.md2ReturnLocGen = new Hashtable<MethodDescriptor, ReturnLocGenerator>();
92   }
93
94   public void init() {
95
96     // construct mapping from the location name to the class descriptor
97     // assume that the location name is unique through the whole program
98
99     Set<ClassDescriptor> cdSet = ssjava.getCd2lattice().keySet();
100     for (Iterator iterator = cdSet.iterator(); iterator.hasNext();) {
101       ClassDescriptor cd = (ClassDescriptor) iterator.next();
102       SSJavaLattice<String> lattice = ssjava.getCd2lattice().get(cd);
103       Set<String> fieldLocNameSet = lattice.getKeySet();
104
105       for (Iterator iterator2 = fieldLocNameSet.iterator(); iterator2.hasNext();) {
106         String fieldLocName = (String) iterator2.next();
107         fieldLocName2cd.put(fieldLocName, cd);
108       }
109
110     }
111
112   }
113
114   public boolean toAnalyzeIsEmpty() {
115     if (deterministic) {
116       return toanalyzeList.isEmpty();
117     } else {
118       return toanalyze.isEmpty();
119     }
120   }
121
122   public ClassDescriptor toAnalyzeNext() {
123     if (deterministic) {
124       return toanalyzeList.remove(0);
125     } else {
126       ClassDescriptor cd = toanalyze.iterator().next();
127       toanalyze.remove(cd);
128       return cd;
129     }
130   }
131
132   public void setupToAnalyze() {
133     SymbolTable classtable = state.getClassSymbolTable();
134     if (deterministic) {
135       toanalyzeList.clear();
136       toanalyzeList.addAll(classtable.getValueSet());
137       Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
138         public int compare(ClassDescriptor o1, ClassDescriptor o2) {
139           return o1.getClassName().compareTo(o2.getClassName());
140         }
141       });
142     } else {
143       toanalyze.clear();
144       toanalyze.addAll(classtable.getValueSet());
145     }
146   }
147
148   public void setupToAnalazeMethod(ClassDescriptor cd) {
149
150     SymbolTable methodtable = cd.getMethodTable();
151     if (deterministic) {
152       toanalyzeMethodList.clear();
153       toanalyzeMethodList.addAll(methodtable.getValueSet());
154       Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
155         public int compare(MethodDescriptor o1, MethodDescriptor o2) {
156           return o1.getSymbol().compareTo(o2.getSymbol());
157         }
158       });
159     } else {
160       toanalyzeMethod.clear();
161       toanalyzeMethod.addAll(methodtable.getValueSet());
162     }
163   }
164
165   public boolean toAnalyzeMethodIsEmpty() {
166     if (deterministic) {
167       return toanalyzeMethodList.isEmpty();
168     } else {
169       return toanalyzeMethod.isEmpty();
170     }
171   }
172
173   public MethodDescriptor toAnalyzeMethodNext() {
174     if (deterministic) {
175       return toanalyzeMethodList.remove(0);
176     } else {
177       MethodDescriptor md = toanalyzeMethod.iterator().next();
178       toanalyzeMethod.remove(md);
179       return md;
180     }
181   }
182
183   public void flowDownCheck() {
184
185     // phase 1 : checking declaration node and creating mapping of 'type
186     // desciptor' & 'location'
187     setupToAnalyze();
188
189     while (!toAnalyzeIsEmpty()) {
190       ClassDescriptor cd = toAnalyzeNext();
191
192       if (ssjava.needToBeAnnoated(cd)) {
193
194         ClassDescriptor superDesc = cd.getSuperDesc();
195
196         if (superDesc != null && (!superDesc.getSymbol().equals("Object"))) {
197           checkOrderingInheritance(superDesc, cd);
198         }
199
200         checkDeclarationInClass(cd);
201
202         setupToAnalazeMethod(cd);
203         while (!toAnalyzeMethodIsEmpty()) {
204           MethodDescriptor md = toAnalyzeMethodNext();
205           if (ssjava.needTobeAnnotated(md)) {
206             checkDeclarationInMethodBody(cd, md);
207           }
208         }
209
210       }
211
212     }
213
214     // phase2 : checking assignments
215     setupToAnalyze();
216
217     while (!toAnalyzeIsEmpty()) {
218       ClassDescriptor cd = toAnalyzeNext();
219
220       setupToAnalazeMethod(cd);
221       while (!toAnalyzeMethodIsEmpty()) {
222         MethodDescriptor md = toAnalyzeMethodNext();
223         if (ssjava.needTobeAnnotated(md)) {
224           System.out.println("SSJAVA: Checking assignments: " + md);
225           checkMethodBody(cd, md);
226         }
227       }
228     }
229
230   }
231
232   private void checkOrderingInheritance(ClassDescriptor superCd, ClassDescriptor cd) {
233     // here, we're going to check that sub class keeps same relative orderings
234     // in respect to super class
235
236     SSJavaLattice<String> superLattice = ssjava.getClassLattice(superCd);
237     SSJavaLattice<String> subLattice = ssjava.getClassLattice(cd);
238
239     if (superLattice != null) {
240       // if super class doesn't define lattice, then we don't need to check its
241       // subclass
242       if (subLattice == null) {
243         throw new Error("If a parent class '" + superCd
244             + "' has a ordering lattice, its subclass '" + cd + "' should have one.");
245       }
246
247       Set<Pair<String, String>> superPairSet = superLattice.getOrderingPairSet();
248       Set<Pair<String, String>> subPairSet = subLattice.getOrderingPairSet();
249
250       for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
251         Pair<String, String> pair = (Pair<String, String>) iterator.next();
252
253         if (!subPairSet.contains(pair)) {
254           throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
255               + pair.getSecond() + " < " + pair.getFirst()
256               + "' that is defined by its superclass '" + superCd + "'.");
257         }
258       }
259     }
260
261     MethodLattice<String> superMethodDefaultLattice = ssjava.getMethodDefaultLattice(superCd);
262     MethodLattice<String> subMethodDefaultLattice = ssjava.getMethodDefaultLattice(cd);
263
264     if (superMethodDefaultLattice != null) {
265       if (subMethodDefaultLattice == null) {
266         throw new Error("When a parent class '" + superCd
267             + "' defines a default method lattice, its subclass '" + cd + "' should define one.");
268       }
269
270       Set<Pair<String, String>> superPairSet = superMethodDefaultLattice.getOrderingPairSet();
271       Set<Pair<String, String>> subPairSet = subMethodDefaultLattice.getOrderingPairSet();
272
273       for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
274         Pair<String, String> pair = (Pair<String, String>) iterator.next();
275
276         if (!subPairSet.contains(pair)) {
277           throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
278               + pair.getSecond() + " < " + pair.getFirst()
279               + "' that is defined by its superclass '" + superCd
280               + "' in the method default lattice.");
281         }
282       }
283
284     }
285
286   }
287
288   public Hashtable getMap() {
289     return d2loc;
290   }
291
292   private void checkDeclarationInMethodBody(ClassDescriptor cd, MethodDescriptor md) {
293     BlockNode bn = state.getMethodBody(md);
294
295     // first, check annotations on method parameters
296     List<CompositeLocation> paramList = new ArrayList<CompositeLocation>();
297     for (int i = 0; i < md.numParameters(); i++) {
298       // process annotations on method parameters
299       VarDescriptor vd = (VarDescriptor) md.getParameter(i);
300       assignLocationOfVarDescriptor(vd, md, md.getParameterTable(), bn);
301       paramList.add(d2loc.get(vd));
302     }
303     Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
304
305     // second, check return location annotation
306     if (!md.getReturnType().isVoid()) {
307       CompositeLocation returnLocComp = null;
308
309       String rtrStr = ssjava.getMethodLattice(md).getReturnLoc();
310       if (rtrStr != null) {
311         returnLocComp = new CompositeLocation(new Location(md, rtrStr));
312       } else {
313         if (methodAnnotations != null) {
314           for (int i = 0; i < methodAnnotations.size(); i++) {
315             AnnotationDescriptor an = methodAnnotations.elementAt(i);
316             if (an.getMarker().equals(ssjava.RETURNLOC)) {
317               // this case, developer explicitly defines method lattice
318               String returnLocDeclaration = an.getValue();
319               returnLocComp = parseLocationDeclaration(md, null, returnLocDeclaration);
320             }
321           }
322         } else {
323           // if developer does not define method lattice
324           // search return location in the method default lattice
325           if (returnLocComp == null) {
326             MethodLattice<String> methodDefaultLattice = ssjava.getMethodDefaultLattice(cd);
327             if (methodDefaultLattice.getReturnLoc() != null) {
328               returnLocComp =
329                   parseLocationDeclaration(md, null, methodDefaultLattice.getReturnLoc());
330             }
331           }
332         }
333       }
334
335       if (returnLocComp == null) {
336         throw new Error("Return location is not specified for the method " + md + " at "
337             + cd.getSourceFileName());
338       }
339
340       md2ReturnLoc.put(md, returnLocComp);
341
342       // check this location
343       MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
344       String thisLocId = methodLattice.getThisLoc();
345       if (thisLocId == null) {
346         throw new Error("Method '" + md + "' does not have the definition of 'this' location at "
347             + md.getClassDesc().getSourceFileName());
348       }
349       CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
350       paramList.add(0, thisLoc);
351
352       System.out.println("### ReturnLocGenerator=" + md);
353       System.out.println("### md2ReturnLoc.get(md)=" + md2ReturnLoc.get(md));
354       md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), paramList, md + " of "
355           + cd.getSourceFileName()));
356     }
357
358     // fourth, check declarations inside of method
359
360     checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
361
362   }
363
364   private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
365     bn.getVarTable().setParent(nametable);
366     for (int i = 0; i < bn.size(); i++) {
367       BlockStatementNode bsn = bn.get(i);
368       checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
369     }
370   }
371
372   private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
373       BlockStatementNode bsn) {
374
375     switch (bsn.kind()) {
376     case Kind.SubBlockNode:
377       checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
378       return;
379
380     case Kind.DeclarationNode:
381       checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
382       break;
383
384     case Kind.LoopNode:
385       checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
386       break;
387
388     case Kind.IfStatementNode:
389       checkDeclarationInIfStatementNode(md, nametable, (IfStatementNode) bsn);
390       return;
391
392     case Kind.SwitchStatementNode:
393       checkDeclarationInSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
394       return;
395
396     case Kind.SynchronizedNode:
397       checkDeclarationInSynchronizedNode(md, nametable, (SynchronizedNode) bsn);
398       return;
399
400     }
401   }
402
403   private void checkDeclarationInSynchronizedNode(MethodDescriptor md, SymbolTable nametable,
404       SynchronizedNode sbn) {
405     checkDeclarationInBlockNode(md, nametable, sbn.getBlockNode());
406   }
407
408   private void checkDeclarationInSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
409       SwitchStatementNode ssn) {
410     BlockNode sbn = ssn.getSwitchBody();
411     for (int i = 0; i < sbn.size(); i++) {
412       SwitchBlockNode node = (SwitchBlockNode) sbn.get(i);
413       checkDeclarationInBlockNode(md, nametable, node.getSwitchBlockStatement());
414     }
415   }
416
417   private void checkDeclarationInIfStatementNode(MethodDescriptor md, SymbolTable nametable,
418       IfStatementNode isn) {
419     checkDeclarationInBlockNode(md, nametable, isn.getTrueBlock());
420     if (isn.getFalseBlock() != null)
421       checkDeclarationInBlockNode(md, nametable, isn.getFalseBlock());
422   }
423
424   private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
425
426     if (ln.getType() == LoopNode.FORLOOP) {
427       // check for loop case
428       ClassDescriptor cd = md.getClassDesc();
429       BlockNode bn = ln.getInitializer();
430       for (int i = 0; i < bn.size(); i++) {
431         BlockStatementNode bsn = bn.get(i);
432         checkDeclarationInBlockStatementNode(md, nametable, bsn);
433       }
434     }
435
436     // check loop body
437     checkDeclarationInBlockNode(md, nametable, ln.getBody());
438   }
439
440   private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
441     BlockNode bn = state.getMethodBody(md);
442     checkLocationFromBlockNode(md, md.getParameterTable(), bn, null);
443   }
444
445   private String generateErrorMessage(ClassDescriptor cd, TreeNode tn) {
446     if (tn != null) {
447       return cd.getSourceFileName() + "::" + tn.getNumLine();
448     } else {
449       return cd.getSourceFileName();
450     }
451
452   }
453
454   private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
455       BlockNode bn, CompositeLocation constraint) {
456
457     bn.getVarTable().setParent(nametable);
458     for (int i = 0; i < bn.size(); i++) {
459       BlockStatementNode bsn = bn.get(i);
460       checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn, constraint);
461     }
462     return new CompositeLocation();
463
464   }
465
466   private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
467       SymbolTable nametable, BlockStatementNode bsn, CompositeLocation constraint) {
468
469     CompositeLocation compLoc = null;
470     switch (bsn.kind()) {
471     case Kind.BlockExpressionNode:
472       compLoc =
473           checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, constraint);
474       break;
475
476     case Kind.DeclarationNode:
477       compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn, constraint);
478       break;
479
480     case Kind.IfStatementNode:
481       compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn, constraint);
482       break;
483
484     case Kind.LoopNode:
485       compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn, constraint);
486       break;
487
488     case Kind.ReturnNode:
489       compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn, constraint);
490       break;
491
492     case Kind.SubBlockNode:
493       compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn, constraint);
494       break;
495
496     case Kind.ContinueBreakNode:
497       compLoc = new CompositeLocation();
498       break;
499
500     case Kind.SwitchStatementNode:
501       compLoc =
502           checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, constraint);
503
504     }
505     return compLoc;
506   }
507
508   private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
509       SymbolTable nametable, SwitchStatementNode ssn, CompositeLocation constraint) {
510
511     ClassDescriptor cd = md.getClassDesc();
512     CompositeLocation condLoc =
513         checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation(),
514             constraint, false);
515     BlockNode sbn = ssn.getSwitchBody();
516
517     constraint = generateNewConstraint(constraint, condLoc);
518
519     for (int i = 0; i < sbn.size(); i++) {
520       checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), constraint);
521     }
522     return new CompositeLocation();
523   }
524
525   private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
526       SymbolTable nametable, SwitchBlockNode sbn, CompositeLocation constraint) {
527
528     CompositeLocation blockLoc =
529         checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement(), constraint);
530
531     return blockLoc;
532
533   }
534
535   private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
536       ReturnNode rn, CompositeLocation constraint) {
537
538     ExpressionNode returnExp = rn.getReturnExpression();
539
540     CompositeLocation returnValueLoc;
541     if (returnExp != null) {
542       returnValueLoc =
543           checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation(),
544               constraint, false);
545
546       // if this return statement is inside branch, return value has an implicit
547       // flow from conditional location
548       if (constraint != null) {
549         Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
550         inputGLB.add(returnValueLoc);
551         inputGLB.add(constraint);
552         returnValueLoc =
553             CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(md.getClassDesc(), rn));
554       }
555
556       // check if return value is equal or higher than RETRUNLOC of method
557       // declaration annotation
558       CompositeLocation declaredReturnLoc = md2ReturnLoc.get(md);
559
560       int compareResult =
561           CompositeLattice.compare(returnValueLoc, declaredReturnLoc, false,
562               generateErrorMessage(md.getClassDesc(), rn));
563
564       if (compareResult == ComparisonResult.LESS || compareResult == ComparisonResult.INCOMPARABLE) {
565         throw new Error(
566             "Return value location is not equal or higher than the declaraed return location at "
567                 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
568       }
569     }
570
571     return new CompositeLocation();
572   }
573
574   private boolean hasOnlyLiteralValue(ExpressionNode en) {
575     if (en.kind() == Kind.LiteralNode) {
576       return true;
577     } else {
578       return false;
579     }
580   }
581
582   private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
583       LoopNode ln, CompositeLocation constraint) {
584
585     ClassDescriptor cd = md.getClassDesc();
586     if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
587
588       CompositeLocation condLoc =
589           checkLocationFromExpressionNode(md, nametable, ln.getCondition(),
590               new CompositeLocation(), constraint, false);
591       addLocationType(ln.getCondition().getType(), (condLoc));
592
593       constraint = generateNewConstraint(constraint, condLoc);
594       checkLocationFromBlockNode(md, nametable, ln.getBody(), constraint);
595
596       return new CompositeLocation();
597
598     } else {
599       // check 'for loop' case
600       BlockNode bn = ln.getInitializer();
601       bn.getVarTable().setParent(nametable);
602
603       // calculate glb location of condition and update statements
604       CompositeLocation condLoc =
605           checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
606               new CompositeLocation(), constraint, false);
607       addLocationType(ln.getCondition().getType(), condLoc);
608
609       constraint = generateNewConstraint(constraint, condLoc);
610
611       checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate(), constraint);
612       checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody(), constraint);
613
614       return new CompositeLocation();
615
616     }
617
618   }
619
620   private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
621       SymbolTable nametable, SubBlockNode sbn, CompositeLocation constraint) {
622     CompositeLocation compLoc =
623         checkLocationFromBlockNode(md, nametable, sbn.getBlockNode(), constraint);
624     return compLoc;
625   }
626
627   private CompositeLocation generateNewConstraint(CompositeLocation currentCon,
628       CompositeLocation newCon) {
629
630     if (currentCon == null) {
631       return newCon;
632     } else {
633       // compute GLB of current constraint and new constraint
634       Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
635       inputSet.add(currentCon);
636       inputSet.add(newCon);
637       return CompositeLattice.calculateGLB(inputSet, "");
638     }
639
640   }
641
642   private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
643       SymbolTable nametable, IfStatementNode isn, CompositeLocation constraint) {
644
645     CompositeLocation condLoc =
646         checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation(),
647             constraint, false);
648
649     addLocationType(isn.getCondition().getType(), condLoc);
650
651     constraint = generateNewConstraint(constraint, condLoc);
652     checkLocationFromBlockNode(md, nametable, isn.getTrueBlock(), constraint);
653
654     if (isn.getFalseBlock() != null) {
655       checkLocationFromBlockNode(md, nametable, isn.getFalseBlock(), constraint);
656     }
657
658     return new CompositeLocation();
659   }
660
661   private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
662       SymbolTable nametable, DeclarationNode dn, CompositeLocation constraint) {
663
664     VarDescriptor vd = dn.getVarDescriptor();
665
666     CompositeLocation destLoc = d2loc.get(vd);
667
668     if (dn.getExpression() != null) {
669       CompositeLocation expressionLoc =
670           checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
671               new CompositeLocation(), constraint, false);
672       // addTypeLocation(dn.getExpression().getType(), expressionLoc);
673
674       if (expressionLoc != null) {
675         // checking location order
676         if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
677             generateErrorMessage(md.getClassDesc(), dn))) {
678           throw new Error("The value flow from " + expressionLoc + " to " + destLoc
679               + " does not respect location hierarchy on the assignment " + dn.printNode(0)
680               + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
681         }
682       }
683       return expressionLoc;
684
685     } else {
686
687       return new CompositeLocation();
688
689     }
690
691   }
692
693   private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
694       SubBlockNode sbn) {
695     checkDeclarationInBlockNode(md, nametable.getParent(), sbn.getBlockNode());
696   }
697
698   private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
699       SymbolTable nametable, BlockExpressionNode ben, CompositeLocation constraint) {
700     CompositeLocation compLoc =
701         checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null, constraint, false);
702     // addTypeLocation(ben.getExpression().getType(), compLoc);
703     return compLoc;
704   }
705
706   private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
707       SymbolTable nametable, ExpressionNode en, CompositeLocation loc,
708       CompositeLocation constraint, boolean isLHS) {
709
710     CompositeLocation compLoc = null;
711     switch (en.kind()) {
712
713     case Kind.AssignmentNode:
714       compLoc =
715           checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc, constraint);
716       break;
717
718     case Kind.FieldAccessNode:
719       compLoc =
720           checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc, constraint);
721       break;
722
723     case Kind.NameNode:
724       compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc, constraint);
725       break;
726
727     case Kind.OpNode:
728       compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en, constraint);
729       break;
730
731     case Kind.CreateObjectNode:
732       compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
733       break;
734
735     case Kind.ArrayAccessNode:
736       compLoc =
737           checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en, constraint, isLHS);
738       break;
739
740     case Kind.LiteralNode:
741       compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
742       break;
743
744     case Kind.MethodInvokeNode:
745       compLoc =
746           checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc, constraint);
747       break;
748
749     case Kind.TertiaryNode:
750       compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en, constraint);
751       break;
752
753     case Kind.CastNode:
754       compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en, constraint);
755       break;
756
757     // case Kind.InstanceOfNode:
758     // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
759     // return null;
760
761     // case Kind.ArrayInitializerNode:
762     // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
763     // td);
764     // return null;
765
766     // case Kind.ClassTypeNode:
767     // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
768     // return null;
769
770     // case Kind.OffsetNode:
771     // checkOffsetNode(md, nametable, (OffsetNode)en, td);
772     // return null;
773
774     default:
775       return null;
776
777     }
778     // addTypeLocation(en.getType(), compLoc);
779     return compLoc;
780
781   }
782
783   private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
784       CastNode cn, CompositeLocation constraint) {
785
786     ExpressionNode en = cn.getExpression();
787     return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
788         false);
789
790   }
791
792   private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
793       SymbolTable nametable, TertiaryNode tn, CompositeLocation constraint) {
794     ClassDescriptor cd = md.getClassDesc();
795
796     CompositeLocation condLoc =
797         checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation(),
798             constraint, false);
799     addLocationType(tn.getCond().getType(), condLoc);
800     CompositeLocation trueLoc =
801         checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation(),
802             constraint, false);
803     addLocationType(tn.getTrueExpr().getType(), trueLoc);
804     CompositeLocation falseLoc =
805         checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation(),
806             constraint, false);
807     addLocationType(tn.getFalseExpr().getType(), falseLoc);
808
809     // locations from true/false branches can be TOP when there are only literal
810     // values
811     // in this case, we don't need to check flow down rule!
812
813     // check if condLoc is higher than trueLoc & falseLoc
814     if (!trueLoc.get(0).isTop()
815         && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
816       throw new Error(
817           "The location of the condition expression is lower than the true expression at "
818               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
819     }
820
821     if (!falseLoc.get(0).isTop()
822         && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
823             generateErrorMessage(cd, tn.getCond()))) {
824       throw new Error(
825           "The location of the condition expression is lower than the true expression at "
826               + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
827     }
828
829     // then, return glb of trueLoc & falseLoc
830     Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
831     glbInputSet.add(trueLoc);
832     glbInputSet.add(falseLoc);
833
834     return CompositeLattice.calculateGLB(glbInputSet, generateErrorMessage(cd, tn));
835   }
836
837   private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
838       SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc,
839       CompositeLocation constraint) {
840
841     CompositeLocation baseLocation = null;
842     if (min.getExpression() != null) {
843       baseLocation =
844           checkLocationFromExpressionNode(md, nametable, min.getExpression(),
845               new CompositeLocation(), constraint, false);
846     } else {
847       String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
848       baseLocation = new CompositeLocation(new Location(md, thisLocId));
849     }
850
851     checkCalleeConstraints(md, nametable, min, baseLocation, constraint);
852
853     if (!min.getMethod().getReturnType().isVoid()) {
854       // If method has a return value, compute the highest possible return
855       // location in the caller's perspective
856       CompositeLocation ceilingLoc =
857           computeCeilingLocationForCaller(md, nametable, min, baseLocation, constraint);
858       return ceilingLoc;
859     }
860
861     return new CompositeLocation();
862
863   }
864
865   private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
866       SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation,
867       CompositeLocation constraint) {
868     List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
869
870     // by default, method has a THIS parameter
871     argList.add(baseLocation);
872
873     for (int i = 0; i < min.numArgs(); i++) {
874       ExpressionNode en = min.getArg(i);
875       CompositeLocation callerArg =
876           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
877               false);
878       argList.add(callerArg);
879     }
880
881     System.out.println("\n## computeReturnLocation=" + min.getMethod() + " argList=" + argList);
882     CompositeLocation compLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
883     DeltaLocation delta = new DeltaLocation(compLoc, 1);
884     System.out.println("##computeReturnLocation=" + delta);
885
886     return delta;
887
888   }
889
890   private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
891       MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
892
893     MethodDescriptor calleemd = min.getMethod();
894
895     MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
896     CompositeLocation calleeThisLoc =
897         new CompositeLocation(new Location(calleemd, calleeLattice.getThisLoc()));
898
899     List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
900     List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
901
902     if (min.numArgs() > 0) {
903       // caller needs to guarantee that it passes arguments in regarding to
904       // callee's hierarchy
905
906       // setup caller args set
907       // first, add caller's base(this) location
908       callerArgList.add(callerBaseLoc);
909       // second, add caller's arguments
910       for (int i = 0; i < min.numArgs(); i++) {
911         ExpressionNode en = min.getArg(i);
912         CompositeLocation callerArgLoc =
913             checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
914                 false);
915         callerArgList.add(callerArgLoc);
916       }
917
918       // setup callee params set
919       // first, add callee's this location
920       calleeParamList.add(calleeThisLoc);
921       // second, add callee's parameters
922       for (int i = 0; i < calleemd.numParameters(); i++) {
923         VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
924         CompositeLocation calleeLoc = d2loc.get(calleevd);
925         calleeParamList.add(calleeLoc);
926       }
927
928       // here, check if ordering relations among caller's args respect
929       // ordering relations in-between callee's args
930       CHECK: for (int i = 0; i < calleeParamList.size(); i++) {
931         CompositeLocation calleeLoc1 = calleeParamList.get(i);
932         CompositeLocation callerLoc1 = callerArgList.get(i);
933
934         for (int j = 0; j < calleeParamList.size(); j++) {
935           if (i != j) {
936             CompositeLocation calleeLoc2 = calleeParamList.get(j);
937             CompositeLocation callerLoc2 = callerArgList.get(j);
938
939             if (callerLoc1.get(callerLoc1.getSize() - 1).isTop()
940                 || callerLoc2.get(callerLoc2.getSize() - 1).isTop()) {
941               continue CHECK;
942             }
943
944             int callerResult =
945                 CompositeLattice.compare(callerLoc1, callerLoc2, true,
946                     generateErrorMessage(md.getClassDesc(), min));
947             int calleeResult =
948                 CompositeLattice.compare(calleeLoc1, calleeLoc2, true,
949                     generateErrorMessage(md.getClassDesc(), min));
950
951             if (calleeResult == ComparisonResult.GREATER
952                 && callerResult != ComparisonResult.GREATER) {
953               // If calleeLoc1 is higher than calleeLoc2
954               // then, caller should have same ordering relation in-bet
955               // callerLoc1 & callerLoc2
956
957               String paramName1, paramName2;
958
959               if (i == 0) {
960                 paramName1 = "'THIS'";
961               } else {
962                 paramName1 = "'parameter " + calleemd.getParamName(i - 1) + "'";
963               }
964
965               if (j == 0) {
966                 paramName2 = "'THIS'";
967               } else {
968                 paramName2 = "'parameter " + calleemd.getParamName(j - 1) + "'";
969               }
970
971               throw new Error(
972                   "Caller doesn't respect an ordering relation among method arguments: callee expects that "
973                       + paramName1 + " should be higher than " + paramName2 + " in " + calleemd
974                       + " at " + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
975             }
976           }
977
978         }
979       }
980
981     }
982
983   }
984
985   private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
986       SymbolTable nametable, ArrayAccessNode aan, CompositeLocation constraint, boolean isLHS) {
987
988     ClassDescriptor cd = md.getClassDesc();
989
990     CompositeLocation arrayLoc =
991         checkLocationFromExpressionNode(md, nametable, aan.getExpression(),
992             new CompositeLocation(), constraint, isLHS);
993     // addTypeLocation(aan.getExpression().getType(), arrayLoc);
994     CompositeLocation indexLoc =
995         checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation(),
996             constraint, isLHS);
997     // addTypeLocation(aan.getIndex().getType(), indexLoc);
998
999     if (isLHS) {
1000       if (!CompositeLattice.isGreaterThan(indexLoc, arrayLoc, generateErrorMessage(cd, aan))) {
1001         throw new Error("Array index value is not higher than array location at "
1002             + generateErrorMessage(cd, aan));
1003       }
1004       return arrayLoc;
1005     } else {
1006       Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1007       inputGLB.add(arrayLoc);
1008       inputGLB.add(indexLoc);
1009       return CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(cd, aan));
1010     }
1011
1012   }
1013
1014   private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
1015       SymbolTable nametable, CreateObjectNode con) {
1016
1017     ClassDescriptor cd = md.getClassDesc();
1018
1019     CompositeLocation compLoc = new CompositeLocation();
1020     compLoc.addLocation(Location.createTopLocation(md));
1021     return compLoc;
1022
1023   }
1024
1025   private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
1026       OpNode on, CompositeLocation constraint) {
1027
1028     ClassDescriptor cd = md.getClassDesc();
1029     CompositeLocation leftLoc = new CompositeLocation();
1030     leftLoc =
1031         checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc, constraint, false);
1032     // addTypeLocation(on.getLeft().getType(), leftLoc);
1033
1034     CompositeLocation rightLoc = new CompositeLocation();
1035     if (on.getRight() != null) {
1036       rightLoc =
1037           checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc, constraint, false);
1038       // addTypeLocation(on.getRight().getType(), rightLoc);
1039     }
1040
1041     System.out.println("\n# OP NODE=" + on.printNode(0));
1042     System.out.println("# left loc=" + leftLoc + " from " + on.getLeft().getClass());
1043     if (on.getRight() != null) {
1044       System.out.println("# right loc=" + rightLoc + " from " + on.getRight().getClass());
1045     }
1046
1047     Operation op = on.getOp();
1048
1049     switch (op.getOp()) {
1050
1051     case Operation.UNARYPLUS:
1052     case Operation.UNARYMINUS:
1053     case Operation.LOGIC_NOT:
1054       // single operand
1055       return leftLoc;
1056
1057     case Operation.LOGIC_OR:
1058     case Operation.LOGIC_AND:
1059     case Operation.COMP:
1060     case Operation.BIT_OR:
1061     case Operation.BIT_XOR:
1062     case Operation.BIT_AND:
1063     case Operation.ISAVAILABLE:
1064     case Operation.EQUAL:
1065     case Operation.NOTEQUAL:
1066     case Operation.LT:
1067     case Operation.GT:
1068     case Operation.LTE:
1069     case Operation.GTE:
1070     case Operation.ADD:
1071     case Operation.SUB:
1072     case Operation.MULT:
1073     case Operation.DIV:
1074     case Operation.MOD:
1075     case Operation.LEFTSHIFT:
1076     case Operation.RIGHTSHIFT:
1077     case Operation.URIGHTSHIFT:
1078
1079       Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
1080       inputSet.add(leftLoc);
1081       inputSet.add(rightLoc);
1082       CompositeLocation glbCompLoc =
1083           CompositeLattice.calculateGLB(inputSet, generateErrorMessage(cd, on));
1084       System.out.println("# glbCompLoc=" + glbCompLoc);
1085       return glbCompLoc;
1086
1087     default:
1088       throw new Error(op.toString());
1089     }
1090
1091   }
1092
1093   private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
1094       SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
1095
1096     // literal value has the top location so that value can be flowed into any
1097     // location
1098     Location literalLoc = Location.createTopLocation(md);
1099     loc.addLocation(literalLoc);
1100     return loc;
1101
1102   }
1103
1104   private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1105       NameNode nn, CompositeLocation loc, CompositeLocation constraint) {
1106
1107     NameDescriptor nd = nn.getName();
1108     if (nd.getBase() != null) {
1109       loc =
1110           checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc, constraint, false);
1111     } else {
1112       String varname = nd.toString();
1113       if (varname.equals("this")) {
1114         // 'this' itself!
1115         MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1116         String thisLocId = methodLattice.getThisLoc();
1117         if (thisLocId == null) {
1118           throw new Error("The location for 'this' is not defined at "
1119               + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1120         }
1121         Location locElement = new Location(md, thisLocId);
1122         loc.addLocation(locElement);
1123         return loc;
1124
1125       }
1126
1127       Descriptor d = (Descriptor) nametable.get(varname);
1128
1129       // CompositeLocation localLoc = null;
1130       if (d instanceof VarDescriptor) {
1131         VarDescriptor vd = (VarDescriptor) d;
1132         // localLoc = d2loc.get(vd);
1133         // the type of var descriptor has a composite location!
1134         loc = ((CompositeLocation) vd.getType().getExtension()).clone();
1135       } else if (d instanceof FieldDescriptor) {
1136         // the type of field descriptor has a location!
1137         FieldDescriptor fd = (FieldDescriptor) d;
1138         if (fd.isStatic()) {
1139           if (fd.isFinal()) {
1140             // if it is 'static final', the location has TOP since no one can
1141             // change its value
1142             loc.addLocation(Location.createTopLocation(md));
1143             return loc;
1144           } else {
1145             // if 'static', the location has pre-assigned global loc
1146             MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1147             String globalLocId = localLattice.getGlobalLoc();
1148             if (globalLocId == null) {
1149               throw new Error("Global location element is not defined in the method " + md);
1150             }
1151             Location globalLoc = new Location(md, globalLocId);
1152
1153             loc.addLocation(globalLoc);
1154           }
1155         } else {
1156           // the location of field access starts from this, followed by field
1157           // location
1158           MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1159           Location thisLoc = new Location(md, localLattice.getThisLoc());
1160           loc.addLocation(thisLoc);
1161         }
1162
1163         Location fieldLoc = (Location) fd.getType().getExtension();
1164         loc.addLocation(fieldLoc);
1165       } else if (d == null) {
1166
1167         // check if the var is a static field of the class
1168         FieldDescriptor fd = nn.getField();
1169         ClassDescriptor cd = nn.getClassDesc();
1170
1171         if (fd != null && cd != null) {
1172
1173           if (fd.isStatic() && fd.isFinal()) {
1174             loc.addLocation(Location.createTopLocation(md));
1175             return loc;
1176           } else {
1177             MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1178             Location fieldLoc = new Location(md, localLattice.getThisLoc());
1179             loc.addLocation(fieldLoc);
1180           }
1181         }
1182
1183       }
1184     }
1185     return loc;
1186   }
1187
1188   private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1189       SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc,
1190       CompositeLocation constraint) {
1191
1192     ExpressionNode left = fan.getExpression();
1193     TypeDescriptor ltd = left.getType();
1194
1195     FieldDescriptor fd = fan.getField();
1196
1197     String varName = null;
1198     if (left.kind() == Kind.NameNode) {
1199       NameDescriptor nd = ((NameNode) left).getName();
1200       varName = nd.toString();
1201     }
1202
1203     if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1204       // using a class name directly or access using this
1205       if (fd.isStatic() && fd.isFinal()) {
1206         loc.addLocation(Location.createTopLocation(md));
1207         return loc;
1208       }
1209     }
1210
1211     loc = checkLocationFromExpressionNode(md, nametable, left, loc, constraint, false);
1212     if (!left.getType().isPrimitive()) {
1213       Location fieldLoc = getFieldLocation(fd);
1214       loc.addLocation(fieldLoc);
1215     }
1216
1217     return loc;
1218   }
1219
1220   private Location getFieldLocation(FieldDescriptor fd) {
1221
1222     Location fieldLoc = (Location) fd.getType().getExtension();
1223
1224     // handle the case that method annotation checking skips checking field
1225     // declaration
1226     if (fieldLoc == null) {
1227       fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1228     }
1229
1230     return fieldLoc;
1231
1232   }
1233
1234   private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1235       SymbolTable nametable, AssignmentNode an, CompositeLocation loc, CompositeLocation constraint) {
1236
1237     System.out.println("\n# ASSIGNMENTNODE=" + an.printNode(0));
1238
1239     ClassDescriptor cd = md.getClassDesc();
1240
1241     Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1242
1243     boolean postinc = true;
1244     if (an.getOperation().getBaseOp() == null
1245         || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1246             .getBaseOp().getOp() != Operation.POSTDEC))
1247       postinc = false;
1248
1249     // if LHS is array access node, need to check if array index is higher
1250     // than array itself
1251     CompositeLocation destLocation =
1252         checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1253             constraint, true);
1254
1255     CompositeLocation rhsLocation;
1256     CompositeLocation srcLocation;
1257
1258     if (!postinc) {
1259       rhsLocation =
1260           checkLocationFromExpressionNode(md, nametable, an.getSrc(), new CompositeLocation(),
1261               constraint, false);
1262
1263       System.out.println("dstLocation=" + destLocation);
1264       System.out.println("rhsLocation=" + rhsLocation);
1265       System.out.println("constraint=" + constraint);
1266
1267       srcLocation = rhsLocation;
1268
1269       if (!rhsLocation.get(rhsLocation.getSize() - 1).isTop()) {
1270         if (constraint != null) {
1271           inputGLBSet.add(rhsLocation);
1272           inputGLBSet.add(constraint);
1273           srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1274         }
1275       }
1276
1277       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1278         throw new Error("The value flow from " + srcLocation + " to " + destLocation
1279             + " does not respect location hierarchy on the assignment " + an.printNode(0) + " at "
1280             + cd.getSourceFileName() + "::" + an.getNumLine());
1281       }
1282
1283     } else {
1284       destLocation =
1285           rhsLocation =
1286               checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1287                   constraint, false);
1288
1289       if (constraint != null) {
1290         inputGLBSet.add(rhsLocation);
1291         inputGLBSet.add(constraint);
1292         srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1293       } else {
1294         srcLocation = rhsLocation;
1295       }
1296
1297       System.out.println("srcLocation=" + srcLocation);
1298       System.out.println("rhsLocation=" + rhsLocation);
1299       System.out.println("constraint=" + constraint);
1300
1301       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1302         throw new Error("Location " + destLocation
1303             + " is not allowed to have the value flow that moves within the same location at "
1304             + cd.getSourceFileName() + "::" + an.getNumLine());
1305       }
1306
1307     }
1308
1309     return destLocation;
1310   }
1311
1312   private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1313       SymbolTable nametable, TreeNode n) {
1314
1315     ClassDescriptor cd = md.getClassDesc();
1316     Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1317
1318     // currently enforce every variable to have corresponding location
1319     if (annotationVec.size() == 0) {
1320       throw new Error("Location is not assigned to variable " + vd.getSymbol() + " in the method "
1321           + md.getSymbol() + " of the class " + cd.getSymbol());
1322     }
1323
1324     if (annotationVec.size() > 1) { // variable can have at most one location
1325       throw new Error(vd.getSymbol() + " has more than one location.");
1326     }
1327
1328     AnnotationDescriptor ad = annotationVec.elementAt(0);
1329
1330     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1331
1332       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1333         String locDec = ad.getValue(); // check if location is defined
1334
1335         if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1336           DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1337           d2loc.put(vd, deltaLoc);
1338           addLocationType(vd.getType(), deltaLoc);
1339         } else {
1340           CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1341
1342           Location lastElement = compLoc.get(compLoc.getSize() - 1);
1343           if (ssjava.isSharedLocation(lastElement)) {
1344             ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1345           }
1346
1347           d2loc.put(vd, compLoc);
1348           addLocationType(vd.getType(), compLoc);
1349         }
1350
1351       }
1352     }
1353
1354   }
1355
1356   private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1357
1358     int deltaCount = 0;
1359     int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1360     while (dIdx >= 0) {
1361       deltaCount++;
1362       int beginIdx = dIdx + 6;
1363       locDec = locDec.substring(beginIdx, locDec.length() - 1);
1364       dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1365     }
1366
1367     CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1368     DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1369
1370     return deltaLoc;
1371   }
1372
1373   private Location parseFieldLocDeclaraton(String decl, String msg) throws Exception {
1374
1375     int idx = decl.indexOf(".");
1376
1377     String className = decl.substring(0, idx);
1378     String fieldName = decl.substring(idx + 1);
1379
1380     className.replaceAll(" ", "");
1381     fieldName.replaceAll(" ", "");
1382
1383     Descriptor d = state.getClassSymbolTable().get(className);
1384
1385     if (d == null) {
1386       System.out.println("state.getClassSymbolTable()=" + state.getClassSymbolTable());
1387       throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1388           + msg);
1389     }
1390
1391     assert (d instanceof ClassDescriptor);
1392     SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1393     if (!lattice.containsKey(fieldName)) {
1394       throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1395           + className + "' at " + msg);
1396     }
1397
1398     return new Location(d, fieldName);
1399   }
1400
1401   private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1402
1403     CompositeLocation compLoc = new CompositeLocation();
1404
1405     StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1406     List<String> locIdList = new ArrayList<String>();
1407     while (tokenizer.hasMoreTokens()) {
1408       String locId = tokenizer.nextToken();
1409       locIdList.add(locId);
1410     }
1411
1412     // at least,one location element needs to be here!
1413     assert (locIdList.size() > 0);
1414
1415     // assume that loc with idx 0 comes from the local lattice
1416     // loc with idx 1 comes from the field lattice
1417
1418     String localLocId = locIdList.get(0);
1419     SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1420     Location localLoc = new Location(md, localLocId);
1421     if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1422       System.out.println("locDec=" + locDec);
1423       throw new Error("Location " + localLocId
1424           + " is not defined in the local variable lattice at "
1425           + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : md) + ".");
1426     }
1427     compLoc.addLocation(localLoc);
1428
1429     for (int i = 1; i < locIdList.size(); i++) {
1430       String locName = locIdList.get(i);
1431       try {
1432         Location fieldLoc =
1433             parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1434         compLoc.addLocation(fieldLoc);
1435       } catch (Exception e) {
1436         throw new Error("The location declaration '" + locName + "' is wrong  at "
1437             + generateErrorMessage(md.getClassDesc(), n));
1438       }
1439     }
1440
1441     return compLoc;
1442
1443   }
1444
1445   private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1446     VarDescriptor vd = dn.getVarDescriptor();
1447     assignLocationOfVarDescriptor(vd, md, nametable, dn);
1448   }
1449
1450   private void checkDeclarationInClass(ClassDescriptor cd) {
1451     // Check to see that fields are okay
1452     for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1453       FieldDescriptor fd = (FieldDescriptor) field_it.next();
1454
1455       if (!(fd.isFinal() && fd.isStatic())) {
1456         checkFieldDeclaration(cd, fd);
1457       } else {
1458         // for static final, assign top location by default
1459         Location loc = Location.createTopLocation(cd);
1460         addLocationType(fd.getType(), loc);
1461       }
1462     }
1463   }
1464
1465   private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1466
1467     Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1468
1469     // currently enforce every field to have corresponding location
1470     if (annotationVec.size() == 0) {
1471       throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1472           + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1473     }
1474
1475     if (annotationVec.size() > 1) {
1476       // variable can have at most one location
1477       throw new Error("Field " + fd.getSymbol() + " of class " + cd
1478           + " has more than one location.");
1479     }
1480
1481     AnnotationDescriptor ad = annotationVec.elementAt(0);
1482     Location loc = null;
1483
1484     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1485       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1486         String locationID = ad.getValue();
1487         // check if location is defined
1488         SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1489         if (lattice == null || (!lattice.containsKey(locationID))) {
1490           throw new Error("Location " + locationID
1491               + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1492               + cd.getSourceFileName() + ".");
1493         }
1494         loc = new Location(cd, locationID);
1495
1496         if (ssjava.isSharedLocation(loc)) {
1497           ssjava.mapSharedLocation2Descriptor(loc, fd);
1498         }
1499
1500         addLocationType(fd.getType(), loc);
1501
1502       }
1503     }
1504
1505     return loc;
1506   }
1507
1508   private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1509     if (type != null) {
1510       type.setExtension(loc);
1511     }
1512   }
1513
1514   private void addLocationType(TypeDescriptor type, Location loc) {
1515     if (type != null) {
1516       type.setExtension(loc);
1517     }
1518   }
1519
1520   static class CompositeLattice {
1521
1522     public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1523
1524       System.out.println("\nisGreaterThan=" + loc1 + " " + loc2 + " msg=" + msg);
1525       int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, false, msg);
1526       if (baseCompareResult == ComparisonResult.EQUAL) {
1527         if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1528           return true;
1529         } else {
1530           return false;
1531         }
1532       } else if (baseCompareResult == ComparisonResult.GREATER) {
1533         return true;
1534       } else {
1535         return false;
1536       }
1537
1538     }
1539
1540     public static int compare(CompositeLocation loc1, CompositeLocation loc2, boolean ignore,
1541         String msg) {
1542
1543       System.out.println("compare=" + loc1 + " " + loc2);
1544       int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, ignore, msg);
1545
1546       if (baseCompareResult == ComparisonResult.EQUAL) {
1547         return compareDelta(loc1, loc2);
1548       } else {
1549         return baseCompareResult;
1550       }
1551
1552     }
1553
1554     private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1555
1556       int deltaCount1 = 0;
1557       int deltaCount2 = 0;
1558       if (dLoc1 instanceof DeltaLocation) {
1559         deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1560       }
1561
1562       if (dLoc2 instanceof DeltaLocation) {
1563         deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1564       }
1565       if (deltaCount1 < deltaCount2) {
1566         return ComparisonResult.GREATER;
1567       } else if (deltaCount1 == deltaCount2) {
1568         return ComparisonResult.EQUAL;
1569       } else {
1570         return ComparisonResult.LESS;
1571       }
1572
1573     }
1574
1575     private static int compareBaseLocationSet(CompositeLocation compLoc1,
1576         CompositeLocation compLoc2, boolean awareSharedLoc, boolean ignore, String msg) {
1577
1578       // if compLoc1 is greater than compLoc2, return true
1579       // else return false;
1580
1581       // compare one by one in according to the order of the tuple
1582       int numOfTie = 0;
1583       for (int i = 0; i < compLoc1.getSize(); i++) {
1584         Location loc1 = compLoc1.get(i);
1585         if (i >= compLoc2.getSize()) {
1586           if (ignore) {
1587             return ComparisonResult.INCOMPARABLE;
1588           } else {
1589             throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1590                 + " because they are not comparable at " + msg);
1591           }
1592         }
1593         Location loc2 = compLoc2.get(i);
1594
1595         Descriptor descriptor = getCommonParentDescriptor(loc1, loc2, msg);
1596         SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
1597
1598         // check if the shared location is appeared only at the end of the
1599         // composite location
1600         if (lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1601           if (i != (compLoc1.getSize() - 1)) {
1602             throw new Error("The shared location " + loc1.getLocIdentifier()
1603                 + " cannot be appeared in the middle of composite location at" + msg);
1604           }
1605         }
1606
1607         if (lattice.getSharedLocSet().contains(loc2.getLocIdentifier())) {
1608           if (i != (compLoc2.getSize() - 1)) {
1609             throw new Error("The shared location " + loc2.getLocIdentifier()
1610                 + " cannot be appeared in the middle of composite location at " + msg);
1611           }
1612         }
1613
1614         // if (!lattice1.equals(lattice2)) {
1615         // throw new Error("Failed to compare two locations of " + compLoc1 +
1616         // " and " + compLoc2
1617         // + " because they are not comparable at " + msg);
1618         // }
1619
1620         if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1621           numOfTie++;
1622           // check if the current location is the spinning location
1623           // note that the spinning location only can be appeared in the last
1624           // part of the composite location
1625           if (awareSharedLoc && numOfTie == compLoc1.getSize()
1626               && lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1627             return ComparisonResult.GREATER;
1628           }
1629           continue;
1630         } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1631           return ComparisonResult.GREATER;
1632         } else {
1633           return ComparisonResult.LESS;
1634         }
1635
1636       }
1637
1638       if (numOfTie == compLoc1.getSize()) {
1639
1640         if (numOfTie != compLoc2.getSize()) {
1641
1642           if (ignore) {
1643             return ComparisonResult.INCOMPARABLE;
1644           } else {
1645             throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1646                 + " because they are not comparable at " + msg);
1647           }
1648
1649         }
1650
1651         return ComparisonResult.EQUAL;
1652       }
1653
1654       return ComparisonResult.LESS;
1655
1656     }
1657
1658     public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet, String errMsg) {
1659
1660       System.out.println("Calculating GLB=" + inputSet);
1661       CompositeLocation glbCompLoc = new CompositeLocation();
1662
1663       // calculate GLB of the first(priority) element
1664       Set<String> priorityLocIdentifierSet = new HashSet<String>();
1665       Descriptor priorityDescriptor = null;
1666
1667       Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1668           new Hashtable<String, Set<CompositeLocation>>();
1669       // mapping from the priority loc ID to its full representation by the
1670       // composite location
1671
1672       int maxTupleSize = 0;
1673       CompositeLocation maxCompLoc = null;
1674
1675       Location prevPriorityLoc = null;
1676       for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1677         CompositeLocation compLoc = (CompositeLocation) iterator.next();
1678         if (compLoc.getSize() > maxTupleSize) {
1679           maxTupleSize = compLoc.getSize();
1680           maxCompLoc = compLoc;
1681         }
1682         Location priorityLoc = compLoc.get(0);
1683         String priorityLocId = priorityLoc.getLocIdentifier();
1684         priorityLocIdentifierSet.add(priorityLocId);
1685
1686         if (locId2CompLocSet.containsKey(priorityLocId)) {
1687           locId2CompLocSet.get(priorityLocId).add(compLoc);
1688         } else {
1689           Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1690           newSet.add(compLoc);
1691           locId2CompLocSet.put(priorityLocId, newSet);
1692         }
1693
1694         // check if priority location are coming from the same lattice
1695         if (priorityDescriptor == null) {
1696           priorityDescriptor = priorityLoc.getDescriptor();
1697         } else {
1698           priorityDescriptor = getCommonParentDescriptor(priorityLoc, prevPriorityLoc, errMsg);
1699         }
1700         prevPriorityLoc = priorityLoc;
1701         // else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1702         // throw new Error("Failed to calculate GLB of " + inputSet
1703         // + " because they are from different lattices.");
1704         // }
1705       }
1706
1707       SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1708       String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1709
1710       glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1711       Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1712
1713       if (compSet == null) {
1714         // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1715         // mean that the result is already lower than <x1,y1> and <x2,y2>
1716         // assign TOP to the rest of the location elements
1717
1718         // in this case, do not take care about delta
1719         // CompositeLocation inputComp = inputSet.iterator().next();
1720         for (int i = 1; i < maxTupleSize; i++) {
1721           glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
1722         }
1723       } else {
1724
1725         // here find out composite location that has a maximum length tuple
1726         // if we have three input set: [A], [A,B], [A,B,C]
1727         // maximum length tuple will be [A,B,C]
1728         int max = 0;
1729         CompositeLocation maxFromCompSet = null;
1730         for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1731           CompositeLocation c = (CompositeLocation) iterator.next();
1732           if (c.getSize() > max) {
1733             max = c.getSize();
1734             maxFromCompSet = c;
1735           }
1736         }
1737
1738         if (compSet.size() == 1) {
1739           // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1740           CompositeLocation comp = compSet.iterator().next();
1741           for (int i = 1; i < comp.getSize(); i++) {
1742             glbCompLoc.addLocation(comp.get(i));
1743           }
1744
1745           // if input location corresponding to glb is a delta, need to apply
1746           // delta to glb result
1747           if (comp instanceof DeltaLocation) {
1748             glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1749           }
1750
1751         } else {
1752           // when GLB(x1,x2)==x1 and x2 : GLB case 1
1753           // if more than one location shares the same priority GLB
1754           // need to calculate the rest of GLB loc
1755
1756           // setup input set starting from the second tuple item
1757           Set<CompositeLocation> innerGLBInput = new HashSet<CompositeLocation>();
1758           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1759             CompositeLocation compLoc = (CompositeLocation) iterator.next();
1760             CompositeLocation innerCompLoc = new CompositeLocation();
1761             for (int idx = 1; idx < compLoc.getSize(); idx++) {
1762               innerCompLoc.addLocation(compLoc.get(idx));
1763             }
1764             if (innerCompLoc.getSize() > 0) {
1765               innerGLBInput.add(innerCompLoc);
1766             }
1767           }
1768
1769           if (innerGLBInput.size() > 0) {
1770             CompositeLocation innerGLB = CompositeLattice.calculateGLB(innerGLBInput, errMsg);
1771             for (int idx = 0; idx < innerGLB.getSize(); idx++) {
1772               glbCompLoc.addLocation(innerGLB.get(idx));
1773             }
1774           }
1775
1776           // if input location corresponding to glb is a delta, need to apply
1777           // delta to glb result
1778
1779           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1780             CompositeLocation compLoc = (CompositeLocation) iterator.next();
1781             if (compLoc instanceof DeltaLocation) {
1782               if (glbCompLoc.equals(compLoc)) {
1783                 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1784                 break;
1785               }
1786             }
1787           }
1788
1789         }
1790       }
1791
1792       System.out.println("GLB=" + glbCompLoc);
1793       return glbCompLoc;
1794
1795     }
1796
1797     static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1798
1799       SSJavaLattice<String> lattice = null;
1800
1801       if (d instanceof ClassDescriptor) {
1802         lattice = ssjava.getCd2lattice().get(d);
1803       } else if (d instanceof MethodDescriptor) {
1804         if (ssjava.getMd2lattice().containsKey(d)) {
1805           lattice = ssjava.getMd2lattice().get(d);
1806         } else {
1807           // use default lattice for the method
1808           lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1809         }
1810       }
1811
1812       return lattice;
1813     }
1814
1815     static Descriptor getCommonParentDescriptor(Location loc1, Location loc2, String msg) {
1816
1817       Descriptor d1 = loc1.getDescriptor();
1818       Descriptor d2 = loc2.getDescriptor();
1819
1820       Descriptor descriptor;
1821
1822       if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
1823
1824         if (d1.equals(d2)) {
1825           descriptor = d1;
1826         } else {
1827           // identifying which one is parent class
1828           Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
1829           Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
1830
1831           if (d1 == null && d2 == null) {
1832             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1833                 + " because they are not comparable at " + msg);
1834           } else if (d1SubClassesSet != null && d1SubClassesSet.contains(d2)) {
1835             descriptor = d1;
1836           } else if (d2SubClassesSet != null && d2SubClassesSet.contains(d1)) {
1837             descriptor = d2;
1838           } else {
1839             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1840                 + " because they are not comparable at " + msg);
1841           }
1842         }
1843
1844       } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
1845
1846         if (d1.equals(d2)) {
1847           descriptor = d1;
1848         } else {
1849
1850           // identifying which one is parent class
1851           MethodDescriptor md1 = (MethodDescriptor) d1;
1852           MethodDescriptor md2 = (MethodDescriptor) d2;
1853
1854           if (!md1.matches(md2)) {
1855             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1856                 + " because they are not comparable at " + msg);
1857           }
1858
1859           Set<Descriptor> d1SubClassesSet =
1860               ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
1861           Set<Descriptor> d2SubClassesSet =
1862               ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
1863
1864           if (d1 == null && d2 == null) {
1865             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1866                 + " because they are not comparable at " + msg);
1867           } else if (d1 != null && d1SubClassesSet.contains(d2)) {
1868             descriptor = d1;
1869           } else if (d2 != null && d2SubClassesSet.contains(d1)) {
1870             descriptor = d2;
1871           } else {
1872             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1873                 + " because they are not comparable at " + msg);
1874           }
1875         }
1876
1877       } else {
1878         throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1879             + " because they are not comparable at " + msg);
1880       }
1881
1882       return descriptor;
1883
1884     }
1885
1886   }
1887
1888   class ComparisonResult {
1889
1890     public static final int GREATER = 0;
1891     public static final int EQUAL = 1;
1892     public static final int LESS = 2;
1893     public static final int INCOMPARABLE = 3;
1894     int result;
1895
1896   }
1897
1898 }
1899
1900 class ReturnLocGenerator {
1901
1902   public static final int PARAMISHIGHER = 0;
1903   public static final int PARAMISSAME = 1;
1904   public static final int IGNORE = 2;
1905
1906   Hashtable<Integer, Integer> paramIdx2paramType;
1907
1908   public ReturnLocGenerator(CompositeLocation returnLoc, List<CompositeLocation> params, String msg) {
1909     // creating mappings
1910     paramIdx2paramType = new Hashtable<Integer, Integer>();
1911     for (int i = 0; i < params.size(); i++) {
1912       CompositeLocation param = params.get(i);
1913       int compareResult = CompositeLattice.compare(param, returnLoc, true, msg);
1914
1915       int type;
1916       if (compareResult == ComparisonResult.GREATER) {
1917         type = 0;
1918       } else if (compareResult == ComparisonResult.EQUAL) {
1919         type = 1;
1920       } else {
1921         type = 2;
1922       }
1923       paramIdx2paramType.put(new Integer(i), new Integer(type));
1924     }
1925
1926   }
1927
1928   public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
1929
1930     // compute the highest possible location in caller's side
1931     assert paramIdx2paramType.keySet().size() == args.size();
1932
1933     Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1934     for (int i = 0; i < args.size(); i++) {
1935       int type = (paramIdx2paramType.get(new Integer(i))).intValue();
1936       CompositeLocation argLoc = args.get(i);
1937       if (type == PARAMISHIGHER) {
1938         // return loc is lower than param
1939         DeltaLocation delta = new DeltaLocation(argLoc, 1);
1940         inputGLB.add(delta);
1941       } else if (type == PARAMISSAME) {
1942         // return loc is equal or lower than param
1943         inputGLB.add(argLoc);
1944       }
1945     }
1946
1947     // compute GLB of arguments subset that are same or higher than return
1948     // location
1949     CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB, "");
1950     return glb;
1951   }
1952 }