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