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.SynchronizedNode;
47 import IR.Tree.TertiaryNode;
48 import IR.Tree.TreeNode;
51 public class FlowDownCheck {
54 static SSJavaAnalysis ssjava;
58 // mapping from 'descriptor' to 'composite location'
59 Hashtable<Descriptor, CompositeLocation> d2loc;
61 Hashtable<MethodDescriptor, CompositeLocation> md2ReturnLoc;
62 Hashtable<MethodDescriptor, ReturnLocGenerator> md2ReturnLocGen;
64 // mapping from 'locID' to 'class descriptor'
65 Hashtable<String, ClassDescriptor> fieldLocName2cd;
67 public FlowDownCheck(SSJavaAnalysis ssjava, State state) {
70 this.toanalyze = new HashSet();
71 this.d2loc = new Hashtable<Descriptor, CompositeLocation>();
72 this.fieldLocName2cd = new Hashtable<String, ClassDescriptor>();
73 this.md2ReturnLoc = new Hashtable<MethodDescriptor, CompositeLocation>();
74 this.md2ReturnLocGen = new Hashtable<MethodDescriptor, ReturnLocGenerator>();
79 // construct mapping from the location name to the class descriptor
80 // assume that the location name is unique through the whole program
82 Set<ClassDescriptor> cdSet = ssjava.getCd2lattice().keySet();
83 for (Iterator iterator = cdSet.iterator(); iterator.hasNext();) {
84 ClassDescriptor cd = (ClassDescriptor) iterator.next();
85 SSJavaLattice<String> lattice = ssjava.getCd2lattice().get(cd);
86 Set<String> fieldLocNameSet = lattice.getKeySet();
88 for (Iterator iterator2 = fieldLocNameSet.iterator(); iterator2.hasNext();) {
89 String fieldLocName = (String) iterator2.next();
90 fieldLocName2cd.put(fieldLocName, cd);
97 public void flowDownCheck() {
98 SymbolTable classtable = state.getClassSymbolTable();
100 // phase 1 : checking declaration node and creating mapping of 'type
101 // desciptor' & 'location'
102 toanalyze.addAll(classtable.getValueSet());
103 toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
105 while (!toanalyze.isEmpty()) {
106 Object obj = toanalyze.iterator().next();
107 ClassDescriptor cd = (ClassDescriptor) obj;
108 toanalyze.remove(cd);
110 if (ssjava.needToBeAnnoated(cd)) {
112 ClassDescriptor superDesc = cd.getSuperDesc();
114 if (superDesc != null && (!superDesc.getSymbol().equals("Object"))) {
115 checkOrderingInheritance(superDesc, cd);
118 checkDeclarationInClass(cd);
119 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
120 MethodDescriptor md = (MethodDescriptor) method_it.next();
121 if (ssjava.needTobeAnnotated(md)) {
122 checkDeclarationInMethodBody(cd, md);
129 // phase2 : checking assignments
130 toanalyze.addAll(classtable.getValueSet());
131 toanalyze.addAll(state.getTaskSymbolTable().getValueSet());
132 while (!toanalyze.isEmpty()) {
133 Object obj = toanalyze.iterator().next();
134 ClassDescriptor cd = (ClassDescriptor) obj;
135 toanalyze.remove(cd);
138 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
139 MethodDescriptor md = (MethodDescriptor) method_it.next();
140 if (ssjava.needTobeAnnotated(md)) {
141 checkMethodBody(cd, md);
148 private void checkOrderingInheritance(ClassDescriptor superCd, ClassDescriptor cd) {
149 // here, we're going to check that sub class keeps same relative orderings
150 // in respect to super class
152 SSJavaLattice<String> superLattice = ssjava.getClassLattice(superCd);
153 SSJavaLattice<String> subLattice = ssjava.getClassLattice(cd);
155 if (superLattice != null) {
156 // if super class doesn't define lattice, then we don't need to check its
158 if (subLattice == null) {
159 throw new Error("If a parent class '" + superCd
160 + "' has a ordering lattice, its subclass '" + cd + "' should have one.");
163 Set<Pair<String, String>> superPairSet = superLattice.getOrderingPairSet();
164 Set<Pair<String, String>> subPairSet = subLattice.getOrderingPairSet();
166 for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
167 Pair<String, String> pair = (Pair<String, String>) iterator.next();
169 if (!subPairSet.contains(pair)) {
170 throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
171 + pair.getSecond() + " < " + pair.getFirst()
172 + "' that is defined by its superclass '" + superCd + "'.");
177 MethodLattice<String> superMethodDefaultLattice = ssjava.getMethodDefaultLattice(superCd);
178 MethodLattice<String> subMethodDefaultLattice = ssjava.getMethodDefaultLattice(cd);
180 if (superMethodDefaultLattice != null) {
181 if (subMethodDefaultLattice == null) {
182 throw new Error("When a parent class '" + superCd
183 + "' defines a default method lattice, its subclass '" + cd + "' should define one.");
186 Set<Pair<String, String>> superPairSet = superMethodDefaultLattice.getOrderingPairSet();
187 Set<Pair<String, String>> subPairSet = subMethodDefaultLattice.getOrderingPairSet();
189 for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
190 Pair<String, String> pair = (Pair<String, String>) iterator.next();
192 if (!subPairSet.contains(pair)) {
193 throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
194 + pair.getSecond() + " < " + pair.getFirst()
195 + "' that is defined by its superclass '" + superCd
196 + "' in the method default lattice.");
204 public Hashtable getMap() {
208 private void checkDeclarationInMethodBody(ClassDescriptor cd, MethodDescriptor md) {
209 BlockNode bn = state.getMethodBody(md);
211 if (ssjava.needTobeAnnotated(md)) {
213 // parsing returnloc annotation
214 Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
215 if (methodAnnotations != null) {
216 for (int i = 0; i < methodAnnotations.size(); i++) {
217 AnnotationDescriptor an = methodAnnotations.elementAt(i);
218 if (an.getMarker().equals(ssjava.RETURNLOC)) {
219 // developer explicitly defines method lattice
220 String returnLocDeclaration = an.getValue();
221 CompositeLocation returnLocComp =
222 parseLocationDeclaration(md, null, returnLocDeclaration);
223 md2ReturnLoc.put(md, returnLocComp);
226 if (!md.getReturnType().isVoid() && !md2ReturnLoc.containsKey(md)) {
227 throw new Error("Return location is not specified for the method " + md + " at "
228 + cd.getSourceFileName());
232 List<CompositeLocation> paramList = new ArrayList<CompositeLocation>();
234 boolean hasReturnValue = (!md.getReturnType().isVoid());
235 if (hasReturnValue) {
236 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
237 String thisLocId = methodLattice.getThisLoc();
238 if (thisLocId == null) {
239 throw new Error("Method '" + md + "' does not have the definition of 'this' location at "
240 + md.getClassDesc().getSourceFileName());
242 CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
243 paramList.add(thisLoc);
246 for (int i = 0; i < md.numParameters(); i++) {
247 // process annotations on method parameters
248 VarDescriptor vd = (VarDescriptor) md.getParameter(i);
249 assignLocationOfVarDescriptor(vd, md, md.getParameterTable(), bn);
250 if (hasReturnValue) {
251 paramList.add(d2loc.get(vd));
255 if (hasReturnValue) {
256 md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), paramList,
257 generateErrorMessage(cd, null)));
259 checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
264 private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
265 bn.getVarTable().setParent(nametable);
266 for (int i = 0; i < bn.size(); i++) {
267 BlockStatementNode bsn = bn.get(i);
268 checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
272 private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
273 BlockStatementNode bsn) {
275 switch (bsn.kind()) {
276 case Kind.SubBlockNode:
277 checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
280 case Kind.DeclarationNode:
281 checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
285 checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
288 case Kind.IfStatementNode:
289 checkDeclarationInIfStatementNode(md, nametable, (IfStatementNode) bsn);
292 case Kind.SwitchStatementNode:
293 checkDeclarationInSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
296 case Kind.SynchronizedNode:
297 checkDeclarationInSynchronizedNode(md, nametable, (SynchronizedNode) bsn);
303 private void checkDeclarationInSynchronizedNode(MethodDescriptor md, SymbolTable nametable,
304 SynchronizedNode sbn) {
305 checkDeclarationInBlockNode(md, nametable, sbn.getBlockNode());
308 private void checkDeclarationInSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
309 SwitchStatementNode ssn) {
310 BlockNode sbn = ssn.getSwitchBody();
311 for (int i = 0; i < sbn.size(); i++) {
312 SwitchBlockNode node = (SwitchBlockNode) sbn.get(i);
313 checkDeclarationInBlockNode(md, nametable, node.getSwitchBlockStatement());
317 private void checkDeclarationInIfStatementNode(MethodDescriptor md, SymbolTable nametable,
318 IfStatementNode isn) {
319 checkDeclarationInBlockNode(md, nametable, isn.getTrueBlock());
320 if (isn.getFalseBlock() != null)
321 checkDeclarationInBlockNode(md, nametable, isn.getFalseBlock());
324 private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
326 if (ln.getType() == LoopNode.FORLOOP) {
327 // check for loop case
328 ClassDescriptor cd = md.getClassDesc();
329 BlockNode bn = ln.getInitializer();
330 for (int i = 0; i < bn.size(); i++) {
331 BlockStatementNode bsn = bn.get(i);
332 checkDeclarationInBlockStatementNode(md, nametable, bsn);
337 checkDeclarationInBlockNode(md, nametable, ln.getBody());
340 private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
341 BlockNode bn = state.getMethodBody(md);
342 checkLocationFromBlockNode(md, md.getParameterTable(), bn);
345 private String generateErrorMessage(ClassDescriptor cd, TreeNode tn) {
347 return cd.getSourceFileName() + "::" + tn.getNumLine();
349 return cd.getSourceFileName();
354 private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
357 bn.getVarTable().setParent(nametable);
358 // it will return the lowest location in the block node
359 CompositeLocation lowestLoc = null;
361 for (int i = 0; i < bn.size(); i++) {
362 BlockStatementNode bsn = bn.get(i);
363 CompositeLocation bLoc = checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn);
364 if (!bLoc.isEmpty()) {
365 if (lowestLoc == null) {
368 if (CompositeLattice.isGreaterThan(lowestLoc, bLoc,
369 generateErrorMessage(md.getClassDesc(), bn))) {
377 if (lowestLoc == null) {
378 lowestLoc = new CompositeLocation(Location.createBottomLocation(md));
384 private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
385 SymbolTable nametable, BlockStatementNode bsn) {
387 CompositeLocation compLoc = null;
388 switch (bsn.kind()) {
389 case Kind.BlockExpressionNode:
390 compLoc = checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn);
393 case Kind.DeclarationNode:
394 compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn);
397 case Kind.IfStatementNode:
398 compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn);
402 compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn);
405 case Kind.ReturnNode:
406 compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn);
409 case Kind.SubBlockNode:
410 compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn);
413 case Kind.ContinueBreakNode:
414 compLoc = new CompositeLocation();
417 case Kind.SwitchStatementNode:
418 compLoc = checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
424 private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
425 SymbolTable nametable, SwitchStatementNode ssn) {
427 ClassDescriptor cd = md.getClassDesc();
428 CompositeLocation condLoc =
429 checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation());
430 BlockNode sbn = ssn.getSwitchBody();
432 Set<CompositeLocation> blockLocSet = new HashSet<CompositeLocation>();
433 for (int i = 0; i < sbn.size(); i++) {
434 CompositeLocation blockLoc =
435 checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i));
436 if (!CompositeLattice.isGreaterThan(condLoc, blockLoc,
437 generateErrorMessage(cd, ssn.getCondition()))) {
439 "The location of the switch-condition statement is lower than the conditional body at "
440 + cd.getSourceFileName() + ":" + ssn.getCondition().getNumLine());
443 blockLocSet.add(blockLoc);
445 return CompositeLattice.calculateGLB(blockLocSet);
448 private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
449 SymbolTable nametable, SwitchBlockNode sbn) {
451 CompositeLocation blockLoc =
452 checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement());
458 private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
461 ExpressionNode returnExp = rn.getReturnExpression();
463 CompositeLocation returnValueLoc;
464 if (returnExp != null) {
466 checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation());
468 // check if return value is equal or higher than RETRUNLOC of method
469 // declaration annotation
470 CompositeLocation declaredReturnLoc = md2ReturnLoc.get(md);
473 CompositeLattice.compare(returnValueLoc, declaredReturnLoc,
474 generateErrorMessage(md.getClassDesc(), rn));
476 if (compareResult == ComparisonResult.LESS || compareResult == ComparisonResult.INCOMPARABLE) {
478 "Return value location is not equal or higher than the declaraed return location at "
479 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
483 return new CompositeLocation();
486 private boolean hasOnlyLiteralValue(ExpressionNode en) {
487 if (en.kind() == Kind.LiteralNode) {
494 private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
497 ClassDescriptor cd = md.getClassDesc();
498 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
500 CompositeLocation condLoc =
501 checkLocationFromExpressionNode(md, nametable, ln.getCondition(), new CompositeLocation());
502 addLocationType(ln.getCondition().getType(), (condLoc));
504 CompositeLocation bodyLoc = checkLocationFromBlockNode(md, nametable, ln.getBody());
506 if (!CompositeLattice.isGreaterThan(condLoc, bodyLoc, generateErrorMessage(cd, ln))) {
507 // loop condition should be higher than loop body
509 "The location of the while-condition statement is lower than the loop body at "
510 + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
516 // check for loop case
517 BlockNode bn = ln.getInitializer();
518 bn.getVarTable().setParent(nametable);
520 // calculate glb location of condition and update statements
521 CompositeLocation condLoc =
522 checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
523 new CompositeLocation());
524 addLocationType(ln.getCondition().getType(), condLoc);
526 CompositeLocation updateLoc =
527 checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate());
529 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
530 glbInputSet.add(condLoc);
531 // glbInputSet.add(updateLoc);
533 CompositeLocation glbLocOfForLoopCond = CompositeLattice.calculateGLB(glbInputSet);
535 // check location of 'forloop' body
536 CompositeLocation blockLoc = checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody());
538 // compute glb of body including loop body and update statement
541 if (blockLoc == null) {
542 // when there is no statement in the loop body
544 if (updateLoc == null) {
545 // also there is no update statement in the loop body
546 return glbLocOfForLoopCond;
548 glbInputSet.add(updateLoc);
551 glbInputSet.add(blockLoc);
552 glbInputSet.add(updateLoc);
555 CompositeLocation loopBodyLoc = CompositeLattice.calculateGLB(glbInputSet);
557 if (!CompositeLattice.isGreaterThan(glbLocOfForLoopCond, loopBodyLoc,
558 generateErrorMessage(cd, ln))) {
560 "The location of the for-condition statement is lower than the for-loop body at "
561 + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
568 private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
569 SymbolTable nametable, SubBlockNode sbn) {
570 CompositeLocation compLoc = checkLocationFromBlockNode(md, nametable, sbn.getBlockNode());
574 private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
575 SymbolTable nametable, IfStatementNode isn) {
577 ClassDescriptor localCD = md.getClassDesc();
578 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
580 CompositeLocation condLoc =
581 checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation());
583 addLocationType(isn.getCondition().getType(), condLoc);
584 glbInputSet.add(condLoc);
586 CompositeLocation locTrueBlock = checkLocationFromBlockNode(md, nametable, isn.getTrueBlock());
587 if (locTrueBlock != null) {
588 glbInputSet.add(locTrueBlock);
589 // here, the location of conditional block should be higher than the
590 // location of true/false blocks
591 if (locTrueBlock != null
592 && !CompositeLattice.isGreaterThan(condLoc, locTrueBlock,
593 generateErrorMessage(localCD, isn.getCondition()))) {
596 "The location of the if-condition statement is lower than the conditional block at "
597 + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
601 if (isn.getFalseBlock() != null) {
602 CompositeLocation locFalseBlock =
603 checkLocationFromBlockNode(md, nametable, isn.getFalseBlock());
605 if (locFalseBlock != null) {
606 glbInputSet.add(locFalseBlock);
608 if (!CompositeLattice.isGreaterThan(condLoc, locFalseBlock,
609 generateErrorMessage(localCD, isn.getCondition()))) {
612 "The location of the if-condition statement is lower than the conditional block at "
613 + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
619 // return GLB location of condition, true, and false block
620 CompositeLocation glbLoc = CompositeLattice.calculateGLB(glbInputSet);
625 private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
626 SymbolTable nametable, DeclarationNode dn) {
628 VarDescriptor vd = dn.getVarDescriptor();
630 CompositeLocation destLoc = d2loc.get(vd);
632 if (dn.getExpression() != null) {
633 CompositeLocation expressionLoc =
634 checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
635 new CompositeLocation());
636 // addTypeLocation(dn.getExpression().getType(), expressionLoc);
638 if (expressionLoc != null) {
639 // checking location order
640 if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
641 generateErrorMessage(md.getClassDesc(), dn))) {
642 throw new Error("The value flow from " + expressionLoc + " to " + destLoc
643 + " does not respect location hierarchy on the assignment " + dn.printNode(0)
644 + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
647 return expressionLoc;
651 return new CompositeLocation();
657 private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
659 checkDeclarationInBlockNode(md, nametable.getParent(), sbn.getBlockNode());
662 private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
663 SymbolTable nametable, BlockExpressionNode ben) {
664 CompositeLocation compLoc =
665 checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null);
666 // addTypeLocation(ben.getExpression().getType(), compLoc);
670 private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
671 SymbolTable nametable, ExpressionNode en, CompositeLocation loc) {
673 CompositeLocation compLoc = null;
676 case Kind.AssignmentNode:
677 compLoc = checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc);
680 case Kind.FieldAccessNode:
681 compLoc = checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc);
685 compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc);
689 compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en);
692 case Kind.CreateObjectNode:
693 compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
696 case Kind.ArrayAccessNode:
697 compLoc = checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en);
700 case Kind.LiteralNode:
701 compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
704 case Kind.MethodInvokeNode:
705 compLoc = checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc);
708 case Kind.TertiaryNode:
709 compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en);
713 compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en);
716 // case Kind.InstanceOfNode:
717 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
720 // case Kind.ArrayInitializerNode:
721 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
725 // case Kind.ClassTypeNode:
726 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
729 // case Kind.OffsetNode:
730 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
737 // addTypeLocation(en.getType(), compLoc);
742 private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
745 ExpressionNode en = cn.getExpression();
746 return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
750 private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
751 SymbolTable nametable, TertiaryNode tn) {
752 ClassDescriptor cd = md.getClassDesc();
754 CompositeLocation condLoc =
755 checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation());
756 addLocationType(tn.getCond().getType(), condLoc);
757 CompositeLocation trueLoc =
758 checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation());
759 addLocationType(tn.getTrueExpr().getType(), trueLoc);
760 CompositeLocation falseLoc =
761 checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation());
762 addLocationType(tn.getFalseExpr().getType(), falseLoc);
764 // locations from true/false branches can be TOP when there are only literal
766 // in this case, we don't need to check flow down rule!
768 // check if condLoc is higher than trueLoc & falseLoc
769 if (!trueLoc.get(0).isTop()
770 && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
772 "The location of the condition expression is lower than the true expression at "
773 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
776 if (!falseLoc.get(0).isTop()
777 && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
778 generateErrorMessage(cd, tn.getCond()))) {
780 "The location of the condition expression is lower than the true expression at "
781 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
784 // then, return glb of trueLoc & falseLoc
785 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
786 glbInputSet.add(trueLoc);
787 glbInputSet.add(falseLoc);
789 return CompositeLattice.calculateGLB(glbInputSet);
792 private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
793 SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc) {
795 checkCalleeConstraints(md, nametable, min);
797 CompositeLocation baseLocation = null;
798 if (min.getExpression() != null) {
800 checkLocationFromExpressionNode(md, nametable, min.getExpression(),
801 new CompositeLocation());
803 String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
804 baseLocation = new CompositeLocation(new Location(md, thisLocId));
807 if (!min.getMethod().getReturnType().isVoid()) {
808 // If method has a return value, compute the highest possible return
809 // location in the caller's perspective
810 CompositeLocation ceilingLoc =
811 computeCeilingLocationForCaller(md, nametable, min, baseLocation);
815 return new CompositeLocation();
819 private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
820 SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation) {
821 List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
823 // by default, method has a THIS parameter
824 argList.add(baseLocation);
826 for (int i = 0; i < min.numArgs(); i++) {
827 ExpressionNode en = min.getArg(i);
828 CompositeLocation callerArg =
829 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
830 argList.add(callerArg);
833 System.out.println("\n## computeReturnLocation=" + min.getMethod() + " argList=" + argList);
834 CompositeLocation compLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
835 DeltaLocation delta = new DeltaLocation(compLoc, 1);
836 System.out.println("##computeReturnLocation=" + delta);
842 private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
843 MethodInvokeNode min) {
845 if (min.numArgs() > 1) {
846 // caller needs to guarantee that it passes arguments in regarding to
847 // callee's hierarchy
848 for (int i = 0; i < min.numArgs(); i++) {
849 ExpressionNode en = min.getArg(i);
850 CompositeLocation callerArg1 =
851 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
853 VarDescriptor calleevd = (VarDescriptor) min.getMethod().getParameter(i);
854 CompositeLocation calleeLoc1 = d2loc.get(calleevd);
856 if (!callerArg1.get(0).isTop()) {
857 // here, check if ordering relations among caller's args respect
858 // ordering relations in-between callee's args
859 for (int currentIdx = 0; currentIdx < min.numArgs(); currentIdx++) {
860 if (currentIdx != i) { // skip itself
861 ExpressionNode argExp = min.getArg(currentIdx);
863 CompositeLocation callerArg2 =
864 checkLocationFromExpressionNode(md, nametable, argExp, new CompositeLocation());
866 VarDescriptor calleevd2 = (VarDescriptor) min.getMethod().getParameter(currentIdx);
867 CompositeLocation calleeLoc2 = d2loc.get(calleevd2);
870 CompositeLattice.compare(callerArg1, callerArg2,
871 generateErrorMessage(md.getClassDesc(), min));
873 CompositeLattice.compare(calleeLoc1, calleeLoc2,
874 generateErrorMessage(md.getClassDesc(), min));
876 if (calleeResult == ComparisonResult.GREATER
877 && callerResult != ComparisonResult.GREATER) {
878 // If calleeLoc1 is higher than calleeLoc2
879 // then, caller should have same ordering relation in-bet
880 // callerLoc1 & callerLoc2
882 throw new Error("Caller doesn't respect ordering relations among method arguments:"
883 + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
896 private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
897 SymbolTable nametable, ArrayAccessNode aan) {
899 // return glb location of array itself and index
901 ClassDescriptor cd = md.getClassDesc();
903 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
905 CompositeLocation arrayLoc =
906 checkLocationFromExpressionNode(md, nametable, aan.getExpression(), new CompositeLocation());
907 // addTypeLocation(aan.getExpression().getType(), arrayLoc);
908 glbInputSet.add(arrayLoc);
909 CompositeLocation indexLoc =
910 checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation());
911 glbInputSet.add(indexLoc);
912 // addTypeLocation(aan.getIndex().getType(), indexLoc);
914 CompositeLocation glbLoc = CompositeLattice.calculateGLB(glbInputSet);
918 private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
919 SymbolTable nametable, CreateObjectNode con) {
921 ClassDescriptor cd = md.getClassDesc();
924 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
925 for (int i = 0; i < con.numArgs(); i++) {
926 ExpressionNode en = con.getArg(i);
927 CompositeLocation argLoc =
928 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation());
929 glbInputSet.add(argLoc);
930 addLocationType(en.getType(), argLoc);
933 // check array initializers
934 // if ((con.getArrayInitializer() != null)) {
935 // checkLocationFromArrayInitializerNode(md, nametable,
936 // con.getArrayInitializer());
939 if (glbInputSet.size() > 0) {
940 return CompositeLattice.calculateGLB(glbInputSet);
943 CompositeLocation compLoc = new CompositeLocation();
944 compLoc.addLocation(Location.createTopLocation(md));
949 private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
952 ClassDescriptor cd = md.getClassDesc();
953 CompositeLocation leftLoc = new CompositeLocation();
954 leftLoc = checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc);
955 // addTypeLocation(on.getLeft().getType(), leftLoc);
957 CompositeLocation rightLoc = new CompositeLocation();
958 if (on.getRight() != null) {
959 rightLoc = checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc);
960 // addTypeLocation(on.getRight().getType(), rightLoc);
963 System.out.println("checking op node=" + on.printNode(0)
964 + generateErrorMessage(md.getClassDesc(), on));
965 System.out.println("# op node=" + on.printNode(0));
966 System.out.println("left loc=" + leftLoc + " from " + on.getLeft().getClass());
967 if (on.getRight() != null) {
968 System.out.println("right loc=" + rightLoc + " from " + on.getRight().kind());
971 Operation op = on.getOp();
973 switch (op.getOp()) {
975 case Operation.UNARYPLUS:
976 case Operation.UNARYMINUS:
977 case Operation.LOGIC_NOT:
981 case Operation.LOGIC_OR:
982 case Operation.LOGIC_AND:
984 case Operation.BIT_OR:
985 case Operation.BIT_XOR:
986 case Operation.BIT_AND:
987 case Operation.ISAVAILABLE:
988 case Operation.EQUAL:
989 case Operation.NOTEQUAL:
999 case Operation.LEFTSHIFT:
1000 case Operation.RIGHTSHIFT:
1001 case Operation.URIGHTSHIFT:
1003 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
1004 inputSet.add(leftLoc);
1005 inputSet.add(rightLoc);
1006 CompositeLocation glbCompLoc = CompositeLattice.calculateGLB(inputSet);
1010 throw new Error(op.toString());
1015 private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
1016 SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
1018 // literal value has the top location so that value can be flowed into any
1020 Location literalLoc = Location.createTopLocation(md);
1021 loc.addLocation(literalLoc);
1026 private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1027 NameNode nn, CompositeLocation loc) {
1029 NameDescriptor nd = nn.getName();
1030 if (nd.getBase() != null) {
1031 loc = checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc);
1033 String varname = nd.toString();
1034 if (varname.equals("this")) {
1036 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1037 String thisLocId = methodLattice.getThisLoc();
1038 if (thisLocId == null) {
1039 throw new Error("The location for 'this' is not defined at "
1040 + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1042 Location locElement = new Location(md, thisLocId);
1043 loc.addLocation(locElement);
1047 Descriptor d = (Descriptor) nametable.get(varname);
1049 // CompositeLocation localLoc = null;
1050 if (d instanceof VarDescriptor) {
1051 VarDescriptor vd = (VarDescriptor) d;
1052 // localLoc = d2loc.get(vd);
1053 // the type of var descriptor has a composite location!
1054 loc = ((CompositeLocation) vd.getType().getExtension()).clone();
1055 } else if (d instanceof FieldDescriptor) {
1056 // the type of field descriptor has a location!
1057 FieldDescriptor fd = (FieldDescriptor) d;
1058 if (fd.isStatic()) {
1060 // if it is 'static final', the location has TOP since no one can
1062 loc.addLocation(Location.createTopLocation(md));
1065 // if 'static', the location has pre-assigned global loc
1066 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1067 String globalLocId = localLattice.getGlobalLoc();
1068 if (globalLocId == null) {
1069 throw new Error("Global location element is not defined in the method " + md);
1071 Location globalLoc = new Location(md, globalLocId);
1073 loc.addLocation(globalLoc);
1076 // the location of field access starts from this, followed by field
1078 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1079 Location thisLoc = new Location(md, localLattice.getThisLoc());
1080 loc.addLocation(thisLoc);
1083 Location fieldLoc = (Location) fd.getType().getExtension();
1084 loc.addLocation(fieldLoc);
1085 } else if (d == null) {
1087 // check if the var is a static field of the class
1088 FieldDescriptor fd = nn.getField();
1089 ClassDescriptor cd = nn.getClassDesc();
1091 if (fd != null && cd != null) {
1093 if (fd.isStatic() && fd.isFinal()) {
1094 loc.addLocation(Location.createTopLocation(md));
1097 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1098 Location fieldLoc = new Location(md, localLattice.getThisLoc());
1099 loc.addLocation(fieldLoc);
1108 private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1109 SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc) {
1111 ExpressionNode left = fan.getExpression();
1112 TypeDescriptor ltd = left.getType();
1114 FieldDescriptor fd = fan.getField();
1116 String varName = null;
1117 if (left.kind() == Kind.NameNode) {
1118 NameDescriptor nd = ((NameNode) left).getName();
1119 varName = nd.toString();
1122 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1123 // using a class name directly or access using this
1124 if (fd.isStatic() && fd.isFinal()) {
1125 loc.addLocation(Location.createTopLocation(md));
1130 loc = checkLocationFromExpressionNode(md, nametable, left, loc);
1131 if (!left.getType().isPrimitive()) {
1132 Location fieldLoc = getFieldLocation(fd);
1133 loc.addLocation(fieldLoc);
1139 private Location getFieldLocation(FieldDescriptor fd) {
1141 Location fieldLoc = (Location) fd.getType().getExtension();
1143 // handle the case that method annotation checking skips checking field
1145 if (fieldLoc == null) {
1146 fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1153 private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1154 SymbolTable nametable, AssignmentNode an, CompositeLocation loc) {
1156 ClassDescriptor cd = md.getClassDesc();
1158 boolean postinc = true;
1159 if (an.getOperation().getBaseOp() == null
1160 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1161 .getBaseOp().getOp() != Operation.POSTDEC))
1164 CompositeLocation destLocation =
1165 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation());
1167 CompositeLocation srcLocation = new CompositeLocation();
1170 if (hasOnlyLiteralValue(an.getSrc())) {
1171 // if source is literal value, src location is TOP. so do not need to
1173 return destLocation;
1175 srcLocation = new CompositeLocation();
1176 srcLocation = checkLocationFromExpressionNode(md, nametable, an.getSrc(), srcLocation);
1178 // System.out.println(" an= " + an.printNode(0) + " an.getSrc()=" +
1179 // an.getSrc().getClass()
1180 // + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1181 // System.out.println("srcLocation=" + srcLocation);
1182 // System.out.println("dstLocation=" + destLocation);
1184 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1185 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1186 + " does not respect location hierarchy on the assignment " + an.printNode(0) + " at "
1187 + cd.getSourceFileName() + "::" + an.getNumLine());
1191 srcLocation = checkLocationFromExpressionNode(md, nametable, an.getDest(), srcLocation);
1193 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1194 throw new Error("Location " + destLocation
1195 + " is not allowed to have the value flow that moves within the same location at "
1196 + cd.getSourceFileName() + "::" + an.getNumLine());
1201 return destLocation;
1204 private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1205 SymbolTable nametable, TreeNode n) {
1207 ClassDescriptor cd = md.getClassDesc();
1208 Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1210 // currently enforce every variable to have corresponding location
1211 if (annotationVec.size() == 0) {
1212 throw new Error("Location is not assigned to variable " + vd.getSymbol() + " in the method "
1213 + md.getSymbol() + " of the class " + cd.getSymbol());
1216 if (annotationVec.size() > 1) { // variable can have at most one location
1217 throw new Error(vd.getSymbol() + " has more than one location.");
1220 AnnotationDescriptor ad = annotationVec.elementAt(0);
1222 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1224 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1225 String locDec = ad.getValue(); // check if location is defined
1227 if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1228 DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1229 d2loc.put(vd, deltaLoc);
1230 addLocationType(vd.getType(), deltaLoc);
1232 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1234 Location lastElement = compLoc.get(compLoc.getSize() - 1);
1235 if (ssjava.isSharedLocation(lastElement)) {
1236 ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1239 d2loc.put(vd, compLoc);
1240 addLocationType(vd.getType(), compLoc);
1248 private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1251 int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1254 int beginIdx = dIdx + 6;
1255 locDec = locDec.substring(beginIdx, locDec.length() - 1);
1256 dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1259 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1260 DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1265 private Location parseFieldLocDeclaraton(String decl, String msg) {
1267 int idx = decl.indexOf(".");
1268 String className = decl.substring(0, idx);
1269 String fieldName = decl.substring(idx + 1);
1271 className.replaceAll(" ", "");
1272 fieldName.replaceAll(" ", "");
1274 Descriptor d = state.getClassSymbolTable().get(className);
1277 throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1281 assert (d instanceof ClassDescriptor);
1282 SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1283 if (!lattice.containsKey(fieldName)) {
1284 throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1285 + className + "' at " + msg);
1288 return new Location(d, fieldName);
1291 private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1293 CompositeLocation compLoc = new CompositeLocation();
1295 StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1296 List<String> locIdList = new ArrayList<String>();
1297 while (tokenizer.hasMoreTokens()) {
1298 String locId = tokenizer.nextToken();
1299 locIdList.add(locId);
1302 // at least,one location element needs to be here!
1303 assert (locIdList.size() > 0);
1305 // assume that loc with idx 0 comes from the local lattice
1306 // loc with idx 1 comes from the field lattice
1308 String localLocId = locIdList.get(0);
1309 SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1310 Location localLoc = new Location(md, localLocId);
1311 if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1312 throw new Error("Location " + localLocId
1313 + " is not defined in the local variable lattice at "
1314 + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : "") + ".");
1316 compLoc.addLocation(localLoc);
1318 for (int i = 1; i < locIdList.size(); i++) {
1319 String locName = locIdList.get(i);
1322 parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1323 // ClassDescriptor cd = fieldLocName2cd.get(locName);
1324 // SSJavaLattice<String> fieldLattice =
1325 // CompositeLattice.getLatticeByDescriptor(cd);
1327 // if (fieldLattice == null || (!fieldLattice.containsKey(locName))) {
1328 // throw new Error("Location " + locName +
1329 // " is not defined in the field lattice at "
1330 // + cd.getSourceFileName() + ".");
1332 // Location fieldLoc = new Location(cd, locName);
1333 compLoc.addLocation(fieldLoc);
1340 private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1341 VarDescriptor vd = dn.getVarDescriptor();
1342 assignLocationOfVarDescriptor(vd, md, nametable, dn);
1345 private void checkClass(ClassDescriptor cd) {
1346 // Check to see that methods respects ss property
1347 for (Iterator method_it = cd.getMethods(); method_it.hasNext();) {
1348 MethodDescriptor md = (MethodDescriptor) method_it.next();
1349 checkMethodDeclaration(cd, md);
1353 private void checkDeclarationInClass(ClassDescriptor cd) {
1354 // Check to see that fields are okay
1355 for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1356 FieldDescriptor fd = (FieldDescriptor) field_it.next();
1358 if (!(fd.isFinal() && fd.isStatic())) {
1359 checkFieldDeclaration(cd, fd);
1361 // for static final, assign top location by default
1362 Location loc = Location.createTopLocation(cd);
1363 addLocationType(fd.getType(), loc);
1368 private void checkMethodDeclaration(ClassDescriptor cd, MethodDescriptor md) {
1372 private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1374 Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1376 // currently enforce every field to have corresponding location
1377 if (annotationVec.size() == 0) {
1378 throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1379 + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1382 if (annotationVec.size() > 1) {
1383 // variable can have at most one location
1384 throw new Error("Field " + fd.getSymbol() + " of class " + cd
1385 + " has more than one location.");
1388 AnnotationDescriptor ad = annotationVec.elementAt(0);
1389 Location loc = null;
1391 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1392 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1393 String locationID = ad.getValue();
1394 // check if location is defined
1395 SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1396 if (lattice == null || (!lattice.containsKey(locationID))) {
1397 throw new Error("Location " + locationID
1398 + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1399 + cd.getSourceFileName() + ".");
1401 loc = new Location(cd, locationID);
1403 if (ssjava.isSharedLocation(loc)) {
1404 ssjava.mapSharedLocation2Descriptor(loc, fd);
1407 addLocationType(fd.getType(), loc);
1415 private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1417 type.setExtension(loc);
1421 private void addLocationType(TypeDescriptor type, Location loc) {
1423 type.setExtension(loc);
1427 static class CompositeLattice {
1429 public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1431 System.out.println("isGreaterThan=" + loc1 + " " + loc2 + " msg=" + msg);
1432 int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, msg);
1433 if (baseCompareResult == ComparisonResult.EQUAL) {
1434 if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1439 } else if (baseCompareResult == ComparisonResult.GREATER) {
1447 public static int compare(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1449 System.out.println("compare=" + loc1 + " " + loc2);
1450 int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, msg);
1452 if (baseCompareResult == ComparisonResult.EQUAL) {
1453 return compareDelta(loc1, loc2);
1455 return baseCompareResult;
1460 private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1462 int deltaCount1 = 0;
1463 int deltaCount2 = 0;
1464 if (dLoc1 instanceof DeltaLocation) {
1465 deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1468 if (dLoc2 instanceof DeltaLocation) {
1469 deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1471 if (deltaCount1 < deltaCount2) {
1472 return ComparisonResult.GREATER;
1473 } else if (deltaCount1 == deltaCount2) {
1474 return ComparisonResult.EQUAL;
1476 return ComparisonResult.LESS;
1481 private static int compareBaseLocationSet(CompositeLocation compLoc1,
1482 CompositeLocation compLoc2, boolean awareSharedLoc, String msg) {
1484 // if compLoc1 is greater than compLoc2, return true
1485 // else return false;
1487 // compare one by one in according to the order of the tuple
1489 for (int i = 0; i < compLoc1.getSize(); i++) {
1490 Location loc1 = compLoc1.get(i);
1491 if (i >= compLoc2.getSize()) {
1492 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1493 + " because they are not comparable.");
1495 Location loc2 = compLoc2.get(i);
1497 Descriptor d1 = loc1.getDescriptor();
1498 Descriptor d2 = loc2.getDescriptor();
1500 Descriptor descriptor;
1502 if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
1504 if (d1.equals(d2)) {
1507 // identifying which one is parent class
1508 Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
1509 Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
1511 if (d1 == null && d2 == null) {
1512 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1513 + " because they are not comparable at " + msg);
1514 } else if (d1 != null && d1SubClassesSet.contains(d2)) {
1516 } else if (d2 != null && d2SubClassesSet.contains(d1)) {
1519 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1520 + " because they are not comparable at " + msg);
1524 } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
1526 if (d1.equals(d2)) {
1530 // identifying which one is parent class
1531 MethodDescriptor md1 = (MethodDescriptor) d1;
1532 MethodDescriptor md2 = (MethodDescriptor) d2;
1534 if (!md1.matches(md2)) {
1535 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1536 + " because they are not comparable at " + msg);
1539 Set<Descriptor> d1SubClassesSet =
1540 ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
1541 Set<Descriptor> d2SubClassesSet =
1542 ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
1544 if (d1 == null && d2 == null) {
1545 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1546 + " because they are not comparable at " + msg);
1547 } else if (d1 != null && d1SubClassesSet.contains(d2)) {
1549 } else if (d2 != null && d2SubClassesSet.contains(d1)) {
1552 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1553 + " because they are not comparable at " + msg);
1558 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1559 + " because they are not comparable at " + msg);
1562 // SSJavaLattice<String> lattice1 = getLatticeByDescriptor(d1);
1563 // SSJavaLattice<String> lattice2 = getLatticeByDescriptor(d2);
1565 SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
1567 // check if the spin location is appeared only at the end of the
1568 // composite location
1569 if (lattice.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1570 if (i != (compLoc1.getSize() - 1)) {
1571 throw new Error("The shared location " + loc1.getLocIdentifier()
1572 + " cannot be appeared in the middle of composite location at" + msg);
1576 if (lattice.getSpinLocSet().contains(loc2.getLocIdentifier())) {
1577 if (i != (compLoc2.getSize() - 1)) {
1578 throw new Error("The spin location " + loc2.getLocIdentifier()
1579 + " cannot be appeared in the middle of composite location at " + msg);
1583 // if (!lattice1.equals(lattice2)) {
1584 // throw new Error("Failed to compare two locations of " + compLoc1 +
1585 // " and " + compLoc2
1586 // + " because they are not comparable at " + msg);
1589 if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1591 // check if the current location is the spinning location
1592 // note that the spinning location only can be appeared in the last
1593 // part of the composite location
1594 if (awareSharedLoc && numOfTie == compLoc1.getSize()
1595 && lattice.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1596 return ComparisonResult.GREATER;
1599 } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1600 return ComparisonResult.GREATER;
1602 return ComparisonResult.LESS;
1607 if (numOfTie == compLoc1.getSize()) {
1609 if (numOfTie != compLoc2.getSize()) {
1610 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1611 + " because they are not comparable at " + msg);
1614 return ComparisonResult.EQUAL;
1617 return ComparisonResult.LESS;
1621 public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet) {
1623 // System.out.println("Calculating GLB=" + inputSet);
1624 CompositeLocation glbCompLoc = new CompositeLocation();
1626 // calculate GLB of the first(priority) element
1627 Set<String> priorityLocIdentifierSet = new HashSet<String>();
1628 Descriptor priorityDescriptor = null;
1630 Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1631 new Hashtable<String, Set<CompositeLocation>>();
1632 // mapping from the priority loc ID to its full representation by the
1633 // composite location
1635 int maxTupleSize = 0;
1636 CompositeLocation maxCompLoc = null;
1638 for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1639 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1640 if (compLoc.getSize() > maxTupleSize) {
1641 maxTupleSize = compLoc.getSize();
1642 maxCompLoc = compLoc;
1644 Location priorityLoc = compLoc.get(0);
1645 String priorityLocId = priorityLoc.getLocIdentifier();
1646 priorityLocIdentifierSet.add(priorityLocId);
1648 if (locId2CompLocSet.containsKey(priorityLocId)) {
1649 locId2CompLocSet.get(priorityLocId).add(compLoc);
1651 Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1652 newSet.add(compLoc);
1653 locId2CompLocSet.put(priorityLocId, newSet);
1656 // check if priority location are coming from the same lattice
1657 if (priorityDescriptor == null) {
1658 priorityDescriptor = priorityLoc.getDescriptor();
1659 } else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1660 throw new Error("Failed to calculate GLB of " + inputSet
1661 + " because they are from different lattices.");
1665 SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1666 String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1668 glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1669 Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1671 if (compSet == null) {
1672 // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1673 // mean that the result is already lower than <x1,y1> and <x2,y2>
1674 // assign TOP to the rest of the location elements
1676 // in this case, do not take care about delta
1677 // CompositeLocation inputComp = inputSet.iterator().next();
1678 for (int i = 1; i < maxTupleSize; i++) {
1679 glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
1683 // here find out composite location that has a maximum length tuple
1684 // if we have three input set: [A], [A,B], [A,B,C]
1685 // maximum length tuple will be [A,B,C]
1687 CompositeLocation maxFromCompSet = null;
1688 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1689 CompositeLocation c = (CompositeLocation) iterator.next();
1690 if (c.getSize() > max) {
1696 if (compSet.size() == 1) {
1698 // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1699 CompositeLocation comp = compSet.iterator().next();
1700 for (int i = 1; i < comp.getSize(); i++) {
1701 glbCompLoc.addLocation(comp.get(i));
1704 // if input location corresponding to glb is a delta, need to apply
1705 // delta to glb result
1706 if (comp instanceof DeltaLocation) {
1707 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1711 // when GLB(x1,x2)==x1 and x2 : GLB case 1
1712 // if more than one location shares the same priority GLB
1713 // need to calculate the rest of GLB loc
1715 // int compositeLocSize = compSet.iterator().next().getSize();
1716 int compositeLocSize = maxFromCompSet.getSize();
1718 Set<String> glbInputSet = new HashSet<String>();
1719 Descriptor currentD = null;
1720 for (int i = 1; i < compositeLocSize; i++) {
1721 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1722 CompositeLocation compositeLocation = (CompositeLocation) iterator.next();
1723 if (compositeLocation.getSize() > i) {
1724 Location currentLoc = compositeLocation.get(i);
1725 currentD = currentLoc.getDescriptor();
1726 // making set of the current location sharing the same idx
1727 glbInputSet.add(currentLoc.getLocIdentifier());
1730 // calculate glb for the current lattice
1732 SSJavaLattice<String> currentLattice = getLatticeByDescriptor(currentD);
1733 String currentGLBLocId = currentLattice.getGLB(glbInputSet);
1734 glbCompLoc.addLocation(new Location(currentD, currentGLBLocId));
1737 // if input location corresponding to glb is a delta, need to apply
1738 // delta to glb result
1740 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1741 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1742 if (compLoc instanceof DeltaLocation) {
1743 if (glbCompLoc.equals(compLoc)) {
1744 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1757 static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1759 SSJavaLattice<String> lattice = null;
1761 if (d instanceof ClassDescriptor) {
1762 lattice = ssjava.getCd2lattice().get(d);
1763 } else if (d instanceof MethodDescriptor) {
1764 if (ssjava.getMd2lattice().containsKey(d)) {
1765 lattice = ssjava.getMd2lattice().get(d);
1767 // use default lattice for the method
1768 lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1777 class ComparisonResult {
1779 public static final int GREATER = 0;
1780 public static final int EQUAL = 1;
1781 public static final int LESS = 2;
1782 public static final int INCOMPARABLE = 3;
1789 class ReturnLocGenerator {
1791 public static final int PARAMISHIGHER = 0;
1792 public static final int PARAMISSAME = 1;
1793 public static final int IGNORE = 2;
1795 Hashtable<Integer, Integer> paramIdx2paramType;
1797 public ReturnLocGenerator(CompositeLocation returnLoc, List<CompositeLocation> params, String msg) {
1798 // creating mappings
1799 paramIdx2paramType = new Hashtable<Integer, Integer>();
1800 for (int i = 0; i < params.size(); i++) {
1801 CompositeLocation param = params.get(i);
1802 int compareResult = CompositeLattice.compare(param, returnLoc, msg);
1805 if (compareResult == ComparisonResult.GREATER) {
1807 } else if (compareResult == ComparisonResult.EQUAL) {
1812 paramIdx2paramType.put(new Integer(i), new Integer(type));
1817 public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
1819 // compute the highest possible location in caller's side
1820 assert paramIdx2paramType.keySet().size() == args.size();
1822 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1823 for (int i = 0; i < args.size(); i++) {
1824 int type = (paramIdx2paramType.get(new Integer(i))).intValue();
1825 CompositeLocation argLoc = args.get(i);
1826 if (type == PARAMISHIGHER) {
1827 // return loc is lower than param
1828 DeltaLocation delta = new DeltaLocation(argLoc, 1);
1829 inputGLB.add(delta);
1830 } else if (type == PARAMISSAME) {
1831 // return loc is equal or lower than param
1832 inputGLB.add(argLoc);
1836 // compute GLB of arguments subset that are same or higher than return
1838 CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB);