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