1 package Analysis.SSJava;
3 import java.util.ArrayList;
4 import java.util.HashSet;
5 import java.util.Hashtable;
6 import java.util.Iterator;
9 import java.util.StringTokenizer;
10 import java.util.Vector;
12 import Analysis.SSJava.FlowDownCheck.ComparisonResult;
13 import Analysis.SSJava.FlowDownCheck.CompositeLattice;
14 import IR.AnnotationDescriptor;
15 import IR.ClassDescriptor;
17 import IR.FieldDescriptor;
18 import IR.MethodDescriptor;
19 import IR.NameDescriptor;
22 import IR.SymbolTable;
23 import IR.TypeDescriptor;
24 import IR.VarDescriptor;
25 import IR.Tree.ArrayAccessNode;
26 import IR.Tree.AssignmentNode;
27 import IR.Tree.BlockExpressionNode;
28 import IR.Tree.BlockNode;
29 import IR.Tree.BlockStatementNode;
30 import IR.Tree.CastNode;
31 import IR.Tree.CreateObjectNode;
32 import IR.Tree.DeclarationNode;
33 import IR.Tree.ExpressionNode;
34 import IR.Tree.FieldAccessNode;
35 import IR.Tree.IfStatementNode;
37 import IR.Tree.LiteralNode;
38 import IR.Tree.LoopNode;
39 import IR.Tree.MethodInvokeNode;
40 import IR.Tree.NameNode;
41 import IR.Tree.OpNode;
42 import IR.Tree.ReturnNode;
43 import IR.Tree.SubBlockNode;
44 import IR.Tree.SwitchBlockNode;
45 import IR.Tree.SwitchStatementNode;
46 import IR.Tree.TertiaryNode;
47 import IR.Tree.TreeNode;
50 public class FlowDownCheck {
53 static SSJavaAnalysis ssjava;
57 // mapping from 'descriptor' to 'composite location'
58 Hashtable<Descriptor, CompositeLocation> d2loc;
60 Hashtable<MethodDescriptor, CompositeLocation> md2ReturnLoc;
61 Hashtable<MethodDescriptor, ReturnLocGenerator> md2ReturnLocGen;
63 // mapping from 'locID' to 'class descriptor'
64 Hashtable<String, ClassDescriptor> fieldLocName2cd;
66 public FlowDownCheck(SSJavaAnalysis ssjava, State state) {
69 this.toanalyze = new HashSet();
70 this.d2loc = new Hashtable<Descriptor, CompositeLocation>();
71 this.fieldLocName2cd = new Hashtable<String, ClassDescriptor>();
72 this.md2ReturnLoc = new Hashtable<MethodDescriptor, CompositeLocation>();
73 this.md2ReturnLocGen = new Hashtable<MethodDescriptor, ReturnLocGenerator>();
78 // construct mapping from the location name to the class descriptor
79 // assume that the location name is unique through the whole program
81 Set<ClassDescriptor> cdSet = ssjava.getCd2lattice().keySet();
82 for (Iterator iterator = cdSet.iterator(); iterator.hasNext();) {
83 ClassDescriptor cd = (ClassDescriptor) iterator.next();
84 SSJavaLattice<String> lattice = ssjava.getCd2lattice().get(cd);
85 Set<String> fieldLocNameSet = lattice.getKeySet();
87 for (Iterator iterator2 = fieldLocNameSet.iterator(); iterator2.hasNext();) {
88 String fieldLocName = (String) iterator2.next();
89 fieldLocName2cd.put(fieldLocName, cd);
96 public void flowDownCheck() {
97 SymbolTable classtable = state.getClassSymbolTable();
99 // phase 1 : checking declaration node and creating mapping of 'type
100 // desciptor' & 'location'
101 toanalyze.addAll(classtable.getValueSet());
102 toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
104 while (!toanalyze.isEmpty()) {
105 Object obj = toanalyze.iterator().next();
106 ClassDescriptor cd = (ClassDescriptor) obj;
107 toanalyze.remove(cd);
109 if (ssjava.needToBeAnnoated(cd)) {
111 ClassDescriptor superDesc = cd.getSuperDesc();
113 if (superDesc != null && (!superDesc.getSymbol().equals("Object"))) {
114 checkOrderingInheritance(superDesc, cd);
117 checkDeclarationInClass(cd);
118 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
119 MethodDescriptor md = (MethodDescriptor) method_it.next();
120 if (ssjava.needTobeAnnotated(md)) {
121 checkDeclarationInMethodBody(cd, md);
128 // phase2 : checking assignments
129 toanalyze.addAll(classtable.getValueSet());
130 toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
131 while (!toanalyze.isEmpty()) {
132 Object obj = toanalyze.iterator().next();
133 ClassDescriptor cd = (ClassDescriptor) obj;
134 toanalyze.remove(cd);
137 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
138 MethodDescriptor md = (MethodDescriptor) method_it.next();
139 if (ssjava.needTobeAnnotated(md)) {
140 checkMethodBody(cd, md);
147 private void checkOrderingInheritance(ClassDescriptor superCd, ClassDescriptor cd) {
148 // here, we're going to check that sub class keeps same relative orderings
149 // in respect to super class
151 SSJavaLattice<String> superLattice = ssjava.getClassLattice(superCd);
152 SSJavaLattice<String> subLattice = ssjava.getClassLattice(cd);
154 if (superLattice != null) {
155 // if super class doesn't define lattice, then we don't need to check its
157 if (subLattice == null) {
158 throw new Error("If a parent class '" + superCd
159 + "' has a ordering lattice, its subclass '" + cd + "' should have one.");
162 Set<Pair<String, String>> superPairSet = superLattice.getOrderingPairSet();
163 Set<Pair<String, String>> subPairSet = subLattice.getOrderingPairSet();
165 for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
166 Pair<String, String> pair = (Pair<String, String>) iterator.next();
168 if (!subPairSet.contains(pair)) {
169 throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
170 + pair.getSecond() + " < " + pair.getFirst()
171 + "' that is defined by its superclass '" + superCd + "'.");
176 MethodLattice<String> superMethodDefaultLattice = ssjava.getMethodDefaultLattice(superCd);
177 MethodLattice<String> subMethodDefaultLattice = ssjava.getMethodDefaultLattice(cd);
179 if (superMethodDefaultLattice != null) {
180 if (subMethodDefaultLattice == null) {
181 throw new Error("When a parent class '" + superCd
182 + "' defines a default method lattice, its subclass '" + cd + "' should define one.");
185 Set<Pair<String, String>> superPairSet = superMethodDefaultLattice.getOrderingPairSet();
186 Set<Pair<String, String>> subPairSet = subMethodDefaultLattice.getOrderingPairSet();
188 for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
189 Pair<String, String> pair = (Pair<String, String>) iterator.next();
191 if (!subPairSet.contains(pair)) {
192 throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
193 + pair.getSecond() + " < " + pair.getFirst()
194 + "' that is defined by its superclass '" + superCd
195 + "' in the method default lattice.");
203 public Hashtable getMap() {
207 private void checkDeclarationInMethodBody(ClassDescriptor cd, MethodDescriptor md) {
208 BlockNode bn = state.getMethodBody(md);
210 if (ssjava.needTobeAnnotated(md)) {
212 // parsing returnloc annotation
213 Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
214 if (methodAnnotations != null) {
215 for (int i = 0; i < methodAnnotations.size(); i++) {
216 AnnotationDescriptor an = methodAnnotations.elementAt(i);
217 if (an.getMarker().equals(ssjava.RETURNLOC)) {
218 // developer explicitly defines method lattice
219 String returnLocDeclaration = an.getValue();
220 CompositeLocation returnLocComp =
221 parseLocationDeclaration(md, null, returnLocDeclaration);
222 md2ReturnLoc.put(md, returnLocComp);
225 if (!md.getReturnType().isVoid() && !md2ReturnLoc.containsKey(md)) {
226 throw new Error("Return location is not specified for the method " + md + " at "
227 + cd.getSourceFileName());
231 List<CompositeLocation> paramList = new ArrayList<CompositeLocation>();
233 boolean hasReturnValue = (!md.getReturnType().isVoid());
234 if (hasReturnValue) {
235 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
236 String thisLocId = methodLattice.getThisLoc();
237 if (thisLocId == null) {
238 throw new Error("Method '" + md + "' does not have the definition of 'this' location at "
239 + md.getClassDesc().getSourceFileName());
241 CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
242 paramList.add(thisLoc);
245 for (int i = 0; i < md.numParameters(); i++) {
246 // process annotations on method parameters
247 VarDescriptor vd = (VarDescriptor) md.getParameter(i);
248 assignLocationOfVarDescriptor(vd, md, md.getParameterTable(), bn);
249 if (hasReturnValue) {
250 paramList.add(d2loc.get(vd));
254 if (hasReturnValue) {
255 md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), paramList,
256 generateErrorMessage(cd, null)));
258 checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
263 private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
264 bn.getVarTable().setParent(nametable);
265 for (int i = 0; i < bn.size(); i++) {
266 BlockStatementNode bsn = bn.get(i);
267 checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
271 private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
272 BlockStatementNode bsn) {
274 switch (bsn.kind()) {
275 case Kind.SubBlockNode:
276 checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
279 case Kind.DeclarationNode:
280 checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
284 checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
289 private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
291 if (ln.getType() == LoopNode.FORLOOP) {
292 // check for loop case
293 ClassDescriptor cd = md.getClassDesc();
294 BlockNode bn = ln.getInitializer();
295 for (int i = 0; i < bn.size(); i++) {
296 BlockStatementNode bsn = bn.get(i);
297 checkDeclarationInBlockStatementNode(md, nametable, bsn);
302 checkDeclarationInBlockNode(md, nametable, ln.getBody());
305 private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
306 BlockNode bn = state.getMethodBody(md);
307 checkLocationFromBlockNode(md, md.getParameterTable(), bn);
310 private String generateErrorMessage(ClassDescriptor cd, TreeNode tn) {
312 return cd.getSourceFileName() + "::" + tn.getNumLine();
314 return cd.getSourceFileName();
319 private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
322 bn.getVarTable().setParent(nametable);
323 // it will return the lowest location in the block node
324 CompositeLocation lowestLoc = null;
326 for (int i = 0; i < bn.size(); i++) {
327 BlockStatementNode bsn = bn.get(i);
328 CompositeLocation bLoc = checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn);
329 if (!bLoc.isEmpty()) {
330 if (lowestLoc == null) {
333 if (CompositeLattice.isGreaterThan(lowestLoc, bLoc,
334 generateErrorMessage(md.getClassDesc(), bn))) {
342 if (lowestLoc == null) {
343 lowestLoc = new CompositeLocation(Location.createBottomLocation(md));
349 private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
350 SymbolTable nametable, BlockStatementNode bsn) {
352 CompositeLocation compLoc = null;
353 switch (bsn.kind()) {
354 case Kind.BlockExpressionNode:
355 compLoc = checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn);
358 case Kind.DeclarationNode:
359 compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn);
362 case Kind.IfStatementNode:
363 compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn);
367 compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn);
370 case Kind.ReturnNode:
371 compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn);
374 case Kind.SubBlockNode:
375 compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn);
378 case Kind.ContinueBreakNode:
379 compLoc = new CompositeLocation();
382 case Kind.SwitchStatementNode:
383 compLoc = checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
389 private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
390 SymbolTable nametable, SwitchStatementNode ssn) {
392 ClassDescriptor cd = md.getClassDesc();
393 CompositeLocation condLoc =
394 checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation());
395 BlockNode sbn = ssn.getSwitchBody();
397 Set<CompositeLocation> blockLocSet = new HashSet<CompositeLocation>();
398 for (int i = 0; i < sbn.size(); i++) {
399 CompositeLocation blockLoc =
400 checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i));
401 if (!CompositeLattice.isGreaterThan(condLoc, blockLoc,
402 generateErrorMessage(cd, ssn.getCondition()))) {
404 "The location of the switch-condition statement is lower than the conditional body at "
405 + cd.getSourceFileName() + ":" + ssn.getCondition().getNumLine());
408 blockLocSet.add(blockLoc);
410 return CompositeLattice.calculateGLB(blockLocSet);
413 private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
414 SymbolTable nametable, SwitchBlockNode sbn) {
416 CompositeLocation blockLoc =
417 checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement());
423 private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
426 ExpressionNode returnExp = rn.getReturnExpression();
428 CompositeLocation returnValueLoc;
429 if (returnExp != null) {
431 checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation());
433 // check if return value is equal or higher than RETRUNLOC of method
434 // declaration annotation
435 CompositeLocation declaredReturnLoc = md2ReturnLoc.get(md);
437 System.out.println("\nreturnLocAt=" + declaredReturnLoc);
438 System.out.println("returnValueLoc=" + returnValueLoc);
439 System.out.println("COMPARE RESULT="
440 + CompositeLattice.compare(declaredReturnLoc, returnValueLoc,
441 generateErrorMessage(md.getClassDesc(), rn)));
444 CompositeLattice.compare(returnValueLoc, declaredReturnLoc,
445 generateErrorMessage(md.getClassDesc(), rn));
447 if (compareResult == ComparisonResult.LESS || compareResult == ComparisonResult.INCOMPARABLE) {
449 "Return value location is not equal or higher than the declaraed return location at "
450 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
454 return new CompositeLocation();
457 private boolean hasOnlyLiteralValue(ExpressionNode en) {
458 if (en.kind() == Kind.LiteralNode) {
465 private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
468 ClassDescriptor cd = md.getClassDesc();
469 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
471 CompositeLocation condLoc =
472 checkLocationFromExpressionNode(md, nametable, ln.getCondition(), new CompositeLocation());
473 addLocationType(ln.getCondition().getType(), (condLoc));
475 CompositeLocation bodyLoc = checkLocationFromBlockNode(md, nametable, ln.getBody());
477 if (!CompositeLattice.isGreaterThan(condLoc, bodyLoc, generateErrorMessage(cd, ln))) {
478 // loop condition should be higher than loop body
480 "The location of the while-condition statement is lower than the loop body at "
481 + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
487 // check for loop case
488 BlockNode bn = ln.getInitializer();
489 bn.getVarTable().setParent(nametable);
491 // calculate glb location of condition and update statements
492 CompositeLocation condLoc =
493 checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
494 new CompositeLocation());
495 addLocationType(ln.getCondition().getType(), condLoc);
497 CompositeLocation updateLoc =
498 checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate());
500 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
501 glbInputSet.add(condLoc);
502 // glbInputSet.add(updateLoc);
504 CompositeLocation glbLocOfForLoopCond = CompositeLattice.calculateGLB(glbInputSet);
506 // check location of 'forloop' body
507 CompositeLocation blockLoc = checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody());
509 // compute glb of body including loop body and update statement
512 if (blockLoc == null) {
513 // when there is no statement in the loop body
515 if (updateLoc == null) {
516 // also there is no update statement in the loop body
517 return glbLocOfForLoopCond;
519 glbInputSet.add(updateLoc);
522 glbInputSet.add(blockLoc);
523 glbInputSet.add(updateLoc);
526 CompositeLocation loopBodyLoc = CompositeLattice.calculateGLB(glbInputSet);
528 if (!CompositeLattice.isGreaterThan(glbLocOfForLoopCond, loopBodyLoc,
529 generateErrorMessage(cd, ln))) {
531 "The location of the for-condition statement is lower than the for-loop body at "
532 + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
539 private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
540 SymbolTable nametable, SubBlockNode sbn) {
541 CompositeLocation compLoc = checkLocationFromBlockNode(md, nametable, sbn.getBlockNode());
545 private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
546 SymbolTable nametable, IfStatementNode isn) {
548 ClassDescriptor localCD = md.getClassDesc();
549 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
551 CompositeLocation condLoc =
552 checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation());
554 addLocationType(isn.getCondition().getType(), condLoc);
555 glbInputSet.add(condLoc);
557 CompositeLocation locTrueBlock = checkLocationFromBlockNode(md, nametable, isn.getTrueBlock());
558 if (locTrueBlock != null) {
559 glbInputSet.add(locTrueBlock);
560 // here, the location of conditional block should be higher than the
561 // location of true/false blocks
562 if (locTrueBlock != null
563 && !CompositeLattice.isGreaterThan(condLoc, locTrueBlock,
564 generateErrorMessage(localCD, isn.getCondition()))) {
567 "The location of the if-condition statement is lower than the conditional block at "
568 + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
572 if (isn.getFalseBlock() != null) {
573 CompositeLocation locFalseBlock =
574 checkLocationFromBlockNode(md, nametable, isn.getFalseBlock());
576 if (locFalseBlock != null) {
577 glbInputSet.add(locFalseBlock);
579 if (!CompositeLattice.isGreaterThan(condLoc, locFalseBlock,
580 generateErrorMessage(localCD, isn.getCondition()))) {
583 "The location of the if-condition statement is lower than the conditional block at "
584 + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
590 // return GLB location of condition, true, and false block
591 CompositeLocation glbLoc = CompositeLattice.calculateGLB(glbInputSet);
596 private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
597 SymbolTable nametable, DeclarationNode dn) {
599 System.out.println("##DeclarationNode=" + dn.printNode(0) + " "
600 + generateErrorMessage(md.getClassDesc(), dn));
602 VarDescriptor vd = dn.getVarDescriptor();
604 CompositeLocation destLoc = d2loc.get(vd);
606 System.out.println("##DeclarationNode destLoc=" + destLoc + " of vd=" + vd + " of md=" + md);
608 if (dn.getExpression() != null) {
609 CompositeLocation expressionLoc =
610 checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
611 new CompositeLocation());
612 // addTypeLocation(dn.getExpression().getType(), expressionLoc);
614 if (expressionLoc != null) {
615 // checking location order
616 if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
617 generateErrorMessage(md.getClassDesc(), dn))) {
618 throw new Error("The value flow from " + expressionLoc + " to " + destLoc
619 + " does not respect location hierarchy on the assignment " + dn.printNode(0)
620 + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
623 return expressionLoc;
627 return new CompositeLocation();
633 private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
635 checkDeclarationInBlockNode(md, nametable.getParent(), sbn.getBlockNode());
638 private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
639 SymbolTable nametable, BlockExpressionNode ben) {
640 CompositeLocation compLoc =
641 checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null);
642 // addTypeLocation(ben.getExpression().getType(), compLoc);
646 private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
647 SymbolTable nametable, ExpressionNode en, CompositeLocation loc) {
649 CompositeLocation compLoc = null;
652 case Kind.AssignmentNode:
653 compLoc = checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc);
656 case Kind.FieldAccessNode:
657 compLoc = checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc);
661 compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc);
665 compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en);
668 case Kind.CreateObjectNode:
669 compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
672 case Kind.ArrayAccessNode:
673 compLoc = checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en);
676 case Kind.LiteralNode:
677 compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
680 case Kind.MethodInvokeNode:
681 compLoc = checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc);
684 case Kind.TertiaryNode:
685 compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en);
689 compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en);
692 // case Kind.InstanceOfNode:
693 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
696 // case Kind.ArrayInitializerNode:
697 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
701 // case Kind.ClassTypeNode:
702 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
705 // case Kind.OffsetNode:
706 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
713 // addTypeLocation(en.getType(), compLoc);
718 private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
721 ExpressionNode en = cn.getExpression();
722 return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
726 private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
727 SymbolTable nametable, TertiaryNode tn) {
728 ClassDescriptor cd = md.getClassDesc();
730 CompositeLocation condLoc =
731 checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation());
732 addLocationType(tn.getCond().getType(), condLoc);
733 CompositeLocation trueLoc =
734 checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation());
735 addLocationType(tn.getTrueExpr().getType(), trueLoc);
736 CompositeLocation falseLoc =
737 checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation());
738 addLocationType(tn.getFalseExpr().getType(), falseLoc);
740 // locations from true/false branches can be TOP when there are only literal
742 // in this case, we don't need to check flow down rule!
744 // check if condLoc is higher than trueLoc & falseLoc
745 if (!trueLoc.get(0).isTop()
746 && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
748 "The location of the condition expression is lower than the true expression at "
749 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
752 if (!falseLoc.get(0).isTop()
753 && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
754 generateErrorMessage(cd, tn.getCond()))) {
756 "The location of the condition expression is lower than the true expression at "
757 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
760 // then, return glb of trueLoc & falseLoc
761 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
762 glbInputSet.add(trueLoc);
763 glbInputSet.add(falseLoc);
765 return CompositeLattice.calculateGLB(glbInputSet);
768 private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
769 SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc) {
771 checkCalleeConstraints(md, nametable, min);
773 CompositeLocation baseLocation = null;
774 if (min.getExpression() != null) {
776 checkLocationFromExpressionNode(md, nametable, min.getExpression(),
777 new CompositeLocation());
779 String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
780 baseLocation = new CompositeLocation(new Location(md, thisLocId));
783 if (!min.getMethod().getReturnType().isVoid()) {
784 // If method has a return value, compute the highest possible return
785 // location in the caller's perspective
786 CompositeLocation ceilingLoc =
787 computeCeilingLocationForCaller(md, nametable, min, baseLocation);
791 return new CompositeLocation();
795 private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
796 SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation) {
797 List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
799 // by default, method has a THIS parameter
800 argList.add(baseLocation);
802 for (int i = 0; i < min.numArgs(); i++) {
803 ExpressionNode en = min.getArg(i);
804 CompositeLocation callerArg =
805 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
806 argList.add(callerArg);
809 System.out.println("##");
810 System.out.println("min.getMethod()=" + min.getMethod() + " argList=" + argList);
811 System.out.println("computeReturnLocation="
812 + md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList));
814 return md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
818 private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
819 MethodInvokeNode min) {
821 System.out.println("checkCalleeConstraints " + generateErrorMessage(md.getClassDesc(), min));
823 if (min.numArgs() > 1) {
824 // caller needs to guarantee that it passes arguments in regarding to
825 // callee's hierarchy
826 for (int i = 0; i < min.numArgs(); i++) {
827 ExpressionNode en = min.getArg(i);
828 CompositeLocation callerArg1 =
829 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
831 ClassDescriptor calleecd = min.getMethod().getClassDesc();
832 VarDescriptor calleevd = (VarDescriptor) min.getMethod().getParameter(i);
833 CompositeLocation calleeLoc1 = d2loc.get(calleevd);
835 if (!callerArg1.get(0).isTop()) {
836 // here, check if ordering relations among caller's args respect
837 // ordering relations in-between callee's args
838 for (int currentIdx = 0; currentIdx < min.numArgs(); currentIdx++) {
839 if (currentIdx != i) { // skip itself
840 ExpressionNode argExp = min.getArg(currentIdx);
842 CompositeLocation callerArg2 =
843 checkLocationFromExpressionNode(md, nametable, argExp, new CompositeLocation());
845 VarDescriptor calleevd2 = (VarDescriptor) min.getMethod().getParameter(currentIdx);
846 CompositeLocation calleeLoc2 = d2loc.get(calleevd2);
848 System.out.println("#callerResult=" + callerArg1 + " " + callerArg2);
849 System.out.println("#calleeResult=" + calleeLoc1 + " " + calleeLoc2);
852 CompositeLattice.compare(callerArg1, callerArg2,
853 generateErrorMessage(md.getClassDesc(), min));
855 CompositeLattice.compare(calleeLoc1, calleeLoc2,
856 generateErrorMessage(md.getClassDesc(), min));
858 if (calleeResult == ComparisonResult.GREATER
859 && callerResult != ComparisonResult.GREATER) {
860 // If calleeLoc1 is higher than calleeLoc2
861 // then, caller should have same ordering relation in-bet
862 // callerLoc1 & callerLoc2
864 throw new Error("Caller doesn't respect ordering relations among method arguments:"
865 + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
878 private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
879 SymbolTable nametable, ArrayAccessNode aan) {
881 // return glb location of array itself and index
883 ClassDescriptor cd = md.getClassDesc();
885 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
887 CompositeLocation arrayLoc =
888 checkLocationFromExpressionNode(md, nametable, aan.getExpression(), new CompositeLocation());
889 // addTypeLocation(aan.getExpression().getType(), arrayLoc);
890 glbInputSet.add(arrayLoc);
891 CompositeLocation indexLoc =
892 checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation());
893 glbInputSet.add(indexLoc);
894 // addTypeLocation(aan.getIndex().getType(), indexLoc);
896 CompositeLocation glbLoc = CompositeLattice.calculateGLB(glbInputSet);
900 private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
901 SymbolTable nametable, CreateObjectNode con) {
903 ClassDescriptor cd = md.getClassDesc();
906 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
907 for (int i = 0; i < con.numArgs(); i++) {
908 ExpressionNode en = con.getArg(i);
909 CompositeLocation argLoc =
910 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
911 glbInputSet.add(argLoc);
912 addLocationType(en.getType(), argLoc);
915 // check array initializers
916 // if ((con.getArrayInitializer() != null)) {
917 // checkLocationFromArrayInitializerNode(md, nametable,
918 // con.getArrayInitializer());
921 if (glbInputSet.size() > 0) {
922 return CompositeLattice.calculateGLB(glbInputSet);
925 CompositeLocation compLoc = new CompositeLocation();
926 compLoc.addLocation(Location.createTopLocation(md));
931 private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
934 ClassDescriptor cd = md.getClassDesc();
935 CompositeLocation leftLoc = new CompositeLocation();
936 leftLoc = checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc);
937 // addTypeLocation(on.getLeft().getType(), leftLoc);
939 CompositeLocation rightLoc = new CompositeLocation();
940 if (on.getRight() != null) {
941 rightLoc = checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc);
942 // addTypeLocation(on.getRight().getType(), rightLoc);
945 System.out.println("checking op node=" + on.printNode(0)
946 + generateErrorMessage(md.getClassDesc(), on));
947 System.out.println("left loc=" + leftLoc + " from " + on.getLeft().getClass());
948 if (on.getRight() != null) {
949 System.out.println("right loc=" + rightLoc + " from " + on.getRight().kind());
952 Operation op = on.getOp();
954 switch (op.getOp()) {
956 case Operation.UNARYPLUS:
957 case Operation.UNARYMINUS:
958 case Operation.LOGIC_NOT:
962 case Operation.LOGIC_OR:
963 case Operation.LOGIC_AND:
965 case Operation.BIT_OR:
966 case Operation.BIT_XOR:
967 case Operation.BIT_AND:
968 case Operation.ISAVAILABLE:
969 case Operation.EQUAL:
970 case Operation.NOTEQUAL:
980 case Operation.LEFTSHIFT:
981 case Operation.RIGHTSHIFT:
982 case Operation.URIGHTSHIFT:
984 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
985 inputSet.add(leftLoc);
986 inputSet.add(rightLoc);
987 CompositeLocation glbCompLoc = CompositeLattice.calculateGLB(inputSet);
991 throw new Error(op.toString());
996 private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
997 SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
999 // literal value has the top location so that value can be flowed into any
1001 Location literalLoc = Location.createTopLocation(md);
1002 loc.addLocation(literalLoc);
1007 private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1008 NameNode nn, CompositeLocation loc) {
1010 NameDescriptor nd = nn.getName();
1011 if (nd.getBase() != null) {
1012 loc = checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc);
1014 String varname = nd.toString();
1015 if (varname.equals("this")) {
1017 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1018 String thisLocId = methodLattice.getThisLoc();
1019 if (thisLocId == null) {
1020 throw new Error("The location for 'this' is not defined at "
1021 + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1023 Location locElement = new Location(md, thisLocId);
1024 loc.addLocation(locElement);
1027 Descriptor d = (Descriptor) nametable.get(varname);
1029 // CompositeLocation localLoc = null;
1030 if (d instanceof VarDescriptor) {
1031 VarDescriptor vd = (VarDescriptor) d;
1032 // localLoc = d2loc.get(vd);
1033 // the type of var descriptor has a composite location!
1034 loc = ((CompositeLocation) vd.getType().getExtension()).clone();
1035 } else if (d instanceof FieldDescriptor) {
1036 // the type of field descriptor has a location!
1037 FieldDescriptor fd = (FieldDescriptor) d;
1038 if (fd.isStatic()) {
1040 // if it is 'static final', the location has TOP since no one can
1042 loc.addLocation(Location.createTopLocation(md));
1044 // if 'static', the location has pre-assigned global loc
1045 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1046 String globalLocId = localLattice.getGlobalLoc();
1047 if (globalLocId == null) {
1048 throw new Error("Global location element is not defined in the method " + md);
1050 Location globalLoc = new Location(md, globalLocId);
1052 loc.addLocation(globalLoc);
1055 // the location of field access starts from this, followed by field
1057 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1058 Location thisLoc = new Location(md, localLattice.getThisLoc());
1059 loc.addLocation(thisLoc);
1062 Location fieldLoc = (Location) fd.getType().getExtension();
1063 loc.addLocation(fieldLoc);
1069 private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1070 SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc) {
1072 ExpressionNode left = fan.getExpression();
1073 TypeDescriptor ltd = left.getType();
1075 FieldDescriptor fd = fan.getField();
1077 if (ltd.isClassNameRef()) {
1078 // using a class name directly
1079 if (fd.isStatic() && fd.isFinal()) {
1080 loc.addLocation(Location.createTopLocation(md));
1085 loc = checkLocationFromExpressionNode(md, nametable, left, loc);
1086 if (!left.getType().isPrimitive()) {
1087 Location fieldLoc = getFieldLocation(fd);
1088 loc.addLocation(fieldLoc);
1094 private Location getFieldLocation(FieldDescriptor fd) {
1096 Location fieldLoc = (Location) fd.getType().getExtension();
1098 // handle the case that method annotation checking skips checking field
1100 if (fieldLoc == null) {
1101 fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1108 private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1109 SymbolTable nametable, AssignmentNode an, CompositeLocation loc) {
1111 ClassDescriptor cd = md.getClassDesc();
1113 boolean postinc = true;
1114 if (an.getOperation().getBaseOp() == null
1115 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1116 .getBaseOp().getOp() != Operation.POSTDEC))
1119 CompositeLocation destLocation =
1120 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation());
1122 CompositeLocation srcLocation = new CompositeLocation();
1125 if (hasOnlyLiteralValue(an.getSrc())) {
1126 // if source is literal value, src location is TOP. so do not need to
1128 return destLocation;
1130 srcLocation = new CompositeLocation();
1131 srcLocation = checkLocationFromExpressionNode(md, nametable, an.getSrc(), srcLocation);
1133 // System.out.println(" an= " + an.printNode(0) + " an.getSrc()=" +
1134 // an.getSrc().getClass()
1135 // + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1136 // System.out.println("srcLocation=" + srcLocation);
1137 // System.out.println("dstLocation=" + destLocation);
1139 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1140 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1141 + " does not respect location hierarchy on the assignment " + an.printNode(0) + " at "
1142 + cd.getSourceFileName() + "::" + an.getNumLine());
1146 srcLocation = checkLocationFromExpressionNode(md, nametable, an.getDest(), srcLocation);
1148 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1149 throw new Error("Location " + destLocation
1150 + " is not allowed to have the value flow that moves within the same location at "
1151 + cd.getSourceFileName() + "::" + an.getNumLine());
1156 return destLocation;
1159 private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1160 SymbolTable nametable, TreeNode n) {
1162 ClassDescriptor cd = md.getClassDesc();
1163 Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1165 // currently enforce every variable to have corresponding location
1166 if (annotationVec.size() == 0) {
1167 throw new Error("Location is not assigned to variable " + vd.getSymbol() + " in the method "
1168 + md.getSymbol() + " of the class " + cd.getSymbol());
1171 if (annotationVec.size() > 1) { // variable can have at most one location
1172 throw new Error(vd.getSymbol() + " has more than one location.");
1175 AnnotationDescriptor ad = annotationVec.elementAt(0);
1177 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1179 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1180 String locDec = ad.getValue(); // check if location is defined
1182 if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1183 DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1184 d2loc.put(vd, deltaLoc);
1185 addLocationType(vd.getType(), deltaLoc);
1187 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1189 Location lastElement = compLoc.get(compLoc.getSize() - 1);
1190 if (ssjava.isSharedLocation(lastElement)) {
1191 ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1194 d2loc.put(vd, compLoc);
1195 addLocationType(vd.getType(), compLoc);
1203 private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1206 int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1209 int beginIdx = dIdx + 6;
1210 locDec = locDec.substring(beginIdx, locDec.length() - 1);
1211 dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1214 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1215 DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1220 private Location parseFieldLocDeclaraton(String decl, String msg) {
1222 int idx = decl.indexOf(".");
1223 String className = decl.substring(0, idx);
1224 String fieldName = decl.substring(idx + 1);
1226 className.replaceAll(" ", "");
1227 fieldName.replaceAll(" ", "");
1229 Descriptor d = state.getClassSymbolTable().get(className);
1232 throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1236 assert (d instanceof ClassDescriptor);
1237 SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1238 if (!lattice.containsKey(fieldName)) {
1239 throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1240 + className + "' at " + msg);
1243 return new Location(d, fieldName);
1246 private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1248 CompositeLocation compLoc = new CompositeLocation();
1250 StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1251 List<String> locIdList = new ArrayList<String>();
1252 while (tokenizer.hasMoreTokens()) {
1253 String locId = tokenizer.nextToken();
1254 locIdList.add(locId);
1257 // at least,one location element needs to be here!
1258 assert (locIdList.size() > 0);
1260 // assume that loc with idx 0 comes from the local lattice
1261 // loc with idx 1 comes from the field lattice
1263 String localLocId = locIdList.get(0);
1264 SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1265 Location localLoc = new Location(md, localLocId);
1266 if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1267 throw new Error("Location " + localLocId
1268 + " is not defined in the local variable lattice at "
1269 + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : "") + ".");
1271 compLoc.addLocation(localLoc);
1273 for (int i = 1; i < locIdList.size(); i++) {
1274 String locName = locIdList.get(i);
1277 parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1278 // ClassDescriptor cd = fieldLocName2cd.get(locName);
1279 // SSJavaLattice<String> fieldLattice =
1280 // CompositeLattice.getLatticeByDescriptor(cd);
1282 // if (fieldLattice == null || (!fieldLattice.containsKey(locName))) {
1283 // throw new Error("Location " + locName +
1284 // " is not defined in the field lattice at "
1285 // + cd.getSourceFileName() + ".");
1287 // Location fieldLoc = new Location(cd, locName);
1288 compLoc.addLocation(fieldLoc);
1295 private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1296 VarDescriptor vd = dn.getVarDescriptor();
1297 assignLocationOfVarDescriptor(vd, md, nametable, dn);
1300 private void checkClass(ClassDescriptor cd) {
1301 // Check to see that methods respects ss property
1302 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
1303 MethodDescriptor md = (MethodDescriptor) method_it.next();
1304 checkMethodDeclaration(cd, md);
1308 private void checkDeclarationInClass(ClassDescriptor cd) {
1309 // Check to see that fields are okay
1310 for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1311 FieldDescriptor fd = (FieldDescriptor) field_it.next();
1313 if (!(fd.isFinal() && fd.isStatic())) {
1314 checkFieldDeclaration(cd, fd);
1316 // for static final, assign top location by default
1317 Location loc = Location.createTopLocation(cd);
1318 addLocationType(fd.getType(), loc);
1323 private void checkMethodDeclaration(ClassDescriptor cd, MethodDescriptor md) {
1327 private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1329 Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1331 // currently enforce every field to have corresponding location
1332 if (annotationVec.size() == 0) {
1333 throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1334 + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1337 if (annotationVec.size() > 1) {
1338 // variable can have at most one location
1339 throw new Error("Field " + fd.getSymbol() + " of class " + cd
1340 + " has more than one location.");
1343 AnnotationDescriptor ad = annotationVec.elementAt(0);
1344 Location loc = null;
1346 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1347 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1348 String locationID = ad.getValue();
1349 // check if location is defined
1350 SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1351 if (lattice == null || (!lattice.containsKey(locationID))) {
1352 throw new Error("Location " + locationID
1353 + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1354 + cd.getSourceFileName() + ".");
1356 loc = new Location(cd, locationID);
1358 if (ssjava.isSharedLocation(loc)) {
1359 ssjava.mapSharedLocation2Descriptor(loc, fd);
1362 addLocationType(fd.getType(), loc);
1370 private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1372 type.setExtension(loc);
1376 private void addLocationType(TypeDescriptor type, Location loc) {
1378 type.setExtension(loc);
1382 static class CompositeLattice {
1384 public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1386 System.out.println("isGreaterThan=" + loc1 + " " + loc2 + " msg=" + msg);
1387 int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, msg);
1388 if (baseCompareResult == ComparisonResult.EQUAL) {
1389 if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1394 } else if (baseCompareResult == ComparisonResult.GREATER) {
1402 public static int compare(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1404 System.out.println("compare=" + loc1 + " " + loc2);
1405 int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, msg);
1407 if (baseCompareResult == ComparisonResult.EQUAL) {
1408 return compareDelta(loc1, loc2);
1410 return baseCompareResult;
1415 private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1417 int deltaCount1 = 0;
1418 int deltaCount2 = 0;
1419 if (dLoc1 instanceof DeltaLocation) {
1420 deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1423 if (dLoc2 instanceof DeltaLocation) {
1424 deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1426 if (deltaCount1 < deltaCount2) {
1427 return ComparisonResult.GREATER;
1428 } else if (deltaCount1 == deltaCount2) {
1429 return ComparisonResult.EQUAL;
1431 return ComparisonResult.LESS;
1436 private static int compareBaseLocationSet(CompositeLocation compLoc1,
1437 CompositeLocation compLoc2, boolean awareSharedLoc, String msg) {
1439 // if compLoc1 is greater than compLoc2, return true
1440 // else return false;
1442 // compare one by one in according to the order of the tuple
1444 for (int i = 0; i < compLoc1.getSize(); i++) {
1445 Location loc1 = compLoc1.get(i);
1446 if (i >= compLoc2.getSize()) {
1447 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1448 + " because they are not comparable.");
1450 Location loc2 = compLoc2.get(i);
1452 if (!loc1.getDescriptor().equals(loc2.getDescriptor())) {
1453 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1454 + " because they are not comparable at " + msg);
1457 Descriptor d1 = loc1.getDescriptor();
1458 Descriptor d2 = loc2.getDescriptor();
1460 SSJavaLattice<String> lattice1 = getLatticeByDescriptor(d1);
1461 SSJavaLattice<String> lattice2 = getLatticeByDescriptor(d2);
1463 // check if the spin location is appeared only at the end of the
1464 // composite location
1465 if (lattice1.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1466 if (i != (compLoc1.getSize() - 1)) {
1467 throw new Error("The spin location " + loc1.getLocIdentifier()
1468 + " cannot be appeared in the middle of composite location at" + msg);
1472 if (lattice2.getSpinLocSet().contains(loc2.getLocIdentifier())) {
1473 if (i != (compLoc2.getSize() - 1)) {
1474 throw new Error("The spin location " + loc2.getLocIdentifier()
1475 + " cannot be appeared in the middle of composite location at " + msg);
1479 if (!lattice1.equals(lattice2)) {
1480 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1481 + " because they are not comparable at " + msg);
1484 if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1486 // check if the current location is the spinning location
1487 // note that the spinning location only can be appeared in the last
1488 // part of the composite location
1489 if (awareSharedLoc && numOfTie == compLoc1.getSize()
1490 && lattice1.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1491 return ComparisonResult.GREATER;
1494 } else if (lattice1.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1495 return ComparisonResult.GREATER;
1497 return ComparisonResult.LESS;
1502 if (numOfTie == compLoc1.getSize()) {
1504 if (numOfTie != compLoc2.getSize()) {
1505 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1506 + " because they are not comparable at " + msg);
1509 return ComparisonResult.EQUAL;
1512 return ComparisonResult.LESS;
1516 public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet) {
1518 // System.out.println("Calculating GLB=" + inputSet);
1519 CompositeLocation glbCompLoc = new CompositeLocation();
1521 // calculate GLB of the first(priority) element
1522 Set<String> priorityLocIdentifierSet = new HashSet<String>();
1523 Descriptor priorityDescriptor = null;
1525 Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1526 new Hashtable<String, Set<CompositeLocation>>();
1527 // mapping from the priority loc ID to its full representation by the
1528 // composite location
1530 int maxTupleSize = 0;
1531 CompositeLocation maxCompLoc = null;
1533 for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1534 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1535 if (compLoc.getSize() > maxTupleSize) {
1536 maxTupleSize = compLoc.getSize();
1537 maxCompLoc = compLoc;
1539 Location priorityLoc = compLoc.get(0);
1540 String priorityLocId = priorityLoc.getLocIdentifier();
1541 priorityLocIdentifierSet.add(priorityLocId);
1543 if (locId2CompLocSet.containsKey(priorityLocId)) {
1544 locId2CompLocSet.get(priorityLocId).add(compLoc);
1546 Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1547 newSet.add(compLoc);
1548 locId2CompLocSet.put(priorityLocId, newSet);
1551 // check if priority location are coming from the same lattice
1552 if (priorityDescriptor == null) {
1553 priorityDescriptor = priorityLoc.getDescriptor();
1554 } else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1555 throw new Error("Failed to calculate GLB of " + inputSet
1556 + " because they are from different lattices.");
1560 SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1561 String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1563 glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1564 Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1566 if (compSet == null) {
1567 // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1568 // mean that the result is already lower than <x1,y1> and <x2,y2>
1569 // assign TOP to the rest of the location elements
1571 // in this case, do not take care about delta
1572 // CompositeLocation inputComp = inputSet.iterator().next();
1573 for (int i = 1; i < maxTupleSize; i++) {
1574 glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
1578 // here find out composite location that has a maximum length tuple
1579 // if we have three input set: [A], [A,B], [A,B,C]
1580 // maximum length tuple will be [A,B,C]
1582 CompositeLocation maxFromCompSet = null;
1583 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1584 CompositeLocation c = (CompositeLocation) iterator.next();
1585 if (c.getSize() > max) {
1591 if (compSet.size() == 1) {
1593 // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1594 CompositeLocation comp = compSet.iterator().next();
1595 for (int i = 1; i < comp.getSize(); i++) {
1596 glbCompLoc.addLocation(comp.get(i));
1599 // if input location corresponding to glb is a delta, need to apply
1600 // delta to glb result
1601 if (comp instanceof DeltaLocation) {
1602 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1606 // when GLB(x1,x2)==x1 and x2 : GLB case 1
1607 // if more than one location shares the same priority GLB
1608 // need to calculate the rest of GLB loc
1610 // int compositeLocSize = compSet.iterator().next().getSize();
1611 int compositeLocSize = maxFromCompSet.getSize();
1613 Set<String> glbInputSet = new HashSet<String>();
1614 Descriptor currentD = null;
1615 for (int i = 1; i < compositeLocSize; i++) {
1616 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1617 CompositeLocation compositeLocation = (CompositeLocation) iterator.next();
1618 if (compositeLocation.getSize() > i) {
1619 Location currentLoc = compositeLocation.get(i);
1620 currentD = currentLoc.getDescriptor();
1621 // making set of the current location sharing the same idx
1622 glbInputSet.add(currentLoc.getLocIdentifier());
1625 // calculate glb for the current lattice
1627 SSJavaLattice<String> currentLattice = getLatticeByDescriptor(currentD);
1628 String currentGLBLocId = currentLattice.getGLB(glbInputSet);
1629 glbCompLoc.addLocation(new Location(currentD, currentGLBLocId));
1632 // if input location corresponding to glb is a delta, need to apply
1633 // delta to glb result
1635 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1636 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1637 if (compLoc instanceof DeltaLocation) {
1638 if (glbCompLoc.equals(compLoc)) {
1639 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1652 static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1654 SSJavaLattice<String> lattice = null;
1656 if (d instanceof ClassDescriptor) {
1657 lattice = ssjava.getCd2lattice().get(d);
1658 } else if (d instanceof MethodDescriptor) {
1659 if (ssjava.getMd2lattice().containsKey(d)) {
1660 lattice = ssjava.getMd2lattice().get(d);
1662 // use default lattice for the method
1663 lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1672 class ComparisonResult {
1674 public static final int GREATER = 0;
1675 public static final int EQUAL = 1;
1676 public static final int LESS = 2;
1677 public static final int INCOMPARABLE = 3;
1684 class ReturnLocGenerator {
1686 public static final int PARAMISHIGHER = 0;
1687 public static final int PARAMISSAME = 1;
1688 public static final int IGNORE = 2;
1690 Hashtable<Integer, Integer> paramIdx2paramType;
1692 public ReturnLocGenerator(CompositeLocation returnLoc, List<CompositeLocation> params, String msg) {
1693 // creating mappings
1694 paramIdx2paramType = new Hashtable<Integer, Integer>();
1695 for (int i = 0; i < params.size(); i++) {
1696 CompositeLocation param = params.get(i);
1697 int compareResult = CompositeLattice.compare(param, returnLoc, msg);
1700 if (compareResult == ComparisonResult.GREATER) {
1702 } else if (compareResult == ComparisonResult.EQUAL) {
1707 paramIdx2paramType.put(new Integer(i), new Integer(type));
1712 public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
1714 // compute the highest possible location in caller's side
1715 assert paramIdx2paramType.keySet().size() == args.size();
1717 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1718 for (int i = 0; i < args.size(); i++) {
1719 int type = (paramIdx2paramType.get(new Integer(i))).intValue();
1720 CompositeLocation argLoc = args.get(i);
1721 if (type == PARAMISHIGHER) {
1722 // return loc is lower than param
1723 DeltaLocation delta = new DeltaLocation(argLoc, 1);
1724 inputGLB.add(delta);
1725 } else if (type == PARAMISSAME) {
1726 // return loc is equal or lower than param
1727 inputGLB.add(argLoc);
1731 // compute GLB of arguments subset that are same or higher than return
1733 CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB);
1735 System.out.println("### computeReturnLocation");
1736 System.out.println("### args=" + args);
1737 System.out.println("### calculateGLB=" + inputGLB);
1738 System.out.println("### glb=" + glb);