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