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