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