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