d3870ccfbc354842d8b673b546aed4a67c326566
[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 callerBaseLoc, 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     System.out.println("checkCallerArgumentLocationConstraints=" + min.printNode(0));
905     System.out.println("base location=" + callerBaseLoc);
906
907     for (int i = 0; i < calleeParamList.size(); i++) {
908       CompositeLocation calleeParamLoc = calleeParamList.get(i);
909       if (calleeParamLoc.get(0).equals(calleeThisLoc) && calleeParamLoc.getSize() > 1) {
910
911         // callee parameter location has field information
912         CompositeLocation callerArgLoc = callerArgList.get(i);
913
914         CompositeLocation paramLocation =
915             translateCalleeParamLocToCaller(md, calleeParamLoc, callerBaseLoc, errorMsg);
916
917         Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
918         if (constraint != null) {
919           inputGLBSet.add(callerArgLoc);
920           inputGLBSet.add(constraint);
921           callerArgLoc =
922               CompositeLattice.calculateGLB(inputGLBSet,
923                   generateErrorMessage(md.getClassDesc(), min));
924         }
925
926         if (!CompositeLattice.isGreaterThan(callerArgLoc, paramLocation, errorMsg)) {
927           throw new Error("Caller argument '" + min.getArg(i).printNode(0) + " : " + callerArgLoc
928               + "' should be higher than corresponding callee's parameter : " + paramLocation
929               + " at " + errorMsg);
930         }
931
932       }
933     }
934
935   }
936
937   private CompositeLocation translateCalleeParamLocToCaller(MethodDescriptor md,
938       CompositeLocation calleeParamLoc, CompositeLocation callerBaseLocation, String errorMsg) {
939
940     CompositeLocation translate = new CompositeLocation();
941
942     for (int i = 0; i < callerBaseLocation.getSize(); i++) {
943       translate.addLocation(callerBaseLocation.get(i));
944     }
945
946     for (int i = 1; i < calleeParamLoc.getSize(); i++) {
947       translate.addLocation(calleeParamLoc.get(i));
948     }
949
950     System.out.println("TRANSLATED=" + translate + " from calleeParamLoc=" + calleeParamLoc);
951
952     return translate;
953   }
954
955   private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
956       SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation,
957       CompositeLocation constraint) {
958     List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
959
960     // by default, method has a THIS parameter
961     argList.add(baseLocation);
962
963     for (int i = 0; i < min.numArgs(); i++) {
964       ExpressionNode en = min.getArg(i);
965       CompositeLocation callerArg =
966           checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
967               false);
968       argList.add(callerArg);
969     }
970
971     System.out.println("\n## computeReturnLocation=" + min.getMethod() + " argList=" + argList);
972     CompositeLocation compLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
973     DeltaLocation delta = new DeltaLocation(compLoc, 1);
974     System.out.println("##computeReturnLocation=" + delta);
975
976     return delta;
977
978   }
979
980   private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
981       MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
982
983     MethodDescriptor calleemd = min.getMethod();
984
985     MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
986     CompositeLocation calleeThisLoc =
987         new CompositeLocation(new Location(calleemd, calleeLattice.getThisLoc()));
988
989     List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
990     List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
991
992     if (min.numArgs() > 0) {
993       // caller needs to guarantee that it passes arguments in regarding to
994       // callee's hierarchy
995
996       // setup caller args set
997       // first, add caller's base(this) location
998       callerArgList.add(callerBaseLoc);
999       // second, add caller's arguments
1000       for (int i = 0; i < min.numArgs(); i++) {
1001         ExpressionNode en = min.getArg(i);
1002         CompositeLocation callerArgLoc =
1003             checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1004                 false);
1005         callerArgList.add(callerArgLoc);
1006       }
1007
1008       // setup callee params set
1009       // first, add callee's this location
1010       calleeParamList.add(calleeThisLoc);
1011       // second, add callee's parameters
1012       for (int i = 0; i < calleemd.numParameters(); i++) {
1013         VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1014         CompositeLocation calleeLoc = d2loc.get(calleevd);
1015         calleeParamList.add(calleeLoc);
1016       }
1017
1018       // here, check if ordering relations among caller's args respect
1019       // ordering relations in-between callee's args
1020       CHECK: for (int i = 0; i < calleeParamList.size(); i++) {
1021         CompositeLocation calleeLoc1 = calleeParamList.get(i);
1022         CompositeLocation callerLoc1 = callerArgList.get(i);
1023
1024         for (int j = 0; j < calleeParamList.size(); j++) {
1025           if (i != j) {
1026             CompositeLocation calleeLoc2 = calleeParamList.get(j);
1027             CompositeLocation callerLoc2 = callerArgList.get(j);
1028
1029             if (callerLoc1.get(callerLoc1.getSize() - 1).isTop()
1030                 || callerLoc2.get(callerLoc2.getSize() - 1).isTop()) {
1031               continue CHECK;
1032             }
1033
1034             int callerResult =
1035                 CompositeLattice.compare(callerLoc1, callerLoc2, true,
1036                     generateErrorMessage(md.getClassDesc(), min));
1037             int calleeResult =
1038                 CompositeLattice.compare(calleeLoc1, calleeLoc2, true,
1039                     generateErrorMessage(md.getClassDesc(), min));
1040
1041             if (calleeResult == ComparisonResult.GREATER
1042                 && callerResult != ComparisonResult.GREATER) {
1043               // If calleeLoc1 is higher than calleeLoc2
1044               // then, caller should have same ordering relation in-bet
1045               // callerLoc1 & callerLoc2
1046
1047               String paramName1, paramName2;
1048
1049               if (i == 0) {
1050                 paramName1 = "'THIS'";
1051               } else {
1052                 paramName1 = "'parameter " + calleemd.getParamName(i - 1) + "'";
1053               }
1054
1055               if (j == 0) {
1056                 paramName2 = "'THIS'";
1057               } else {
1058                 paramName2 = "'parameter " + calleemd.getParamName(j - 1) + "'";
1059               }
1060
1061               throw new Error(
1062                   "Caller doesn't respect an ordering relation among method arguments: callee expects that "
1063                       + paramName1 + " should be higher than " + paramName2 + " in " + calleemd
1064                       + " at " + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
1065             }
1066           }
1067
1068         }
1069       }
1070
1071     }
1072
1073   }
1074
1075   private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
1076       SymbolTable nametable, ArrayAccessNode aan, CompositeLocation constraint, boolean isLHS) {
1077
1078     ClassDescriptor cd = md.getClassDesc();
1079
1080     CompositeLocation arrayLoc =
1081         checkLocationFromExpressionNode(md, nametable, aan.getExpression(),
1082             new CompositeLocation(), constraint, isLHS);
1083     // addTypeLocation(aan.getExpression().getType(), arrayLoc);
1084     CompositeLocation indexLoc =
1085         checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation(),
1086             constraint, isLHS);
1087     // addTypeLocation(aan.getIndex().getType(), indexLoc);
1088
1089     if (isLHS) {
1090       if (!CompositeLattice.isGreaterThan(indexLoc, arrayLoc, generateErrorMessage(cd, aan))) {
1091         throw new Error("Array index value is not higher than array location at "
1092             + generateErrorMessage(cd, aan));
1093       }
1094       return arrayLoc;
1095     } else {
1096       Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1097       inputGLB.add(arrayLoc);
1098       inputGLB.add(indexLoc);
1099       return CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(cd, aan));
1100     }
1101
1102   }
1103
1104   private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
1105       SymbolTable nametable, CreateObjectNode con) {
1106
1107     ClassDescriptor cd = md.getClassDesc();
1108
1109     CompositeLocation compLoc = new CompositeLocation();
1110     compLoc.addLocation(Location.createTopLocation(md));
1111     return compLoc;
1112
1113   }
1114
1115   private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
1116       OpNode on, CompositeLocation constraint) {
1117
1118     ClassDescriptor cd = md.getClassDesc();
1119     CompositeLocation leftLoc = new CompositeLocation();
1120     leftLoc =
1121         checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc, constraint, false);
1122     // addTypeLocation(on.getLeft().getType(), leftLoc);
1123
1124     CompositeLocation rightLoc = new CompositeLocation();
1125     if (on.getRight() != null) {
1126       rightLoc =
1127           checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc, constraint, false);
1128       // addTypeLocation(on.getRight().getType(), rightLoc);
1129     }
1130
1131     System.out.println("\n# OP NODE=" + on.printNode(0));
1132     System.out.println("# left loc=" + leftLoc + " from " + on.getLeft().getClass());
1133     if (on.getRight() != null) {
1134       System.out.println("# right loc=" + rightLoc + " from " + on.getRight().getClass());
1135     }
1136
1137     Operation op = on.getOp();
1138
1139     switch (op.getOp()) {
1140
1141     case Operation.UNARYPLUS:
1142     case Operation.UNARYMINUS:
1143     case Operation.LOGIC_NOT:
1144       // single operand
1145       return leftLoc;
1146
1147     case Operation.LOGIC_OR:
1148     case Operation.LOGIC_AND:
1149     case Operation.COMP:
1150     case Operation.BIT_OR:
1151     case Operation.BIT_XOR:
1152     case Operation.BIT_AND:
1153     case Operation.ISAVAILABLE:
1154     case Operation.EQUAL:
1155     case Operation.NOTEQUAL:
1156     case Operation.LT:
1157     case Operation.GT:
1158     case Operation.LTE:
1159     case Operation.GTE:
1160     case Operation.ADD:
1161     case Operation.SUB:
1162     case Operation.MULT:
1163     case Operation.DIV:
1164     case Operation.MOD:
1165     case Operation.LEFTSHIFT:
1166     case Operation.RIGHTSHIFT:
1167     case Operation.URIGHTSHIFT:
1168
1169       Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
1170       inputSet.add(leftLoc);
1171       inputSet.add(rightLoc);
1172       CompositeLocation glbCompLoc =
1173           CompositeLattice.calculateGLB(inputSet, generateErrorMessage(cd, on));
1174       System.out.println("# glbCompLoc=" + glbCompLoc);
1175       return glbCompLoc;
1176
1177     default:
1178       throw new Error(op.toString());
1179     }
1180
1181   }
1182
1183   private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
1184       SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
1185
1186     // literal value has the top location so that value can be flowed into any
1187     // location
1188     Location literalLoc = Location.createTopLocation(md);
1189     loc.addLocation(literalLoc);
1190     return loc;
1191
1192   }
1193
1194   private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1195       NameNode nn, CompositeLocation loc, CompositeLocation constraint) {
1196
1197     NameDescriptor nd = nn.getName();
1198     if (nd.getBase() != null) {
1199       loc =
1200           checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc, constraint, false);
1201     } else {
1202       String varname = nd.toString();
1203       if (varname.equals("this")) {
1204         // 'this' itself!
1205         MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1206         String thisLocId = methodLattice.getThisLoc();
1207         if (thisLocId == null) {
1208           throw new Error("The location for 'this' is not defined at "
1209               + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1210         }
1211         Location locElement = new Location(md, thisLocId);
1212         loc.addLocation(locElement);
1213         return loc;
1214
1215       }
1216
1217       Descriptor d = (Descriptor) nametable.get(varname);
1218
1219       // CompositeLocation localLoc = null;
1220       if (d instanceof VarDescriptor) {
1221         VarDescriptor vd = (VarDescriptor) d;
1222         // localLoc = d2loc.get(vd);
1223         // the type of var descriptor has a composite location!
1224         loc = ((CompositeLocation) vd.getType().getExtension()).clone();
1225       } else if (d instanceof FieldDescriptor) {
1226         // the type of field descriptor has a location!
1227         FieldDescriptor fd = (FieldDescriptor) d;
1228         if (fd.isStatic()) {
1229           if (fd.isFinal()) {
1230             // if it is 'static final', the location has TOP since no one can
1231             // change its value
1232             loc.addLocation(Location.createTopLocation(md));
1233             return loc;
1234           } else {
1235             // if 'static', the location has pre-assigned global loc
1236             MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1237             String globalLocId = localLattice.getGlobalLoc();
1238             if (globalLocId == null) {
1239               throw new Error("Global location element is not defined in the method " + md);
1240             }
1241             Location globalLoc = new Location(md, globalLocId);
1242
1243             loc.addLocation(globalLoc);
1244           }
1245         } else {
1246           // the location of field access starts from this, followed by field
1247           // location
1248           MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1249           Location thisLoc = new Location(md, localLattice.getThisLoc());
1250           loc.addLocation(thisLoc);
1251         }
1252
1253         Location fieldLoc = (Location) fd.getType().getExtension();
1254         loc.addLocation(fieldLoc);
1255       } else if (d == null) {
1256         // access static field
1257         ClassDescriptor cd = nn.getClassDesc();
1258
1259         MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1260         String globalLocId = localLattice.getGlobalLoc();
1261         if (globalLocId == null) {
1262           throw new Error("Method lattice does not define global variable location at "
1263               + generateErrorMessage(md.getClassDesc(), nn));
1264         }
1265         loc.addLocation(new Location(md, globalLocId));
1266         return loc;
1267
1268       }
1269     }
1270     return loc;
1271   }
1272
1273   private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1274       SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc,
1275       CompositeLocation constraint) {
1276
1277     ExpressionNode left = fan.getExpression();
1278     TypeDescriptor ltd = left.getType();
1279
1280     FieldDescriptor fd = fan.getField();
1281
1282     String varName = null;
1283     if (left.kind() == Kind.NameNode) {
1284       NameDescriptor nd = ((NameNode) left).getName();
1285       varName = nd.toString();
1286     }
1287
1288     if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1289       // using a class name directly or access using this
1290       if (fd.isStatic() && fd.isFinal()) {
1291         loc.addLocation(Location.createTopLocation(md));
1292         return loc;
1293       }
1294     }
1295
1296     loc = checkLocationFromExpressionNode(md, nametable, left, loc, constraint, false);
1297     System.out.println("### checkLocationFromFieldAccessNode=" + fan.printNode(0));
1298     System.out.println("### left=" + left.printNode(0));
1299     if (!left.getType().isPrimitive()) {
1300       Location fieldLoc = getFieldLocation(fd);
1301       loc.addLocation(fieldLoc);
1302     }
1303
1304     return loc;
1305   }
1306
1307   private Location getFieldLocation(FieldDescriptor fd) {
1308
1309     System.out.println("### getFieldLocation=" + fd);
1310     System.out.println("### fd.getType().getExtension()=" + fd.getType().getExtension());
1311
1312     Location fieldLoc = (Location) fd.getType().getExtension();
1313
1314     // handle the case that method annotation checking skips checking field
1315     // declaration
1316     if (fieldLoc == null) {
1317       fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1318     }
1319
1320     return fieldLoc;
1321
1322   }
1323
1324   private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1325       SymbolTable nametable, AssignmentNode an, CompositeLocation loc, CompositeLocation constraint) {
1326
1327     System.out.println("\n# ASSIGNMENTNODE=" + an.printNode(0));
1328
1329     ClassDescriptor cd = md.getClassDesc();
1330
1331     Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1332
1333     boolean postinc = true;
1334     if (an.getOperation().getBaseOp() == null
1335         || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1336             .getBaseOp().getOp() != Operation.POSTDEC))
1337       postinc = false;
1338
1339     // if LHS is array access node, need to check if array index is higher
1340     // than array itself
1341     CompositeLocation destLocation =
1342         checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1343             constraint, true);
1344
1345     CompositeLocation rhsLocation;
1346     CompositeLocation srcLocation;
1347
1348     if (!postinc) {
1349       rhsLocation =
1350           checkLocationFromExpressionNode(md, nametable, an.getSrc(), new CompositeLocation(),
1351               constraint, false);
1352
1353       System.out.println("dstLocation=" + destLocation);
1354       System.out.println("rhsLocation=" + rhsLocation);
1355       System.out.println("constraint=" + constraint);
1356
1357       srcLocation = rhsLocation;
1358
1359       if (!rhsLocation.get(rhsLocation.getSize() - 1).isTop()) {
1360         if (constraint != null) {
1361           inputGLBSet.add(rhsLocation);
1362           inputGLBSet.add(constraint);
1363           srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1364         }
1365       }
1366
1367       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1368         throw new Error("The value flow from " + srcLocation + " to " + destLocation
1369             + " does not respect location hierarchy on the assignment " + an.printNode(0) + " at "
1370             + cd.getSourceFileName() + "::" + an.getNumLine());
1371       }
1372
1373     } else {
1374       destLocation =
1375           rhsLocation =
1376               checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1377                   constraint, false);
1378
1379       if (constraint != null) {
1380         inputGLBSet.add(rhsLocation);
1381         inputGLBSet.add(constraint);
1382         srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1383       } else {
1384         srcLocation = rhsLocation;
1385       }
1386
1387       System.out.println("srcLocation=" + srcLocation);
1388       System.out.println("rhsLocation=" + rhsLocation);
1389       System.out.println("constraint=" + constraint);
1390
1391       if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1392
1393         if (srcLocation.equals(destLocation)) {
1394           throw new Error("Location " + srcLocation
1395               + " is not allowed to have the value flow that moves within the same location at '"
1396               + an.printNode(0) + "' of " + cd.getSourceFileName() + "::" + an.getNumLine());
1397         } else {
1398           throw new Error("The value flow from " + srcLocation + " to " + destLocation
1399               + " does not respect location hierarchy on the assignment " + an.printNode(0)
1400               + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1401         }
1402
1403       }
1404
1405     }
1406
1407     return destLocation;
1408   }
1409
1410   private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1411       SymbolTable nametable, TreeNode n) {
1412
1413     ClassDescriptor cd = md.getClassDesc();
1414     Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1415
1416     // currently enforce every variable to have corresponding location
1417     if (annotationVec.size() == 0) {
1418       throw new Error("Location is not assigned to variable " + vd.getSymbol() + " in the method "
1419           + md.getSymbol() + " of the class " + cd.getSymbol());
1420     }
1421
1422     if (annotationVec.size() > 1) { // variable can have at most one location
1423       throw new Error(vd.getSymbol() + " has more than one location.");
1424     }
1425
1426     AnnotationDescriptor ad = annotationVec.elementAt(0);
1427
1428     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1429
1430       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1431         String locDec = ad.getValue(); // check if location is defined
1432
1433         if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1434           DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1435           d2loc.put(vd, deltaLoc);
1436           addLocationType(vd.getType(), deltaLoc);
1437         } else {
1438           CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1439
1440           Location lastElement = compLoc.get(compLoc.getSize() - 1);
1441           if (ssjava.isSharedLocation(lastElement)) {
1442             ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1443           }
1444
1445           d2loc.put(vd, compLoc);
1446           addLocationType(vd.getType(), compLoc);
1447         }
1448
1449       }
1450     }
1451
1452   }
1453
1454   private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1455
1456     int deltaCount = 0;
1457     int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1458     while (dIdx >= 0) {
1459       deltaCount++;
1460       int beginIdx = dIdx + 6;
1461       locDec = locDec.substring(beginIdx, locDec.length() - 1);
1462       dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1463     }
1464
1465     CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1466     DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1467
1468     return deltaLoc;
1469   }
1470
1471   private Location parseFieldLocDeclaraton(String decl, String msg) throws Exception {
1472
1473     int idx = decl.indexOf(".");
1474
1475     String className = decl.substring(0, idx);
1476     String fieldName = decl.substring(idx + 1);
1477
1478     className.replaceAll(" ", "");
1479     fieldName.replaceAll(" ", "");
1480
1481     Descriptor d = state.getClassSymbolTable().get(className);
1482
1483     if (d == null) {
1484       System.out.println("state.getClassSymbolTable()=" + state.getClassSymbolTable());
1485       throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1486           + msg);
1487     }
1488
1489     assert (d instanceof ClassDescriptor);
1490     SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1491     if (!lattice.containsKey(fieldName)) {
1492       throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1493           + className + "' at " + msg);
1494     }
1495
1496     return new Location(d, fieldName);
1497   }
1498
1499   private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1500
1501     CompositeLocation compLoc = new CompositeLocation();
1502
1503     StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1504     List<String> locIdList = new ArrayList<String>();
1505     while (tokenizer.hasMoreTokens()) {
1506       String locId = tokenizer.nextToken();
1507       locIdList.add(locId);
1508     }
1509
1510     // at least,one location element needs to be here!
1511     assert (locIdList.size() > 0);
1512
1513     // assume that loc with idx 0 comes from the local lattice
1514     // loc with idx 1 comes from the field lattice
1515
1516     String localLocId = locIdList.get(0);
1517     SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1518     Location localLoc = new Location(md, localLocId);
1519     if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1520       System.out.println("locDec=" + locDec);
1521       throw new Error("Location " + localLocId
1522           + " is not defined in the local variable lattice at "
1523           + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : md) + ".");
1524     }
1525     compLoc.addLocation(localLoc);
1526
1527     for (int i = 1; i < locIdList.size(); i++) {
1528       String locName = locIdList.get(i);
1529       try {
1530         Location fieldLoc =
1531             parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1532         compLoc.addLocation(fieldLoc);
1533       } catch (Exception e) {
1534         throw new Error("The location declaration '" + locName + "' is wrong  at "
1535             + generateErrorMessage(md.getClassDesc(), n));
1536       }
1537     }
1538
1539     return compLoc;
1540
1541   }
1542
1543   private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1544     VarDescriptor vd = dn.getVarDescriptor();
1545     assignLocationOfVarDescriptor(vd, md, nametable, dn);
1546   }
1547
1548   private void checkDeclarationInClass(ClassDescriptor cd) {
1549     // Check to see that fields are okay
1550     for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1551       FieldDescriptor fd = (FieldDescriptor) field_it.next();
1552
1553       if (!(fd.isFinal() && fd.isStatic())) {
1554         checkFieldDeclaration(cd, fd);
1555       } else {
1556         // for static final, assign top location by default
1557         Location loc = Location.createTopLocation(cd);
1558         addLocationType(fd.getType(), loc);
1559       }
1560     }
1561   }
1562
1563   private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1564
1565     Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1566
1567     // currently enforce every field to have corresponding location
1568     if (annotationVec.size() == 0) {
1569       throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1570           + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1571     }
1572
1573     if (annotationVec.size() > 1) {
1574       // variable can have at most one location
1575       throw new Error("Field " + fd.getSymbol() + " of class " + cd
1576           + " has more than one location.");
1577     }
1578
1579     AnnotationDescriptor ad = annotationVec.elementAt(0);
1580     Location loc = null;
1581
1582     if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1583       if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1584         String locationID = ad.getValue();
1585         // check if location is defined
1586         SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1587         if (lattice == null || (!lattice.containsKey(locationID))) {
1588           throw new Error("Location " + locationID
1589               + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1590               + cd.getSourceFileName() + ".");
1591         }
1592         loc = new Location(cd, locationID);
1593
1594         if (ssjava.isSharedLocation(loc)) {
1595           ssjava.mapSharedLocation2Descriptor(loc, fd);
1596         }
1597
1598         addLocationType(fd.getType(), loc);
1599
1600       }
1601     }
1602
1603     return loc;
1604   }
1605
1606   private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1607     if (type != null) {
1608       type.setExtension(loc);
1609     }
1610   }
1611
1612   private void addLocationType(TypeDescriptor type, Location loc) {
1613     if (type != null) {
1614       type.setExtension(loc);
1615     }
1616   }
1617
1618   static class CompositeLattice {
1619
1620     public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1621
1622       System.out.println("\nisGreaterThan=" + loc1 + " " + loc2 + " msg=" + msg);
1623       int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, false, msg);
1624       if (baseCompareResult == ComparisonResult.EQUAL) {
1625         if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1626           return true;
1627         } else {
1628           return false;
1629         }
1630       } else if (baseCompareResult == ComparisonResult.GREATER) {
1631         return true;
1632       } else {
1633         return false;
1634       }
1635
1636     }
1637
1638     public static int compare(CompositeLocation loc1, CompositeLocation loc2, boolean ignore,
1639         String msg) {
1640
1641       System.out.println("compare=" + loc1 + " " + loc2);
1642       int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, ignore, msg);
1643
1644       if (baseCompareResult == ComparisonResult.EQUAL) {
1645         return compareDelta(loc1, loc2);
1646       } else {
1647         return baseCompareResult;
1648       }
1649
1650     }
1651
1652     private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1653
1654       int deltaCount1 = 0;
1655       int deltaCount2 = 0;
1656       if (dLoc1 instanceof DeltaLocation) {
1657         deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1658       }
1659
1660       if (dLoc2 instanceof DeltaLocation) {
1661         deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1662       }
1663       if (deltaCount1 < deltaCount2) {
1664         return ComparisonResult.GREATER;
1665       } else if (deltaCount1 == deltaCount2) {
1666         return ComparisonResult.EQUAL;
1667       } else {
1668         return ComparisonResult.LESS;
1669       }
1670
1671     }
1672
1673     private static int compareBaseLocationSet(CompositeLocation compLoc1,
1674         CompositeLocation compLoc2, boolean awareSharedLoc, boolean ignore, String msg) {
1675
1676       // if compLoc1 is greater than compLoc2, return true
1677       // else return false;
1678
1679       // compare one by one in according to the order of the tuple
1680       int numOfTie = 0;
1681       for (int i = 0; i < compLoc1.getSize(); i++) {
1682         Location loc1 = compLoc1.get(i);
1683         if (i >= compLoc2.getSize()) {
1684           if (ignore) {
1685             return ComparisonResult.INCOMPARABLE;
1686           } else {
1687             throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1688                 + " because they are not comparable at " + msg);
1689           }
1690         }
1691         Location loc2 = compLoc2.get(i);
1692
1693         Descriptor descriptor = getCommonParentDescriptor(loc1, loc2, msg);
1694         SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
1695
1696         // check if the shared location is appeared only at the end of the
1697         // composite location
1698         if (lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1699           if (i != (compLoc1.getSize() - 1)) {
1700             throw new Error("The shared location " + loc1.getLocIdentifier()
1701                 + " cannot be appeared in the middle of composite location at" + msg);
1702           }
1703         }
1704
1705         if (lattice.getSharedLocSet().contains(loc2.getLocIdentifier())) {
1706           if (i != (compLoc2.getSize() - 1)) {
1707             throw new Error("The shared location " + loc2.getLocIdentifier()
1708                 + " cannot be appeared in the middle of composite location at " + msg);
1709           }
1710         }
1711
1712         // if (!lattice1.equals(lattice2)) {
1713         // throw new Error("Failed to compare two locations of " + compLoc1 +
1714         // " and " + compLoc2
1715         // + " because they are not comparable at " + msg);
1716         // }
1717
1718         if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1719           numOfTie++;
1720           // check if the current location is the spinning location
1721           // note that the spinning location only can be appeared in the last
1722           // part of the composite location
1723           if (awareSharedLoc && numOfTie == compLoc1.getSize()
1724               && lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1725             return ComparisonResult.GREATER;
1726           }
1727           continue;
1728         } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1729           return ComparisonResult.GREATER;
1730         } else {
1731           return ComparisonResult.LESS;
1732         }
1733
1734       }
1735
1736       if (numOfTie == compLoc1.getSize()) {
1737
1738         if (numOfTie != compLoc2.getSize()) {
1739
1740           if (ignore) {
1741             return ComparisonResult.INCOMPARABLE;
1742           } else {
1743             throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1744                 + " because they are not comparable at " + msg);
1745           }
1746
1747         }
1748
1749         return ComparisonResult.EQUAL;
1750       }
1751
1752       return ComparisonResult.LESS;
1753
1754     }
1755
1756     public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet, String errMsg) {
1757
1758       System.out.println("Calculating GLB=" + inputSet);
1759       CompositeLocation glbCompLoc = new CompositeLocation();
1760
1761       // calculate GLB of the first(priority) element
1762       Set<String> priorityLocIdentifierSet = new HashSet<String>();
1763       Descriptor priorityDescriptor = null;
1764
1765       Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1766           new Hashtable<String, Set<CompositeLocation>>();
1767       // mapping from the priority loc ID to its full representation by the
1768       // composite location
1769
1770       int maxTupleSize = 0;
1771       CompositeLocation maxCompLoc = null;
1772
1773       Location prevPriorityLoc = null;
1774       for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1775         CompositeLocation compLoc = (CompositeLocation) iterator.next();
1776         if (compLoc.getSize() > maxTupleSize) {
1777           maxTupleSize = compLoc.getSize();
1778           maxCompLoc = compLoc;
1779         }
1780         Location priorityLoc = compLoc.get(0);
1781         String priorityLocId = priorityLoc.getLocIdentifier();
1782         priorityLocIdentifierSet.add(priorityLocId);
1783
1784         if (locId2CompLocSet.containsKey(priorityLocId)) {
1785           locId2CompLocSet.get(priorityLocId).add(compLoc);
1786         } else {
1787           Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1788           newSet.add(compLoc);
1789           locId2CompLocSet.put(priorityLocId, newSet);
1790         }
1791
1792         // check if priority location are coming from the same lattice
1793         if (priorityDescriptor == null) {
1794           priorityDescriptor = priorityLoc.getDescriptor();
1795         } else {
1796           priorityDescriptor = getCommonParentDescriptor(priorityLoc, prevPriorityLoc, errMsg);
1797         }
1798         prevPriorityLoc = priorityLoc;
1799         // else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1800         // throw new Error("Failed to calculate GLB of " + inputSet
1801         // + " because they are from different lattices.");
1802         // }
1803       }
1804
1805       SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1806       String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1807
1808       glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1809       Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1810
1811       if (compSet == null) {
1812         // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1813         // mean that the result is already lower than <x1,y1> and <x2,y2>
1814         // assign TOP to the rest of the location elements
1815
1816         // in this case, do not take care about delta
1817         // CompositeLocation inputComp = inputSet.iterator().next();
1818         for (int i = 1; i < maxTupleSize; i++) {
1819           glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
1820         }
1821       } else {
1822
1823         // here find out composite location that has a maximum length tuple
1824         // if we have three input set: [A], [A,B], [A,B,C]
1825         // maximum length tuple will be [A,B,C]
1826         int max = 0;
1827         CompositeLocation maxFromCompSet = null;
1828         for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1829           CompositeLocation c = (CompositeLocation) iterator.next();
1830           if (c.getSize() > max) {
1831             max = c.getSize();
1832             maxFromCompSet = c;
1833           }
1834         }
1835
1836         if (compSet.size() == 1) {
1837           // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1838           CompositeLocation comp = compSet.iterator().next();
1839           for (int i = 1; i < comp.getSize(); i++) {
1840             glbCompLoc.addLocation(comp.get(i));
1841           }
1842
1843           // if input location corresponding to glb is a delta, need to apply
1844           // delta to glb result
1845           if (comp instanceof DeltaLocation) {
1846             glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1847           }
1848
1849         } else {
1850           // when GLB(x1,x2)==x1 and x2 : GLB case 1
1851           // if more than one location shares the same priority GLB
1852           // need to calculate the rest of GLB loc
1853
1854           // setup input set starting from the second tuple item
1855           Set<CompositeLocation> innerGLBInput = new HashSet<CompositeLocation>();
1856           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1857             CompositeLocation compLoc = (CompositeLocation) iterator.next();
1858             CompositeLocation innerCompLoc = new CompositeLocation();
1859             for (int idx = 1; idx < compLoc.getSize(); idx++) {
1860               innerCompLoc.addLocation(compLoc.get(idx));
1861             }
1862             if (innerCompLoc.getSize() > 0) {
1863               innerGLBInput.add(innerCompLoc);
1864             }
1865           }
1866
1867           if (innerGLBInput.size() > 0) {
1868             CompositeLocation innerGLB = CompositeLattice.calculateGLB(innerGLBInput, errMsg);
1869             for (int idx = 0; idx < innerGLB.getSize(); idx++) {
1870               glbCompLoc.addLocation(innerGLB.get(idx));
1871             }
1872           }
1873
1874           // if input location corresponding to glb is a delta, need to apply
1875           // delta to glb result
1876
1877           for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1878             CompositeLocation compLoc = (CompositeLocation) iterator.next();
1879             if (compLoc instanceof DeltaLocation) {
1880               if (glbCompLoc.equals(compLoc)) {
1881                 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1882                 break;
1883               }
1884             }
1885           }
1886
1887         }
1888       }
1889
1890       System.out.println("GLB=" + glbCompLoc);
1891       return glbCompLoc;
1892
1893     }
1894
1895     static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1896
1897       SSJavaLattice<String> lattice = null;
1898
1899       if (d instanceof ClassDescriptor) {
1900         lattice = ssjava.getCd2lattice().get(d);
1901       } else if (d instanceof MethodDescriptor) {
1902         if (ssjava.getMd2lattice().containsKey(d)) {
1903           lattice = ssjava.getMd2lattice().get(d);
1904         } else {
1905           // use default lattice for the method
1906           lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1907         }
1908       }
1909
1910       return lattice;
1911     }
1912
1913     static Descriptor getCommonParentDescriptor(Location loc1, Location loc2, String msg) {
1914
1915       Descriptor d1 = loc1.getDescriptor();
1916       Descriptor d2 = loc2.getDescriptor();
1917
1918       Descriptor descriptor;
1919
1920       if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
1921
1922         if (d1.equals(d2)) {
1923           descriptor = d1;
1924         } else {
1925           // identifying which one is parent class
1926           Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
1927           Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
1928
1929           if (d1 == null && d2 == null) {
1930             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1931                 + " because they are not comparable at " + msg);
1932           } else if (d1SubClassesSet != null && d1SubClassesSet.contains(d2)) {
1933             descriptor = d1;
1934           } else if (d2SubClassesSet != null && d2SubClassesSet.contains(d1)) {
1935             descriptor = d2;
1936           } else {
1937             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1938                 + " because they are not comparable at " + msg);
1939           }
1940         }
1941
1942       } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
1943
1944         if (d1.equals(d2)) {
1945           descriptor = d1;
1946         } else {
1947
1948           // identifying which one is parent class
1949           MethodDescriptor md1 = (MethodDescriptor) d1;
1950           MethodDescriptor md2 = (MethodDescriptor) d2;
1951
1952           if (!md1.matches(md2)) {
1953             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1954                 + " because they are not comparable at " + msg);
1955           }
1956
1957           Set<Descriptor> d1SubClassesSet =
1958               ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
1959           Set<Descriptor> d2SubClassesSet =
1960               ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
1961
1962           if (d1 == null && d2 == null) {
1963             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1964                 + " because they are not comparable at " + msg);
1965           } else if (d1 != null && d1SubClassesSet.contains(d2)) {
1966             descriptor = d1;
1967           } else if (d2 != null && d2SubClassesSet.contains(d1)) {
1968             descriptor = d2;
1969           } else {
1970             throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1971                 + " because they are not comparable at " + msg);
1972           }
1973         }
1974
1975       } else {
1976         throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1977             + " because they are not comparable at " + msg);
1978       }
1979
1980       return descriptor;
1981
1982     }
1983
1984   }
1985
1986   class ComparisonResult {
1987
1988     public static final int GREATER = 0;
1989     public static final int EQUAL = 1;
1990     public static final int LESS = 2;
1991     public static final int INCOMPARABLE = 3;
1992     int result;
1993
1994   }
1995
1996 }
1997
1998 class ReturnLocGenerator {
1999
2000   public static final int PARAMISHIGHER = 0;
2001   public static final int PARAMISSAME = 1;
2002   public static final int IGNORE = 2;
2003
2004   private Hashtable<Integer, Integer> paramIdx2paramType;
2005
2006   private CompositeLocation declaredReturnLoc = null;
2007
2008   public ReturnLocGenerator(CompositeLocation returnLoc, MethodDescriptor md,
2009       List<CompositeLocation> params, String msg) {
2010
2011     CompositeLocation thisLoc = params.get(0);
2012     if (returnLoc.get(0).equals(thisLoc.get(0)) && returnLoc.getSize() > 1) {
2013       // if the declared return location consists of THIS and field location,
2014       // return location for the caller's side has to have same field element
2015       this.declaredReturnLoc = returnLoc;
2016     } else {
2017       // creating mappings
2018       paramIdx2paramType = new Hashtable<Integer, Integer>();
2019       for (int i = 0; i < params.size(); i++) {
2020         CompositeLocation param = params.get(i);
2021         int compareResult = CompositeLattice.compare(param, returnLoc, true, msg);
2022
2023         int type;
2024         if (compareResult == ComparisonResult.GREATER) {
2025           type = 0;
2026         } else if (compareResult == ComparisonResult.EQUAL) {
2027           type = 1;
2028         } else {
2029           type = 2;
2030         }
2031         paramIdx2paramType.put(new Integer(i), new Integer(type));
2032       }
2033     }
2034
2035   }
2036
2037   public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
2038
2039     if (declaredReturnLoc != null) {
2040       // when developer specify that the return value is [THIS,field]
2041       // needs to translate to the caller's location
2042       CompositeLocation callerLoc = new CompositeLocation();
2043       CompositeLocation callerBaseLocation = args.get(0);
2044
2045       for (int i = 0; i < callerBaseLocation.getSize(); i++) {
2046         callerLoc.addLocation(callerBaseLocation.get(i));
2047       }
2048       for (int i = 1; i < declaredReturnLoc.getSize(); i++) {
2049         callerLoc.addLocation(declaredReturnLoc.get(i));
2050       }
2051       return callerLoc;
2052     } else {
2053       // compute the highest possible location in caller's side
2054       assert paramIdx2paramType.keySet().size() == args.size();
2055
2056       Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
2057       for (int i = 0; i < args.size(); i++) {
2058         int type = (paramIdx2paramType.get(new Integer(i))).intValue();
2059         CompositeLocation argLoc = args.get(i);
2060         if (type == PARAMISHIGHER) {
2061           // return loc is lower than param
2062           DeltaLocation delta = new DeltaLocation(argLoc, 1);
2063           inputGLB.add(delta);
2064         } else if (type == PARAMISSAME) {
2065           // return loc is equal or lower than param
2066           inputGLB.add(argLoc);
2067         }
2068       }
2069
2070       // compute GLB of arguments subset that are same or higher than return
2071       // location
2072       CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB, "");
2073       return glb;
2074     }
2075
2076   }
2077 }