From bdc086e2ec7fcc674a604906627b52e16fba7eb3 Mon Sep 17 00:00:00 2001 From: bdemsky Date: Wed, 27 Apr 2011 20:51:40 +0000 Subject: [PATCH] switch to spaces only.. --- .../src/Analysis/CallGraph/BaseCallGraph.java | 228 +- .../src/Analysis/CallGraph/JavaCallGraph.java | 60 +- Robust/src/Analysis/Disjoint/AllocSite.java | 8 +- .../Analysis/Disjoint/BuildStateMachines.java | 6 +- Robust/src/Analysis/Disjoint/Canonical.java | 392 +- .../Analysis/Disjoint/DisjointAnalysis.java | 1350 +++---- .../Analysis/Disjoint/EffectsAnalysis.java | 52 +- Robust/src/Analysis/Disjoint/ExistPred.java | 174 +- .../src/Analysis/Disjoint/ExistPredSet.java | 16 +- .../src/Analysis/Disjoint/HeapRegionNode.java | 10 +- .../src/Analysis/Disjoint/PointerMethod.java | 46 +- .../Disjoint/ProcessStateMachines.java | 256 +- Robust/src/Analysis/Disjoint/ReachGraph.java | 3476 ++++++++--------- Robust/src/Analysis/Disjoint/ReachSet.java | 48 +- Robust/src/Analysis/Disjoint/ReachState.java | 2 +- Robust/src/Analysis/Disjoint/RefEdge.java | 2 +- Robust/src/Analysis/Disjoint/RefSrcNode.java | 2 +- Robust/src/Analysis/Disjoint/SMFEState.java | 34 +- .../Disjoint/StateMachineForEffects.java | 6 +- Robust/src/Analysis/Disjoint/TaintSet.java | 6 +- .../src/Analysis/FlatIRGraph/FlatIRGraph.java | 24 +- .../src/Analysis/Locality/BranchAnalysis.java | 140 +- Robust/src/Analysis/Locality/DCWrapper.java | 66 +- .../Analysis/Locality/DelayComputation.java | 996 ++--- .../Analysis/Locality/DiscoverConflicts.java | 866 ++-- .../Locality/GenerateConversions.java | 300 +- .../Analysis/Locality/LocalityAnalysis.java | 686 ++-- .../Analysis/Locality/LocalityBinding.java | 34 +- .../src/Analysis/Locality/TempNodePair.java | 6 +- .../src/Analysis/Locality/TypeAnalysis.java | 136 +- Robust/src/Analysis/Loops/CSE.java | 192 +- .../src/Analysis/Loops/CopyPropagation.java | 166 +- Robust/src/Analysis/Loops/DeadCode.java | 134 +- Robust/src/Analysis/Loops/DomTree.java | 78 +- .../src/Analysis/Loops/GlobalFieldType.java | 144 +- Robust/src/Analysis/Loops/LoopFinder.java | 170 +- Robust/src/Analysis/Loops/LoopInvariant.java | 190 +- Robust/src/Analysis/Loops/LoopOptimize.java | 118 +- Robust/src/Analysis/Loops/UseDef.java | 70 +- Robust/src/Analysis/Loops/WriteBarrier.java | 88 +- Robust/src/Analysis/Loops/localCSE.java | 268 +- Robust/src/Analysis/OoOJava/Accessible.java | 218 +- .../src/Analysis/OoOJava/ConflictGraph.java | 594 +-- Robust/src/Analysis/OoOJava/ConflictNode.java | 28 +- .../src/Analysis/OoOJava/OoOJavaAnalysis.java | 1346 +++---- .../OoOJava/RBlockRelationAnalysis.java | 412 +- Robust/src/Analysis/OoOJava/SESELock.java | 36 +- .../Analysis/OoOJava/SESEWaitingQueue.java | 2 +- .../src/Analysis/OoOJava/VarSrcTokTable.java | 250 +- .../OwnershipAnalysis/AllocationSite.java | 8 +- .../OwnershipAnalysis/ChangeTuple.java | 6 +- .../OwnershipAnalysis/ChangeTupleSet.java | 6 +- .../OwnershipAnalysis/EffectsSet.java | 30 +- .../OwnershipAnalysis/HeapRegionNode.java | 2 +- .../OwnershipAnalysis/MethodContext.java | 2 +- .../OwnershipAnalysis/MethodEffects.java | 594 +-- .../MethodEffectsAnalysis.java | 90 +- .../OwnershipAnalysis/OwnershipAnalysis.java | 678 ++-- .../OwnershipAnalysis/OwnershipGraph.java | 3352 ++++++++-------- .../OwnershipAnalysis/OwnershipNode.java | 2 +- .../ParameterDecomposition.java | 8 +- .../OwnershipAnalysis/ReachabilitySet.java | 154 +- .../OwnershipAnalysis/TokenTuple.java | 10 +- .../OwnershipAnalysis/TokenTupleSet.java | 110 +- Robust/src/Analysis/Pointer/AllocFactory.java | 12 +- Robust/src/Analysis/Pointer/BasicBlock.java | 74 +- Robust/src/Analysis/Pointer/Delta.java | 36 +- Robust/src/Analysis/Pointer/Edge.java | 26 +- Robust/src/Analysis/Pointer/Graph.java | 48 +- Robust/src/Analysis/Pointer/GraphManip.java | 220 +- Robust/src/Analysis/Pointer/Pointer.java | 1454 +++---- Robust/src/Analysis/Pointer/Util.java | 6 +- .../Analysis/Prefetch/IndexDescriptor.java | 4 +- Robust/src/Analysis/Prefetch/LoopExit.java | 28 +- .../Analysis/Prefetch/PrefetchAnalysis.java | 772 ++-- .../src/Analysis/Prefetch/PrefetchPair.java | 50 +- .../Analysis/SSJava/CompositeLocation.java | 28 +- .../SSJava/DefinitelyWrittenCheck.java | 212 +- Robust/src/Analysis/SSJava/DeltaLocation.java | 10 +- Robust/src/Analysis/SSJava/FlowDownCheck.java | 580 +-- Robust/src/Analysis/SSJava/Location.java | 12 +- Robust/src/Analysis/Scheduling/ClassNode.java | 2 +- .../Analysis/Scheduling/CombinationUtil.java | 844 ++-- .../Analysis/Scheduling/CoreSimulator.java | 86 +- .../Analysis/Scheduling/FIFORSchedule.java | 14 +- .../Analysis/Scheduling/MCImplSynthesis.java | 1576 ++++---- .../src/Analysis/Scheduling/ObjectInfo.java | 2 +- .../Analysis/Scheduling/ObjectSimulator.java | 8 +- .../Analysis/Scheduling/ScheduleAnalysis.java | 1512 +++---- .../src/Analysis/Scheduling/ScheduleEdge.java | 34 +- .../src/Analysis/Scheduling/ScheduleNode.java | 174 +- .../Scheduling/ScheduleSimulator.java | 736 ++-- .../Analysis/Scheduling/SchedulingUtil.java | 1012 ++--- .../Analysis/Scheduling/SimExecutionEdge.java | 40 +- .../Analysis/Scheduling/TaskSimulator.java | 288 +- .../TaskStateAnalysis/ExecutionGraph.java | 42 +- .../src/Analysis/TaskStateAnalysis/FEdge.java | 32 +- .../Analysis/TaskStateAnalysis/FlagInfo.java | 10 +- .../Analysis/TaskStateAnalysis/FlagState.java | 154 +- .../TaskStateAnalysis/GarbageAnalysis.java | 16 +- .../OptionalTaskDescriptor.java | 2 +- .../Analysis/TaskStateAnalysis/Predicate.java | 2 +- .../TaskStateAnalysis/SafetyAnalysis.java | 524 +-- .../TaskStateAnalysis/TagAnalysis.java | 216 +- .../TaskStateAnalysis/TagBinding.java | 14 +- .../Analysis/TaskStateAnalysis/TagEdge.java | 2 +- .../Analysis/TaskStateAnalysis/TagState.java | 2 +- .../TaskStateAnalysis/TaskAnalysis.java | 270 +- .../TaskStateAnalysis/TaskBinding.java | 128 +- .../Analysis/TaskStateAnalysis/TaskGraph.java | 134 +- .../Analysis/TaskStateAnalysis/TaskIndex.java | 4 +- .../Analysis/TaskStateAnalysis/TaskQueue.java | 10 +- .../TaskStateAnalysis/TaskQueueIterator.java | 132 +- .../TaskStateAnalysis/TaskTagAnalysis.java | 398 +- Robust/src/ClassLibrary/Character.java | 4 +- Robust/src/ClassLibrary/HashMap.java | 40 +- Robust/src/ClassLibrary/HashMapIterator.java | 8 +- Robust/src/ClassLibrary/InetAddress.java | 6 +- Robust/src/ClassLibrary/Integer.java | 14 +- Robust/src/ClassLibrary/LinkedList.java | 32 +- Robust/src/ClassLibrary/Math.java | 4 +- Robust/src/ClassLibrary/Queue.java | 24 +- .../src/ClassLibrary/SocketInputStream.java | 4 +- Robust/src/ClassLibrary/String.java | 66 +- Robust/src/ClassLibrary/StringBuffer.java | 14 +- Robust/src/ClassLibrary/Vector.java | 10 +- Robust/src/ClassLibrary/gnu/Random.java | 4 +- .../src/ClassLibrary/gnu/StringTokenizer.java | 30 +- Robust/src/IR/AnnotationDescriptor.java | 4 +- Robust/src/IR/ClassDescriptor.java | 44 +- Robust/src/IR/Flat/BuildCode.java | 2032 +++++----- Robust/src/IR/Flat/BuildCodeMultiCore.java | 1382 +++---- Robust/src/IR/Flat/BuildCodeTran.java | 1738 ++++----- Robust/src/IR/Flat/BuildFlat.java | 1062 ++--- Robust/src/IR/Flat/BuildOoOJavaCode.java | 1294 +++--- Robust/src/IR/Flat/FieldShadow.java | 16 +- Robust/src/IR/Flat/FlatCall.java | 22 +- Robust/src/IR/Flat/FlatFlagActionNode.java | 10 +- Robust/src/IR/Flat/FlatLiteralNode.java | 10 +- Robust/src/IR/Flat/FlatMethod.java | 114 +- Robust/src/IR/Flat/FlatNode.java | 22 +- Robust/src/IR/Flat/FlatPrefetchNode.java | 2 +- Robust/src/IR/Flat/FlatSESEEnterNode.java | 10 +- .../src/IR/Flat/FlatWriteDynamicVarNode.java | 8 +- Robust/src/IR/Flat/Inliner.java | 150 +- .../src/IR/Flat/RuntimeConflictResolver.java | 256 +- Robust/src/IR/Flat/TempObject.java | 2 +- Robust/src/IR/Flat/TempTagPair.java | 6 +- Robust/src/IR/MethodDescriptor.java | 6 +- Robust/src/IR/SymbolTable.java | 22 +- Robust/src/IR/TaskDescriptor.java | 12 +- Robust/src/IR/Tree/ArrayInitializerNode.java | 2 +- Robust/src/IR/Tree/BlockNode.java | 36 +- Robust/src/IR/Tree/BuildIR.java | 824 ++-- Robust/src/IR/Tree/ConstraintCheck.java | 2 +- Robust/src/IR/Tree/CreateObjectNode.java | 8 +- Robust/src/IR/Tree/DNFFlag.java | 56 +- Robust/src/IR/Tree/FlagEffects.java | 2 +- Robust/src/IR/Tree/JavaBuilder.java | 162 +- Robust/src/IR/Tree/LiteralNode.java | 4 +- Robust/src/IR/Tree/MethodInvokeNode.java | 2 +- Robust/src/IR/Tree/NameNode.java | 4 +- Robust/src/IR/Tree/OpNode.java | 94 +- Robust/src/IR/Tree/ParseNode.java | 24 +- Robust/src/IR/Tree/ParseNodeDOTVisitor.java | 2 +- Robust/src/IR/Tree/SemanticCheck.java | 938 ++--- Robust/src/IR/Tree/TertiaryNode.java | 16 +- Robust/src/IR/TypeDescriptor.java | 8 +- Robust/src/IR/TypeUtil.java | 232 +- Robust/src/IR/Virtual.java | 150 +- Robust/src/Interface/HTTPServices.java | 2 +- Robust/src/Interface/HashStrings.java | 6 +- Robust/src/Interface/IdentityRelation.java | 2 +- Robust/src/Interface/Imap.java | 78 +- Robust/src/Interface/JhttpServer.java | 4 +- Robust/src/Interface/JhttpWorker.java | 108 +- Robust/src/Interface/WebInterface.java | 94 +- Robust/src/Lex/Comment.java | 4 +- Robust/src/Lex/EscapedUnicodeReader.java | 18 +- Robust/src/Lex/Lexer.java | 78 +- Robust/src/Lex/Token.java | 8 +- Robust/src/Main/Main.java | 648 +-- .../src/Runtime/DSTM/interface/abortreaders.c | 124 +- .../DSTM/interface/addPrefetchEnhance.c | 10 +- .../Runtime/DSTM/interface/addUdpEnhance.c | 22 +- .../src/Runtime/DSTM/interface/altmlookup.c | 50 +- .../src/Runtime/DSTM/interface/altprelookup.c | 40 +- .../Runtime/DSTM/interface/clocksyncserver.c | 2 +- Robust/src/Runtime/DSTM/interface/clookup.c | 86 +- Robust/src/Runtime/DSTM/interface/clookup2.c | 18 +- Robust/src/Runtime/DSTM/interface/dht.c | 1226 +++--- Robust/src/Runtime/DSTM/interface/dsmlock.c | 14 +- Robust/src/Runtime/DSTM/interface/dstm.h | 6 +- .../src/Runtime/DSTM/interface/dstmserver.c | 374 +- Robust/src/Runtime/DSTM/interface/gCollect.c | 34 +- Robust/src/Runtime/DSTM/interface/llookup.c | 46 +- .../src/Runtime/DSTM/interface/machinepile.c | 56 +- Robust/src/Runtime/DSTM/interface/mlookup.c | 54 +- Robust/src/Runtime/DSTM/interface/prefetch.c | 244 +- Robust/src/Runtime/DSTM/interface/prelookup.c | 58 +- Robust/src/Runtime/DSTM/interface/sandbox.c | 74 +- Robust/src/Runtime/DSTM/interface/sockpool.c | 68 +- .../src/Runtime/DSTM/interface/threadnotify.c | 60 +- Robust/src/Runtime/DSTM/interface/trans.c | 466 +-- Robust/src/Runtime/GenericHashtable.c | 38 +- Robust/src/Runtime/ObjectHash.c | 28 +- Robust/src/Runtime/Queue.c | 12 +- Robust/src/Runtime/SimpleHash.c | 36 +- Robust/src/Runtime/chash.c | 46 +- Robust/src/Runtime/checkpoint.c | 236 +- Robust/src/Runtime/deque.c | 2 +- Robust/src/Runtime/garbage.c | 218 +- Robust/src/Runtime/garbage.h | 20 +- Robust/src/Runtime/mem.c | 2 +- Robust/src/Runtime/mlp_lock.h | 48 +- Robust/src/Runtime/mlp_runtime.c | 346 +- Robust/src/Runtime/object.c | 14 +- Robust/src/Runtime/oojgarbage.c | 288 +- Robust/src/Runtime/option.c | 8 +- Robust/src/Runtime/runtime.c | 18 +- Robust/src/Runtime/socket.c | 12 +- Robust/src/Runtime/squeue.h | 8 +- Robust/src/Runtime/task.c | 922 ++--- Robust/src/Runtime/taskgarbage.c | 98 +- Robust/src/Runtime/workschedule.c | 84 +- Robust/src/Util/CodePrinter.java | 42 +- Robust/src/Util/GraphNode.java | 270 +- Robust/src/Util/Lattice.java | 66 +- Robust/src/Util/MultiHash.java | 18 +- Robust/src/Util/OptimizedView.java | 2 +- Robust/src/Util/UtilAlgorithms.java | 24 +- Robust/src/c.cfg | 1 + Robust/src/java.cfg | 1 + 233 files changed, 24559 insertions(+), 24557 deletions(-) diff --git a/Robust/src/Analysis/CallGraph/BaseCallGraph.java b/Robust/src/Analysis/CallGraph/BaseCallGraph.java index 22a8dc6c..0ad8e2f2 100644 --- a/Robust/src/Analysis/CallGraph/BaseCallGraph.java +++ b/Robust/src/Analysis/CallGraph/BaseCallGraph.java @@ -86,48 +86,48 @@ public class BaseCallGraph implements CallGraph { Iterator methodit=cn.getMethods(); //Iterator through methods while(methodit.hasNext()) { - MethodDescriptor md=(MethodDescriptor)methodit.next(); - if (md.isStatic()||md.getReturnType()==null) - continue; - Stack possInterfaces=new Stack(); - ClassDescriptor tmpcd=cn; - while(tmpcd!=null) { - for(Iterator supit=tmpcd.getSuperInterfaces(); supit.hasNext(); ) { - possInterfaces.add((ClassDescriptor)supit.next()); - } - tmpcd=tmpcd.getSuperDesc(); - } - while(!possInterfaces.isEmpty()) { - ClassDescriptor IFdesc=possInterfaces.pop(); - for(Iterator supit=IFdesc.getSuperInterfaces(); supit.hasNext(); ) { - possInterfaces.add((ClassDescriptor)supit.next()); - } - Set possiblematches=IFdesc.getMethodTable().getSet(md.getSymbol()); - for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { - MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); - if (md.matches(matchmd)) { - if (!mapVirtual2ImplementationSet.containsKey(matchmd)) - mapVirtual2ImplementationSet.put(matchmd,new HashSet()); - ((HashSet)mapVirtual2ImplementationSet.get(matchmd)).add(md); - break; - } - } - } - - - ClassDescriptor superdesc=cn.getSuperDesc(); - if (superdesc!=null) { - Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol()); - for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { - MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); - if (md.matches(matchmd)) { - if (!mapVirtual2ImplementationSet.containsKey(matchmd)) - mapVirtual2ImplementationSet.put(matchmd,new HashSet()); - ((HashSet)mapVirtual2ImplementationSet.get(matchmd)).add(md); - break; - } - } - } + MethodDescriptor md=(MethodDescriptor)methodit.next(); + if (md.isStatic()||md.getReturnType()==null) + continue; + Stack possInterfaces=new Stack(); + ClassDescriptor tmpcd=cn; + while(tmpcd!=null) { + for(Iterator supit=tmpcd.getSuperInterfaces(); supit.hasNext(); ) { + possInterfaces.add((ClassDescriptor)supit.next()); + } + tmpcd=tmpcd.getSuperDesc(); + } + while(!possInterfaces.isEmpty()) { + ClassDescriptor IFdesc=possInterfaces.pop(); + for(Iterator supit=IFdesc.getSuperInterfaces(); supit.hasNext(); ) { + possInterfaces.add((ClassDescriptor)supit.next()); + } + Set possiblematches=IFdesc.getMethodTable().getSet(md.getSymbol()); + for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { + MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); + if (md.matches(matchmd)) { + if (!mapVirtual2ImplementationSet.containsKey(matchmd)) + mapVirtual2ImplementationSet.put(matchmd,new HashSet()); + ((HashSet)mapVirtual2ImplementationSet.get(matchmd)).add(md); + break; + } + } + } + + + ClassDescriptor superdesc=cn.getSuperDesc(); + if (superdesc!=null) { + Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol()); + for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { + MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); + if (md.matches(matchmd)) { + if (!mapVirtual2ImplementationSet.containsKey(matchmd)) + mapVirtual2ImplementationSet.put(matchmd,new HashSet()); + ((HashSet)mapVirtual2ImplementationSet.get(matchmd)).add(md); + break; + } + } + } } } } @@ -144,8 +144,8 @@ public class BaseCallGraph implements CallGraph { Set s=(Set)mapVirtual2ImplementationSet.get(md); if (s!=null) for(Iterator it=s.iterator(); it.hasNext(); ) { - MethodDescriptor md2=(MethodDescriptor)it.next(); - ns.addAll(getMethods(md2)); + MethodDescriptor md2=(MethodDescriptor)it.next(); + ns.addAll(getMethods(md2)); } return ns; } @@ -176,10 +176,10 @@ public class BaseCallGraph implements CallGraph { Set s=(Set)mapCaller2CalleeSet.get(d); if (s!=null) for(Iterator it=s.iterator(); it.hasNext(); ) { - MethodDescriptor md=(MethodDescriptor)it.next(); - if( !found.contains(md) ) { - ns.addAll(getMoreMethodCalls(found, md)); - } + MethodDescriptor md=(MethodDescriptor)it.next(); + if( !found.contains(md) ) { + ns.addAll(getMoreMethodCalls(found, md)); + } } return ns; } @@ -200,13 +200,13 @@ public class BaseCallGraph implements CallGraph { Set s=(Set)mapCaller2CalleeSet.get(md); if (s!=null) { - for(Iterator it=s.iterator(); it.hasNext(); ) { - MethodDescriptor md2=(MethodDescriptor)it.next(); - if( !callable.contains(md2) ) { - callable.add(md2); - tovisit.add(md2); - } - } + for(Iterator it=s.iterator(); it.hasNext(); ) { + MethodDescriptor md2=(MethodDescriptor)it.next(); + if( !callable.contains(md2) ) { + callable.add(md2); + tovisit.add(md2); + } + } } } return callable; @@ -225,16 +225,16 @@ public class BaseCallGraph implements CallGraph { Set s = (Set) mapCaller2CalleeSet.get(md); if (s != null) { - for (Iterator it = s.iterator(); it.hasNext(); ) { - MethodDescriptor md2 = (MethodDescriptor) it.next(); - if (!callable.contains(md2)) { - callable.add(md2); - if (!methodsContainingSESEs.contains(md2)) { - // if current method has sese, do not need to go down - tovisit.add(md2); - } - } - } + for (Iterator it = s.iterator(); it.hasNext(); ) { + MethodDescriptor md2 = (MethodDescriptor) it.next(); + if (!callable.contains(md2)) { + callable.add(md2); + if (!methodsContainingSESEs.contains(md2)) { + // if current method has sese, do not need to go down + tovisit.add(md2); + } + } + } } } // callable.retainAll(methodsContainingSESEs); @@ -249,8 +249,8 @@ public class BaseCallGraph implements CallGraph { Iterator methodit=cn.getMethods(); //Iterator through methods while(methodit.hasNext()) { - MethodDescriptor md=(MethodDescriptor)methodit.next(); - analyzeMethod( (Object)md, state.getMethodFlat(md) ); + MethodDescriptor md=(MethodDescriptor)methodit.next(); + analyzeMethod( (Object)md, state.getMethodFlat(md) ); } } it=state.getTaskSymbolTable().getDescriptorsIterator(); @@ -270,31 +270,31 @@ public class BaseCallGraph implements CallGraph { toexplore.remove(fn); explored.add(fn); for(int i=0; i callee maps - if( !mapCaller2CalleeSet.containsKey(caller) ) { - mapCaller2CalleeSet.put(caller, new HashSet() ); - } - ((HashSet)mapCaller2CalleeSet.get(caller)).addAll(methodsthatcouldbecalled); - - // add callee -> caller maps - Iterator calleeItr = methodsthatcouldbecalled.iterator(); - while( calleeItr.hasNext() ) { - MethodDescriptor callee = (MethodDescriptor) calleeItr.next(); - if( !mapCallee2CallerSet.containsKey(callee) ) { - mapCallee2CallerSet.put(callee, new HashSet() ); - } - ((HashSet)mapCallee2CallerSet.get(callee)).add(caller); - } + FlatCall fc=(FlatCall)fn; + MethodDescriptor calledmethod=fc.getMethod(); + Set methodsthatcouldbecalled=fc.getThis()==null?getMethods(calledmethod): + getMethods(calledmethod, fc.getThis().getType()); + + // add caller -> callee maps + if( !mapCaller2CalleeSet.containsKey(caller) ) { + mapCaller2CalleeSet.put(caller, new HashSet() ); + } + ((HashSet)mapCaller2CalleeSet.get(caller)).addAll(methodsthatcouldbecalled); + + // add callee -> caller maps + Iterator calleeItr = methodsthatcouldbecalled.iterator(); + while( calleeItr.hasNext() ) { + MethodDescriptor callee = (MethodDescriptor) calleeItr.next(); + if( !mapCallee2CallerSet.containsKey(callee) ) { + mapCallee2CallerSet.put(callee, new HashSet() ); + } + ((HashSet)mapCallee2CallerSet.get(callee)).add(caller); + } } } } @@ -312,20 +312,20 @@ public class BaseCallGraph implements CallGraph { HashSet implemSet = (HashSet) me.getValue(); if( !labeledInDot.contains(virtual) ) { - labeledInDot.add(virtual); - bw.write(" "+virtual.getNum()+"[label=\""+virtual+"\"];\n"); + labeledInDot.add(virtual); + bw.write(" "+virtual.getNum()+"[label=\""+virtual+"\"];\n"); } Iterator implemItr = implemSet.iterator(); while( implemItr.hasNext() ) { - Descriptor implem = (Descriptor) implemItr.next(); + Descriptor implem = (Descriptor) implemItr.next(); - if( !labeledInDot.contains(implem) ) { - labeledInDot.add(implem); - bw.write(" "+implem.getNum()+"[label=\""+implem+"\"];\n"); - } + if( !labeledInDot.contains(implem) ) { + labeledInDot.add(implem); + bw.write(" "+implem.getNum()+"[label=\""+implem+"\"];\n"); + } - bw.write(" "+virtual.getNum()+"->"+implem.getNum()+";\n"); + bw.write(" "+virtual.getNum()+"->"+implem.getNum()+";\n"); } } bw.write("}\n"); @@ -346,20 +346,20 @@ public class BaseCallGraph implements CallGraph { HashSet calleeSet = (HashSet) me.getValue(); if( !labeledInDot.contains(caller) ) { - labeledInDot.add(caller); - bw.write(" "+caller.getNum()+"[label=\"" +caller+"\"];\n"); + labeledInDot.add(caller); + bw.write(" "+caller.getNum()+"[label=\"" +caller+"\"];\n"); } Iterator calleeItr = calleeSet.iterator(); while( calleeItr.hasNext() ) { - MethodDescriptor callee = (MethodDescriptor) calleeItr.next(); + MethodDescriptor callee = (MethodDescriptor) calleeItr.next(); - if( !labeledInDot.contains(callee) ) { - labeledInDot.add(callee); - bw.write(" "+callee.getNum()+"[label=\""+callee+"\"];\n"); - } + if( !labeledInDot.contains(callee) ) { + labeledInDot.add(callee); + bw.write(" "+callee.getNum()+"[label=\""+callee+"\"];\n"); + } - bw.write(" "+caller.getNum()+"->"+callee.getNum()+";\n"); + bw.write(" "+caller.getNum()+"->"+callee.getNum()+";\n"); } } bw.write("}\n"); @@ -382,20 +382,20 @@ public class BaseCallGraph implements CallGraph { HashSet callerSet = (HashSet) me.getValue(); if( !labeledInDot.contains(callee) ) { - labeledInDot.add(callee); - bw.write(" "+callee.getNum()+"[label=\""+callee+"\"];\n"); + labeledInDot.add(callee); + bw.write(" "+callee.getNum()+"[label=\""+callee+"\"];\n"); } Iterator callerItr = callerSet.iterator(); while( callerItr.hasNext() ) { - Descriptor caller = (Descriptor) callerItr.next(); + Descriptor caller = (Descriptor) callerItr.next(); - if( !labeledInDot.contains(caller) ) { - labeledInDot.add(caller); - bw.write(" "+caller.getNum()+"[label=\""+caller+"\"];\n"); - } + if( !labeledInDot.contains(caller) ) { + labeledInDot.add(caller); + bw.write(" "+caller.getNum()+"[label=\""+caller+"\"];\n"); + } - bw.write(" "+caller.getNum()+"->"+callee.getNum()+";\n"); + bw.write(" "+caller.getNum()+"->"+callee.getNum()+";\n"); } } bw.write("}\n"); diff --git a/Robust/src/Analysis/CallGraph/JavaCallGraph.java b/Robust/src/Analysis/CallGraph/JavaCallGraph.java index 5b8a7765..51256a83 100644 --- a/Robust/src/Analysis/CallGraph/JavaCallGraph.java +++ b/Robust/src/Analysis/CallGraph/JavaCallGraph.java @@ -49,11 +49,11 @@ public class JavaCallGraph extends BaseCallGraph { Iterator methodit=cn.getMethods(); //Iterator through methods while(methodit.hasNext()) { - MethodDescriptor md=(MethodDescriptor)methodit.next(); - if (md.isStaticBlock()) { - tovisit.add(md); - discovered.add(md); - } + MethodDescriptor md=(MethodDescriptor)methodit.next(); + if (md.isStaticBlock()) { + tovisit.add(md); + discovered.add(md); + } } } @@ -63,36 +63,36 @@ public class JavaCallGraph extends BaseCallGraph { tovisit.remove(md); FlatMethod fm=state.getMethodFlat(md); if (fm==null) - continue; + continue; analyzeMethod(md, fm); for(Iterator fnit=fm.getNodeSet().iterator(); fnit.hasNext(); ) { - FlatNode fn=fnit.next(); - if (fn.kind()==FKind.FlatCall) { - FlatCall fcall=(FlatCall)fn; - Set callees=fcall.getThis()==null?getMethods(fcall.getMethod()):getMethods(fcall.getMethod(),fcall.getThis().getType()); + FlatNode fn=fnit.next(); + if (fn.kind()==FKind.FlatCall) { + FlatCall fcall=(FlatCall)fn; + Set callees=fcall.getThis()==null?getMethods(fcall.getMethod()):getMethods(fcall.getMethod(),fcall.getThis().getType()); - if (fcall.getThis()!=null) { - MethodDescriptor methodd=fcall.getMethod(); + if (fcall.getThis()!=null) { + MethodDescriptor methodd=fcall.getMethod(); - if (methodd.getClassDesc()==tu.getClass(TypeUtil.ThreadClass)&& - methodd.getSymbol().equals("start")&&methodd.numParameters()==0&&!methodd.getModifiers().isStatic()) { - //Have call to start - HashSet ns=new HashSet(); - ns.addAll(callees); - ns.addAll(getMethods(tu.getRun(), fcall.getThis().getType())); - ns.addAll(getMethods(tu.getStaticStart(), fcall.getThis().getType())); - callees=ns; - } - } + if (methodd.getClassDesc()==tu.getClass(TypeUtil.ThreadClass)&& + methodd.getSymbol().equals("start")&&methodd.numParameters()==0&&!methodd.getModifiers().isStatic()) { + //Have call to start + HashSet ns=new HashSet(); + ns.addAll(callees); + ns.addAll(getMethods(tu.getRun(), fcall.getThis().getType())); + ns.addAll(getMethods(tu.getStaticStart(), fcall.getThis().getType())); + callees=ns; + } + } - for(Iterator mdit=callees.iterator(); mdit.hasNext(); ) { - MethodDescriptor callee=(MethodDescriptor)mdit.next(); - if (!discovered.contains(callee)) { - discovered.add(callee); - tovisit.add(callee); - } - } - } + for(Iterator mdit=callees.iterator(); mdit.hasNext(); ) { + MethodDescriptor callee=(MethodDescriptor)mdit.next(); + if (!discovered.contains(callee)) { + discovered.add(callee); + tovisit.add(callee); + } + } + } } } } diff --git a/Robust/src/Analysis/Disjoint/AllocSite.java b/Robust/src/Analysis/Disjoint/AllocSite.java index 7c1961b1..b41a5405 100644 --- a/Robust/src/Analysis/Disjoint/AllocSite.java +++ b/Robust/src/Analysis/Disjoint/AllocSite.java @@ -184,7 +184,7 @@ public class AllocSite extends Canonical implements Alloc { for( int i = 0; i < allocationDepth - 1; ++i ) { if( id.equals(ithOldest.get(i) ) ) { - return AGE_in_I; + return AGE_in_I; } } @@ -194,7 +194,7 @@ public class AllocSite extends Canonical implements Alloc { public Integer getAge(Integer id) { for( int i = 0; i < allocationDepth; ++i ) { if( id.equals(ithOldest.get(i) ) ) { - return new Integer(i); + return new Integer(i); } } @@ -212,7 +212,7 @@ public class AllocSite extends Canonical implements Alloc { for( int i = 0; i < allocationDepth - 1; ++i ) { if( id.equals(getIthOldestShadow(i) ) ) { - return SHADOWAGE_in_I; + return SHADOWAGE_in_I; } } @@ -222,7 +222,7 @@ public class AllocSite extends Canonical implements Alloc { public Integer getShadowAge(Integer id) { for( int i = 0; i < allocationDepth - 1; ++i ) { if( id.equals(getIthOldestShadow(i) ) ) { - return new Integer(-i); + return new Integer(-i); } } diff --git a/Robust/src/Analysis/Disjoint/BuildStateMachines.java b/Robust/src/Analysis/Disjoint/BuildStateMachines.java index 64b470db..b4e0b6a2 100644 --- a/Robust/src/Analysis/Disjoint/BuildStateMachines.java +++ b/Robust/src/Analysis/Disjoint/BuildStateMachines.java @@ -109,11 +109,11 @@ public class BuildStateMachines { Iterator varItr = var2smfe.keySet().iterator(); while( varItr.hasNext() ) { - TempDescriptor var = varItr.next(); + TempDescriptor var = varItr.next(); - StateMachineForEffects smfe = var2smfe.get(var); + StateMachineForEffects smfe = var2smfe.get(var); - smfe.writeAsDOT(prefix+"statemachine_"+fn.toString()+var.toString() ); + smfe.writeAsDOT(prefix+"statemachine_"+fn.toString()+var.toString() ); } } } diff --git a/Robust/src/Analysis/Disjoint/Canonical.java b/Robust/src/Analysis/Disjoint/Canonical.java index 85a5c8a8..ef17d832 100644 --- a/Robust/src/Analysis/Disjoint/Canonical.java +++ b/Robust/src/Analysis/Disjoint/Canonical.java @@ -105,7 +105,7 @@ abstract public class Canonical { if( hasHash ) { if( oldHash != hash ) { - throw new Error("A CANONICAL HASH CHANGED"); + throw new Error("A CANONICAL HASH CHANGED"); } } else { hasHash = true; @@ -270,9 +270,9 @@ abstract public class Canonical { rt1.isOutOfContext() ); if( rt2 != null ) { - out.reachTuples.add(unionUpArity(rt1, rt2) ); + out.reachTuples.add(unionUpArity(rt1, rt2) ); } else { - out.reachTuples.add(rt1); + out.reachTuples.add(rt1); } } @@ -284,7 +284,7 @@ abstract public class Canonical { rt2.isOutOfContext() ); if( rt1 == null ) { - out.reachTuples.add(rt2); + out.reachTuples.add(rt2); } } @@ -388,30 +388,30 @@ abstract public class Canonical { if( age == AllocSite.AGE_notInThisSite || rt.isOutOfContext() ) { - out.reachTuples.add(rt); + out.reachTuples.add(rt); } else if( age == AllocSite.AGE_summary ) { - // remember the summary tuple, but don't add it - // we may combine it with the oldest tuple - rtSummary = rt; + // remember the summary tuple, but don't add it + // we may combine it with the oldest tuple + rtSummary = rt; } else if( age == AllocSite.AGE_oldest ) { - // found an oldest hrnID, again just remember - // for later - rtOldest = rt; + // found an oldest hrnID, again just remember + // for later + rtOldest = rt; } else { - assert age == AllocSite.AGE_in_I; + assert age == AllocSite.AGE_in_I; - Integer I = as.getAge(hrnID); - assert I != null; + Integer I = as.getAge(hrnID); + assert I != null; - // otherwise, we change this hrnID to the - // next older hrnID - Integer hrnIDToChangeTo = as.getIthOldest(I + 1); - ReachTuple rtAged = - Canonical.changeHrnIDTo(rt, hrnIDToChangeTo); - out.reachTuples.add(rtAged); + // otherwise, we change this hrnID to the + // next older hrnID + Integer hrnIDToChangeTo = as.getIthOldest(I + 1); + ReachTuple rtAged = + Canonical.changeHrnIDTo(rt, hrnIDToChangeTo); + out.reachTuples.add(rtAged); } } @@ -482,13 +482,13 @@ abstract public class Canonical { ReachState state2 = rs2.containsIgnorePreds(state1); if( state2 != null ) { - out.reachStates.add(ReachState.factory(state1.reachTuples, - Canonical.join(state1.preds, - state2.preds - ) - ) ); + out.reachStates.add(ReachState.factory(state1.reachTuples, + Canonical.join(state1.preds, + state2.preds + ) + ) ); } else { - out.reachStates.add(state1); + out.reachStates.add(state1); } } @@ -499,7 +499,7 @@ abstract public class Canonical { ReachState state1 = rs1.containsIgnorePreds(state2); if( state1 == null ) { - out.reachStates.add(state2); + out.reachStates.add(state2); } } @@ -540,9 +540,9 @@ abstract public class Canonical { ReachState state1 = (ReachState) itr.next(); ReachState state2 = rs2.containsIgnorePreds(state1); if( state2 != null ) { - // prefer the predicates on state1, an overapproximation - // of state1 preds AND state2 preds - out.reachStates.add(state1); + // prefer the predicates on state1, an overapproximation + // of state1 preds AND state2 preds + out.reachStates.add(state1); } } @@ -626,21 +626,21 @@ abstract public class Canonical { Iterator ctItr = cs.iterator(); while( ctItr.hasNext() ) { - ChangeTuple ct = ctItr.next(); - - if( stateOrig.equalsIgnorePreds(ct.getStateToMatch() ) ) { - // use the new state, but the original predicates - ReachState stateNew = - ReachState.factory(ct.getStateToAdd().reachTuples, - stateOrig.preds - ); - out.reachStates.add(stateNew); - changeFound = true; - } + ChangeTuple ct = ctItr.next(); + + if( stateOrig.equalsIgnorePreds(ct.getStateToMatch() ) ) { + // use the new state, but the original predicates + ReachState stateNew = + ReachState.factory(ct.getStateToAdd().reachTuples, + stateOrig.preds + ); + out.reachStates.add(stateNew); + changeFound = true; + } } if( keepSourceState || !changeFound ) { - out.reachStates.add(stateOrig); + out.reachStates.add(stateOrig); } } @@ -676,50 +676,50 @@ abstract public class Canonical { Iterator itrR = rsR.iterator(); while( itrR.hasNext() ) { - ReachState r = itrR.next(); - - ReachState theUnion = ReachState.factory(); - - Iterator itrRelement = r.iterator(); - while( itrRelement.hasNext() ) { - ReachTuple rtR = itrRelement.next(); - ReachTuple rtO = o.containsHrnID(rtR.getHrnID(), - rtR.isOutOfContext() - ); - if( rtO != null ) { - theUnion = Canonical.add(theUnion, - Canonical.unionUpArity(rtR, - rtO - ) - ); - } else { - theUnion = Canonical.add(theUnion, - rtR - ); - } - } - - Iterator itrOelement = o.iterator(); - while( itrOelement.hasNext() ) { - ReachTuple rtO = itrOelement.next(); - ReachTuple rtR = theUnion.containsHrnID(rtO.getHrnID(), - rtO.isOutOfContext() - ); - if( rtR == null ) { - theUnion = Canonical.add(theUnion, - rtO - ); - } - } - - if( !theUnion.isEmpty() ) { - out = - Canonical.union(out, - ChangeSet.factory( - ChangeTuple.factory(o, theUnion) - ) - ); - } + ReachState r = itrR.next(); + + ReachState theUnion = ReachState.factory(); + + Iterator itrRelement = r.iterator(); + while( itrRelement.hasNext() ) { + ReachTuple rtR = itrRelement.next(); + ReachTuple rtO = o.containsHrnID(rtR.getHrnID(), + rtR.isOutOfContext() + ); + if( rtO != null ) { + theUnion = Canonical.add(theUnion, + Canonical.unionUpArity(rtR, + rtO + ) + ); + } else { + theUnion = Canonical.add(theUnion, + rtR + ); + } + } + + Iterator itrOelement = o.iterator(); + while( itrOelement.hasNext() ) { + ReachTuple rtO = itrOelement.next(); + ReachTuple rtR = theUnion.containsHrnID(rtO.getHrnID(), + rtO.isOutOfContext() + ); + if( rtR == null ) { + theUnion = Canonical.add(theUnion, + rtO + ); + } + } + + if( !theUnion.isEmpty() ) { + out = + Canonical.union(out, + ChangeSet.factory( + ChangeTuple.factory(o, theUnion) + ) + ); + } } } @@ -789,15 +789,15 @@ abstract public class Canonical { Iterator itrP = rsP.iterator(); while( itrP.hasNext() && !subsetExists ) { - ReachState stateP = itrP.next(); + ReachState stateP = itrP.next(); - if( stateP.isSubset(stateO) ) { - subsetExists = true; - } + if( stateP.isSubset(stateO) ) { + subsetExists = true; + } } if( subsetExists ) { - out.reachStates.add(stateO); + out.reachStates.add(stateO); } } @@ -1004,76 +1004,76 @@ abstract public class Canonical { int age = as.getAgeCategory(rt.getHrnID() ); if( age == AllocSite.AGE_notInThisSite ) { - // things not from the site just go back in - baseState = Canonical.addUpArity(baseState, rt); + // things not from the site just go back in + baseState = Canonical.addUpArity(baseState, rt); } else if( age == AllocSite.AGE_summary ) { - if( rt.isOutOfContext() ) { - // if its out-of-context, we only deal here with the ZERO-OR-MORE - // arity, if ARITY-ONE we'll branch the base state after the loop - if( rt.getArity() == ReachTuple.ARITY_ZEROORMORE ) { - // add two overly conservative symbols to reach state (PUNTING) - - baseState = Canonical.addUpArity(baseState, - ReachTuple.factory(as.getSummary(), - true, // multi - ReachTuple.ARITY_ZEROORMORE, - false // out-of-context - ) - ); - - baseState = Canonical.addUpArity(baseState, - ReachTuple.factory(as.getSummary(), - true, // multi - ReachTuple.ARITY_ZEROORMORE, - true // out-of-context - ) - ); - } else { - assert rt.getArity() == ReachTuple.ARITY_ONE; - found2Sooc = true; - } - - } else { - // the in-context just becomes shadow - baseState = Canonical.addUpArity(baseState, - ReachTuple.factory(as.getSummaryShadow(), - true, // multi - rt.getArity(), - false // out-of-context - ) - ); - } + if( rt.isOutOfContext() ) { + // if its out-of-context, we only deal here with the ZERO-OR-MORE + // arity, if ARITY-ONE we'll branch the base state after the loop + if( rt.getArity() == ReachTuple.ARITY_ZEROORMORE ) { + // add two overly conservative symbols to reach state (PUNTING) + + baseState = Canonical.addUpArity(baseState, + ReachTuple.factory(as.getSummary(), + true, // multi + ReachTuple.ARITY_ZEROORMORE, + false // out-of-context + ) + ); + + baseState = Canonical.addUpArity(baseState, + ReachTuple.factory(as.getSummary(), + true, // multi + ReachTuple.ARITY_ZEROORMORE, + true // out-of-context + ) + ); + } else { + assert rt.getArity() == ReachTuple.ARITY_ONE; + found2Sooc = true; + } + + } else { + // the in-context just becomes shadow + baseState = Canonical.addUpArity(baseState, + ReachTuple.factory(as.getSummaryShadow(), + true, // multi + rt.getArity(), + false // out-of-context + ) + ); + } } else { - // otherwise age is in range [0, k] - Integer I = as.getAge(rt.getHrnID() ); - assert I != null; - assert !rt.isMultiObject(); - assert rt.getArity() == ReachTuple.ARITY_ONE; - - if( rt.isOutOfContext() ) { - // becomes the in-context version - baseState = Canonical.addUpArity(baseState, - ReachTuple.factory(rt.getHrnID(), - false, // multi - ReachTuple.ARITY_ONE, - false // out-of-context - ) - ); - - } else { - // otherwise the ith symbol becomes shadowed - baseState = Canonical.addUpArity(baseState, - ReachTuple.factory(-rt.getHrnID(), - false, // multi - ReachTuple.ARITY_ONE, - false // out-of-context - ) - ); - } + // otherwise age is in range [0, k] + Integer I = as.getAge(rt.getHrnID() ); + assert I != null; + assert !rt.isMultiObject(); + assert rt.getArity() == ReachTuple.ARITY_ONE; + + if( rt.isOutOfContext() ) { + // becomes the in-context version + baseState = Canonical.addUpArity(baseState, + ReachTuple.factory(rt.getHrnID(), + false, // multi + ReachTuple.ARITY_ONE, + false // out-of-context + ) + ); + + } else { + // otherwise the ith symbol becomes shadowed + baseState = Canonical.addUpArity(baseState, + ReachTuple.factory(-rt.getHrnID(), + false, // multi + ReachTuple.ARITY_ONE, + false // out-of-context + ) + ); + } } } @@ -1103,15 +1103,15 @@ abstract public class Canonical { ); for( int i = 0; i < as.getAllocationDepth(); ++i ) { - out = Canonical.add(out, - Canonical.addUpArity(baseState, - ReachTuple.factory(as.getIthOldest(i), - false, // multi - ReachTuple.ARITY_ONE, - true // out-of-context - ) - ) - ); + out = Canonical.add(out, + Canonical.addUpArity(baseState, + ReachTuple.factory(as.getIthOldest(i), + false, // multi + ReachTuple.ARITY_ONE, + true // out-of-context + ) + ) + ); } } else { @@ -1193,20 +1193,20 @@ abstract public class Canonical { int age = as.getShadowAgeCategory(rt.getHrnID() ); if( age == AllocSite.SHADOWAGE_notInThisSite ) { - // things not from the site just go back in - out = Canonical.addUpArity(out, rt); + // things not from the site just go back in + out = Canonical.addUpArity(out, rt); } else { - assert !rt.isOutOfContext(); - - // otherwise unshadow it - out = Canonical.addUpArity(out, - ReachTuple.factory(-rt.getHrnID(), - rt.isMultiObject(), - rt.getArity(), - false - ) - ); + assert !rt.isOutOfContext(); + + // otherwise unshadow it + out = Canonical.addUpArity(out, + ReachTuple.factory(-rt.getHrnID(), + rt.isMultiObject(), + rt.getArity(), + false + ) + ); } } @@ -1370,14 +1370,14 @@ abstract public class Canonical { Taint t2 = ts2.containsIgnorePreds(t1); if( t2 != null ) { - Taint tNew = new Taint(t1); - tNew.preds = Canonical.join(t1.preds, - t2.preds - ); - tNew = (Taint) makeCanonical(tNew); - out.taints.add(tNew); + Taint tNew = new Taint(t1); + tNew.preds = Canonical.join(t1.preds, + t2.preds + ); + tNew = (Taint) makeCanonical(tNew); + out.taints.add(tNew); } else { - out.taints.add(t1); + out.taints.add(t1); } } @@ -1388,7 +1388,7 @@ abstract public class Canonical { Taint t1 = ts1.containsIgnorePreds(t2); if( t1 == null ) { - out.taints.add(t2); + out.taints.add(t2); } } @@ -1452,14 +1452,14 @@ abstract public class Canonical { Taint t2 = ts2.containsIgnorePreds(t1); if( t2 != null ) { - Taint tNew = new Taint(t1); - tNew.preds = Canonical.join(t1.preds, - t2.preds - ); - tNew = (Taint) makeCanonical(tNew); - out.taints.add(tNew); + Taint tNew = new Taint(t1); + tNew.preds = Canonical.join(t1.preds, + t2.preds + ); + tNew = (Taint) makeCanonical(tNew); + out.taints.add(tNew); } else { - out.taints.add(t1); + out.taints.add(t1); } } @@ -1470,7 +1470,7 @@ abstract public class Canonical { Taint t1 = ts1.containsIgnorePreds(t2); if( t1 == null ) { - out.taints.add(t2); + out.taints.add(t2); } } @@ -1504,7 +1504,7 @@ abstract public class Canonical { !t.getSESE().equals(sese) || !t.getPreds().isEmpty() ) { - out.taints.add(t); + out.taints.add(t); } } @@ -1534,7 +1534,7 @@ abstract public class Canonical { // it is out of context so it should go through, too if( t.getSESE() == null || !seseSet.contains(t)) { - out.taints.add(t); + out.taints.add(t); } } @@ -1560,7 +1560,7 @@ abstract public class Canonical { // unaffected, and if the taint has a non-empty predicate // it is out of context so it should go through, too if( t.getSESE()!=null && t.getSESE()!=sese) { - out.taints.add(t); + out.taints.add(t); } } @@ -1591,7 +1591,7 @@ abstract public class Canonical { // only take non-stall site taints onward if( t.getStallSite() == null ) { - out.taints.add(t); + out.taints.add(t); } } diff --git a/Robust/src/Analysis/Disjoint/DisjointAnalysis.java b/Robust/src/Analysis/Disjoint/DisjointAnalysis.java index d9c057af..37a54341 100644 --- a/Robust/src/Analysis/Disjoint/DisjointAnalysis.java +++ b/Robust/src/Analysis/Disjoint/DisjointAnalysis.java @@ -122,10 +122,10 @@ public class DisjointAnalysis implements HeapAnalysis { AllocSite as = n.getAllocSite(); if (as == null) { - out += " " + n.toString() + ",\n"; + out += " " + n.toString() + ",\n"; } else { - out += " " + n.toString() + ": " + as.toStringVerbose() - + ",\n"; + out += " " + n.toString() + ": " + as.toStringVerbose() + + ",\n"; } } @@ -161,7 +161,7 @@ public class DisjointAnalysis implements HeapAnalysis { TaskDescriptor td = (TaskDescriptor) taskItr.next(); if (!tabularOutput) { - bw.write("\n---------" + td + "--------\n"); + bw.write("\n---------" + td + "--------\n"); } HashSet allocSites = getFlaggedAllocationSitesReachableFromTask(td); @@ -176,52 +176,52 @@ public class DisjointAnalysis implements HeapAnalysis { FlatMethod fm = state.getMethodFlat(td); for (int i = 0; i < fm.numParameters(); ++i) { - // skip parameters with types that cannot reference - // into the heap - if( !shouldAnalysisTrack(fm.getParameter(i).getType() ) ) { - continue; - } - - // for the ith parameter check for sharing classes to all - // higher numbered parameters - for (int j = i + 1; j < fm.numParameters(); ++j) { - - // skip parameters with types that cannot reference - // into the heap - if( !shouldAnalysisTrack(fm.getParameter(j).getType() ) ) { - continue; - } - - - common = hasPotentialSharing(td, i, j); - if (!common.isEmpty()) { - foundSomeSharing = true; - ++numSharing; - if (!tabularOutput) { - bw.write("Potential sharing between parameters " + i - + " and " + j + ".\n"); - bw.write(prettyPrintNodeSet(common) + "\n"); - } - } - } - - // for the ith parameter, check for sharing classes against - // the set of allocation sites reachable from this - // task context - Iterator allocItr = allocSites.iterator(); - while (allocItr.hasNext()) { - AllocSite as = (AllocSite) allocItr.next(); - common = hasPotentialSharing(td, i, as); - if (!common.isEmpty()) { - foundSomeSharing = true; - ++numSharing; - if (!tabularOutput) { - bw.write("Potential sharing between parameter " + i - + " and " + as.getFlatNew() + ".\n"); - bw.write(prettyPrintNodeSet(common) + "\n"); - } - } - } + // skip parameters with types that cannot reference + // into the heap + if( !shouldAnalysisTrack(fm.getParameter(i).getType() ) ) { + continue; + } + + // for the ith parameter check for sharing classes to all + // higher numbered parameters + for (int j = i + 1; j < fm.numParameters(); ++j) { + + // skip parameters with types that cannot reference + // into the heap + if( !shouldAnalysisTrack(fm.getParameter(j).getType() ) ) { + continue; + } + + + common = hasPotentialSharing(td, i, j); + if (!common.isEmpty()) { + foundSomeSharing = true; + ++numSharing; + if (!tabularOutput) { + bw.write("Potential sharing between parameters " + i + + " and " + j + ".\n"); + bw.write(prettyPrintNodeSet(common) + "\n"); + } + } + } + + // for the ith parameter, check for sharing classes against + // the set of allocation sites reachable from this + // task context + Iterator allocItr = allocSites.iterator(); + while (allocItr.hasNext()) { + AllocSite as = (AllocSite) allocItr.next(); + common = hasPotentialSharing(td, i, as); + if (!common.isEmpty()) { + foundSomeSharing = true; + ++numSharing; + if (!tabularOutput) { + bw.write("Potential sharing between parameter " + i + + " and " + as.getFlatNew() + ".\n"); + bw.write(prettyPrintNodeSet(common) + "\n"); + } + } + } } // for each allocation site check for sharing classes with @@ -230,36 +230,36 @@ public class DisjointAnalysis implements HeapAnalysis { HashSet outerChecked = new HashSet(); Iterator allocItr1 = allocSites.iterator(); while (allocItr1.hasNext()) { - AllocSite as1 = (AllocSite) allocItr1.next(); + AllocSite as1 = (AllocSite) allocItr1.next(); - Iterator allocItr2 = allocSites.iterator(); - while (allocItr2.hasNext()) { - AllocSite as2 = (AllocSite) allocItr2.next(); + Iterator allocItr2 = allocSites.iterator(); + while (allocItr2.hasNext()) { + AllocSite as2 = (AllocSite) allocItr2.next(); - if (!outerChecked.contains(as2)) { - common = hasPotentialSharing(td, as1, as2); + if (!outerChecked.contains(as2)) { + common = hasPotentialSharing(td, as1, as2); - if (!common.isEmpty()) { - foundSomeSharing = true; - ++numSharing; - if (!tabularOutput) { - bw.write("Potential sharing between " - + as1.getFlatNew() + " and " - + as2.getFlatNew() + ".\n"); - bw.write(prettyPrintNodeSet(common) + "\n"); - } - } - } - } + if (!common.isEmpty()) { + foundSomeSharing = true; + ++numSharing; + if (!tabularOutput) { + bw.write("Potential sharing between " + + as1.getFlatNew() + " and " + + as2.getFlatNew() + ".\n"); + bw.write(prettyPrintNodeSet(common) + "\n"); + } + } + } + } - outerChecked.add(as1); + outerChecked.add(as1); } if (!foundSomeSharing) { - if (!tabularOutput) { - bw.write("No sharing between flagged objects in Task " + td - + ".\n"); - } + if (!tabularOutput) { + bw.write("No sharing between flagged objects in Task " + td + + ".\n"); + } } } @@ -316,21 +316,21 @@ public class DisjointAnalysis implements HeapAnalysis { Iterator allocItr2 = allocSites.iterator(); while (allocItr2.hasNext()) { - AllocSite as2 = (AllocSite) allocItr2.next(); + AllocSite as2 = (AllocSite) allocItr2.next(); - if (!outerChecked.contains(as2)) { - Set common = hasPotentialSharing(d, - as1, as2); + if (!outerChecked.contains(as2)) { + Set common = hasPotentialSharing(d, + as1, as2); - if (!common.isEmpty()) { - foundSomeSharing = true; - bw.write("Potential sharing between " - + as1.getDisjointAnalysisId() + " and " - + as2.getDisjointAnalysisId() + ".\n"); - bw.write(prettyPrintNodeSet(common) + "\n"); - ++numSharing; - } - } + if (!common.isEmpty()) { + foundSomeSharing = true; + bw.write("Potential sharing between " + + as1.getDisjointAnalysisId() + " and " + + as2.getDisjointAnalysisId() + ".\n"); + bw.write(prettyPrintNodeSet(common) + "\n"); + ++numSharing; + } + } } outerChecked.add(as1); @@ -755,7 +755,7 @@ public class DisjointAnalysis implements HeapAnalysis { if( sitesToFlag != null ) { treport = String.format("Disjoint reachability analysis flagged %d sites and took %.3f sec.", sitesToFlag.size(), dt); if(sitesToFlag.size()>0) { - treport+="\nFlagged sites:"+"\n"+sitesToFlag.toString(); + treport+="\nFlagged sites:"+"\n"+sitesToFlag.toString(); } } else { treport = String.format("Disjoint reachability analysis took %.3f sec.", dt); @@ -766,32 +766,32 @@ public class DisjointAnalysis implements HeapAnalysis { try { if( writeFinalDOTs && !writeAllIncrementalDOTs ) { - writeFinalGraphs(); + writeFinalGraphs(); } if( state.DISJOINTWRITEIHMS && !suppressOutput ) { - writeFinalIHMs(); + writeFinalIHMs(); } if( state.DISJOINTWRITEINITCONTEXTS && !suppressOutput ) { - writeInitialContexts(); + writeInitialContexts(); } if( state.DISJOINTALIASFILE != null && !suppressOutput ) { - if( state.TASK ) { - writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines); - } else { - writeAllSharingJava(state.DISJOINTALIASFILE, - treport, - justtime, - state.DISJOINTALIASTAB, - state.lines - ); - } + if( state.TASK ) { + writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines); + } else { + writeAllSharingJava(state.DISJOINTALIASFILE, + treport, + justtime, + state.DISJOINTALIASTAB, + state.lines + ); + } } if( state.RCR ) { - buildStateMachines.writeStateMachines(); + buildStateMachines.writeStateMachines(); } } catch( IOException e ) { @@ -824,23 +824,23 @@ public class DisjointAnalysis implements HeapAnalysis { if( state.TASK ) { if( !suppressOutput ) { - System.out.println("Bamboo mode..."); + System.out.println("Bamboo mode..."); } Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator(); while( taskItr.hasNext() ) { - TaskDescriptor td = (TaskDescriptor) taskItr.next(); - if( !descriptorsToAnalyze.contains(td) ) { - // add all methods transitively reachable from the - // tasks as well - descriptorsToAnalyze.add(td); - descriptorsToAnalyze.addAll(callGraph.getAllMethods(td) ); - } + TaskDescriptor td = (TaskDescriptor) taskItr.next(); + if( !descriptorsToAnalyze.contains(td) ) { + // add all methods transitively reachable from the + // tasks as well + descriptorsToAnalyze.add(td); + descriptorsToAnalyze.addAll(callGraph.getAllMethods(td) ); + } } } else { if( !suppressOutput ) { - System.out.println("Java mode..."); + System.out.println("Java mode..."); } // add all methods transitively reachable from the @@ -876,11 +876,11 @@ public class DisjointAnalysis implements HeapAnalysis { // for the priority queue, give items at the head // of the sorted list a low number (highest priority) while( !sortedDescriptors.isEmpty() ) { - Descriptor d = sortedDescriptors.removeFirst(); - mapDescriptorToPriority.put(d, new Integer(p) ); - descriptorsToVisitQ.add(new DescriptorQWrapper(p, d) ); - descriptorsToVisitSet.add(d); - ++p; + Descriptor d = sortedDescriptors.removeFirst(); + mapDescriptorToPriority.put(d, new Integer(p) ); + descriptorsToVisitQ.add(new DescriptorQWrapper(p, d) ); + descriptorsToVisitSet.add(d); + ++p; } } else if( state.DISJOINTDVISITSTACK || @@ -889,16 +889,16 @@ public class DisjointAnalysis implements HeapAnalysis { // if we're doing the stack scheme, just throw the root // method or tasks on the stack if( state.TASK ) { - Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator(); - while( taskItr.hasNext() ) { - TaskDescriptor td = (TaskDescriptor) taskItr.next(); - descriptorsToVisitStack.add(td); - descriptorsToVisitSet.add(td); - } + Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator(); + while( taskItr.hasNext() ) { + TaskDescriptor td = (TaskDescriptor) taskItr.next(); + descriptorsToVisitStack.add(td); + descriptorsToVisitSet.add(td); + } } else { - descriptorsToVisitStack.add(mdAnalysisEntry); - descriptorsToVisitSet.add(mdAnalysisEntry); + descriptorsToVisitStack.add(mdAnalysisEntry); + descriptorsToVisitSet.add(mdAnalysisEntry); } } else { @@ -913,10 +913,10 @@ public class DisjointAnalysis implements HeapAnalysis { if( state.DISJOINTDVISITSTACK || state.DISJOINTDVISITSTACKEESONTOP ) { - d = descriptorsToVisitStack.pop(); + d = descriptorsToVisitStack.pop(); } else if( state.DISJOINTDVISITPQUE ) { - d = descriptorsToVisitQ.poll().getDescriptor(); + d = descriptorsToVisitQ.poll().getDescriptor(); } assert descriptorsToVisitSet.contains(d); @@ -931,34 +931,34 @@ public class DisjointAnalysis implements HeapAnalysis { // that depend on this one to the "to visit" set. if( !suppressOutput ) { - System.out.println("Analyzing " + d); + System.out.println("Analyzing " + d); } if( state.DISJOINTDVISITSTACKEESONTOP ) { - assert calleesToEnqueue.isEmpty(); + assert calleesToEnqueue.isEmpty(); } ReachGraph rg = analyzeMethod(d); ReachGraph rgPrev = getPartial(d); if( !rg.equals(rgPrev) ) { - setPartial(d, rg); + setPartial(d, rg); - if( state.DISJOINTDEBUGSCHEDULING ) { - System.out.println(" complete graph changed, scheduling callers for analysis:"); - } + if( state.DISJOINTDEBUGSCHEDULING ) { + System.out.println(" complete graph changed, scheduling callers for analysis:"); + } - // results for d changed, so enqueue dependents - // of d for further analysis - Iterator depsItr = getDependents(d).iterator(); - while( depsItr.hasNext() ) { - Descriptor dNext = depsItr.next(); - enqueue(dNext); + // results for d changed, so enqueue dependents + // of d for further analysis + Iterator depsItr = getDependents(d).iterator(); + while( depsItr.hasNext() ) { + Descriptor dNext = depsItr.next(); + enqueue(dNext); - if( state.DISJOINTDEBUGSCHEDULING ) { - System.out.println(" "+dNext); - } - } + if( state.DISJOINTDEBUGSCHEDULING ) { + System.out.println(" "+dNext); + } + } } // whether or not the method under analysis changed, @@ -967,12 +967,12 @@ public class DisjointAnalysis implements HeapAnalysis { // the stack now (in other method-visiting modes they // are already enqueued at this point if( state.DISJOINTDVISITSTACKEESONTOP ) { - Iterator depsItr = calleesToEnqueue.iterator(); - while( depsItr.hasNext() ) { - Descriptor dNext = depsItr.next(); - enqueue(dNext); - } - calleesToEnqueue.clear(); + Iterator depsItr = calleesToEnqueue.iterator(); + while( depsItr.hasNext() ) { + Descriptor dNext = depsItr.next(); + enqueue(dNext); + } + calleesToEnqueue.clear(); } } @@ -1014,10 +1014,10 @@ public class DisjointAnalysis implements HeapAnalysis { FlatNode fn; if( determinismDesired ) { - assert !flatNodesToVisitQ.isEmpty(); - fn = flatNodesToVisitQ.remove(); + assert !flatNodesToVisitQ.isEmpty(); + fn = flatNodesToVisitQ.remove(); } else { - fn = flatNodesToVisit.iterator().next(); + fn = flatNodesToVisit.iterator().next(); } flatNodesToVisit.remove(fn); @@ -1028,31 +1028,31 @@ public class DisjointAnalysis implements HeapAnalysis { ReachGraph rg = new ReachGraph(); TaskDescriptor taskDesc; if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null) { - if(mapDescriptorToReachGraph.containsKey(taskDesc)) { - // retrieve existing reach graph if it is not first time - rg=mapDescriptorToReachGraph.get(taskDesc); - } else { - // create initial reach graph for a task - rg=createInitialTaskReachGraph((FlatMethod)fn); - rg.globalSweep(); - mapDescriptorToReachGraph.put(taskDesc, rg); - } + if(mapDescriptorToReachGraph.containsKey(taskDesc)) { + // retrieve existing reach graph if it is not first time + rg=mapDescriptorToReachGraph.get(taskDesc); + } else { + // create initial reach graph for a task + rg=createInitialTaskReachGraph((FlatMethod)fn); + rg.globalSweep(); + mapDescriptorToReachGraph.put(taskDesc, rg); + } } // start by merging all node's parents' graphs for( int i = 0; i < pm.numPrev(fn); ++i ) { - FlatNode pn = pm.getPrev(fn,i); - if( mapFlatNodeToReachGraph.containsKey(pn) ) { - ReachGraph rgParent = mapFlatNodeToReachGraph.get(pn); - rg.merge(rgParent); - } + FlatNode pn = pm.getPrev(fn,i); + if( mapFlatNodeToReachGraph.containsKey(pn) ) { + ReachGraph rgParent = mapFlatNodeToReachGraph.get(pn); + rg.merge(rgParent); + } } if( takeDebugSnapshots && d.getSymbol().equals(descSymbolDebug) ) { - debugSnapshot(rg, fn, true); + debugSnapshot(rg, fn, true); } @@ -1063,8 +1063,8 @@ public class DisjointAnalysis implements HeapAnalysis { if( takeDebugSnapshots && d.getSymbol().equals(descSymbolDebug) ) { - debugSnapshot(rg, fn, false); - ++snapNodeCounter; + debugSnapshot(rg, fn, false); + ++snapNodeCounter; } @@ -1073,16 +1073,16 @@ public class DisjointAnalysis implements HeapAnalysis { // with the update and enqueue the children ReachGraph rgPrev = mapFlatNodeToReachGraph.get(fn); if( !rg.equals(rgPrev) ) { - mapFlatNodeToReachGraph.put(fn, rg); + mapFlatNodeToReachGraph.put(fn, rg); - for( int i = 0; i < pm.numNext(fn); i++ ) { - FlatNode nn = pm.getNext(fn, i); + for( int i = 0; i < pm.numNext(fn); i++ ) { + FlatNode nn = pm.getNext(fn, i); - flatNodesToVisit.add(nn); - if( determinismDesired ) { - flatNodesToVisitQ.add(nn); - } - } + flatNodesToVisit.add(nn); + if( determinismDesired ) { + flatNodesToVisitQ.add(nn); + } + } } } @@ -1116,8 +1116,8 @@ public class DisjointAnalysis implements HeapAnalysis { if( snapVisitCounter == visitStartCapture + numVisitsToCapture && stopAfterCapture ) { - System.out.println("!!! Stopping analysis after debug snap captures. !!!"); - System.exit(0); + System.out.println("!!! Stopping analysis after debug snap captures. !!!"); + System.exit(0); } } @@ -1183,13 +1183,13 @@ public class DisjointAnalysis implements HeapAnalysis { Set entrySet = heapsFromCallers.entrySet(); Iterator itr = entrySet.iterator(); while( itr.hasNext() ) { - Map.Entry me = (Map.Entry)itr.next(); - FlatCall fc = (FlatCall) me.getKey(); - ReachGraph rgContrib = (ReachGraph) me.getValue(); + Map.Entry me = (Map.Entry)itr.next(); + FlatCall fc = (FlatCall) me.getKey(); + ReachGraph rgContrib = (ReachGraph) me.getValue(); - assert fc.getMethod().equals(d); + assert fc.getMethod().equals(d); - rg.merge(rgContrib); + rg.merge(rgContrib); } // additionally, we are enforcing STRICT MONOTONICITY for the @@ -1205,22 +1205,22 @@ public class DisjointAnalysis implements HeapAnalysis { case FKind.FlatOpNode: FlatOpNode fon = (FlatOpNode) fn; if( fon.getOp().getOp() == Operation.ASSIGN ) { - lhs = fon.getDest(); - rhs = fon.getLeft(); + lhs = fon.getDest(); + rhs = fon.getLeft(); - // before transfer, do effects analysis support - if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { - if(rblockRel.isPotentialStallSite(fn)) { - // x gets status of y + // before transfer, do effects analysis support + if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { + if(rblockRel.isPotentialStallSite(fn)) { + // x gets status of y // if(!rg.isAccessible(rhs)){ - if(!accessible.isAccessible(fn, rhs)) { - rg.makeInaccessible(lhs); - } - } - } + if(!accessible.isAccessible(fn, rhs)) { + rg.makeInaccessible(lhs); + } + } + } - // transfer func - rg.assignTempXEqualToTempY(lhs, rhs); + // transfer func + rg.assignTempXEqualToTempY(lhs, rhs); } break; @@ -1234,13 +1234,13 @@ public class DisjointAnalysis implements HeapAnalysis { // before transfer, do effects analysis support if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { - if(rblockRel.isPotentialStallSite(fn)) { - // x gets status of y + if(rblockRel.isPotentialStallSite(fn)) { + // x gets status of y // if(!rg.isAccessible(rhs)){ - if(!accessible.isAccessible(fn,rhs)) { - rg.makeInaccessible(lhs); - } - } + if(!accessible.isAccessible(fn,rhs)) { + rg.makeInaccessible(lhs); + } + } } // transfer func @@ -1258,29 +1258,29 @@ public class DisjointAnalysis implements HeapAnalysis { // a stall-site taint if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { - if(rblockRel.isPotentialStallSite(fn)) { - // x=y.f, stall y if not accessible - // contributes read effects on stall site of y + if(rblockRel.isPotentialStallSite(fn)) { + // x=y.f, stall y if not accessible + // contributes read effects on stall site of y // if(!rg.isAccessible(rhs)) { - if(!accessible.isAccessible(fn,rhs)) { - rg.taintStallSite(fn, rhs); - } + if(!accessible.isAccessible(fn,rhs)) { + rg.taintStallSite(fn, rhs); + } - // after this, x and y are accessbile. - rg.makeAccessible(lhs); - rg.makeAccessible(rhs); - } + // after this, x and y are accessbile. + rg.makeAccessible(lhs); + rg.makeAccessible(rhs); + } } if( shouldAnalysisTrack(fld.getType() ) ) { - // transfer func - rg.assignTempXEqualToTempYFieldF(lhs, rhs, fld, fn); + // transfer func + rg.assignTempXEqualToTempYFieldF(lhs, rhs, fld, fn); } // after transfer, use updated graph to // do effects analysis if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { - effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fld, fn); + effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fld, fn); } break; @@ -1297,33 +1297,33 @@ public class DisjointAnalysis implements HeapAnalysis { // stall-site taints if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { - if(rblockRel.isPotentialStallSite(fn)) { - // x.y=f , stall x and y if they are not accessible - // also contribute write effects on stall site of x + if(rblockRel.isPotentialStallSite(fn)) { + // x.y=f , stall x and y if they are not accessible + // also contribute write effects on stall site of x // if(!rg.isAccessible(lhs)) { - if(!accessible.isAccessible(fn,lhs)) { - rg.taintStallSite(fn, lhs); - } + if(!accessible.isAccessible(fn,lhs)) { + rg.taintStallSite(fn, lhs); + } // if(!rg.isAccessible(rhs)) { - if(!accessible.isAccessible(fn,rhs)) { - rg.taintStallSite(fn, rhs); - } + if(!accessible.isAccessible(fn,rhs)) { + rg.taintStallSite(fn, rhs); + } - // accessible status update - rg.makeAccessible(lhs); - rg.makeAccessible(rhs); - } + // accessible status update + rg.makeAccessible(lhs); + rg.makeAccessible(rhs); + } } if( shouldAnalysisTrack(fld.getType() ) ) { - // transfer func - strongUpdate = rg.assignTempXFieldFEqualToTempY(lhs, fld, rhs, fn); + // transfer func + strongUpdate = rg.assignTempXFieldFEqualToTempY(lhs, fld, rhs, fn); } // use transformed graph to do effects analysis if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { - effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fld, fn, strongUpdate); + effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fld, fn, strongUpdate); } break; @@ -1342,28 +1342,28 @@ public class DisjointAnalysis implements HeapAnalysis { // before transfer func, possibly inject // stall-site taint if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { - if(rblockRel.isPotentialStallSite(fn)) { - // x=y.f, stall y if not accessible - // contributes read effects on stall site of y - // after this, x and y are accessbile. + if(rblockRel.isPotentialStallSite(fn)) { + // x=y.f, stall y if not accessible + // contributes read effects on stall site of y + // after this, x and y are accessbile. // if(!rg.isAccessible(rhs)) { - if(!accessible.isAccessible(fn,rhs)) { - rg.taintStallSite(fn, rhs); - } + if(!accessible.isAccessible(fn,rhs)) { + rg.taintStallSite(fn, rhs); + } - rg.makeAccessible(lhs); - rg.makeAccessible(rhs); - } + rg.makeAccessible(lhs); + rg.makeAccessible(rhs); + } } if( shouldAnalysisTrack(lhs.getType() ) ) { - // transfer func - rg.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement, fn); + // transfer func + rg.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement, fn); } // use transformed graph to do effects analysis if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { - effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fdElement, fn); + effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fdElement, fn); } break; @@ -1383,37 +1383,37 @@ public class DisjointAnalysis implements HeapAnalysis { // stall-site taints if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { - if(rblockRel.isPotentialStallSite(fn)) { - // x.y=f , stall x and y if they are not accessible - // also contribute write effects on stall site of x + if(rblockRel.isPotentialStallSite(fn)) { + // x.y=f , stall x and y if they are not accessible + // also contribute write effects on stall site of x // if(!rg.isAccessible(lhs)) { - if(!accessible.isAccessible(fn,lhs)) { - rg.taintStallSite(fn, lhs); - } + if(!accessible.isAccessible(fn,lhs)) { + rg.taintStallSite(fn, lhs); + } // if(!rg.isAccessible(rhs)) { - if(!accessible.isAccessible(fn,rhs)) { - rg.taintStallSite(fn, rhs); - } + if(!accessible.isAccessible(fn,rhs)) { + rg.taintStallSite(fn, rhs); + } - // accessible status update - rg.makeAccessible(lhs); - rg.makeAccessible(rhs); - } + // accessible status update + rg.makeAccessible(lhs); + rg.makeAccessible(rhs); + } } if( shouldAnalysisTrack(rhs.getType() ) ) { - // transfer func, BUT - // skip this node if it cannot create new reachability paths - if( !arrayReferencees.doesNotCreateNewReaching(fsen) ) { - rg.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs, fn); - } + // transfer func, BUT + // skip this node if it cannot create new reachability paths + if( !arrayReferencees.doesNotCreateNewReaching(fsen) ) { + rg.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs, fn); + } } // use transformed graph to do effects analysis if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { - effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fdElement, fn, - false); + effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fdElement, fn, + false); } break; @@ -1421,18 +1421,18 @@ public class DisjointAnalysis implements HeapAnalysis { FlatNew fnn = (FlatNew) fn; lhs = fnn.getDst(); if( shouldAnalysisTrack(lhs.getType() ) ) { - AllocSite as = getAllocSiteFromFlatNewPRIVATE(fnn); + AllocSite as = getAllocSiteFromFlatNewPRIVATE(fnn); - // before transform, support effects analysis - if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) { - if (rblockRel.isPotentialStallSite(fn)) { - // after creating new object, lhs is accessible - rg.makeAccessible(lhs); - } - } + // before transform, support effects analysis + if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) { + if (rblockRel.isPotentialStallSite(fn)) { + // after creating new object, lhs is accessible + rg.makeAccessible(lhs); + } + } - // transfer func - rg.assignTempEqualToNewAlloc(lhs, as); + // transfer func + rg.assignTempEqualToNewAlloc(lhs, as); } break; @@ -1441,11 +1441,11 @@ public class DisjointAnalysis implements HeapAnalysis { if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { - // always remove ALL stall site taints at enter - rg.removeAllStallSiteTaints(); + // always remove ALL stall site taints at enter + rg.removeAllStallSiteTaints(); - // inject taints for in-set vars - rg.taintInSetVars(sese); + // inject taints for in-set vars + rg.taintInSetVars(sese); } break; @@ -1456,15 +1456,15 @@ public class DisjointAnalysis implements HeapAnalysis { if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { - // @ sese exit make all live variables - // inaccessible to later parent statements - rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) ); + // @ sese exit make all live variables + // inaccessible to later parent statements + rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) ); - // always remove ALL stall site taints at exit - rg.removeAllStallSiteTaints(); + // always remove ALL stall site taints at exit + rg.removeAllStallSiteTaints(); - // remove in-set var taints for the exiting rblock - rg.removeInContextTaints(sese); + // remove in-set var taints for the exiting rblock + rg.removeInContextTaints(sese); } break; @@ -1472,9 +1472,9 @@ public class DisjointAnalysis implements HeapAnalysis { case FKind.FlatCall: { Descriptor mdCaller; if( fmContaining.getMethod() != null ) { - mdCaller = fmContaining.getMethod(); + mdCaller = fmContaining.getMethod(); } else { - mdCaller = fmContaining.getTask(); + mdCaller = fmContaining.getTask(); } FlatCall fc = (FlatCall) fn; MethodDescriptor mdCallee = fc.getMethod(); @@ -1482,15 +1482,15 @@ public class DisjointAnalysis implements HeapAnalysis { if( mdCallee.getSymbol().equals("genReach") ) { - rg.writeGraph("genReach"+d, - true, // write labels (variables) - true, // selectively hide intermediate temp vars - true, // prune unreachable heap regions - false, // hide reachability altogether - true, // hide subset reachability states - true, // hide predicates - true); // hide edge taints - break; + rg.writeGraph("genReach"+d, + true, // write labels (variables) + true, // selectively hide intermediate temp vars + true, // prune unreachable heap regions + false, // hide reachability altogether + true, // hide subset reachability states + true, // hide predicates + true); // hide edge taints + break; } @@ -1502,29 +1502,29 @@ public class DisjointAnalysis implements HeapAnalysis { boolean writeDebugDOTs = false; boolean stopAfter = false; if( debugCallSite ) { - ++ReachGraph.debugCallSiteVisitCounter; - System.out.println(" $$$ Debug call site visit "+ - ReachGraph.debugCallSiteVisitCounter+ - " $$$" - ); - if( - (ReachGraph.debugCallSiteVisitCounter >= - ReachGraph.debugCallSiteVisitStartCapture) && - - (ReachGraph.debugCallSiteVisitCounter < - ReachGraph.debugCallSiteVisitStartCapture + - ReachGraph.debugCallSiteNumVisitsToCapture) - ) { - writeDebugDOTs = true; - System.out.println(" $$$ Capturing this call site visit $$$"); - if( ReachGraph.debugCallSiteStopAfter && - (ReachGraph.debugCallSiteVisitCounter == - ReachGraph.debugCallSiteVisitStartCapture + - ReachGraph.debugCallSiteNumVisitsToCapture - 1) - ) { - stopAfter = true; - } - } + ++ReachGraph.debugCallSiteVisitCounter; + System.out.println(" $$$ Debug call site visit "+ + ReachGraph.debugCallSiteVisitCounter+ + " $$$" + ); + if( + (ReachGraph.debugCallSiteVisitCounter >= + ReachGraph.debugCallSiteVisitStartCapture) && + + (ReachGraph.debugCallSiteVisitCounter < + ReachGraph.debugCallSiteVisitStartCapture + + ReachGraph.debugCallSiteNumVisitsToCapture) + ) { + writeDebugDOTs = true; + System.out.println(" $$$ Capturing this call site visit $$$"); + if( ReachGraph.debugCallSiteStopAfter && + (ReachGraph.debugCallSiteVisitCounter == + ReachGraph.debugCallSiteVisitStartCapture + + ReachGraph.debugCallSiteNumVisitsToCapture - 1) + ) { + stopAfter = true; + } + } } @@ -1553,23 +1553,23 @@ public class DisjointAnalysis implements HeapAnalysis { heapForThisCall_cur.merge(heapForThisCall_old); if( !heapForThisCall_cur.equals(heapForThisCall_old) ) { - // if heap at call site changed, update the contribution, - // and reschedule the callee for analysis - addIHMcontribution(mdCallee, fc, heapForThisCall_cur); + // if heap at call site changed, update the contribution, + // and reschedule the callee for analysis + addIHMcontribution(mdCallee, fc, heapForThisCall_cur); - // map a FlatCall to its enclosing method/task descriptor - // so we can write that info out later - fc2enclosing.put(fc, mdCaller); + // map a FlatCall to its enclosing method/task descriptor + // so we can write that info out later + fc2enclosing.put(fc, mdCaller); - if( state.DISJOINTDEBUGSCHEDULING ) { - System.out.println(" context changed, scheduling callee: "+mdCallee); - } + if( state.DISJOINTDEBUGSCHEDULING ) { + System.out.println(" context changed, scheduling callee: "+mdCallee); + } - if( state.DISJOINTDVISITSTACKEESONTOP ) { - calleesToEnqueue.add(mdCallee); - } else { - enqueue(mdCallee); - } + if( state.DISJOINTDVISITSTACKEESONTOP ) { + calleesToEnqueue.add(mdCallee); + } else { + enqueue(mdCallee); + } } @@ -1579,78 +1579,78 @@ public class DisjointAnalysis implements HeapAnalysis { // callees, so find the set of callees... Set setPossibleCallees; if( determinismDesired ) { - // use an ordered set - setPossibleCallees = new TreeSet(dComp); + // use an ordered set + setPossibleCallees = new TreeSet(dComp); } else { - // otherwise use a speedy hashset - setPossibleCallees = new HashSet(); + // otherwise use a speedy hashset + setPossibleCallees = new HashSet(); } if( mdCallee.isStatic() ) { - setPossibleCallees.add(mdCallee); + setPossibleCallees.add(mdCallee); } else { - TypeDescriptor typeDesc = fc.getThis().getType(); - setPossibleCallees.addAll(callGraph.getMethods(mdCallee, - typeDesc) - ); + TypeDescriptor typeDesc = fc.getThis().getType(); + setPossibleCallees.addAll(callGraph.getMethods(mdCallee, + typeDesc) + ); } ReachGraph rgMergeOfPossibleCallers = new ReachGraph(); Iterator mdItr = setPossibleCallees.iterator(); while( mdItr.hasNext() ) { - MethodDescriptor mdPossible = mdItr.next(); - FlatMethod fmPossible = state.getMethodFlat(mdPossible); - - addDependent(mdPossible, // callee - d); // caller - - // don't alter the working graph (rg) until we compute a - // result for every possible callee, merge them all together, - // then set rg to that - ReachGraph rgPossibleCaller = new ReachGraph(); - rgPossibleCaller.merge(rg); - - ReachGraph rgPossibleCallee = getPartial(mdPossible); - - if( rgPossibleCallee == null ) { - // if this method has never been analyzed just schedule it - // for analysis and skip over this call site for now - if( state.DISJOINTDVISITSTACKEESONTOP ) { - calleesToEnqueue.add(mdPossible); - } else { - enqueue(mdPossible); - } - - if( state.DISJOINTDEBUGSCHEDULING ) { - System.out.println(" callee hasn't been analyzed, scheduling: "+mdPossible); - } - - } else { - // calculate the method call transform - rgPossibleCaller.resolveMethodCall(fc, - fmPossible, - rgPossibleCallee, - callerNodeIDsCopiedToCallee, - writeDebugDOTs - ); - - if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { + MethodDescriptor mdPossible = mdItr.next(); + FlatMethod fmPossible = state.getMethodFlat(mdPossible); + + addDependent(mdPossible, // callee + d); // caller + + // don't alter the working graph (rg) until we compute a + // result for every possible callee, merge them all together, + // then set rg to that + ReachGraph rgPossibleCaller = new ReachGraph(); + rgPossibleCaller.merge(rg); + + ReachGraph rgPossibleCallee = getPartial(mdPossible); + + if( rgPossibleCallee == null ) { + // if this method has never been analyzed just schedule it + // for analysis and skip over this call site for now + if( state.DISJOINTDVISITSTACKEESONTOP ) { + calleesToEnqueue.add(mdPossible); + } else { + enqueue(mdPossible); + } + + if( state.DISJOINTDEBUGSCHEDULING ) { + System.out.println(" callee hasn't been analyzed, scheduling: "+mdPossible); + } + + } else { + // calculate the method call transform + rgPossibleCaller.resolveMethodCall(fc, + fmPossible, + rgPossibleCallee, + callerNodeIDsCopiedToCallee, + writeDebugDOTs + ); + + if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { // if( !rgPossibleCallee.isAccessible( ReachGraph.tdReturn ) ) { - if( !accessible.isAccessible(fn, ReachGraph.tdReturn) ) { - rgPossibleCaller.makeInaccessible(fc.getReturnTemp() ); - } - } + if( !accessible.isAccessible(fn, ReachGraph.tdReturn) ) { + rgPossibleCaller.makeInaccessible(fc.getReturnTemp() ); + } + } - } + } - rgMergeOfPossibleCallers.merge(rgPossibleCaller); + rgMergeOfPossibleCallers.merge(rgPossibleCaller); } if( stopAfter ) { - System.out.println("$$$ Exiting after requested captures of call site. $$$"); - System.exit(0); + System.out.println("$$$ Exiting after requested captures of call site. $$$"); + System.exit(0); } @@ -1665,10 +1665,10 @@ public class DisjointAnalysis implements HeapAnalysis { //need to consider more FlatNode nextFN=fmCallee.getNext(0); if( nextFN instanceof FlatSESEEnterNode ) { - FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN; - if(!calleeSESE.getIsLeafSESE()) { - rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) ); - } + FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN; + if(!calleeSESE.getIsLeafSESE()) { + rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) ); + } } } break; @@ -1681,13 +1681,13 @@ public class DisjointAnalysis implements HeapAnalysis { // before transfer, do effects analysis support if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) { // if(!rg.isAccessible(rhs)){ - if(!accessible.isAccessible(fn,rhs)) { - rg.makeInaccessible(ReachGraph.tdReturn); - } + if(!accessible.isAccessible(fn,rhs)) { + rg.makeInaccessible(ReachGraph.tdReturn); + } } if( rhs != null && shouldAnalysisTrack(rhs.getType() ) ) { - rg.assignReturnEqualToTemp(rhs); + rg.assignReturnEqualToTemp(rhs); } setRetNodes.add(frn); @@ -1754,9 +1754,9 @@ public class DisjointAnalysis implements HeapAnalysis { String graphName; if( d instanceof TaskDescriptor ) { - graphName = "COMPLETEtask"+d; + graphName = "COMPLETEtask"+d; } else { - graphName = "COMPLETE"+d; + graphName = "COMPLETE"+d; } rg.writeGraph(graphName, @@ -1779,18 +1779,18 @@ public class DisjointAnalysis implements HeapAnalysis { Iterator fc2rgItr = IHMs.entrySet().iterator(); while( fc2rgItr.hasNext() ) { - Map.Entry me2 = (Map.Entry)fc2rgItr.next(); - FlatCall fc = (FlatCall) me2.getKey(); - ReachGraph rg = (ReachGraph) me2.getValue(); - - rg.writeGraph("IHMPARTFOR"+d+"FROM"+fc2enclosing.get(fc)+fc, - true, // write labels (variables) - true, // selectively hide intermediate temp vars - true, // hide reachability altogether - true, // prune unreachable heap regions - true, // hide subset reachability states - false, // hide predicates - true); // hide edge taints + Map.Entry me2 = (Map.Entry)fc2rgItr.next(); + FlatCall fc = (FlatCall) me2.getKey(); + ReachGraph rg = (ReachGraph) me2.getValue(); + + rg.writeGraph("IHMPARTFOR"+d+"FROM"+fc2enclosing.get(fc)+fc, + true, // write labels (variables) + true, // selectively hide intermediate temp vars + true, // hide reachability altogether + true, // prune unreachable heap regions + true, // hide subset reachability states + false, // hide predicates + true); // hide edge taints } } } @@ -1829,15 +1829,15 @@ public class DisjointAnalysis implements HeapAnalysis { // descriptor we've already written out if( writeAllIncrementalDOTs ) { if( !mapDescriptorToNumUpdates.containsKey(d) ) { - mapDescriptorToNumUpdates.put(d, new Integer(0) ); + mapDescriptorToNumUpdates.put(d, new Integer(0) ); } Integer n = mapDescriptorToNumUpdates.get(d); String graphName; if( d instanceof TaskDescriptor ) { - graphName = d+"COMPLETEtask"+String.format("%05d", n); + graphName = d+"COMPLETEtask"+String.format("%05d", n); } else { - graphName = d+"COMPLETE"+String.format("%05d", n); + graphName = d+"COMPLETE"+String.format("%05d", n); } rg.writeGraph(graphName, @@ -1872,9 +1872,9 @@ public class DisjointAnalysis implements HeapAnalysis { // the newest nodes are single objects for( int i = 0; i < allocationDepth; ++i ) { - Integer id = generateUniqueHeapRegionNodeID(); - as.setIthOldest(i, id); - mapHrnIdToAllocSite.put(id, as); + Integer id = generateUniqueHeapRegionNodeID(); + as.setIthOldest(i, id); + mapHrnIdToAllocSite.put(id, as); } // the oldest node is a summary node @@ -1982,7 +1982,7 @@ public class DisjointAnalysis implements HeapAnalysis { Descriptor d = itr.next(); if( !discovered.contains(d) ) { - dfsVisit(d, toSort, sorted, discovered); + dfsVisit(d, toSort, sorted, discovered); } } @@ -2010,31 +2010,31 @@ public class DisjointAnalysis implements HeapAnalysis { // the call graph is not aware that we have a fabricated // analysis entry that calls the program source's entry if( md == mdSourceEntry ) { - if( !discovered.contains(mdAnalysisEntry) ) { - addDependent(mdSourceEntry, // callee - mdAnalysisEntry // caller - ); - dfsVisit(mdAnalysisEntry, toSort, sorted, discovered); - } + if( !discovered.contains(mdAnalysisEntry) ) { + addDependent(mdSourceEntry, // callee + mdAnalysisEntry // caller + ); + dfsVisit(mdAnalysisEntry, toSort, sorted, discovered); + } } // otherwise call graph guides DFS Iterator itr = callGraph.getCallerSet(md).iterator(); while( itr.hasNext() ) { - Descriptor dCaller = (Descriptor) itr.next(); + Descriptor dCaller = (Descriptor) itr.next(); - // only consider callers in the original set to analyze - if( !toSort.contains(dCaller) ) { - continue; - } + // only consider callers in the original set to analyze + if( !toSort.contains(dCaller) ) { + continue; + } - if( !discovered.contains(dCaller) ) { - addDependent(md, // callee - dCaller // caller - ); + if( !discovered.contains(dCaller) ) { + addDependent(md, // callee + dCaller // caller + ); - dfsVisit(dCaller, toSort, sorted, discovered); - } + dfsVisit(dCaller, toSort, sorted, discovered); + } } } @@ -2050,13 +2050,13 @@ public class DisjointAnalysis implements HeapAnalysis { if( state.DISJOINTDVISITSTACK || state.DISJOINTDVISITSTACKEESONTOP ) { - descriptorsToVisitStack.add(d); + descriptorsToVisitStack.add(d); } else if( state.DISJOINTDVISITPQUE ) { - Integer priority = mapDescriptorToPriority.get(d); - descriptorsToVisitQ.add(new DescriptorQWrapper(priority, - d) - ); + Integer priority = mapDescriptorToPriority.get(d); + descriptorsToVisitQ.add(new DescriptorQWrapper(priority, + d) + ); } descriptorsToVisitSet.add(d); @@ -2170,11 +2170,11 @@ public class DisjointAnalysis implements HeapAnalysis { if(!typeDesc.isImmutable()) { ClassDescriptor classDesc = typeDesc.getClassDesc(); for (Iterator it = classDesc.getFields(); it.hasNext(); ) { - FieldDescriptor field = (FieldDescriptor) it.next(); - TypeDescriptor fieldType = field.getType(); - if (shouldAnalysisTrack(fieldType)) { - fieldSet.add(field); - } + FieldDescriptor field = (FieldDescriptor) it.next(); + TypeDescriptor fieldType = field.getType(); + if (shouldAnalysisTrack(fieldType)) { + fieldSet.add(field); + } } } return fieldSet; @@ -2192,59 +2192,59 @@ public class DisjointAnalysis implements HeapAnalysis { TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc); HeapRegionNode hrnSummary; if(!mapToExistingNode.containsKey(typeDesc)) { - AllocSite as; - if(i==dimCount) { - as = alloc; - } else { - as = createParameterAllocSite(rg, tempDesc, false); - } - // make a new reference to allocated node - hrnSummary = - rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one - false, // single object? - true, // summary? - false, // out-of-context? - as.getType(), // type - as, // allocation site - alpha, // inherent reach - alpha, // current reach - ExistPredSet.factory(rg.predTrue), // predicates - tempDesc.toString() // description - ); - rg.id2hrn.put(as.getSummary(),hrnSummary); - - mapToExistingNode.put(typeDesc, hrnSummary); + AllocSite as; + if(i==dimCount) { + as = alloc; + } else { + as = createParameterAllocSite(rg, tempDesc, false); + } + // make a new reference to allocated node + hrnSummary = + rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one + false, // single object? + true, // summary? + false, // out-of-context? + as.getType(), // type + as, // allocation site + alpha, // inherent reach + alpha, // current reach + ExistPredSet.factory(rg.predTrue), // predicates + tempDesc.toString() // description + ); + rg.id2hrn.put(as.getSummary(),hrnSummary); + + mapToExistingNode.put(typeDesc, hrnSummary); } else { - hrnSummary=mapToExistingNode.get(typeDesc); + hrnSummary=mapToExistingNode.get(typeDesc); } if(prevNode==null) { - // make a new reference between new summary node and source - RefEdge edgeToSummary = new RefEdge(srcHRN, // source - hrnSummary, // dest - typeDesc, // type - fd.getSymbol(), // field name - alpha, // beta - ExistPredSet.factory(rg.predTrue), // predicates - null - ); - - rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary); - prevNode=hrnSummary; - arrayEntryNode=hrnSummary; + // make a new reference between new summary node and source + RefEdge edgeToSummary = new RefEdge(srcHRN, // source + hrnSummary, // dest + typeDesc, // type + fd.getSymbol(), // field name + alpha, // beta + ExistPredSet.factory(rg.predTrue), // predicates + null + ); + + rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary); + prevNode=hrnSummary; + arrayEntryNode=hrnSummary; } else { - // make a new reference between summary nodes of array - RefEdge edgeToSummary = new RefEdge(prevNode, // source - hrnSummary, // dest - typeDesc, // type - arrayElementFieldName, // field name - alpha, // beta - ExistPredSet.factory(rg.predTrue), // predicates - null - ); + // make a new reference between summary nodes of array + RefEdge edgeToSummary = new RefEdge(prevNode, // source + hrnSummary, // dest + typeDesc, // type + arrayElementFieldName, // field name + alpha, // beta + ExistPredSet.factory(rg.predTrue), // predicates + null + ); - rg.addRefEdge(prevNode, hrnSummary, edgeToSummary); - prevNode=hrnSummary; + rg.addRefEdge(prevNode, hrnSummary, edgeToSummary); + prevNode=hrnSummary; } } @@ -2255,47 +2255,47 @@ public class DisjointAnalysis implements HeapAnalysis { TypeDescriptor typeDesc=type.dereference(); typeDesc.setArrayCount(0); if(!mapToExistingNode.containsKey(typeDesc)) { - TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc); - AllocSite as = createParameterAllocSite(rg, tempDesc, false); - // make a new reference to allocated node - HeapRegionNode hrnSummary = - rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one - false, // single object? - true, // summary? - false, // out-of-context? - typeDesc, // type - as, // allocation site - alpha, // inherent reach - alpha, // current reach - ExistPredSet.factory(rg.predTrue), // predicates - tempDesc.toString() // description - ); - rg.id2hrn.put(as.getSummary(),hrnSummary); - mapToExistingNode.put(typeDesc, hrnSummary); - RefEdge edgeToSummary = new RefEdge(prevNode, // source - hrnSummary, // dest - typeDesc, // type - arrayElementFieldName, // field name - alpha, // beta - ExistPredSet.factory(rg.predTrue), // predicates - null - ); - rg.addRefEdge(prevNode, hrnSummary, edgeToSummary); - prevNode=hrnSummary; + TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc); + AllocSite as = createParameterAllocSite(rg, tempDesc, false); + // make a new reference to allocated node + HeapRegionNode hrnSummary = + rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one + false, // single object? + true, // summary? + false, // out-of-context? + typeDesc, // type + as, // allocation site + alpha, // inherent reach + alpha, // current reach + ExistPredSet.factory(rg.predTrue), // predicates + tempDesc.toString() // description + ); + rg.id2hrn.put(as.getSummary(),hrnSummary); + mapToExistingNode.put(typeDesc, hrnSummary); + RefEdge edgeToSummary = new RefEdge(prevNode, // source + hrnSummary, // dest + typeDesc, // type + arrayElementFieldName, // field name + alpha, // beta + ExistPredSet.factory(rg.predTrue), // predicates + null + ); + rg.addRefEdge(prevNode, hrnSummary, edgeToSummary); + prevNode=hrnSummary; } else { - HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc); - if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null) { - RefEdge edgeToSummary = new RefEdge(prevNode, // source - hrnSummary, // dest - typeDesc, // type - arrayElementFieldName, // field name - alpha, // beta - ExistPredSet.factory(rg.predTrue), // predicates - null - ); - rg.addRefEdge(prevNode, hrnSummary, edgeToSummary); - } - prevNode=hrnSummary; + HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc); + if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null) { + RefEdge edgeToSummary = new RefEdge(prevNode, // source + hrnSummary, // dest + typeDesc, // type + arrayElementFieldName, // field name + alpha, // beta + ExistPredSet.factory(rg.predTrue), // predicates + null + ); + rg.addRefEdge(prevNode, hrnSummary, edgeToSummary); + } + prevNode=hrnSummary; } } @@ -2341,118 +2341,118 @@ public class DisjointAnalysis implements HeapAnalysis { // set-up a work set for class field ClassDescriptor classDesc = paramTypeDesc.getClassDesc(); for (Iterator it = classDesc.getFields(); it.hasNext(); ) { - FieldDescriptor fd = (FieldDescriptor) it.next(); - TypeDescriptor fieldType = fd.getType(); - if (shouldAnalysisTrack(fieldType)) { - HashMap newMap = new HashMap(); - newMap.put(hrnNewest, fd); - workSet.add(newMap); - } + FieldDescriptor fd = (FieldDescriptor) it.next(); + TypeDescriptor fieldType = fd.getType(); + if (shouldAnalysisTrack(fieldType)) { + HashMap newMap = new HashMap(); + newMap.put(hrnNewest, fd); + workSet.add(newMap); + } } int uniqueIdentifier = 0; while (!workSet.isEmpty()) { - HashMap map = workSet - .iterator().next(); - workSet.remove(map); - - Set key = map.keySet(); - HeapRegionNode srcHRN = key.iterator().next(); - FieldDescriptor fd = map.get(srcHRN); - TypeDescriptor type = fd.getType(); - String doneSetIdentifier = srcHRN.getIDString() + "_" + fd; - - if (!doneSet.contains(doneSetIdentifier)) { - doneSet.add(doneSetIdentifier); - if (!mapTypeToExistingSummaryNode.containsKey(type)) { - // create new summary Node - TempDescriptor td = new TempDescriptor("temp" - + uniqueIdentifier, type); - - AllocSite allocSite; - if(type.equals(paramTypeDesc)) { - //corresponding allocsite has already been created for a parameter variable. - allocSite=as; - } else { - allocSite = createParameterAllocSite(rg, td, false); - } - String strDesc = allocSite.toStringForDOT() - + "\\nsummary"; - TypeDescriptor allocType=allocSite.getType(); - - HeapRegionNode hrnSummary; - if(allocType.isArray() && allocType.getArrayCount()>0) { - hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha()); - } else { - hrnSummary = - rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one - false, // single object? - true, // summary? - false, // out-of-context? - allocSite.getType(), // type - allocSite, // allocation site - hrnNewest.getAlpha(), // inherent reach - hrnNewest.getAlpha(), // current reach - ExistPredSet.factory(rg.predTrue), // predicates - strDesc // description - ); - rg.id2hrn.put(allocSite.getSummary(),hrnSummary); - - // make a new reference to summary node - RefEdge edgeToSummary = new RefEdge(srcHRN, // source - hrnSummary, // dest - type, // type - fd.getSymbol(), // field name - hrnNewest.getAlpha(), // beta - ExistPredSet.factory(rg.predTrue), // predicates - null - ); - - rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary); - } - uniqueIdentifier++; - - mapTypeToExistingSummaryNode.put(type, hrnSummary); - - // set-up a work set for fields of the class - Set fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type); - for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator - .hasNext(); ) { - FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator - .next(); - HeapRegionNode newDstHRN; - if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)) { - //related heap region node is already exsited. - newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary); - } else { - newDstHRN=hrnSummary; - } - doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor; - if(!doneSet.contains(doneSetIdentifier)) { - // add new work item - HashMap newMap = - new HashMap(); - newMap.put(newDstHRN, fieldDescriptor); - workSet.add(newMap); - } - } - - } else { - // if there exists corresponding summary node - HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type); - - RefEdge edgeToSummary = new RefEdge(srcHRN, // source - hrnDst, // dest - fd.getType(), // type - fd.getSymbol(), // field name - srcHRN.getAlpha(), // beta - ExistPredSet.factory(rg.predTrue), // predicates - null - ); - rg.addRefEdge(srcHRN, hrnDst, edgeToSummary); - - } - } + HashMap map = workSet + .iterator().next(); + workSet.remove(map); + + Set key = map.keySet(); + HeapRegionNode srcHRN = key.iterator().next(); + FieldDescriptor fd = map.get(srcHRN); + TypeDescriptor type = fd.getType(); + String doneSetIdentifier = srcHRN.getIDString() + "_" + fd; + + if (!doneSet.contains(doneSetIdentifier)) { + doneSet.add(doneSetIdentifier); + if (!mapTypeToExistingSummaryNode.containsKey(type)) { + // create new summary Node + TempDescriptor td = new TempDescriptor("temp" + + uniqueIdentifier, type); + + AllocSite allocSite; + if(type.equals(paramTypeDesc)) { + //corresponding allocsite has already been created for a parameter variable. + allocSite=as; + } else { + allocSite = createParameterAllocSite(rg, td, false); + } + String strDesc = allocSite.toStringForDOT() + + "\\nsummary"; + TypeDescriptor allocType=allocSite.getType(); + + HeapRegionNode hrnSummary; + if(allocType.isArray() && allocType.getArrayCount()>0) { + hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha()); + } else { + hrnSummary = + rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one + false, // single object? + true, // summary? + false, // out-of-context? + allocSite.getType(), // type + allocSite, // allocation site + hrnNewest.getAlpha(), // inherent reach + hrnNewest.getAlpha(), // current reach + ExistPredSet.factory(rg.predTrue), // predicates + strDesc // description + ); + rg.id2hrn.put(allocSite.getSummary(),hrnSummary); + + // make a new reference to summary node + RefEdge edgeToSummary = new RefEdge(srcHRN, // source + hrnSummary, // dest + type, // type + fd.getSymbol(), // field name + hrnNewest.getAlpha(), // beta + ExistPredSet.factory(rg.predTrue), // predicates + null + ); + + rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary); + } + uniqueIdentifier++; + + mapTypeToExistingSummaryNode.put(type, hrnSummary); + + // set-up a work set for fields of the class + Set fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type); + for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator + .hasNext(); ) { + FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator + .next(); + HeapRegionNode newDstHRN; + if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)) { + //related heap region node is already exsited. + newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary); + } else { + newDstHRN=hrnSummary; + } + doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor; + if(!doneSet.contains(doneSetIdentifier)) { + // add new work item + HashMap newMap = + new HashMap(); + newMap.put(newDstHRN, fieldDescriptor); + workSet.add(newMap); + } + } + + } else { + // if there exists corresponding summary node + HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type); + + RefEdge edgeToSummary = new RefEdge(srcHRN, // source + hrnDst, // dest + fd.getType(), // type + fd.getSymbol(), // field name + srcHRN.getAlpha(), // beta + ExistPredSet.factory(rg.predTrue), // predicates + null + ); + rg.addRefEdge(srcHRN, hrnDst, edgeToSummary); + + } + } } } @@ -2493,17 +2493,17 @@ public class DisjointAnalysis implements HeapAnalysis { FlatNode n = toVisit.iterator().next(); if( n instanceof FlatNew ) { - s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) ); + s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) ); } toVisit.remove(n); visited.add(n); for( int i = 0; i < pm.numNext(n); ++i ) { - FlatNode child = pm.getNext(n, i); - if( !visited.contains(child) ) { - toVisit.add(child); - } + FlatNode child = pm.getNext(n, i); + if( !visited.contains(child) ) { + toVisit.add(child); + } } } @@ -2526,24 +2526,24 @@ public class DisjointAnalysis implements HeapAnalysis { HashSet asSet = getAllocationSiteSet(d); Iterator asItr = asSet.iterator(); while (asItr.hasNext()) { - AllocSite as = (AllocSite) asItr.next(); - if (as.getDisjointAnalysisId() != null) { - out.add(as); - } + AllocSite as = (AllocSite) asItr.next(); + if (as.getDisjointAnalysisId() != null) { + out.add(as); + } } // enqueue callees of this method to be searched for // allocation sites also Set callees = callGraph.getCalleeSet(d); if (callees != null) { - Iterator methItr = callees.iterator(); - while (methItr.hasNext()) { - MethodDescriptor md = (MethodDescriptor) methItr.next(); + Iterator methItr = callees.iterator(); + while (methItr.hasNext()) { + MethodDescriptor md = (MethodDescriptor) methItr.next(); - if (!visited.contains(md)) { - toVisit.add(md); - } - } + if (!visited.contains(md)) { + toVisit.add(md); + } + } } } @@ -2569,28 +2569,28 @@ public class DisjointAnalysis implements HeapAnalysis { HashSet asSet = getAllocationSiteSet(d); Iterator asItr = asSet.iterator(); while( asItr.hasNext() ) { - AllocSite as = (AllocSite) asItr.next(); - TypeDescriptor typed = as.getType(); - if( typed != null ) { - ClassDescriptor cd = typed.getClassDesc(); - if( cd != null && cd.hasFlags() ) { - asSetTotal.add(as); - } - } + AllocSite as = (AllocSite) asItr.next(); + TypeDescriptor typed = as.getType(); + if( typed != null ) { + ClassDescriptor cd = typed.getClassDesc(); + if( cd != null && cd.hasFlags() ) { + asSetTotal.add(as); + } + } } // enqueue callees of this method to be searched for // allocation sites also Set callees = callGraph.getCalleeSet(d); if( callees != null ) { - Iterator methItr = callees.iterator(); - while( methItr.hasNext() ) { - MethodDescriptor md = (MethodDescriptor) methItr.next(); + Iterator methItr = callees.iterator(); + while( methItr.hasNext() ) { + MethodDescriptor md = (MethodDescriptor) methItr.next(); - if( !visited.contains(md) ) { - toVisit.add(md); - } - } + if( !visited.contains(md) ) { + toVisit.add(md); + } + } } } @@ -2639,16 +2639,16 @@ public class DisjointAnalysis implements HeapAnalysis { " @@@"); String graphName; if( in ) { - graphName = String.format("snap%03d_%04din", - snapVisitCounter, - snapNodeCounter); + graphName = String.format("snap%03d_%04din", + snapVisitCounter, + snapNodeCounter); } else { - graphName = String.format("snap%03d_%04dout", - snapVisitCounter, - snapNodeCounter); + graphName = String.format("snap%03d_%04dout", + snapVisitCounter, + snapNodeCounter); } if( fn != null ) { - graphName = graphName + fn; + graphName = graphName + fn; } rg.writeGraph(graphName, true, // write labels (variables) diff --git a/Robust/src/Analysis/Disjoint/EffectsAnalysis.java b/Robust/src/Analysis/Disjoint/EffectsAnalysis.java index 0825957a..fbf21ea6 100644 --- a/Robust/src/Analysis/Disjoint/EffectsAnalysis.java +++ b/Robust/src/Analysis/Disjoint/EffectsAnalysis.java @@ -83,12 +83,12 @@ public class EffectsAnalysis { Hashtable> te = sese2te.get(sese); if( te == null ) { - te = new Hashtable>(); + te = new Hashtable>(); } Set effects = te.get(tNoPreds); if (effects == null) { - effects = new HashSet(); + effects = new HashSet(); } effects.add(e); te.put(tNoPreds, effects); @@ -101,12 +101,12 @@ public class EffectsAnalysis { Hashtable> te = stallSite2te.get(stallSite); if( te == null ) { - te = new Hashtable>(); + te = new Hashtable>(); } Set effects = te.get(tNoPreds); if (effects == null) { - effects = new HashSet(); + effects = new HashSet(); } effects.add(e); te.put(tNoPreds, effects); @@ -139,8 +139,8 @@ public class EffectsAnalysis { Effect effect = new Effect(affectedAlloc, Effect.read, fld); for (Iterator taintSetIter = taintSet.iterator(); taintSetIter.hasNext(); ) { - Taint taint = taintSetIter.next(); - add(taint, effect, currentProgramPoint); + Taint taint = taintSetIter.next(); + add(taint, effect, currentProgramPoint); } } } @@ -152,9 +152,9 @@ public class EffectsAnalysis { Effect effect = new Effect(affectedAlloc, Effect.read, fld); if (taintSet!=null) - for (Taint taint : taintSet.getTaints()) { - add(taint, effect, currentProgramPoint); - } + for (Taint taint : taintSet.getTaints()) { + add(taint, effect, currentProgramPoint); + } } } @@ -173,16 +173,16 @@ public class EffectsAnalysis { Effect effectSU = null; if (strongUpdate) { - effectSU = new Effect(affectedAlloc, Effect.strongupdate, fld); + effectSU = new Effect(affectedAlloc, Effect.strongupdate, fld); } for (Iterator taintSetIter = taintSet.iterator(); taintSetIter.hasNext(); ) { - Taint taint = taintSetIter.next(); - add(taint, effect, currentProgramPoint); + Taint taint = taintSetIter.next(); + add(taint, effect, currentProgramPoint); - if (strongUpdate) { - add(taint, effectSU, currentProgramPoint); - } + if (strongUpdate) { + add(taint, effectSU, currentProgramPoint); + } } } } @@ -194,9 +194,9 @@ public class EffectsAnalysis { Alloc affectedAlloc = edge.getDst().getAllocSite(); Effect effect = new Effect(affectedAlloc, Effect.write, fld); if (taintSet!=null) - for (Taint taint : taintSet.getTaints()) { - add(taint, effect, currentProgramPoint); - } + for (Taint taint : taintSet.getTaints()) { + add(taint, effect, currentProgramPoint); + } } } @@ -213,16 +213,16 @@ public class EffectsAnalysis { Iterator meItr = taint2effects.entrySet().iterator(); while( meItr.hasNext() ) { - Map.Entry me = (Map.Entry)meItr.next(); - Taint taint = (Taint) me.getKey(); - Set effects = (Set)me.getValue(); + Map.Entry me = (Map.Entry)meItr.next(); + Taint taint = (Taint) me.getKey(); + Set effects = (Set)me.getValue(); - Iterator eItr = effects.iterator(); - while( eItr.hasNext() ) { - Effect e = eItr.next(); + Iterator eItr = effects.iterator(); + while( eItr.hasNext() ) { + Effect e = eItr.next(); - bw.write(taint+"-->"+e+"\n"); - } + bw.write(taint+"-->"+e+"\n"); + } } bw.close(); diff --git a/Robust/src/Analysis/Disjoint/ExistPred.java b/Robust/src/Analysis/Disjoint/ExistPred.java index a1c31319..fc34a97c 100644 --- a/Robust/src/Analysis/Disjoint/ExistPred.java +++ b/Robust/src/Analysis/Disjoint/ExistPred.java @@ -243,30 +243,30 @@ public class ExistPred extends Canonical { // first find node HeapRegionNode hrn = rg.id2hrn.get(n_hrnID); if( hrn == null ) { - return null; + return null; } if( !calleeReachableNodes.contains(n_hrnID) ) { - return null; + return null; } // when the state is null we're done! if( ne_state == null ) { - return hrn.getPreds(); + return hrn.getPreds(); } else { - // otherwise look for state too + // otherwise look for state too - // TODO: contains OR containsSuperSet OR containsWithZeroes?? - ReachState stateCaller = hrn.getAlpha().containsIgnorePreds(ne_state); + // TODO: contains OR containsSuperSet OR containsWithZeroes?? + ReachState stateCaller = hrn.getAlpha().containsIgnorePreds(ne_state); - if( stateCaller == null ) { - return null; + if( stateCaller == null ) { + return null; - } else { - // it was here, return the predicates on the state!! - return stateCaller.getPreds(); - } + } else { + // it was here, return the predicates on the state!! + return stateCaller.getPreds(); + } } // unreachable program point! @@ -278,61 +278,61 @@ public class ExistPred extends Canonical { // reference edge exists VariableNode vnSrc = null; if( e_tdSrc != null ) { - vnSrc = rg.td2vn.get(e_tdSrc); + vnSrc = rg.td2vn.get(e_tdSrc); } HeapRegionNode hrnSrc = null; if( e_hrnSrcID != null ) { - hrnSrc = rg.id2hrn.get(e_hrnSrcID); + hrnSrc = rg.id2hrn.get(e_hrnSrcID); } assert(vnSrc == null) || (hrnSrc == null); // the source is not present in graph if( vnSrc == null && hrnSrc == null ) { - return null; + return null; } RefSrcNode rsn; if( vnSrc != null ) { - rsn = vnSrc; - assert e_srcOutCalleeContext; - assert !e_srcOutCallerContext; + rsn = vnSrc; + assert e_srcOutCalleeContext; + assert !e_srcOutCallerContext; } else { - assert !(e_srcOutCalleeContext && e_srcOutCallerContext); + assert !(e_srcOutCalleeContext && e_srcOutCallerContext); - if( e_srcOutCalleeContext ) { - if( calleeReachableNodes.contains(e_hrnSrcID) ) { - return null; - } + if( e_srcOutCalleeContext ) { + if( calleeReachableNodes.contains(e_hrnSrcID) ) { + return null; + } - } else if( e_srcOutCallerContext ) { - if( !hrnSrc.isOutOfContext() ) { - return null; - } + } else if( e_srcOutCallerContext ) { + if( !hrnSrc.isOutOfContext() ) { + return null; + } - } else { + } else { - if( !calleeReachableNodes.contains(e_hrnSrcID) ) { - return null; - } - if( hrnSrc.isOutOfContext() ) { - return null; - } + if( !calleeReachableNodes.contains(e_hrnSrcID) ) { + return null; + } + if( hrnSrc.isOutOfContext() ) { + return null; + } - } + } - rsn = hrnSrc; + rsn = hrnSrc; } // is the destination present? HeapRegionNode hrnDst = rg.id2hrn.get(e_hrnDstID); if( hrnDst == null ) { - return null; + return null; } if( !calleeReachableNodes.contains(e_hrnDstID) ) { - return null; + return null; } // is there an edge between them with the given @@ -342,40 +342,40 @@ public class ExistPred extends Canonical { e_type, e_field); if( edge == null ) { - return null; + return null; } // when the state and taint are null we're done! if( ne_state == null && e_taint == null ) { - return edge.getPreds(); + return edge.getPreds(); } else if( ne_state != null ) { - // otherwise look for state too + // otherwise look for state too - // TODO: contains OR containsSuperSet OR containsWithZeroes?? - ReachState stateCaller = edge.getBeta().containsIgnorePreds(ne_state); + // TODO: contains OR containsSuperSet OR containsWithZeroes?? + ReachState stateCaller = edge.getBeta().containsIgnorePreds(ne_state); - if( stateCaller == null ) { - return null; + if( stateCaller == null ) { + return null; - } else { - // it was here, return the predicates on the state!! - return stateCaller.getPreds(); - } + } else { + // it was here, return the predicates on the state!! + return stateCaller.getPreds(); + } } else { - // otherwise look for taint + // otherwise look for taint - Taint tCaller = edge.getTaints().containsIgnorePreds(e_taint); + Taint tCaller = edge.getTaints().containsIgnorePreds(e_taint); - if( tCaller == null ) { - return null; + if( tCaller == null ) { + return null; - } else { - // it was here, return the predicates on the taint!! - return tCaller.getPreds(); - } + } else { + // it was here, return the predicates on the taint!! + return tCaller.getPreds(); + } } // unreachable program point! @@ -403,7 +403,7 @@ public class ExistPred extends Canonical { if( ne_state == null ) { if( pred.ne_state != null ) { - return false; + return false; } } else if( !ne_state.equals(pred.ne_state) ) { return false; @@ -411,7 +411,7 @@ public class ExistPred extends Canonical { if( n_hrnID == null ) { if( pred.n_hrnID != null ) { - return false; + return false; } } else if( !n_hrnID.equals(pred.n_hrnID) ) { return false; @@ -419,7 +419,7 @@ public class ExistPred extends Canonical { if( e_tdSrc == null ) { if( pred.e_tdSrc != null ) { - return false; + return false; } } else if( !e_tdSrc.equals(pred.e_tdSrc) ) { return false; @@ -427,23 +427,23 @@ public class ExistPred extends Canonical { if( e_hrnSrcID == null ) { if( pred.e_hrnSrcID != null ) { - return false; + return false; } } else { if( !e_hrnSrcID.equals(pred.e_hrnSrcID) ) { - return false; + return false; } if( e_srcOutCalleeContext != pred.e_srcOutCalleeContext ) { - return false; + return false; } if( e_srcOutCallerContext != pred.e_srcOutCallerContext ) { - return false; + return false; } } if( e_hrnDstID == null ) { if( pred.e_hrnDstID != null ) { - return false; + return false; } } else if( !e_hrnDstID.equals(pred.e_hrnDstID) ) { return false; @@ -451,7 +451,7 @@ public class ExistPred extends Canonical { if( e_type == null ) { if( pred.e_type != null ) { - return false; + return false; } } else if( !e_type.equals(pred.e_type) ) { return false; @@ -459,7 +459,7 @@ public class ExistPred extends Canonical { if( e_field == null ) { if( pred.e_field != null ) { - return false; + return false; } } else if( !e_field.equals(pred.e_field) ) { return false; @@ -467,7 +467,7 @@ public class ExistPred extends Canonical { if( e_taint == null ) { if( pred.e_taint != null ) { - return false; + return false; } } else if( !e_taint.equals(pred.e_taint) ) { return false; @@ -486,7 +486,7 @@ public class ExistPred extends Canonical { int hash = n_hrnID.intValue()*17; if( ne_state != null ) { - hash ^= ne_state.hashCode(); + hash ^= ne_state.hashCode(); } return hash; @@ -498,29 +498,29 @@ public class ExistPred extends Canonical { hash += e_type.hashCode()*17; if( e_field != null ) { - hash += e_field.hashCode()*7; + hash += e_field.hashCode()*7; } if( e_tdSrc != null ) { - hash ^= e_tdSrc.hashCode()*11; + hash ^= e_tdSrc.hashCode()*11; } else { - hash ^= e_hrnSrcID.hashCode()*11; - if( e_srcOutCalleeContext ) { - hash ^= 0xf1aeb; - } - if( e_srcOutCallerContext ) { - hash ^= 0x875d; - } + hash ^= e_hrnSrcID.hashCode()*11; + if( e_srcOutCalleeContext ) { + hash ^= 0xf1aeb; + } + if( e_srcOutCallerContext ) { + hash ^= 0x875d; + } } hash += e_hrnDstID.hashCode(); if( ne_state != null ) { - hash ^= ne_state.hashCode(); + hash ^= ne_state.hashCode(); } if( e_taint != null ) { - hash ^= e_taint.hashCode(); + hash ^= e_taint.hashCode(); } return hash; @@ -538,7 +538,7 @@ public class ExistPred extends Canonical { if( predType == TYPE_NODE ) { String s = n_hrnID.toString(); if( ne_state != null ) { - s += "w"+ne_state; + s += "w"+ne_state; } return s; } @@ -547,27 +547,27 @@ public class ExistPred extends Canonical { String s = "("; if( e_tdSrc != null ) { - s += e_tdSrc.toString(); + s += e_tdSrc.toString(); } else { - s += e_hrnSrcID.toString(); + s += e_hrnSrcID.toString(); } if( e_srcOutCalleeContext ) { - s += "(ooCLEEc)"; + s += "(ooCLEEc)"; } if( e_srcOutCallerContext ) { - s += "(ooCLERc)"; + s += "(ooCLERc)"; } s += "-->"+e_hrnDstID+")"; if( ne_state != null ) { - s += "w"+ne_state; + s += "w"+ne_state; } if( e_taint != null ) { - s += "w"+e_taint; + s += "w"+e_taint; } return s; diff --git a/Robust/src/Analysis/Disjoint/ExistPredSet.java b/Robust/src/Analysis/Disjoint/ExistPredSet.java index 28d6d574..d2fa2865 100644 --- a/Robust/src/Analysis/Disjoint/ExistPredSet.java +++ b/Robust/src/Analysis/Disjoint/ExistPredSet.java @@ -71,12 +71,12 @@ public class ExistPredSet extends Canonical { calleeReachableNodes); if( predsFromSatisfier != null ) { - if( predsOut == null ) { - predsOut = predsFromSatisfier; - } else { - predsOut = Canonical.join(predsOut, - predsFromSatisfier); - } + if( predsOut == null ) { + predsOut = predsFromSatisfier; + } else { + predsOut = Canonical.join(predsOut, + predsFromSatisfier); + } } } @@ -117,7 +117,7 @@ public class ExistPredSet extends Canonical { ExistPred pred = predItr.next(); s += pred.toString(); if( predItr.hasNext() ) { - s += " ||\\n"; + s += " ||\\n"; } } s += "]"; @@ -132,7 +132,7 @@ public class ExistPredSet extends Canonical { ExistPred pred = predItr.next(); s += pred.toString(); if( predItr.hasNext() ) { - s += " || "; + s += " || "; } } s += "]"; diff --git a/Robust/src/Analysis/Disjoint/HeapRegionNode.java b/Robust/src/Analysis/Disjoint/HeapRegionNode.java index b9603985..ed7e101f 100644 --- a/Robust/src/Analysis/Disjoint/HeapRegionNode.java +++ b/Robust/src/Analysis/Disjoint/HeapRegionNode.java @@ -197,7 +197,7 @@ public class HeapRegionNode extends RefSrcNode { edge.typeEquals(type) && edge.fieldEquals(field) ) { - return edge; + return edge; } } @@ -262,11 +262,11 @@ public class HeapRegionNode extends RefSrcNode { Iterator rtItr = state.iterator(); while( rtItr.hasNext() ) { - ReachTuple rt = rtItr.next(); + ReachTuple rt = rtItr.next(); - if( !rt.isOutOfContext() ) { - return false; - } + if( !rt.isOutOfContext() ) { + return false; + } } } diff --git a/Robust/src/Analysis/Disjoint/PointerMethod.java b/Robust/src/Analysis/Disjoint/PointerMethod.java index 88f23b99..501ecdfe 100644 --- a/Robust/src/Analysis/Disjoint/PointerMethod.java +++ b/Robust/src/Analysis/Disjoint/PointerMethod.java @@ -25,37 +25,37 @@ public class PointerMethod { toprocess.remove(fn); HashSet myset=new HashSet(); if (!analysisCares(fn)) { - for(int i=0; i it=map.keySet().iterator(); it.hasNext(); ) { FlatNode fn=it.next(); if (analysisCares(fn)) { - HashSet myset=new HashSet(); - for(int i=0; i it2=myset.iterator(); it2.hasNext(); ) { - FlatNode fnprev=it2.next(); - if (!nextmap.containsKey(fnprev)) - nextmap.put(fnprev, new Vector()); - nextmap.get(fnprev).add(fn); - prevmap.get(fn).add(fnprev); - } + HashSet myset=new HashSet(); + for(int i=0; i it2=myset.iterator(); it2.hasNext(); ) { + FlatNode fnprev=it2.next(); + if (!nextmap.containsKey(fnprev)) + nextmap.put(fnprev, new Vector()); + nextmap.get(fnprev).add(fn); + prevmap.get(fn).add(fnprev); + } } } } diff --git a/Robust/src/Analysis/Disjoint/ProcessStateMachines.java b/Robust/src/Analysis/Disjoint/ProcessStateMachines.java index 76ef30c2..4c0ef14e 100644 --- a/Robust/src/Analysis/Disjoint/ProcessStateMachines.java +++ b/Robust/src/Analysis/Disjoint/ProcessStateMachines.java @@ -41,27 +41,27 @@ public class ProcessStateMachines { mergeAgain=false; HashMap, Set> revMap=buildReverse(backMap); for(Map.Entry, Set> entry : revMap.entrySet()) { - if (entry.getValue().size()>1) { - SMFEState first=null; - for(SMFEState state : entry.getValue()) { - if (removedStates.contains(state)) - continue; - if (first==null) { - first=state; - } else { - mergeAgain=true; - System.out.println("MERGING:"+first+" and "+state); - //Make sure we don't merge the initial state someplace else - if (state==sm.initialState) { - state=first; - first=sm.initialState; - } - mergeTwoStates(first, state, backMap); - removedStates.add(state); - sm.fn2state.remove(state.whereDefined); - } - } - } + if (entry.getValue().size()>1) { + SMFEState first=null; + for(SMFEState state : entry.getValue()) { + if (removedStates.contains(state)) + continue; + if (first==null) { + first=state; + } else { + mergeAgain=true; + System.out.println("MERGING:"+first+" and "+state); + //Make sure we don't merge the initial state someplace else + if (state==sm.initialState) { + state=first; + first=sm.initialState; + } + mergeTwoStates(first, state, backMap); + removedStates.add(state); + sm.fn2state.remove(state.whereDefined); + } + } + } } } while(mergeAgain); } @@ -72,9 +72,9 @@ public class ProcessStateMachines { for(Map.Entry>>entry : backMap.entrySet()) { SMFEState state=entry.getKey(); for(Pair pair : entry.getValue()) { - if (!revMap.containsKey(pair)) - revMap.put(pair, new HashSet()); - revMap.get(pair).add(state); + if (!revMap.containsKey(pair)) + revMap.put(pair, new HashSet()); + revMap.get(pair).add(state); } } return revMap; @@ -93,36 +93,36 @@ public class ProcessStateMachines { Effect e=entry.getKey(); Set states=entry.getValue(); if (state1.e2states.containsKey(e)) { - for(SMFEState statetoadd : states) { - if (!state1.e2states.get(e).add(statetoadd)) { - //already added...reduce reference count - statetoadd.refCount--; - } - } + for(SMFEState statetoadd : states) { + if (!state1.e2states.get(e).add(statetoadd)) { + //already added...reduce reference count + statetoadd.refCount--; + } + } } else { - state1.e2states.put(e, states); + state1.e2states.put(e, states); } Set states1=state1.e2states.get(e); //move now-self edges if (states1.contains(state2)) { - states1.remove(state2); - states1.add(state1); + states1.remove(state2); + states1.add(state1); } //fix up the backmap of the edges we point to for(SMFEState st : states1) { - HashSet> toRemove=new HashSet>(); - HashSet> toAdd=new HashSet>(); - for(Pair backpair : backMap.get(st)) { - if (backpair.getFirst()==state2) { - Pair newpair=new Pair(state1, backpair.getSecond()); - toRemove.add(backpair); - toAdd.add(newpair); - } - } - backMap.get(st).removeAll(toRemove); - backMap.get(st).addAll(toAdd); + HashSet> toRemove=new HashSet>(); + HashSet> toAdd=new HashSet>(); + for(Pair backpair : backMap.get(st)) { + if (backpair.getFirst()==state2) { + Pair newpair=new Pair(state1, backpair.getSecond()); + toRemove.add(backpair); + toAdd.add(newpair); + } + } + backMap.get(st).removeAll(toRemove); + backMap.get(st).addAll(toAdd); } } @@ -130,14 +130,14 @@ public class ProcessStateMachines { for(Pair fromStatePair : backMap.get(state2)) { SMFEState fromState=fromStatePair.getFirst(); for(Map.Entry> fromEntry : fromState.e2states.entrySet()) { - Effect e=fromEntry.getKey(); - Set states=fromEntry.getValue(); - if (states.contains(state2)) { - states.remove(state2); - if(states.add(state1) && !fromState.equals(state2)) { - state1.refCount++; - } - } + Effect e=fromEntry.getKey(); + Set states=fromEntry.getValue(); + if (states.contains(state2)) { + states.remove(state2); + if(states.add(state1) && !fromState.equals(state2)) { + state1.refCount++; + } + } } } //Clear out unreachable state's backmap @@ -158,15 +158,15 @@ public class ProcessStateMachines { FlatNode fn=fnit.next(); SMFEState state=sm.fn2state.get(fn); for(Iterator efit=state.effects.iterator(); efit.hasNext(); ) { - Effect e=efit.next(); - //Is it a conflicting effecting - if (state.getConflicts().contains(e)) - continue; - //Does it still have transitions - if (state.e2states.containsKey(e)) - continue; - //If no to both, remove it - efit.remove(); + Effect e=efit.next(); + //Is it a conflicting effecting + if (state.getConflicts().contains(e)) + continue; + //Does it still have transitions + if (state.e2states.containsKey(e)) + continue; + //If no to both, remove it + efit.remove(); } } } @@ -177,19 +177,19 @@ public class ProcessStateMachines { FlatNode fn=fnit.next(); SMFEState state=sm.fn2state.get(fn); if (canReachConflicts.contains(state)) { - for(Iterator efit=state.e2states.keySet().iterator(); efit.hasNext(); ) { - Effect e=efit.next(); - Set stateset=state.e2states.get(e); - for(Iterator stit=stateset.iterator(); stit.hasNext(); ) { - SMFEState tostate=stit.next(); - if(!canReachConflicts.contains(tostate)) - stit.remove(); - } - if (stateset.isEmpty()) - efit.remove(); - } + for(Iterator efit=state.e2states.keySet().iterator(); efit.hasNext(); ) { + Effect e=efit.next(); + Set stateset=state.e2states.get(e); + for(Iterator stit=stateset.iterator(); stit.hasNext(); ) { + SMFEState tostate=stit.next(); + if(!canReachConflicts.contains(tostate)) + stit.remove(); + } + if (stateset.isEmpty()) + efit.remove(); + } } else { - fnit.remove(); + fnit.remove(); } } } @@ -206,17 +206,17 @@ public class ProcessStateMachines { while(!toprocess.isEmpty()) { SMFEState state=toprocess.pop(); if (!state.getConflicts().isEmpty()&&conflictStates!=null) { - conflictStates.add(state); + conflictStates.add(state); } for(Effect e : state.getEffectsAllowed()) { - for(SMFEState stateout : state.transitionsTo(e)) { - if (!backMap.containsKey(stateout)) { - toprocess.add(stateout); - backMap.put(stateout, new HashSet>()); - } - Pair p=new Pair(state, e.getField()); - backMap.get(stateout).add(p); - } + for(SMFEState stateout : state.transitionsTo(e)) { + if (!backMap.containsKey(stateout)) { + toprocess.add(stateout); + backMap.put(stateout, new HashSet>()); + } + Pair p=new Pair(state, e.getField()); + backMap.get(stateout).add(p); + } } } return backMap; @@ -235,11 +235,11 @@ public class ProcessStateMachines { SMFEState state=toprocess.pop(); for(Pair instatepair : backMap.get(state)) { - SMFEState instate=instatepair.getFirst(); - if (!canReachConflicts.contains(instate)) { - toprocess.add(instate); - canReachConflicts.add(instate); - } + SMFEState instate=instatepair.getFirst(); + if (!canReachConflicts.contains(instate)) { + toprocess.add(instate); + canReachConflicts.add(instate); + } } } return canReachConflicts; @@ -251,9 +251,9 @@ public class ProcessStateMachines { StateMachineForEffects sm=bsm.getStateMachine(machinePair); Set taskSet=taskAnalysis.getPossibleExecutingRBlocks(fn); for(FlatSESEEnterNode sese : taskSet) { - if (!groupMap.containsKey(sese)) - groupMap.put(sese, new HashSet()); - groupMap.get(sese).add(sm); + if (!groupMap.containsKey(sese)) + groupMap.put(sese, new HashSet()); + groupMap.get(sese).add(sm); } } } @@ -265,8 +265,8 @@ public class ProcessStateMachines { StateMachineForEffects sm=bsm.getStateMachine(machinePair); Set taskSet=taskAnalysis.getPossibleExecutingRBlocks(fn); for(FlatSESEEnterNode sese : taskSet) { - Set smgroup=groupMap.get(sese); - computeConflictingEffects(sm, smgroup); + Set smgroup=groupMap.get(sese); + computeConflictingEffects(sm, smgroup); } } } @@ -275,34 +275,34 @@ public class ProcessStateMachines { boolean isStall=sm.getStallorSESE().kind()!=FKind.FlatSESEEnterNode; for(SMFEState state : sm.getStates()) { for(Effect e : state.getEffectsAllowed()) { - Alloc a=e.getAffectedAllocSite(); - FieldDescriptor fd=e.getField(); - int type=e.getType(); - boolean hasConflict=false; - if (!isStall&&Effect.isWrite(type)) { - hasConflict=true; - } else { - for(StateMachineForEffects othersm : smgroup) { - boolean otherIsStall=othersm.getStallorSESE().kind()!=FKind.FlatSESEEnterNode; - //Stall sites can't conflict with each other - if (isStall&&otherIsStall) continue; - - int effectType=othersm.getEffects(a, fd); - if (Effect.isWrite(type)&&effectType!=0) { - //Original effect is a write and we have some effect on the same field/alloc site - hasConflict=true; - break; - } - if (Effect.isWrite(effectType)) { - //We are a write - hasConflict=true; - break; - } - } - } - if (hasConflict) { - state.addConflict(e); - } + Alloc a=e.getAffectedAllocSite(); + FieldDescriptor fd=e.getField(); + int type=e.getType(); + boolean hasConflict=false; + if (!isStall&&Effect.isWrite(type)) { + hasConflict=true; + } else { + for(StateMachineForEffects othersm : smgroup) { + boolean otherIsStall=othersm.getStallorSESE().kind()!=FKind.FlatSESEEnterNode; + //Stall sites can't conflict with each other + if (isStall&&otherIsStall) continue; + + int effectType=othersm.getEffects(a, fd); + if (Effect.isWrite(type)&&effectType!=0) { + //Original effect is a write and we have some effect on the same field/alloc site + hasConflict=true; + break; + } + if (Effect.isWrite(effectType)) { + //We are a write + hasConflict=true; + break; + } + } + } + if (hasConflict) { + state.addConflict(e); + } } } } @@ -324,11 +324,11 @@ public class ProcessStateMachines { if( (effectType & Effect.read) != 0 && (effectType & Effect.write) != 0 ) { - allocAndFieldRW.add(new Effect(af.getFirst(), - Effect.read, - af.getSecond() - ) - ); + allocAndFieldRW.add(new Effect(af.getFirst(), + Effect.read, + af.getSecond() + ) + ); } } @@ -337,9 +337,9 @@ public class ProcessStateMachines { // as... POSSIBLY EVIL!!!!! for( SMFEState state : sm.getStates() ) { for( Effect effect : state.getTransitionEffects() ) { - if( allocAndFieldRW.contains(effect) ) { - sm.addPossiblyEvilEffect(effect); - } + if( allocAndFieldRW.contains(effect) ) { + sm.addPossiblyEvilEffect(effect); + } } } } diff --git a/Robust/src/Analysis/Disjoint/ReachGraph.java b/Robust/src/Analysis/Disjoint/ReachGraph.java index b2c85fb7..4db4c91f 100644 --- a/Robust/src/Analysis/Disjoint/ReachGraph.java +++ b/Robust/src/Analysis/Disjoint/ReachGraph.java @@ -147,21 +147,21 @@ public class ReachGraph { if( inherent == null ) { if( markForAnalysis ) { - inherent = - Canonical.changePredsTo( - ReachSet.factory( - ReachState.factory( - ReachTuple.factory(id, - !isSingleObject, - ReachTuple.ARITY_ONE, - false // out-of-context - ) - ) - ), - predsTrue - ); + inherent = + Canonical.changePredsTo( + ReachSet.factory( + ReachState.factory( + ReachTuple.factory(id, + !isSingleObject, + ReachTuple.ARITY_ONE, + false // out-of-context + ) + ) + ), + predsTrue + ); } else { - inherent = rsetWithEmptyState; + inherent = rsetWithEmptyState; } } @@ -267,14 +267,14 @@ public class ReachGraph { (edge.typeEquals(type) && edge.fieldEquals(field)) ) { - HeapRegionNode referencee = edge.getDst(); + HeapRegionNode referencee = edge.getDst(); - removeRefEdge(referencer, - referencee, - edge.getType(), - edge.getField() ); + removeRefEdge(referencer, + referencee, + edge.getType(), + edge.getField() ); - atLeastOneEdgeRemoved = true; + atLeastOneEdgeRemoved = true; } } @@ -298,12 +298,12 @@ public class ReachGraph { (edge.typeEquals(type) && edge.fieldEquals(field)) ) { - RefSrcNode referencer = edge.getSrc(); + RefSrcNode referencer = edge.getSrc(); - removeRefEdge(referencer, - referencee, - edge.getType(), - edge.getField() ); + removeRefEdge(referencer, + referencee, + edge.getType(), + edge.getField() ); } } } @@ -319,10 +319,10 @@ public class ReachGraph { RefEdge edge = i.next(); RefSrcNode referencer = edge.getSrc(); if( !(referencer instanceof VariableNode) ) { - removeRefEdge(referencer, - referencee, - edge.getType(), - edge.getField() ); + removeRefEdge(referencer, + referencee, + edge.getType(), + edge.getField() ); } } } @@ -407,25 +407,25 @@ public class ReachGraph { RefEdge edgeNew = edgeY.copy(); if( !isSuperiorType(x.getType(), edgeY.getType() ) ) { - impossibleEdges.add(edgeY); - continue; + impossibleEdges.add(edgeY); + continue; } edgeNew.setSrc(lnX); if( tdCast == null ) { - edgeNew.setType(mostSpecificType(y.getType(), - edgeY.getType(), - referencee.getType() - ) - ); + edgeNew.setType(mostSpecificType(y.getType(), + edgeY.getType(), + referencee.getType() + ) + ); } else { - edgeNew.setType(mostSpecificType(y.getType(), - edgeY.getType(), - referencee.getType(), - tdCast - ) - ); + edgeNew.setType(mostSpecificType(y.getType(), + edgeY.getType(), + referencee.getType(), + tdCast + ) + ); } edgeNew.setField(null); @@ -466,47 +466,47 @@ public class ReachGraph { Iterator itrHrnFhrn = hrnY.iteratorToReferencees(); while( itrHrnFhrn.hasNext() ) { - RefEdge edgeHrn = itrHrnFhrn.next(); - HeapRegionNode hrnHrn = edgeHrn.getDst(); - ReachSet betaHrn = edgeHrn.getBeta(); - - // prune edges that are not a matching field - if( edgeHrn.getType() != null && - !edgeHrn.getField().equals(f.getSymbol() ) - ) { - continue; - } - - // check for impossible edges - if( !isSuperiorType(x.getType(), edgeHrn.getType() ) ) { - impossibleEdges.add(edgeHrn); - continue; - } - - TypeDescriptor tdNewEdge = - mostSpecificType(edgeHrn.getType(), - hrnHrn.getType() - ); - - TaintSet taints = Canonical.unionORpreds(edgeHrn.getTaints(), - edgeY.getTaints() - ); - if( state.RCR ) { - // the DFJ way to generate taints changes for field statements - taints = Canonical.changeWhereDefined(taints, - currentProgramPoint); - } - - RefEdge edgeNew = new RefEdge(lnX, - hrnHrn, - tdNewEdge, - null, - Canonical.intersection(betaY, betaHrn), - predsTrue, - taints - ); - - addEdgeOrMergeWithExisting(edgeNew); + RefEdge edgeHrn = itrHrnFhrn.next(); + HeapRegionNode hrnHrn = edgeHrn.getDst(); + ReachSet betaHrn = edgeHrn.getBeta(); + + // prune edges that are not a matching field + if( edgeHrn.getType() != null && + !edgeHrn.getField().equals(f.getSymbol() ) + ) { + continue; + } + + // check for impossible edges + if( !isSuperiorType(x.getType(), edgeHrn.getType() ) ) { + impossibleEdges.add(edgeHrn); + continue; + } + + TypeDescriptor tdNewEdge = + mostSpecificType(edgeHrn.getType(), + hrnHrn.getType() + ); + + TaintSet taints = Canonical.unionORpreds(edgeHrn.getTaints(), + edgeY.getTaints() + ); + if( state.RCR ) { + // the DFJ way to generate taints changes for field statements + taints = Canonical.changeWhereDefined(taints, + currentProgramPoint); + } + + RefEdge edgeNew = new RefEdge(lnX, + hrnHrn, + tdNewEdge, + null, + Canonical.intersection(betaY, betaHrn), + predsTrue, + taints + ); + + addEdgeOrMergeWithExisting(edgeNew); } } @@ -520,7 +520,7 @@ public class ReachGraph { // you must global sweep to clean up broken reachability if( !impossibleEdges.isEmpty() ) { if( !DISABLE_GLOBAL_SWEEP ) { - globalSweep(); + globalSweep(); } } @@ -561,18 +561,18 @@ public class ReachGraph { (hrnX.isSingleObject() && lnX.getNumReferencees() == 1) // case 2 ) ) { - if( !DISABLE_STRONG_UPDATES ) { - strongUpdateCond = true; - - boolean atLeastOne = - clearRefEdgesFrom(hrnX, - f.getType(), - f.getSymbol(), - false); - if( atLeastOne ) { - edgeRemovedByStrongUpdate = true; - } - } + if( !DISABLE_STRONG_UPDATES ) { + strongUpdateCond = true; + + boolean atLeastOne = + clearRefEdgesFrom(hrnX, + f.getType(), + f.getSymbol(), + false); + if( atLeastOne ) { + edgeRemovedByStrongUpdate = true; + } + } } } @@ -588,38 +588,38 @@ public class ReachGraph { Iterator itrYhrn = lnY.iteratorToReferencees(); while( itrYhrn.hasNext() ) { - RefEdge edgeY = itrYhrn.next(); - HeapRegionNode hrnY = edgeY.getDst(); - ReachSet O = edgeY.getBeta(); - - // check for impossible edges - if( !isSuperiorType(f.getType(), edgeY.getType() ) ) { - impossibleEdges.add(edgeY); - continue; - } - - // propagate tokens over nodes starting from hrnSrc, and it will - // take care of propagating back up edges from any touched nodes - ChangeSet Cy = Canonical.unionUpArityToChangeSet(O, R); - propagateTokensOverNodes(hrnY, Cy, nodesWithNewAlpha, edgesWithNewBeta); - - // then propagate back just up the edges from hrn - ChangeSet Cx = Canonical.unionUpArityToChangeSet(R, O); - HashSet todoEdges = new HashSet(); - - Hashtable edgePlannedChanges = - new Hashtable(); - - Iterator referItr = hrnX.iteratorToReferencers(); - while( referItr.hasNext() ) { - RefEdge edgeUpstream = referItr.next(); - todoEdges.add(edgeUpstream); - edgePlannedChanges.put(edgeUpstream, Cx); - } - - propagateTokensOverEdges(todoEdges, - edgePlannedChanges, - edgesWithNewBeta); + RefEdge edgeY = itrYhrn.next(); + HeapRegionNode hrnY = edgeY.getDst(); + ReachSet O = edgeY.getBeta(); + + // check for impossible edges + if( !isSuperiorType(f.getType(), edgeY.getType() ) ) { + impossibleEdges.add(edgeY); + continue; + } + + // propagate tokens over nodes starting from hrnSrc, and it will + // take care of propagating back up edges from any touched nodes + ChangeSet Cy = Canonical.unionUpArityToChangeSet(O, R); + propagateTokensOverNodes(hrnY, Cy, nodesWithNewAlpha, edgesWithNewBeta); + + // then propagate back just up the edges from hrn + ChangeSet Cx = Canonical.unionUpArityToChangeSet(R, O); + HashSet todoEdges = new HashSet(); + + Hashtable edgePlannedChanges = + new Hashtable(); + + Iterator referItr = hrnX.iteratorToReferencers(); + while( referItr.hasNext() ) { + RefEdge edgeUpstream = referItr.next(); + todoEdges.add(edgeUpstream); + edgePlannedChanges.put(edgeUpstream, Cx); + } + + propagateTokensOverEdges(todoEdges, + edgePlannedChanges, + edgesWithNewBeta); } } @@ -644,46 +644,46 @@ public class ReachGraph { Iterator itrYhrn = lnY.iteratorToReferencees(); while( itrYhrn.hasNext() ) { - RefEdge edgeY = itrYhrn.next(); - HeapRegionNode hrnY = edgeY.getDst(); - - // skip impossible edges here, we already marked them - // when computing reachability propagations above - if( !isSuperiorType(f.getType(), edgeY.getType() ) ) { - continue; - } - - // prepare the new reference edge hrnX.f -> hrnY - TypeDescriptor tdNewEdge = - mostSpecificType(y.getType(), - edgeY.getType(), - hrnY.getType() - ); - - TaintSet taints = edgeY.getTaints(); - - if( state.RCR ) { - // the DFJ way to generate taints changes for field statements - taints = Canonical.changeWhereDefined(taints, - currentProgramPoint); - } - - RefEdge edgeNew = - new RefEdge(hrnX, - hrnY, - tdNewEdge, - f.getSymbol(), - Canonical.changePredsTo( - Canonical.pruneBy(edgeY.getBeta(), - hrnX.getAlpha() - ), - predsTrue - ), - predsTrue, - taints - ); - - addEdgeOrMergeWithExisting(edgeNew); + RefEdge edgeY = itrYhrn.next(); + HeapRegionNode hrnY = edgeY.getDst(); + + // skip impossible edges here, we already marked them + // when computing reachability propagations above + if( !isSuperiorType(f.getType(), edgeY.getType() ) ) { + continue; + } + + // prepare the new reference edge hrnX.f -> hrnY + TypeDescriptor tdNewEdge = + mostSpecificType(y.getType(), + edgeY.getType(), + hrnY.getType() + ); + + TaintSet taints = edgeY.getTaints(); + + if( state.RCR ) { + // the DFJ way to generate taints changes for field statements + taints = Canonical.changeWhereDefined(taints, + currentProgramPoint); + } + + RefEdge edgeNew = + new RefEdge(hrnX, + hrnY, + tdNewEdge, + f.getSymbol(), + Canonical.changePredsTo( + Canonical.pruneBy(edgeY.getBeta(), + hrnX.getAlpha() + ), + predsTrue + ), + predsTrue, + taints + ); + + addEdgeOrMergeWithExisting(edgeNew); } } @@ -697,7 +697,7 @@ public class ReachGraph { // reachability with a global sweep if( edgeRemovedByStrongUpdate || !impossibleEdges.isEmpty() ) { if( !DISABLE_GLOBAL_SWEEP ) { - globalSweep(); + globalSweep(); } } @@ -804,16 +804,16 @@ public class ReachGraph { // only do the transfer if the i-1 node exists Integer idImin1th = as.getIthOldest(i - 1); if( id2hrn.containsKey(idImin1th) ) { - HeapRegionNode hrnImin1 = id2hrn.get(idImin1th); - if( hrnImin1.isWiped() ) { - // there is no info on this node, just skip - continue; - } + HeapRegionNode hrnImin1 = id2hrn.get(idImin1th); + if( hrnImin1.isWiped() ) { + // there is no info on this node, just skip + continue; + } - // either retrieve or make target of transfer - HeapRegionNode hrnI = getIthNode(as, i, false); + // either retrieve or make target of transfer + HeapRegionNode hrnI = getIthNode(as, i, false); - transferOnto(hrnImin1, hrnI); + transferOnto(hrnImin1, hrnI); } } @@ -834,7 +834,7 @@ public class ReachGraph { Iterator itrEdges = hrnToAge.iteratorToReferencers(); while( itrEdges.hasNext() ) { - ageTuplesFrom(as, itrEdges.next() ); + ageTuplesFrom(as, itrEdges.next() ); } } @@ -940,22 +940,22 @@ public class ReachGraph { ); if( edgeSummary == null ) { - // the merge is trivial, nothing to be done - addRefEdge(hrnSummary, hrnReferencee, edgeMerged); + // the merge is trivial, nothing to be done + addRefEdge(hrnSummary, hrnReferencee, edgeMerged); } else { - // otherwise an edge from the referencer to hrnSummary exists already - // and the edge referencer->hrn should be merged with it - edgeSummary.setBeta( - Canonical.unionORpreds(edgeMerged.getBeta(), - edgeSummary.getBeta() - ) - ); - edgeSummary.setPreds( - Canonical.join(edgeMerged.getPreds(), - edgeSummary.getPreds() - ) - ); + // otherwise an edge from the referencer to hrnSummary exists already + // and the edge referencer->hrn should be merged with it + edgeSummary.setBeta( + Canonical.unionORpreds(edgeMerged.getBeta(), + edgeSummary.getBeta() + ) + ); + edgeSummary.setPreds( + Canonical.join(edgeMerged.getPreds(), + edgeSummary.getPreds() + ) + ); } } @@ -974,22 +974,22 @@ public class ReachGraph { ); if( edgeSummary == null ) { - // the merge is trivial, nothing to be done - addRefEdge(onReferencer, hrnSummary, edgeMerged); + // the merge is trivial, nothing to be done + addRefEdge(onReferencer, hrnSummary, edgeMerged); } else { - // otherwise an edge from the referencer to alpha_S exists already - // and the edge referencer->alpha_K should be merged with it - edgeSummary.setBeta( - Canonical.unionORpreds(edgeMerged.getBeta(), - edgeSummary.getBeta() - ) - ); - edgeSummary.setPreds( - Canonical.join(edgeMerged.getPreds(), - edgeSummary.getPreds() - ) - ); + // otherwise an edge from the referencer to alpha_S exists already + // and the edge referencer->alpha_K should be merged with it + edgeSummary.setBeta( + Canonical.unionORpreds(edgeMerged.getBeta(), + edgeSummary.getBeta() + ) + ); + edgeSummary.setPreds( + Canonical.join(edgeMerged.getPreds(), + edgeSummary.getPreds() + ) + ); } } @@ -1120,56 +1120,56 @@ public class ReachGraph { Iterator referItr = n.iteratorToReferencers(); while( referItr.hasNext() ) { - RefEdge edge = referItr.next(); - todoEdges.add(edge); - - if( !edgePlannedChanges.containsKey(edge) ) { - edgePlannedChanges.put(edge, - ChangeSet.factory() - ); - } - - edgePlannedChanges.put(edge, - Canonical.union(edgePlannedChanges.get(edge), - C - ) - ); + RefEdge edge = referItr.next(); + todoEdges.add(edge); + + if( !edgePlannedChanges.containsKey(edge) ) { + edgePlannedChanges.put(edge, + ChangeSet.factory() + ); + } + + edgePlannedChanges.put(edge, + Canonical.union(edgePlannedChanges.get(edge), + C + ) + ); } Iterator refeeItr = n.iteratorToReferencees(); while( refeeItr.hasNext() ) { - RefEdge edgeF = refeeItr.next(); - HeapRegionNode m = edgeF.getDst(); - - ChangeSet changesToPass = ChangeSet.factory(); - - Iterator itrCprime = C.iterator(); - while( itrCprime.hasNext() ) { - ChangeTuple c = itrCprime.next(); - if( edgeF.getBeta().containsIgnorePreds(c.getStateToMatch() ) - != null - ) { - changesToPass = Canonical.add(changesToPass, c); - } - } - - if( !changesToPass.isEmpty() ) { - if( !nodePlannedChanges.containsKey(m) ) { - nodePlannedChanges.put(m, ChangeSet.factory() ); - } - - ChangeSet currentChanges = nodePlannedChanges.get(m); - - if( !changesToPass.isSubset(currentChanges) ) { - - nodePlannedChanges.put(m, - Canonical.union(currentChanges, - changesToPass - ) - ); - todoNodes.add(m); - } - } + RefEdge edgeF = refeeItr.next(); + HeapRegionNode m = edgeF.getDst(); + + ChangeSet changesToPass = ChangeSet.factory(); + + Iterator itrCprime = C.iterator(); + while( itrCprime.hasNext() ) { + ChangeTuple c = itrCprime.next(); + if( edgeF.getBeta().containsIgnorePreds(c.getStateToMatch() ) + != null + ) { + changesToPass = Canonical.add(changesToPass, c); + } + } + + if( !changesToPass.isEmpty() ) { + if( !nodePlannedChanges.containsKey(m) ) { + nodePlannedChanges.put(m, ChangeSet.factory() ); + } + + ChangeSet currentChanges = nodePlannedChanges.get(m); + + if( !changesToPass.isSubset(currentChanges) ) { + + nodePlannedChanges.put(m, + Canonical.union(currentChanges, + changesToPass + ) + ); + todoNodes.add(m); + } + } } todoNodes.remove(n); @@ -1216,9 +1216,9 @@ public class ReachGraph { todoEdges.remove(edgeE); if( !edgePlannedChanges.containsKey(edgeE) ) { - edgePlannedChanges.put(edgeE, - ChangeSet.factory() - ); + edgePlannedChanges.put(edgeE, + ChangeSet.factory() + ); } ChangeSet C = edgePlannedChanges.get(edgeE); @@ -1227,40 +1227,40 @@ public class ReachGraph { Iterator itrC = C.iterator(); while( itrC.hasNext() ) { - ChangeTuple c = itrC.next(); - if( edgeE.getBeta().containsIgnorePreds(c.getStateToMatch() ) - != null - ) { - changesToPass = Canonical.add(changesToPass, c); - } + ChangeTuple c = itrC.next(); + if( edgeE.getBeta().containsIgnorePreds(c.getStateToMatch() ) + != null + ) { + changesToPass = Canonical.add(changesToPass, c); + } } RefSrcNode rsn = edgeE.getSrc(); if( !changesToPass.isEmpty() && rsn instanceof HeapRegionNode ) { - HeapRegionNode n = (HeapRegionNode) rsn; - - Iterator referItr = n.iteratorToReferencers(); - while( referItr.hasNext() ) { - RefEdge edgeF = referItr.next(); - - if( !edgePlannedChanges.containsKey(edgeF) ) { - edgePlannedChanges.put(edgeF, - ChangeSet.factory() - ); - } - - ChangeSet currentChanges = edgePlannedChanges.get(edgeF); - - if( !changesToPass.isSubset(currentChanges) ) { - todoEdges.add(edgeF); - edgePlannedChanges.put(edgeF, - Canonical.union(currentChanges, - changesToPass - ) - ); - } - } + HeapRegionNode n = (HeapRegionNode) rsn; + + Iterator referItr = n.iteratorToReferencers(); + while( referItr.hasNext() ) { + RefEdge edgeF = referItr.next(); + + if( !edgePlannedChanges.containsKey(edgeF) ) { + edgePlannedChanges.put(edgeF, + ChangeSet.factory() + ); + } + + ChangeSet currentChanges = edgePlannedChanges.get(edgeF); + + if( !changesToPass.isSubset(currentChanges) ) { + todoEdges.add(edgeF); + edgePlannedChanges.put(edgeF, + Canonical.union(currentChanges, + changesToPass + ) + ); + } + } } } @@ -1301,7 +1301,7 @@ public class ReachGraph { // use this where defined flatnode to support RCR/DFJ FlatNode whereDefined = null; if( state.RCR ) { - whereDefined = sese; + whereDefined = sese; } // in-set var taints should NOT propagate back into callers @@ -1372,12 +1372,12 @@ public class ReachGraph { Iterator reItr = hrn.iteratorToReferencers(); while( reItr.hasNext() ) { - RefEdge re = reItr.next(); + RefEdge re = reItr.next(); - re.setTaints(Canonical.removeInContextTaints(re.getTaints(), - sese - ) - ); + re.setTaints(Canonical.removeInContextTaints(re.getTaints(), + sese + ) + ); } } } @@ -1392,11 +1392,11 @@ public class ReachGraph { Iterator reItr = hrn.iteratorToReferencers(); while( reItr.hasNext() ) { - RefEdge re = reItr.next(); + RefEdge re = reItr.next(); - re.setTaints(Canonical.removeStallSiteTaints(re.getTaints() - ) - ); + re.setTaints(Canonical.removeStallSiteTaints(re.getTaints() + ) + ); } } } @@ -1425,30 +1425,30 @@ public class ReachGraph { assert belongsToThis(re.getDst() ); if( !(re.getSrc() instanceof HeapRegionNode) ) { - continue; + continue; } HeapRegionNode hrnSrc = (HeapRegionNode) re.getSrc(); if( !hrnSrc.isOutOfContext() ) { - continue; + continue; } if( srcType == null ) { - if( hrnSrc.getType() != null ) { - continue; - } + if( hrnSrc.getType() != null ) { + continue; + } } else { - if( !srcType.equals(hrnSrc.getType() ) ) { - continue; - } + if( !srcType.equals(hrnSrc.getType() ) ) { + continue; + } } if( !re.typeEquals(refType) ) { - continue; + continue; } if( !re.fieldEquals(refField) ) { - continue; + continue; } // tada! We found it! @@ -1474,74 +1474,74 @@ public class ReachGraph { Iterator asItr = allocSites.iterator(); while( asItr.hasNext() ) { - AllocSite as = asItr.next(); - - ReachState stateNew = ReachState.factory(); - Iterator rtItr = stateCallee.iterator(); - while( rtItr.hasNext() ) { - ReachTuple rt = rtItr.next(); - - // only translate this tuple if it is - // in the out-callee-context bag - HrnIdOoc hio = new HrnIdOoc(rt.getHrnID(), - rt.isOutOfContext() - ); - if( !oocHrnIdOoc2callee.contains(hio) ) { - stateNew = Canonical.addUpArity(stateNew, rt); - continue; - } - - int age = as.getAgeCategory(rt.getHrnID() ); - - // this is the current mapping, where 0, 1, 2S were allocated - // in the current context, 0?, 1? and 2S? were allocated in a - // previous context, and we're translating to a future context - // - // 0 -> 0? - // 1 -> 1? - // 2S -> 2S? - // 2S* -> 2S?* - // - // 0? -> 2S? - // 1? -> 2S? - // 2S? -> 2S? - // 2S?* -> 2S?* - - if( age == AllocSite.AGE_notInThisSite ) { - // things not from the site just go back in - stateNew = Canonical.addUpArity(stateNew, rt); - - } else if( age == AllocSite.AGE_summary || - rt.isOutOfContext() - ) { - - stateNew = Canonical.addUpArity(stateNew, - ReachTuple.factory(as.getSummary(), - true, // multi - rt.getArity(), - true // out-of-context - ) - ); - - } else { - // otherwise everything else just goes to an out-of-context - // version, everything else the same - Integer I = as.getAge(rt.getHrnID() ); - assert I != null; - - assert !rt.isMultiObject(); - - stateNew = Canonical.addUpArity(stateNew, - ReachTuple.factory(rt.getHrnID(), - rt.isMultiObject(), // multi - rt.getArity(), - true // out-of-context - ) - ); - } - } - - stateCallee = stateNew; + AllocSite as = asItr.next(); + + ReachState stateNew = ReachState.factory(); + Iterator rtItr = stateCallee.iterator(); + while( rtItr.hasNext() ) { + ReachTuple rt = rtItr.next(); + + // only translate this tuple if it is + // in the out-callee-context bag + HrnIdOoc hio = new HrnIdOoc(rt.getHrnID(), + rt.isOutOfContext() + ); + if( !oocHrnIdOoc2callee.contains(hio) ) { + stateNew = Canonical.addUpArity(stateNew, rt); + continue; + } + + int age = as.getAgeCategory(rt.getHrnID() ); + + // this is the current mapping, where 0, 1, 2S were allocated + // in the current context, 0?, 1? and 2S? were allocated in a + // previous context, and we're translating to a future context + // + // 0 -> 0? + // 1 -> 1? + // 2S -> 2S? + // 2S* -> 2S?* + // + // 0? -> 2S? + // 1? -> 2S? + // 2S? -> 2S? + // 2S?* -> 2S?* + + if( age == AllocSite.AGE_notInThisSite ) { + // things not from the site just go back in + stateNew = Canonical.addUpArity(stateNew, rt); + + } else if( age == AllocSite.AGE_summary || + rt.isOutOfContext() + ) { + + stateNew = Canonical.addUpArity(stateNew, + ReachTuple.factory(as.getSummary(), + true, // multi + rt.getArity(), + true // out-of-context + ) + ); + + } else { + // otherwise everything else just goes to an out-of-context + // version, everything else the same + Integer I = as.getAge(rt.getHrnID() ); + assert I != null; + + assert !rt.isMultiObject(); + + stateNew = Canonical.addUpArity(stateNew, + ReachTuple.factory(rt.getHrnID(), + rt.isMultiObject(), // multi + rt.getArity(), + true // out-of-context + ) + ); + } + } + + stateCallee = stateNew; } // make a predicate of the caller graph element @@ -1550,22 +1550,22 @@ public class ReachGraph { Iterator predItr = predsNodeOrEdge.iterator(); while( predItr.hasNext() ) { - ExistPred predNodeOrEdge = predItr.next(); - - predsWithState = - Canonical.add(predsWithState, - ExistPred.factory(predNodeOrEdge.n_hrnID, - predNodeOrEdge.e_tdSrc, - predNodeOrEdge.e_hrnSrcID, - predNodeOrEdge.e_hrnDstID, - predNodeOrEdge.e_type, - predNodeOrEdge.e_field, - stateCallee, - null, - predNodeOrEdge.e_srcOutCalleeContext, - predNodeOrEdge.e_srcOutCallerContext - ) - ); + ExistPred predNodeOrEdge = predItr.next(); + + predsWithState = + Canonical.add(predsWithState, + ExistPred.factory(predNodeOrEdge.n_hrnID, + predNodeOrEdge.e_tdSrc, + predNodeOrEdge.e_hrnSrcID, + predNodeOrEdge.e_hrnDstID, + predNodeOrEdge.e_type, + predNodeOrEdge.e_field, + stateCallee, + null, + predNodeOrEdge.e_srcOutCalleeContext, + predNodeOrEdge.e_srcOutCallerContext + ) + ); } stateCallee = Canonical.changePredsTo(stateCallee, @@ -1599,30 +1599,30 @@ public class ReachGraph { if( calleeStatesSatisfied.containsKey(stateCallee) ) { - // starting from one callee state... - ReachSet rsCaller = ReachSet.factory(stateCallee); - - // possibly branch it into many states, which any - // allocation site might do, so lots of derived states - Iterator asItr = allocSites.iterator(); - while( asItr.hasNext() ) { - AllocSite as = asItr.next(); - rsCaller = Canonical.toCallerContext(rsCaller, as); - } - - // then before adding each derived, now caller-context - // states to the output, attach the appropriate pred - // based on the source callee state - Iterator stateItr = rsCaller.iterator(); - while( stateItr.hasNext() ) { - ReachState stateCaller = stateItr.next(); - stateCaller = Canonical.attach(stateCaller, - calleeStatesSatisfied.get(stateCallee) - ); - out = Canonical.add(out, - stateCaller - ); - } + // starting from one callee state... + ReachSet rsCaller = ReachSet.factory(stateCallee); + + // possibly branch it into many states, which any + // allocation site might do, so lots of derived states + Iterator asItr = allocSites.iterator(); + while( asItr.hasNext() ) { + AllocSite as = asItr.next(); + rsCaller = Canonical.toCallerContext(rsCaller, as); + } + + // then before adding each derived, now caller-context + // states to the output, attach the appropriate pred + // based on the source callee state + Iterator stateItr = rsCaller.iterator(); + while( stateItr.hasNext() ) { + ReachState stateCaller = stateItr.next(); + stateCaller = Canonical.attach(stateCaller, + calleeStatesSatisfied.get(stateCallee) + ); + out = Canonical.add(out, + stateCaller + ); + } } } @@ -1666,21 +1666,21 @@ public class ReachGraph { Iterator predItr = predsEdge.iterator(); while( predItr.hasNext() ) { - ExistPred predEdge = predItr.next(); - - predsWithTaint = - Canonical.add(predsWithTaint, - ExistPred.factory(predEdge.e_tdSrc, - predEdge.e_hrnSrcID, - predEdge.e_hrnDstID, - predEdge.e_type, - predEdge.e_field, - null, - tCaller, - predEdge.e_srcOutCalleeContext, - predEdge.e_srcOutCallerContext - ) - ); + ExistPred predEdge = predItr.next(); + + predsWithTaint = + Canonical.add(predsWithTaint, + ExistPred.factory(predEdge.e_tdSrc, + predEdge.e_hrnSrcID, + predEdge.e_hrnDstID, + predEdge.e_type, + predEdge.e_field, + null, + tCaller, + predEdge.e_srcOutCalleeContext, + predEdge.e_srcOutCallerContext + ) + ); } Taint tCallee = Canonical.changePredsTo(tCaller, @@ -1717,18 +1717,18 @@ public class ReachGraph { if( calleeTaintsSatisfied.containsKey(tCallee) ) { - Taint tCaller = - Canonical.attach(Taint.factory(tCallee.sese, - tCallee.stallSite, - tCallee.var, - tCallee.allocSite, - tCallee.fnDefined, - ExistPredSet.factory() ), - calleeTaintsSatisfied.get(tCallee) - ); - out = Canonical.add(out, - tCaller - ); + Taint tCaller = + Canonical.attach(Taint.factory(tCallee.sese, + tCallee.stallSite, + tCallee.var, + tCallee.allocSite, + tCallee.fnDefined, + ExistPredSet.factory() ), + calleeTaintsSatisfied.get(tCallee) + ); + out = Canonical.add(out, + tCaller + ); } } @@ -1782,33 +1782,33 @@ public class ReachGraph { toVisitInCaller.add(vnArgCaller); while( !toVisitInCaller.isEmpty() ) { - RefSrcNode rsnCaller = toVisitInCaller.iterator().next(); - toVisitInCaller.remove(rsnCaller); - visitedInCaller.add(rsnCaller); - - Iterator itrRefEdges = rsnCaller.iteratorToReferencees(); - while( itrRefEdges.hasNext() ) { - RefEdge reCaller = itrRefEdges.next(); - HeapRegionNode hrnCaller = reCaller.getDst(); - - callerNodeIDsCopiedToCallee.add(hrnCaller.getID() ); - reachableCallerNodes.add(hrnCaller); - - if( reCaller.getSrc() instanceof HeapRegionNode ) { - reachableCallerEdges.add(reCaller); - } else { - if( rsnCaller.equals(vnArgCaller) ) { - reachableCallerArgEdges2paramIndex.put(reCaller, i); - } else { - oocCallerEdges.add(reCaller); - } - } - - if( !visitedInCaller.contains(hrnCaller) ) { - toVisitInCaller.add(hrnCaller); - } - - } // end edge iteration + RefSrcNode rsnCaller = toVisitInCaller.iterator().next(); + toVisitInCaller.remove(rsnCaller); + visitedInCaller.add(rsnCaller); + + Iterator itrRefEdges = rsnCaller.iteratorToReferencees(); + while( itrRefEdges.hasNext() ) { + RefEdge reCaller = itrRefEdges.next(); + HeapRegionNode hrnCaller = reCaller.getDst(); + + callerNodeIDsCopiedToCallee.add(hrnCaller.getID() ); + reachableCallerNodes.add(hrnCaller); + + if( reCaller.getSrc() instanceof HeapRegionNode ) { + reachableCallerEdges.add(reCaller); + } else { + if( rsnCaller.equals(vnArgCaller) ) { + reachableCallerArgEdges2paramIndex.put(reCaller, i); + } else { + oocCallerEdges.add(reCaller); + } + } + + if( !visitedInCaller.contains(hrnCaller) ) { + toVisitInCaller.add(hrnCaller); + } + + } // end edge iteration } // end visiting heap nodes in caller } // end iterating over parameters as starting points @@ -1827,48 +1827,48 @@ public class ReachGraph { Iterator itrMightCross = hrnCallerAndInContext.iteratorToReferencers(); while( itrMightCross.hasNext() ) { - RefEdge edgeMightCross = itrMightCross.next(); - - RefSrcNode rsnCallerAndOutContext = - edgeMightCross.getSrc(); - - if( rsnCallerAndOutContext instanceof VariableNode ) { - // variables do not have out-of-context reach states, - // so jump out now - oocCallerEdges.add(edgeMightCross); - continue; - } - - HeapRegionNode hrnCallerAndOutContext = - (HeapRegionNode) rsnCallerAndOutContext; - - // is this source node out-of-context? - if( callerNodeIDsCopiedToCallee.contains(hrnCallerAndOutContext.getID() ) ) { - // no, skip this edge - continue; - } - - // okay, we got one - oocCallerEdges.add(edgeMightCross); - - // add all reach tuples on the node to list - // of things that are out-of-context: insight - // if this node is reachable from someting that WAS - // in-context, then this node should already be in-context - Iterator stateItr = hrnCallerAndOutContext.getAlpha().iterator(); - while( stateItr.hasNext() ) { - ReachState state = stateItr.next(); - - Iterator rtItr = state.iterator(); - while( rtItr.hasNext() ) { - ReachTuple rt = rtItr.next(); - - oocHrnIdOoc2callee.add(new HrnIdOoc(rt.getHrnID(), - rt.isOutOfContext() - ) - ); - } - } + RefEdge edgeMightCross = itrMightCross.next(); + + RefSrcNode rsnCallerAndOutContext = + edgeMightCross.getSrc(); + + if( rsnCallerAndOutContext instanceof VariableNode ) { + // variables do not have out-of-context reach states, + // so jump out now + oocCallerEdges.add(edgeMightCross); + continue; + } + + HeapRegionNode hrnCallerAndOutContext = + (HeapRegionNode) rsnCallerAndOutContext; + + // is this source node out-of-context? + if( callerNodeIDsCopiedToCallee.contains(hrnCallerAndOutContext.getID() ) ) { + // no, skip this edge + continue; + } + + // okay, we got one + oocCallerEdges.add(edgeMightCross); + + // add all reach tuples on the node to list + // of things that are out-of-context: insight + // if this node is reachable from someting that WAS + // in-context, then this node should already be in-context + Iterator stateItr = hrnCallerAndOutContext.getAlpha().iterator(); + while( stateItr.hasNext() ) { + ReachState state = stateItr.next(); + + Iterator rtItr = state.iterator(); + while( rtItr.hasNext() ) { + ReachTuple rt = rtItr.next(); + + oocHrnIdOoc2callee.add(new HrnIdOoc(rt.getHrnID(), + rt.isOutOfContext() + ) + ); + } + } } } @@ -2024,26 +2024,26 @@ public class ReachGraph { boolean outOfCallerContext; if( rsnCaller instanceof VariableNode ) { - VariableNode vnCaller = (VariableNode) rsnCaller; - oocNodeType = null; - oocReach = rsetEmpty; - oocPredSrcTemp = vnCaller.getTempDescriptor(); - outOfCalleeContext = true; - outOfCallerContext = false; + VariableNode vnCaller = (VariableNode) rsnCaller; + oocNodeType = null; + oocReach = rsetEmpty; + oocPredSrcTemp = vnCaller.getTempDescriptor(); + outOfCalleeContext = true; + outOfCallerContext = false; } else { - HeapRegionNode hrnSrcCaller = (HeapRegionNode) rsnCaller; - assert !callerNodeIDsCopiedToCallee.contains(hrnSrcCaller.getID() ); - oocNodeType = hrnSrcCaller.getType(); - oocReach = hrnSrcCaller.getAlpha(); - oocPredSrcID = hrnSrcCaller.getID(); - if( hrnSrcCaller.isOutOfContext() ) { - outOfCalleeContext = false; - outOfCallerContext = true; - } else { - outOfCalleeContext = true; - outOfCallerContext = false; - } + HeapRegionNode hrnSrcCaller = (HeapRegionNode) rsnCaller; + assert !callerNodeIDsCopiedToCallee.contains(hrnSrcCaller.getID() ); + oocNodeType = hrnSrcCaller.getType(); + oocReach = hrnSrcCaller.getAlpha(); + oocPredSrcID = hrnSrcCaller.getID(); + if( hrnSrcCaller.isOutOfContext() ) { + outOfCalleeContext = false; + outOfCallerContext = true; + } else { + outOfCalleeContext = true; + outOfCallerContext = false; + } } ExistPred pred = @@ -2069,131 +2069,131 @@ public class ReachGraph { ); if( oocEdgeExisting == null ) { - // for consistency, map one out-of-context "identifier" - // to one heap region node id, otherwise no convergence - String oocid = "oocid"+ - fmCallee+ - hrnDstCallee.getIDString()+ - oocNodeType+ - reCaller.getType()+ - reCaller.getField(); - - Integer oocHrnID = oocid2hrnid.get(oocid); - - HeapRegionNode hrnCalleeAndOutContext; - - if( oocHrnID == null ) { - - hrnCalleeAndOutContext = - rg.createNewHeapRegionNode(null, // ID - false, // single object? - false, // new summary? - true, // out-of-context? - oocNodeType, - null, // alloc site, shouldn't be used - toCalleeContext(oocReach, - preds, - oocHrnIdOoc2callee - ), - toCalleeContext(oocReach, - preds, - oocHrnIdOoc2callee - ), - preds, - "out-of-context" - ); - - oocid2hrnid.put(oocid, hrnCalleeAndOutContext.getID() ); - - } else { - - // the mapping already exists, so see if node is there - hrnCalleeAndOutContext = rg.id2hrn.get(oocHrnID); - - if( hrnCalleeAndOutContext == null ) { - // nope, make it - hrnCalleeAndOutContext = - rg.createNewHeapRegionNode(oocHrnID, // ID - false, // single object? - false, // new summary? - true, // out-of-context? - oocNodeType, - null, // alloc site, shouldn't be used - toCalleeContext(oocReach, - preds, - oocHrnIdOoc2callee - ), - toCalleeContext(oocReach, - preds, - oocHrnIdOoc2callee - ), - preds, - "out-of-context" - ); - - } else { - // otherwise it is there, so merge reachability - hrnCalleeAndOutContext.setAlpha(Canonical.unionORpreds(hrnCalleeAndOutContext.getAlpha(), - toCalleeContext(oocReach, - preds, - oocHrnIdOoc2callee - ) - ) - ); - } - } - - assert hrnCalleeAndOutContext.reachHasOnlyOOC(); - - rg.addRefEdge(hrnCalleeAndOutContext, - hrnDstCallee, - new RefEdge(hrnCalleeAndOutContext, - hrnDstCallee, - reCaller.getType(), - reCaller.getField(), - toCalleeContext(reCaller.getBeta(), - preds, - oocHrnIdOoc2callee - ), - preds, - toCalleeContext(reCaller.getTaints(), - preds) - ) - ); + // for consistency, map one out-of-context "identifier" + // to one heap region node id, otherwise no convergence + String oocid = "oocid"+ + fmCallee+ + hrnDstCallee.getIDString()+ + oocNodeType+ + reCaller.getType()+ + reCaller.getField(); + + Integer oocHrnID = oocid2hrnid.get(oocid); + + HeapRegionNode hrnCalleeAndOutContext; + + if( oocHrnID == null ) { + + hrnCalleeAndOutContext = + rg.createNewHeapRegionNode(null, // ID + false, // single object? + false, // new summary? + true, // out-of-context? + oocNodeType, + null, // alloc site, shouldn't be used + toCalleeContext(oocReach, + preds, + oocHrnIdOoc2callee + ), + toCalleeContext(oocReach, + preds, + oocHrnIdOoc2callee + ), + preds, + "out-of-context" + ); + + oocid2hrnid.put(oocid, hrnCalleeAndOutContext.getID() ); + + } else { + + // the mapping already exists, so see if node is there + hrnCalleeAndOutContext = rg.id2hrn.get(oocHrnID); + + if( hrnCalleeAndOutContext == null ) { + // nope, make it + hrnCalleeAndOutContext = + rg.createNewHeapRegionNode(oocHrnID, // ID + false, // single object? + false, // new summary? + true, // out-of-context? + oocNodeType, + null, // alloc site, shouldn't be used + toCalleeContext(oocReach, + preds, + oocHrnIdOoc2callee + ), + toCalleeContext(oocReach, + preds, + oocHrnIdOoc2callee + ), + preds, + "out-of-context" + ); + + } else { + // otherwise it is there, so merge reachability + hrnCalleeAndOutContext.setAlpha(Canonical.unionORpreds(hrnCalleeAndOutContext.getAlpha(), + toCalleeContext(oocReach, + preds, + oocHrnIdOoc2callee + ) + ) + ); + } + } + + assert hrnCalleeAndOutContext.reachHasOnlyOOC(); + + rg.addRefEdge(hrnCalleeAndOutContext, + hrnDstCallee, + new RefEdge(hrnCalleeAndOutContext, + hrnDstCallee, + reCaller.getType(), + reCaller.getField(), + toCalleeContext(reCaller.getBeta(), + preds, + oocHrnIdOoc2callee + ), + preds, + toCalleeContext(reCaller.getTaints(), + preds) + ) + ); } else { - // the out-of-context edge already exists - oocEdgeExisting.setBeta(Canonical.unionORpreds(oocEdgeExisting.getBeta(), - toCalleeContext(reCaller.getBeta(), - preds, - oocHrnIdOoc2callee - ) - ) - ); - - oocEdgeExisting.setPreds(Canonical.join(oocEdgeExisting.getPreds(), - preds - ) - ); - - oocEdgeExisting.setTaints(Canonical.unionORpreds(oocEdgeExisting.getTaints(), - toCalleeContext(reCaller.getTaints(), - preds - ) - ) - ); - - HeapRegionNode hrnCalleeAndOutContext = - (HeapRegionNode) oocEdgeExisting.getSrc(); - hrnCalleeAndOutContext.setAlpha(Canonical.unionORpreds(hrnCalleeAndOutContext.getAlpha(), - toCalleeContext(oocReach, - preds, - oocHrnIdOoc2callee - ) - ) - ); - - assert hrnCalleeAndOutContext.reachHasOnlyOOC(); + // the out-of-context edge already exists + oocEdgeExisting.setBeta(Canonical.unionORpreds(oocEdgeExisting.getBeta(), + toCalleeContext(reCaller.getBeta(), + preds, + oocHrnIdOoc2callee + ) + ) + ); + + oocEdgeExisting.setPreds(Canonical.join(oocEdgeExisting.getPreds(), + preds + ) + ); + + oocEdgeExisting.setTaints(Canonical.unionORpreds(oocEdgeExisting.getTaints(), + toCalleeContext(reCaller.getTaints(), + preds + ) + ) + ); + + HeapRegionNode hrnCalleeAndOutContext = + (HeapRegionNode) oocEdgeExisting.getSrc(); + hrnCalleeAndOutContext.setAlpha(Canonical.unionORpreds(hrnCalleeAndOutContext.getAlpha(), + toCalleeContext(oocReach, + preds, + oocHrnIdOoc2callee + ) + ) + ); + + assert hrnCalleeAndOutContext.reachHasOnlyOOC(); } } @@ -2324,10 +2324,10 @@ public class ReachGraph { ); if( predsIfSatis != null ) { - calleeNodesSatisfied.put(hrnCallee, predsIfSatis); + calleeNodesSatisfied.put(hrnCallee, predsIfSatis); } else { - // otherwise don't bother looking at edges to this node - continue; + // otherwise don't bother looking at edges to this node + continue; } // since the node is coming over, find out which reach @@ -2336,215 +2336,215 @@ public class ReachGraph { Iterator stateItr = hrnCallee.getAlpha().iterator(); while( stateItr.hasNext() ) { - ReachState stateCallee = stateItr.next(); + ReachState stateCallee = stateItr.next(); - predsIfSatis = - stateCallee.getPreds().isSatisfiedBy(this, - callerNodeIDsCopiedToCallee - ); - if( predsIfSatis != null ) { + predsIfSatis = + stateCallee.getPreds().isSatisfiedBy(this, + callerNodeIDsCopiedToCallee + ); + if( predsIfSatis != null ) { - Hashtable calleeStatesSatisfied = - calleeNode2calleeStatesSatisfied.get(hrnCallee); + Hashtable calleeStatesSatisfied = + calleeNode2calleeStatesSatisfied.get(hrnCallee); - if( calleeStatesSatisfied == null ) { - calleeStatesSatisfied = - new Hashtable(); + if( calleeStatesSatisfied == null ) { + calleeStatesSatisfied = + new Hashtable(); - calleeNode2calleeStatesSatisfied.put(hrnCallee, calleeStatesSatisfied); - } + calleeNode2calleeStatesSatisfied.put(hrnCallee, calleeStatesSatisfied); + } - calleeStatesSatisfied.put(stateCallee, predsIfSatis); - } + calleeStatesSatisfied.put(stateCallee, predsIfSatis); + } } // then look at edges to the node Iterator reItr = hrnCallee.iteratorToReferencers(); while( reItr.hasNext() ) { - RefEdge reCallee = reItr.next(); - RefSrcNode rsnCallee = reCallee.getSrc(); - - // (caller local variables to in-context heap regions) - // have an (out-of-context heap region -> in-context heap region) - // abstraction in the callEE, so its true we never need to - // look at a (var node -> heap region) edge in callee to bring - // those over for the call site transfer, except for the special - // case of *RETURN var* -> heap region edges. - // What about (param var->heap region) - // edges in callee? They are dealt with below this loop. - - if( rsnCallee instanceof VariableNode ) { - - // looking for the return-value variable only - VariableNode vnCallee = (VariableNode) rsnCallee; - if( vnCallee.getTempDescriptor() != tdReturn ) { - continue; - } - - TempDescriptor returnTemp = fc.getReturnTemp(); - if( returnTemp == null || - !DisjointAnalysis.shouldAnalysisTrack(returnTemp.getType() ) - ) { - continue; - } - - // note that the assignment of the return value is to a - // variable in the caller which is out-of-context with - // respect to the callee - VariableNode vnLhsCaller = getVariableNodeFromTemp(returnTemp); - Set rsnCallers = new HashSet(); - rsnCallers.add(vnLhsCaller); - calleeEdges2oocCallerSrcMatches.put(reCallee, rsnCallers); - - - } else { - // for HeapRegionNode callee sources... - - // first see if the source is out-of-context, and only - // proceed with this edge if we find some caller-context - // matches - HeapRegionNode hrnSrcCallee = (HeapRegionNode) rsnCallee; - boolean matchedOutOfContext = false; - - if( !hrnSrcCallee.isOutOfContext() ) { - - predsIfSatis = - hrnSrcCallee.getPreds().isSatisfiedBy(this, - callerNodeIDsCopiedToCallee - ); - if( predsIfSatis != null ) { - calleeNodesSatisfied.put(hrnSrcCallee, predsIfSatis); - } else { - // otherwise forget this edge - continue; - } - - } else { - // hrnSrcCallee is out-of-context - - assert !calleeEdges2oocCallerSrcMatches.containsKey(reCallee); - - Set rsnCallers = new HashSet(); - - // is the target node in the caller? - HeapRegionNode hrnDstCaller = this.id2hrn.get(hrnCallee.getID() ); - if( hrnDstCaller == null ) { - continue; - } - - Iterator reDstItr = hrnDstCaller.iteratorToReferencers(); - while( reDstItr.hasNext() ) { - // the edge and field (either possibly null) must match - RefEdge reCaller = reDstItr.next(); - - if( !reCaller.typeEquals(reCallee.getType() ) || - !reCaller.fieldEquals(reCallee.getField() ) - ) { - continue; - } - - RefSrcNode rsnCaller = reCaller.getSrc(); - if( rsnCaller instanceof VariableNode ) { - - // a variable node matches an OOC region with null type - if( hrnSrcCallee.getType() != null ) { - continue; - } - - } else { - // otherwise types should match - HeapRegionNode hrnCallerSrc = (HeapRegionNode) rsnCaller; - if( hrnSrcCallee.getType() == null ) { - if( hrnCallerSrc.getType() != null ) { - continue; - } - } else { - if( !hrnSrcCallee.getType().equals(hrnCallerSrc.getType() ) ) { - continue; - } - } - } - - rsnCallers.add(rsnCaller); - matchedOutOfContext = true; - } - - if( !rsnCallers.isEmpty() ) { - calleeEdges2oocCallerSrcMatches.put(reCallee, rsnCallers); - } - } - - if( hrnSrcCallee.isOutOfContext() && - !matchedOutOfContext ) { - continue; - } - } - - - predsIfSatis = - reCallee.getPreds().isSatisfiedBy(this, - callerNodeIDsCopiedToCallee - ); - - if( predsIfSatis != null ) { - calleeEdgesSatisfied.put(reCallee, predsIfSatis); - - // since the edge is coming over, find out which reach - // states on it should come over, too - assert calleeEdge2calleeStatesSatisfied.get(reCallee) == null; - - stateItr = reCallee.getBeta().iterator(); - while( stateItr.hasNext() ) { - ReachState stateCallee = stateItr.next(); - - predsIfSatis = - stateCallee.getPreds().isSatisfiedBy(this, - callerNodeIDsCopiedToCallee - ); - if( predsIfSatis != null ) { - - Hashtable calleeStatesSatisfied = - calleeEdge2calleeStatesSatisfied.get(reCallee); - - if( calleeStatesSatisfied == null ) { - calleeStatesSatisfied = - new Hashtable(); - - calleeEdge2calleeStatesSatisfied.put(reCallee, calleeStatesSatisfied); - } - - calleeStatesSatisfied.put(stateCallee, predsIfSatis); - } - } - - // since the edge is coming over, find out which taints - // on it should come over, too - assert calleeEdge2calleeTaintsSatisfied.get(reCallee) == null; - - Iterator tItr = reCallee.getTaints().iterator(); - while( tItr.hasNext() ) { - Taint tCallee = tItr.next(); - - predsIfSatis = - tCallee.getPreds().isSatisfiedBy(this, - callerNodeIDsCopiedToCallee - ); - if( predsIfSatis != null ) { - - Hashtable calleeTaintsSatisfied = - calleeEdge2calleeTaintsSatisfied.get(reCallee); - - if( calleeTaintsSatisfied == null ) { - calleeTaintsSatisfied = - new Hashtable(); - - calleeEdge2calleeTaintsSatisfied.put(reCallee, calleeTaintsSatisfied); - } - - calleeTaintsSatisfied.put(tCallee, predsIfSatis); - } - } - } + RefEdge reCallee = reItr.next(); + RefSrcNode rsnCallee = reCallee.getSrc(); + + // (caller local variables to in-context heap regions) + // have an (out-of-context heap region -> in-context heap region) + // abstraction in the callEE, so its true we never need to + // look at a (var node -> heap region) edge in callee to bring + // those over for the call site transfer, except for the special + // case of *RETURN var* -> heap region edges. + // What about (param var->heap region) + // edges in callee? They are dealt with below this loop. + + if( rsnCallee instanceof VariableNode ) { + + // looking for the return-value variable only + VariableNode vnCallee = (VariableNode) rsnCallee; + if( vnCallee.getTempDescriptor() != tdReturn ) { + continue; + } + + TempDescriptor returnTemp = fc.getReturnTemp(); + if( returnTemp == null || + !DisjointAnalysis.shouldAnalysisTrack(returnTemp.getType() ) + ) { + continue; + } + + // note that the assignment of the return value is to a + // variable in the caller which is out-of-context with + // respect to the callee + VariableNode vnLhsCaller = getVariableNodeFromTemp(returnTemp); + Set rsnCallers = new HashSet(); + rsnCallers.add(vnLhsCaller); + calleeEdges2oocCallerSrcMatches.put(reCallee, rsnCallers); + + + } else { + // for HeapRegionNode callee sources... + + // first see if the source is out-of-context, and only + // proceed with this edge if we find some caller-context + // matches + HeapRegionNode hrnSrcCallee = (HeapRegionNode) rsnCallee; + boolean matchedOutOfContext = false; + + if( !hrnSrcCallee.isOutOfContext() ) { + + predsIfSatis = + hrnSrcCallee.getPreds().isSatisfiedBy(this, + callerNodeIDsCopiedToCallee + ); + if( predsIfSatis != null ) { + calleeNodesSatisfied.put(hrnSrcCallee, predsIfSatis); + } else { + // otherwise forget this edge + continue; + } + + } else { + // hrnSrcCallee is out-of-context + + assert !calleeEdges2oocCallerSrcMatches.containsKey(reCallee); + + Set rsnCallers = new HashSet(); + + // is the target node in the caller? + HeapRegionNode hrnDstCaller = this.id2hrn.get(hrnCallee.getID() ); + if( hrnDstCaller == null ) { + continue; + } + + Iterator reDstItr = hrnDstCaller.iteratorToReferencers(); + while( reDstItr.hasNext() ) { + // the edge and field (either possibly null) must match + RefEdge reCaller = reDstItr.next(); + + if( !reCaller.typeEquals(reCallee.getType() ) || + !reCaller.fieldEquals(reCallee.getField() ) + ) { + continue; + } + + RefSrcNode rsnCaller = reCaller.getSrc(); + if( rsnCaller instanceof VariableNode ) { + + // a variable node matches an OOC region with null type + if( hrnSrcCallee.getType() != null ) { + continue; + } + + } else { + // otherwise types should match + HeapRegionNode hrnCallerSrc = (HeapRegionNode) rsnCaller; + if( hrnSrcCallee.getType() == null ) { + if( hrnCallerSrc.getType() != null ) { + continue; + } + } else { + if( !hrnSrcCallee.getType().equals(hrnCallerSrc.getType() ) ) { + continue; + } + } + } + + rsnCallers.add(rsnCaller); + matchedOutOfContext = true; + } + + if( !rsnCallers.isEmpty() ) { + calleeEdges2oocCallerSrcMatches.put(reCallee, rsnCallers); + } + } + + if( hrnSrcCallee.isOutOfContext() && + !matchedOutOfContext ) { + continue; + } + } + + + predsIfSatis = + reCallee.getPreds().isSatisfiedBy(this, + callerNodeIDsCopiedToCallee + ); + + if( predsIfSatis != null ) { + calleeEdgesSatisfied.put(reCallee, predsIfSatis); + + // since the edge is coming over, find out which reach + // states on it should come over, too + assert calleeEdge2calleeStatesSatisfied.get(reCallee) == null; + + stateItr = reCallee.getBeta().iterator(); + while( stateItr.hasNext() ) { + ReachState stateCallee = stateItr.next(); + + predsIfSatis = + stateCallee.getPreds().isSatisfiedBy(this, + callerNodeIDsCopiedToCallee + ); + if( predsIfSatis != null ) { + + Hashtable calleeStatesSatisfied = + calleeEdge2calleeStatesSatisfied.get(reCallee); + + if( calleeStatesSatisfied == null ) { + calleeStatesSatisfied = + new Hashtable(); + + calleeEdge2calleeStatesSatisfied.put(reCallee, calleeStatesSatisfied); + } + + calleeStatesSatisfied.put(stateCallee, predsIfSatis); + } + } + + // since the edge is coming over, find out which taints + // on it should come over, too + assert calleeEdge2calleeTaintsSatisfied.get(reCallee) == null; + + Iterator tItr = reCallee.getTaints().iterator(); + while( tItr.hasNext() ) { + Taint tCallee = tItr.next(); + + predsIfSatis = + tCallee.getPreds().isSatisfiedBy(this, + callerNodeIDsCopiedToCallee + ); + if( predsIfSatis != null ) { + + Hashtable calleeTaintsSatisfied = + calleeEdge2calleeTaintsSatisfied.get(reCallee); + + if( calleeTaintsSatisfied == null ) { + calleeTaintsSatisfied = + new Hashtable(); + + calleeEdge2calleeTaintsSatisfied.put(reCallee, calleeTaintsSatisfied); + } + + calleeTaintsSatisfied.put(tCallee, predsIfSatis); + } + } + } } } @@ -2619,7 +2619,7 @@ public class ReachGraph { // it to link everything up in caller context, so that's why we're // skipping this... maybe that's a sillier way to do it? if( hrnCallee.isOutOfContext() ) { - continue; + continue; } AllocSite as = hrnCallee.getAllocSite(); @@ -2629,21 +2629,21 @@ public class ReachGraph { HeapRegionNode hrnCaller = id2hrn.get(hrnIDshadow); if( hrnCaller == null ) { - hrnCaller = - createNewHeapRegionNode(hrnIDshadow, // id or null to generate a new one - hrnCallee.isSingleObject(), // single object? - hrnCallee.isNewSummary(), // summary? - false, // out-of-context? - hrnCallee.getType(), // type - hrnCallee.getAllocSite(), // allocation site - toCallerContext(hrnCallee.getInherent(), - calleeNode2calleeStatesSatisfied.get(hrnCallee) ), // inherent reach - null, // current reach - predsEmpty, // predicates - hrnCallee.getDescription() // description - ); + hrnCaller = + createNewHeapRegionNode(hrnIDshadow, // id or null to generate a new one + hrnCallee.isSingleObject(), // single object? + hrnCallee.isNewSummary(), // summary? + false, // out-of-context? + hrnCallee.getType(), // type + hrnCallee.getAllocSite(), // allocation site + toCallerContext(hrnCallee.getInherent(), + calleeNode2calleeStatesSatisfied.get(hrnCallee) ), // inherent reach + null, // current reach + predsEmpty, // predicates + hrnCallee.getDescription() // description + ); } else { - assert hrnCaller.isWiped(); + assert hrnCaller.isWiped(); } hrnCaller.setAlpha(toCallerContext(hrnCallee.getAlpha(), @@ -2708,57 +2708,57 @@ public class ReachGraph { calleeEdges2oocCallerSrcMatches.get(reCallee); if( rsnCallee instanceof HeapRegionNode ) { - HeapRegionNode hrnCalleeSrc = (HeapRegionNode) rsnCallee; - if( hrnCalleeSrc.isOutOfContext() ) { - assert oocCallers != null; - } + HeapRegionNode hrnCalleeSrc = (HeapRegionNode) rsnCallee; + if( hrnCalleeSrc.isOutOfContext() ) { + assert oocCallers != null; + } } if( oocCallers == null ) { - // there are no out-of-context matches, so it's - // either a param/arg var or one in-context heap region - if( rsnCallee instanceof VariableNode ) { - // variable -> node in the callee should only - // come into the caller if its from a param var - VariableNode vnCallee = (VariableNode) rsnCallee; - TempDescriptor tdParam = vnCallee.getTempDescriptor(); - TempDescriptor tdArg = fc.getArgMatchingParam(fmCallee, - tdParam); - if( tdArg == null ) { - // this means the variable isn't a parameter, its local - // to the callee so we ignore it in call site transfer - // shouldn't this NEVER HAPPEN? - assert false; - } + // there are no out-of-context matches, so it's + // either a param/arg var or one in-context heap region + if( rsnCallee instanceof VariableNode ) { + // variable -> node in the callee should only + // come into the caller if its from a param var + VariableNode vnCallee = (VariableNode) rsnCallee; + TempDescriptor tdParam = vnCallee.getTempDescriptor(); + TempDescriptor tdArg = fc.getArgMatchingParam(fmCallee, + tdParam); + if( tdArg == null ) { + // this means the variable isn't a parameter, its local + // to the callee so we ignore it in call site transfer + // shouldn't this NEVER HAPPEN? + assert false; + } - rsnCallers.add(this.getVariableNodeFromTemp(tdArg) ); + rsnCallers.add(this.getVariableNodeFromTemp(tdArg) ); - } else { - // otherwise source is in context, one region + } else { + // otherwise source is in context, one region - HeapRegionNode hrnSrcCallee = (HeapRegionNode) rsnCallee; + HeapRegionNode hrnSrcCallee = (HeapRegionNode) rsnCallee; - // translate an in-context node to shadow - AllocSite asSrc = hrnSrcCallee.getAllocSite(); - allocSites.add(asSrc); + // translate an in-context node to shadow + AllocSite asSrc = hrnSrcCallee.getAllocSite(); + allocSites.add(asSrc); - Integer hrnIDSrcShadow = - asSrc.getShadowIDfromID(hrnSrcCallee.getID() ); + Integer hrnIDSrcShadow = + asSrc.getShadowIDfromID(hrnSrcCallee.getID() ); - HeapRegionNode hrnSrcCallerShadow = - this.id2hrn.get(hrnIDSrcShadow); + HeapRegionNode hrnSrcCallerShadow = + this.id2hrn.get(hrnIDSrcShadow); - assert hrnSrcCallerShadow != null; + assert hrnSrcCallerShadow != null; - rsnCallers.add(hrnSrcCallerShadow); - } + rsnCallers.add(hrnSrcCallerShadow); + } } else { - // otherwise we have a set of out-of-context srcs - // that should NOT be translated to shadow nodes - assert !oocCallers.isEmpty(); - rsnCallers.addAll(oocCallers); + // otherwise we have a set of out-of-context srcs + // that should NOT be translated to shadow nodes + assert !oocCallers.isEmpty(); + rsnCallers.addAll(oocCallers); } // now make all caller edges we've identified from @@ -2766,73 +2766,73 @@ public class ReachGraph { assert !rsnCallers.isEmpty(); Iterator rsnItr = rsnCallers.iterator(); while( rsnItr.hasNext() ) { - RefSrcNode rsnCaller = rsnItr.next(); - - RefEdge reCaller = new RefEdge(rsnCaller, - hrnDstCaller, - reCallee.getType(), - reCallee.getField(), - toCallerContext(reCallee.getBeta(), - calleeEdge2calleeStatesSatisfied.get(reCallee) ), - preds, - toCallerContext(reCallee.getTaints(), - calleeEdge2calleeTaintsSatisfied.get(reCallee) ) - ); - - ChangeSet cs = ChangeSet.factory(); - Iterator rsItr = reCaller.getBeta().iterator(); - while( rsItr.hasNext() ) { - ReachState state = rsItr.next(); - ExistPredSet predsPreCallee = state.getPreds(); - - if( state.isEmpty() ) { - continue; - } - - Iterator predItr = predsPreCallee.iterator(); - while( predItr.hasNext() ) { - ExistPred pred = predItr.next(); - ReachState old = pred.ne_state; - - if( old == null ) { - old = rstateEmpty; - } - - cs = Canonical.add(cs, - ChangeTuple.factory(old, - state - ) - ); - } - } - - // we're just going to use the convenient "merge-if-exists" - // edge call below, but still take a separate look if there - // is an existing caller edge to build change sets properly - if( !cs.isEmpty() ) { - RefEdge edgeExisting = rsnCaller.getReferenceTo(hrnDstCaller, - reCallee.getType(), - reCallee.getField() - ); - if( edgeExisting != null ) { - ChangeSet csExisting = edgePlannedChanges.get(edgeExisting); - if( csExisting == null ) { - csExisting = ChangeSet.factory(); - } - edgePlannedChanges.put(edgeExisting, - Canonical.union(csExisting, - cs - ) - ); - } else { - edgesForPropagation.add(reCaller); - assert !edgePlannedChanges.containsKey(reCaller); - edgePlannedChanges.put(reCaller, cs); - } - } - - // then add new caller edge or merge - addEdgeOrMergeWithExisting(reCaller); + RefSrcNode rsnCaller = rsnItr.next(); + + RefEdge reCaller = new RefEdge(rsnCaller, + hrnDstCaller, + reCallee.getType(), + reCallee.getField(), + toCallerContext(reCallee.getBeta(), + calleeEdge2calleeStatesSatisfied.get(reCallee) ), + preds, + toCallerContext(reCallee.getTaints(), + calleeEdge2calleeTaintsSatisfied.get(reCallee) ) + ); + + ChangeSet cs = ChangeSet.factory(); + Iterator rsItr = reCaller.getBeta().iterator(); + while( rsItr.hasNext() ) { + ReachState state = rsItr.next(); + ExistPredSet predsPreCallee = state.getPreds(); + + if( state.isEmpty() ) { + continue; + } + + Iterator predItr = predsPreCallee.iterator(); + while( predItr.hasNext() ) { + ExistPred pred = predItr.next(); + ReachState old = pred.ne_state; + + if( old == null ) { + old = rstateEmpty; + } + + cs = Canonical.add(cs, + ChangeTuple.factory(old, + state + ) + ); + } + } + + // we're just going to use the convenient "merge-if-exists" + // edge call below, but still take a separate look if there + // is an existing caller edge to build change sets properly + if( !cs.isEmpty() ) { + RefEdge edgeExisting = rsnCaller.getReferenceTo(hrnDstCaller, + reCallee.getType(), + reCallee.getField() + ); + if( edgeExisting != null ) { + ChangeSet csExisting = edgePlannedChanges.get(edgeExisting); + if( csExisting == null ) { + csExisting = ChangeSet.factory(); + } + edgePlannedChanges.put(edgeExisting, + Canonical.union(csExisting, + cs + ) + ); + } else { + edgesForPropagation.add(reCaller); + assert !edgePlannedChanges.containsKey(reCaller); + edgePlannedChanges.put(reCaller, cs); + } + } + + // then add new caller edge or merge + addEdgeOrMergeWithExisting(reCaller); } } @@ -2901,89 +2901,89 @@ public class ReachGraph { while( ageNorm < allocationDepth && ageShad < allocationDepth ) { - // first, are there any normal nodes left? - Integer idNorm = as.getIthOldest(ageNorm); - HeapRegionNode hrnNorm = id2hrn.get(idNorm); - if( hrnNorm == null ) { - // no, this age of normal node not in the caller graph - ageNorm++; - continue; - } - - // yes, a normal node exists, is there an empty shadow - // "slot" to transfer it onto? - HeapRegionNode hrnShad = getIthNode(as, ageShad, true); - if( !hrnShad.isWiped() ) { - // no, this age of shadow node is not empty - ageShad++; - continue; - } - - // yes, this shadow node is empty - transferOnto(hrnNorm, hrnShad); - ageNorm++; - ageShad++; + // first, are there any normal nodes left? + Integer idNorm = as.getIthOldest(ageNorm); + HeapRegionNode hrnNorm = id2hrn.get(idNorm); + if( hrnNorm == null ) { + // no, this age of normal node not in the caller graph + ageNorm++; + continue; + } + + // yes, a normal node exists, is there an empty shadow + // "slot" to transfer it onto? + HeapRegionNode hrnShad = getIthNode(as, ageShad, true); + if( !hrnShad.isWiped() ) { + // no, this age of shadow node is not empty + ageShad++; + continue; + } + + // yes, this shadow node is empty + transferOnto(hrnNorm, hrnShad); + ageNorm++; + ageShad++; } // now, while there are still normal nodes but no shadow // slots, merge normal nodes into the shadow summary while( ageNorm < allocationDepth ) { - // first, are there any normal nodes left? - Integer idNorm = as.getIthOldest(ageNorm); - HeapRegionNode hrnNorm = id2hrn.get(idNorm); - if( hrnNorm == null ) { - // no, this age of normal node not in the caller graph - ageNorm++; - continue; - } - - // yes, a normal node exists, so get the shadow summary - HeapRegionNode summShad = getSummaryNode(as, true); - mergeIntoSummary(hrnNorm, summShad); - - // now tokens in reachability sets need to age also - Iterator itrAllHRNodes = id2hrn.entrySet().iterator(); - while( itrAllHRNodes.hasNext() ) { - Map.Entry me = (Map.Entry)itrAllHRNodes.next(); - HeapRegionNode hrnToAge = (HeapRegionNode) me.getValue(); - - ageTuplesFrom(as, hrnToAge); - - Iterator itrEdges = hrnToAge.iteratorToReferencers(); - while( itrEdges.hasNext() ) { - ageTuplesFrom(as, itrEdges.next() ); - } - } - - ageNorm++; + // first, are there any normal nodes left? + Integer idNorm = as.getIthOldest(ageNorm); + HeapRegionNode hrnNorm = id2hrn.get(idNorm); + if( hrnNorm == null ) { + // no, this age of normal node not in the caller graph + ageNorm++; + continue; + } + + // yes, a normal node exists, so get the shadow summary + HeapRegionNode summShad = getSummaryNode(as, true); + mergeIntoSummary(hrnNorm, summShad); + + // now tokens in reachability sets need to age also + Iterator itrAllHRNodes = id2hrn.entrySet().iterator(); + while( itrAllHRNodes.hasNext() ) { + Map.Entry me = (Map.Entry)itrAllHRNodes.next(); + HeapRegionNode hrnToAge = (HeapRegionNode) me.getValue(); + + ageTuplesFrom(as, hrnToAge); + + Iterator itrEdges = hrnToAge.iteratorToReferencers(); + while( itrEdges.hasNext() ) { + ageTuplesFrom(as, itrEdges.next() ); + } + } + + ageNorm++; } // if there is a normal summary, merge it into shadow summary Integer idNorm = as.getSummary(); HeapRegionNode summNorm = id2hrn.get(idNorm); if( summNorm != null ) { - HeapRegionNode summShad = getSummaryNode(as, true); - mergeIntoSummary(summNorm, summShad); + HeapRegionNode summShad = getSummaryNode(as, true); + mergeIntoSummary(summNorm, summShad); } // finally, flip all existing shadow nodes onto the normal for( int i = 0; i < allocationDepth; ++i ) { - Integer idShad = as.getIthOldestShadow(i); - HeapRegionNode hrnShad = id2hrn.get(idShad); - if( hrnShad != null ) { - // flip it - HeapRegionNode hrnNorm = getIthNode(as, i, false); - assert hrnNorm.isWiped(); - transferOnto(hrnShad, hrnNorm); - } + Integer idShad = as.getIthOldestShadow(i); + HeapRegionNode hrnShad = id2hrn.get(idShad); + if( hrnShad != null ) { + // flip it + HeapRegionNode hrnNorm = getIthNode(as, i, false); + assert hrnNorm.isWiped(); + transferOnto(hrnShad, hrnNorm); + } } Integer idShad = as.getSummaryShadow(); HeapRegionNode summShad = id2hrn.get(idShad); if( summShad != null ) { - summNorm = getSummaryNode(as, false); - transferOnto(summShad, summNorm); + summNorm = getSummaryNode(as, false); + transferOnto(summShad, summNorm); } } @@ -3013,8 +3013,8 @@ public class ReachGraph { Iterator itrEdges = hrn.iteratorToReferencers(); while( itrEdges.hasNext() ) { - RefEdge re = itrEdges.next(); - re.setBeta(unshadow(re.getBeta() ) ); + RefEdge re = itrEdges.next(); + re.setBeta(unshadow(re.getBeta() ) ); } } @@ -3084,12 +3084,12 @@ public class ReachGraph { VariableNode vn = (VariableNode) me.getValue(); if( liveSet.contains(td) ) { - toVisit.add(vn); + toVisit.add(vn); } else { - // dead var, remove completely from graph - td2vn.remove(td); - clearRefEdgesFrom(vn, null, null, true); + // dead var, remove completely from graph + td2vn.remove(td); + clearRefEdgesFrom(vn, null, null, true); } } @@ -3104,12 +3104,12 @@ public class ReachGraph { Iterator hrnItr = rsn.iteratorToReferencees(); while( hrnItr.hasNext() ) { - RefEdge edge = hrnItr.next(); - HeapRegionNode hrn = edge.getDst(); + RefEdge edge = hrnItr.next(); + HeapRegionNode hrn = edge.getDst(); - if( !visited.contains(hrn) ) { - toVisit.add(hrn); - } + if( !visited.contains(hrn) ) { + toVisit.add(hrn); + } } } @@ -3128,24 +3128,24 @@ public class ReachGraph { if( !visited.contains(hrn) ) { - // heap region nodes are compared across ReachGraph - // objects by their integer ID, so when discarding - // garbage nodes we must also discard entries in - // the ID -> heap region hashtable. - id2hrn.remove(hrn.getID() ); - - // RefEdge objects are two-way linked between - // nodes, so when a node is identified as garbage, - // actively clear references to and from it so - // live nodes won't have dangling RefEdge's - wipeOut(hrn, true); - - // if we just removed the last node from an allocation - // site, it should be taken out of the ReachGraph's list - AllocSite as = hrn.getAllocSite(); - if( !hasNodesOf(as) ) { - allocSites.remove(as); - } + // heap region nodes are compared across ReachGraph + // objects by their integer ID, so when discarding + // garbage nodes we must also discard entries in + // the ID -> heap region hashtable. + id2hrn.remove(hrn.getID() ); + + // RefEdge objects are two-way linked between + // nodes, so when a node is identified as garbage, + // actively clear references to and from it so + // live nodes won't have dangling RefEdge's + wipeOut(hrn, true); + + // if we just removed the last node from an allocation + // site, it should be taken out of the ReachGraph's list + AllocSite as = hrn.getAllocSite(); + if( !hasNodesOf(as) ) { + allocSites.remove(as); + } } } } @@ -3157,7 +3157,7 @@ public class ReachGraph { for( int i = 0; i < allocationDepth; ++i ) { if( id2hrn.containsKey(as.getIthOldest(i) ) ) { - return true; + return true; } } return false; @@ -3206,49 +3206,49 @@ public class ReachGraph { Iterator itrRers = hrn.iteratorToReferencers(); while( itrRers.hasNext() ) { - RefEdge edge = itrRers.next(); - assert rsetEmpty.equals(edge.getBetaNew() ); + RefEdge edge = itrRers.next(); + assert rsetEmpty.equals(edge.getBetaNew() ); } // make a mapping of IDs to heap regions they propagate from if( hrn.isFlagged() ) { - assert !hrn.isOutOfContext(); - assert !icID2srcs.containsKey(hrn.getID() ); - - // in-context flagged node IDs simply propagate from the - // node they name - Set srcs = new HashSet(); - srcs.add(hrn); - icID2srcs.put(hrn.getID(), srcs); + assert !hrn.isOutOfContext(); + assert !icID2srcs.containsKey(hrn.getID() ); + + // in-context flagged node IDs simply propagate from the + // node they name + Set srcs = new HashSet(); + srcs.add(hrn); + icID2srcs.put(hrn.getID(), srcs); } if( hrn.isOutOfContext() ) { - assert !hrn.isFlagged(); - - // the reachability states on an out-of-context - // node are not really important (combinations of - // IDs or arity)--what matters is that the states - // specify which nodes this out-of-context node - // stands in for. For example, if the state [17?, 19*] - // appears on the ooc node, it may serve as a source - // for node 17? and a source for node 19. - Iterator stateItr = hrn.getAlpha().iterator(); - while( stateItr.hasNext() ) { - ReachState state = stateItr.next(); - - Iterator rtItr = state.iterator(); - while( rtItr.hasNext() ) { - ReachTuple rt = rtItr.next(); - assert rt.isOutOfContext(); - - Set srcs = oocID2srcs.get(rt.getHrnID() ); - if( srcs == null ) { - srcs = new HashSet(); - } - srcs.add(hrn); - oocID2srcs.put(rt.getHrnID(), srcs); - } - } + assert !hrn.isFlagged(); + + // the reachability states on an out-of-context + // node are not really important (combinations of + // IDs or arity)--what matters is that the states + // specify which nodes this out-of-context node + // stands in for. For example, if the state [17?, 19*] + // appears on the ooc node, it may serve as a source + // for node 17? and a source for node 19. + Iterator stateItr = hrn.getAlpha().iterator(); + while( stateItr.hasNext() ) { + ReachState state = stateItr.next(); + + Iterator rtItr = state.iterator(); + while( rtItr.hasNext() ) { + ReachTuple rt = rtItr.next(); + assert rt.isOutOfContext(); + + Set srcs = oocID2srcs.get(rt.getHrnID() ); + if( srcs == null ) { + srcs = new HashSet(); + } + srcs.add(hrn); + oocID2srcs.put(rt.getHrnID(), srcs); + } + } } } @@ -3261,20 +3261,20 @@ public class ReachGraph { boolean inContext; if( !icID2srcs.isEmpty() ) { - Map.Entry me = (Map.Entry)icID2srcs.entrySet().iterator().next(); - hrnID = (Integer) me.getKey(); - srcs = (Set)me.getValue(); - inContext = true; - icID2srcs.remove(hrnID); + Map.Entry me = (Map.Entry)icID2srcs.entrySet().iterator().next(); + hrnID = (Integer) me.getKey(); + srcs = (Set)me.getValue(); + inContext = true; + icID2srcs.remove(hrnID); } else { - assert !oocID2srcs.isEmpty(); + assert !oocID2srcs.isEmpty(); - Map.Entry me = (Map.Entry)oocID2srcs.entrySet().iterator().next(); - hrnID = (Integer) me.getKey(); - srcs = (Set)me.getValue(); - inContext = false; - oocID2srcs.remove(hrnID); + Map.Entry me = (Map.Entry)oocID2srcs.entrySet().iterator().next(); + hrnID = (Integer) me.getKey(); + srcs = (Set)me.getValue(); + inContext = false; + oocID2srcs.remove(hrnID); } @@ -3285,65 +3285,65 @@ public class ReachGraph { Iterator hrnItr = srcs.iterator(); while( hrnItr.hasNext() ) { - HeapRegionNode hrn = hrnItr.next(); - - assert workSetEdges.isEmpty(); - - // initial boldB_f constraints - Iterator itrRees = hrn.iteratorToReferencees(); - while( itrRees.hasNext() ) { - RefEdge edge = itrRees.next(); - - assert !boldB_f.containsKey(edge); - boldB_f.put(edge, edge.getBeta() ); - - assert !workSetEdges.contains(edge); - workSetEdges.add(edge); - } - - // enforce the boldB_f constraint at edges until we reach a fixed point - while( !workSetEdges.isEmpty() ) { - RefEdge edge = workSetEdges.iterator().next(); - workSetEdges.remove(edge); - - Iterator itrPrime = edge.getDst().iteratorToReferencees(); - while( itrPrime.hasNext() ) { - RefEdge edgePrime = itrPrime.next(); - - ReachSet prevResult = boldB_f.get(edgePrime); - ReachSet intersection = Canonical.intersection(boldB_f.get(edge), - edgePrime.getBeta() - ); - - if( prevResult == null || - Canonical.unionORpreds(prevResult, - intersection).size() - > prevResult.size() - ) { - - if( prevResult == null ) { - boldB_f.put(edgePrime, - Canonical.unionORpreds(edgePrime.getBeta(), - intersection - ) - ); - } else { - boldB_f.put(edgePrime, - Canonical.unionORpreds(prevResult, - intersection - ) - ); - } - workSetEdges.add(edgePrime); - } - } - } + HeapRegionNode hrn = hrnItr.next(); + + assert workSetEdges.isEmpty(); + + // initial boldB_f constraints + Iterator itrRees = hrn.iteratorToReferencees(); + while( itrRees.hasNext() ) { + RefEdge edge = itrRees.next(); + + assert !boldB_f.containsKey(edge); + boldB_f.put(edge, edge.getBeta() ); + + assert !workSetEdges.contains(edge); + workSetEdges.add(edge); + } + + // enforce the boldB_f constraint at edges until we reach a fixed point + while( !workSetEdges.isEmpty() ) { + RefEdge edge = workSetEdges.iterator().next(); + workSetEdges.remove(edge); + + Iterator itrPrime = edge.getDst().iteratorToReferencees(); + while( itrPrime.hasNext() ) { + RefEdge edgePrime = itrPrime.next(); + + ReachSet prevResult = boldB_f.get(edgePrime); + ReachSet intersection = Canonical.intersection(boldB_f.get(edge), + edgePrime.getBeta() + ); + + if( prevResult == null || + Canonical.unionORpreds(prevResult, + intersection).size() + > prevResult.size() + ) { + + if( prevResult == null ) { + boldB_f.put(edgePrime, + Canonical.unionORpreds(edgePrime.getBeta(), + intersection + ) + ); + } else { + boldB_f.put(edgePrime, + Canonical.unionORpreds(prevResult, + intersection + ) + ); + } + workSetEdges.add(edgePrime); + } + } + } } if( inContext ) { - boldBic.put(hrnID, boldB_f); + boldBic.put(hrnID, boldB_f); } else { - boldBooc.put(hrnID, boldB_f); + boldBooc.put(hrnID, boldB_f); } } @@ -3366,7 +3366,7 @@ public class ReachGraph { // global sweep, they serve as sources for the pass // performed above if( hrn.isOutOfContext() ) { - continue; + continue; } // the inherent states of a region are the exception @@ -3382,107 +3382,107 @@ public class ReachGraph { // mark hrnIDs for removal Iterator stateItr = hrn.getAlpha().iterator(); while( stateItr.hasNext() ) { - ReachState stateOld = stateItr.next(); - - ReachState markedHrnIDs = ReachState.factory(); - - Iterator rtItr = stateOld.iterator(); - while( rtItr.hasNext() ) { - ReachTuple rtOld = rtItr.next(); - - // never remove the inherent hrnID from a flagged region - // because it is trivially satisfied - if( hrn.isFlagged() ) { - if( rtOld == rtException ) { - continue; - } - } - - // does boldB allow this hrnID? - boolean foundState = false; - Iterator incidentEdgeItr = hrn.iteratorToReferencers(); - while( incidentEdgeItr.hasNext() ) { - RefEdge incidentEdge = incidentEdgeItr.next(); - - Hashtable B; - if( rtOld.isOutOfContext() ) { - B = boldBooc.get(rtOld.getHrnID() ); - } else { - - if( !id2hrn.containsKey(rtOld.getHrnID() ) ) { - // let symbols not in the graph get pruned - break; - } - - B = boldBic.get(rtOld.getHrnID() ); - } - - if( B != null ) { - ReachSet boldB_rtOld_incident = B.get(incidentEdge); - if( boldB_rtOld_incident != null && - boldB_rtOld_incident.containsIgnorePreds(stateOld) != null - ) { - foundState = true; - } - } - } - - if( !foundState ) { - markedHrnIDs = Canonical.addUpArity(markedHrnIDs, rtOld); - } - } - - // if there is nothing marked, just move on - if( markedHrnIDs.isEmpty() ) { - hrn.setAlphaNew(Canonical.add(hrn.getAlphaNew(), - stateOld - ) - ); - continue; - } - - // remove all marked hrnIDs and establish a change set that should - // propagate backwards over edges from this node - ReachState statePruned = ReachState.factory(); - rtItr = stateOld.iterator(); - while( rtItr.hasNext() ) { - ReachTuple rtOld = rtItr.next(); - - if( !markedHrnIDs.containsTuple(rtOld) ) { - statePruned = Canonical.addUpArity(statePruned, rtOld); - } - } - assert !stateOld.equals(statePruned); - - hrn.setAlphaNew(Canonical.add(hrn.getAlphaNew(), - statePruned - ) - ); - ChangeTuple ct = ChangeTuple.factory(stateOld, - statePruned - ); - cts = Canonical.add(cts, ct); + ReachState stateOld = stateItr.next(); + + ReachState markedHrnIDs = ReachState.factory(); + + Iterator rtItr = stateOld.iterator(); + while( rtItr.hasNext() ) { + ReachTuple rtOld = rtItr.next(); + + // never remove the inherent hrnID from a flagged region + // because it is trivially satisfied + if( hrn.isFlagged() ) { + if( rtOld == rtException ) { + continue; + } + } + + // does boldB allow this hrnID? + boolean foundState = false; + Iterator incidentEdgeItr = hrn.iteratorToReferencers(); + while( incidentEdgeItr.hasNext() ) { + RefEdge incidentEdge = incidentEdgeItr.next(); + + Hashtable B; + if( rtOld.isOutOfContext() ) { + B = boldBooc.get(rtOld.getHrnID() ); + } else { + + if( !id2hrn.containsKey(rtOld.getHrnID() ) ) { + // let symbols not in the graph get pruned + break; + } + + B = boldBic.get(rtOld.getHrnID() ); + } + + if( B != null ) { + ReachSet boldB_rtOld_incident = B.get(incidentEdge); + if( boldB_rtOld_incident != null && + boldB_rtOld_incident.containsIgnorePreds(stateOld) != null + ) { + foundState = true; + } + } + } + + if( !foundState ) { + markedHrnIDs = Canonical.addUpArity(markedHrnIDs, rtOld); + } + } + + // if there is nothing marked, just move on + if( markedHrnIDs.isEmpty() ) { + hrn.setAlphaNew(Canonical.add(hrn.getAlphaNew(), + stateOld + ) + ); + continue; + } + + // remove all marked hrnIDs and establish a change set that should + // propagate backwards over edges from this node + ReachState statePruned = ReachState.factory(); + rtItr = stateOld.iterator(); + while( rtItr.hasNext() ) { + ReachTuple rtOld = rtItr.next(); + + if( !markedHrnIDs.containsTuple(rtOld) ) { + statePruned = Canonical.addUpArity(statePruned, rtOld); + } + } + assert !stateOld.equals(statePruned); + + hrn.setAlphaNew(Canonical.add(hrn.getAlphaNew(), + statePruned + ) + ); + ChangeTuple ct = ChangeTuple.factory(stateOld, + statePruned + ); + cts = Canonical.add(cts, ct); } // throw change tuple set on all incident edges if( !cts.isEmpty() ) { - Iterator incidentEdgeItr = hrn.iteratorToReferencers(); - while( incidentEdgeItr.hasNext() ) { - RefEdge incidentEdge = incidentEdgeItr.next(); - - edgesForPropagation.add(incidentEdge); - - if( edgePlannedChanges.get(incidentEdge) == null ) { - edgePlannedChanges.put(incidentEdge, cts); - } else { - edgePlannedChanges.put( - incidentEdge, - Canonical.union(edgePlannedChanges.get(incidentEdge), - cts - ) - ); - } - } + Iterator incidentEdgeItr = hrn.iteratorToReferencers(); + while( incidentEdgeItr.hasNext() ) { + RefEdge incidentEdge = incidentEdgeItr.next(); + + edgesForPropagation.add(incidentEdge); + + if( edgePlannedChanges.get(incidentEdge) == null ) { + edgePlannedChanges.put(incidentEdge, cts); + } else { + edgePlannedChanges.put( + incidentEdge, + Canonical.union(edgePlannedChanges.get(incidentEdge), + cts + ) + ); + } + } } } @@ -3509,14 +3509,14 @@ public class ReachGraph { // as sources of reach states for the sweep, not part // of the changes if( hrn.isOutOfContext() ) { - assert hrn.getAlphaNew().equals(rsetEmpty); + assert hrn.getAlphaNew().equals(rsetEmpty); } else { - hrn.applyAlphaNew(); + hrn.applyAlphaNew(); } Iterator itrRes = hrn.iteratorToReferencers(); while( itrRes.hasNext() ) { - res.add(itrRes.next() ); + res.add(itrRes.next() ); } } @@ -3529,7 +3529,7 @@ public class ReachGraph { // commit results of last phase if( edgesUpdated.contains(edge) ) { - edge.applyBetaNew(); + edge.applyBetaNew(); } // compute intial condition of 2nd phase @@ -3547,35 +3547,35 @@ public class ReachGraph { RefSrcNode rsn = edgePrime.getSrc(); if( !(rsn instanceof HeapRegionNode) ) { - continue; + continue; } HeapRegionNode hrn = (HeapRegionNode) rsn; Iterator itrEdge = hrn.iteratorToReferencers(); while( itrEdge.hasNext() ) { - RefEdge edge = itrEdge.next(); - - ReachSet prevResult = edge.getBetaNew(); - assert prevResult != null; - - ReachSet intersection = - Canonical.intersection(edge.getBeta(), - edgePrime.getBetaNew() - ); - - if( Canonical.unionORpreds(prevResult, - intersection - ).size() - > prevResult.size() - ) { - - edge.setBetaNew( - Canonical.unionORpreds(prevResult, - intersection - ) - ); - edgeWorkSet.add(edge); - } + RefEdge edge = itrEdge.next(); + + ReachSet prevResult = edge.getBetaNew(); + assert prevResult != null; + + ReachSet intersection = + Canonical.intersection(edge.getBeta(), + edgePrime.getBetaNew() + ); + + if( Canonical.unionORpreds(prevResult, + intersection + ).size() + > prevResult.size() + ) { + + edge.setBetaNew( + Canonical.unionORpreds(prevResult, + intersection + ) + ); + edgeWorkSet.add(edge); + } } } @@ -3599,44 +3599,44 @@ public class ReachGraph { HeapRegionNode hrn = (HeapRegionNode) me.getValue(); { - Iterator stateItr = hrn.getAlpha().iterator(); - while( stateItr.hasNext() ) { - ReachState state = stateItr.next(); - - Iterator rtItr = state.iterator(); - while( rtItr.hasNext() ) { - ReachTuple rt = rtItr.next(); - - if( !rt.isOutOfContext() ) { - if( !id2hrn.containsKey(rt.getHrnID() ) ) { - System.out.println(rt.getHrnID()+" is missing"); - return false; - } - } - } - } + Iterator stateItr = hrn.getAlpha().iterator(); + while( stateItr.hasNext() ) { + ReachState state = stateItr.next(); + + Iterator rtItr = state.iterator(); + while( rtItr.hasNext() ) { + ReachTuple rt = rtItr.next(); + + if( !rt.isOutOfContext() ) { + if( !id2hrn.containsKey(rt.getHrnID() ) ) { + System.out.println(rt.getHrnID()+" is missing"); + return false; + } + } + } + } } Iterator edgeItr = hrn.iteratorToReferencers(); while( edgeItr.hasNext() ) { - RefEdge edge = edgeItr.next(); - - Iterator stateItr = edge.getBeta().iterator(); - while( stateItr.hasNext() ) { - ReachState state = stateItr.next(); - - Iterator rtItr = state.iterator(); - while( rtItr.hasNext() ) { - ReachTuple rt = rtItr.next(); - - if( !rt.isOutOfContext() ) { - if( !id2hrn.containsKey(rt.getHrnID() ) ) { - System.out.println(rt.getHrnID()+" is missing"); - return false; - } - } - } - } + RefEdge edge = edgeItr.next(); + + Iterator stateItr = edge.getBeta().iterator(); + while( stateItr.hasNext() ) { + ReachState state = stateItr.next(); + + Iterator rtItr = state.iterator(); + while( rtItr.hasNext() ) { + ReachTuple rt = rtItr.next(); + + if( !rt.isOutOfContext() ) { + if( !id2hrn.containsKey(rt.getHrnID() ) ) { + System.out.println(rt.getHrnID()+" is missing"); + return false; + } + } + } + } } } @@ -3656,18 +3656,18 @@ public class ReachGraph { !hrn.isWiped() && hrn.getAlpha().isEmpty() ) { - System.out.println("!!! "+hrn+" has an empty ReachSet !!!"); - return false; + System.out.println("!!! "+hrn+" has an empty ReachSet !!!"); + return false; } Iterator edgeItr = hrn.iteratorToReferencers(); while( edgeItr.hasNext() ) { - RefEdge edge = edgeItr.next(); + RefEdge edge = edgeItr.next(); - if( edge.getBeta().isEmpty() ) { - System.out.println("!!! "+edge+" has an empty ReachSet !!!"); - return false; - } + if( edge.getBeta().isEmpty() ) { + System.out.println("!!! "+edge+" has an empty ReachSet !!!"); + return false; + } } } @@ -3683,28 +3683,28 @@ public class ReachGraph { HeapRegionNode hrn = (HeapRegionNode) me.getValue(); { - Iterator stateItr = hrn.getAlpha().iterator(); - while( stateItr.hasNext() ) { - ReachState state = stateItr.next(); - - if( !state.getPreds().equals(predsTrue) ) { - return false; - } - } + Iterator stateItr = hrn.getAlpha().iterator(); + while( stateItr.hasNext() ) { + ReachState state = stateItr.next(); + + if( !state.getPreds().equals(predsTrue) ) { + return false; + } + } } Iterator edgeItr = hrn.iteratorToReferencers(); while( edgeItr.hasNext() ) { - RefEdge edge = edgeItr.next(); + RefEdge edge = edgeItr.next(); - Iterator stateItr = edge.getBeta().iterator(); - while( stateItr.hasNext() ) { - ReachState state = stateItr.next(); + Iterator stateItr = edge.getBeta().iterator(); + while( stateItr.hasNext() ) { + ReachState state = stateItr.next(); - if( !state.getPreds().equals(predsTrue) ) { - return false; - } - } + if( !state.getPreds().equals(predsTrue) ) { + return false; + } + } } } @@ -3747,31 +3747,31 @@ public class ReachGraph { // if this graph doesn't have a node the // incoming graph has, allocate it if( !id2hrn.containsKey(idA) ) { - HeapRegionNode hrnB = hrnA.copy(); - id2hrn.put(idA, hrnB); + HeapRegionNode hrnB = hrnA.copy(); + id2hrn.put(idA, hrnB); } else { - // otherwise this is a node present in both graphs - // so make the new reachability set a union of the - // nodes' reachability sets - HeapRegionNode hrnB = id2hrn.get(idA); - hrnB.setAlpha(Canonical.unionORpreds(hrnB.getAlpha(), - hrnA.getAlpha() - ) - ); + // otherwise this is a node present in both graphs + // so make the new reachability set a union of the + // nodes' reachability sets + HeapRegionNode hrnB = id2hrn.get(idA); + hrnB.setAlpha(Canonical.unionORpreds(hrnB.getAlpha(), + hrnA.getAlpha() + ) + ); - hrnB.setPreds(Canonical.join(hrnB.getPreds(), - hrnA.getPreds() - ) - ); + hrnB.setPreds(Canonical.join(hrnB.getPreds(), + hrnA.getPreds() + ) + ); - if( !hrnA.equals(hrnB) ) { - rg.writeGraph("graphA"); - this.writeGraph("graphB"); - throw new Error("flagged not matching"); - } + if( !hrnA.equals(hrnB) ) { + rg.writeGraph("graphA"); + this.writeGraph("graphB"); + throw new Error("flagged not matching"); + } @@ -3804,65 +3804,65 @@ public class ReachGraph { Iterator heapRegionsItrA = hrnA.iteratorToReferencees(); while( heapRegionsItrA.hasNext() ) { - RefEdge edgeA = heapRegionsItrA.next(); - HeapRegionNode hrnChildA = edgeA.getDst(); - Integer idChildA = hrnChildA.getID(); - - // at this point we know an edge in graph A exists - // idA -> idChildA, does this exist in B? - assert id2hrn.containsKey(idA); - HeapRegionNode hrnB = id2hrn.get(idA); - RefEdge edgeToMerge = null; - - Iterator heapRegionsItrB = hrnB.iteratorToReferencees(); - while( heapRegionsItrB.hasNext() && - edgeToMerge == null ) { - - RefEdge edgeB = heapRegionsItrB.next(); - HeapRegionNode hrnChildB = edgeB.getDst(); - Integer idChildB = hrnChildB.getID(); - - // don't use the RefEdge.equals() here because - // we're talking about existence between graphs, - // not intragraph equal - if( idChildB.equals(idChildA) && - edgeB.typeAndFieldEquals(edgeA) ) { - - edgeToMerge = edgeB; - } - } - - // if the edge from A was not found in B, - // add it to B. - if( edgeToMerge == null ) { - assert id2hrn.containsKey(idChildA); - HeapRegionNode hrnChildB = id2hrn.get(idChildA); - edgeToMerge = edgeA.copy(); - edgeToMerge.setSrc(hrnB); - edgeToMerge.setDst(hrnChildB); - addRefEdge(hrnB, hrnChildB, edgeToMerge); - } - // otherwise, the edge already existed in both graphs - // so merge their reachability sets - else { - // just replace this beta set with the union - assert edgeToMerge != null; - edgeToMerge.setBeta( - Canonical.unionORpreds(edgeToMerge.getBeta(), - edgeA.getBeta() - ) - ); - edgeToMerge.setPreds( - Canonical.join(edgeToMerge.getPreds(), - edgeA.getPreds() - ) - ); - edgeToMerge.setTaints( - Canonical.union(edgeToMerge.getTaints(), - edgeA.getTaints() - ) - ); - } + RefEdge edgeA = heapRegionsItrA.next(); + HeapRegionNode hrnChildA = edgeA.getDst(); + Integer idChildA = hrnChildA.getID(); + + // at this point we know an edge in graph A exists + // idA -> idChildA, does this exist in B? + assert id2hrn.containsKey(idA); + HeapRegionNode hrnB = id2hrn.get(idA); + RefEdge edgeToMerge = null; + + Iterator heapRegionsItrB = hrnB.iteratorToReferencees(); + while( heapRegionsItrB.hasNext() && + edgeToMerge == null ) { + + RefEdge edgeB = heapRegionsItrB.next(); + HeapRegionNode hrnChildB = edgeB.getDst(); + Integer idChildB = hrnChildB.getID(); + + // don't use the RefEdge.equals() here because + // we're talking about existence between graphs, + // not intragraph equal + if( idChildB.equals(idChildA) && + edgeB.typeAndFieldEquals(edgeA) ) { + + edgeToMerge = edgeB; + } + } + + // if the edge from A was not found in B, + // add it to B. + if( edgeToMerge == null ) { + assert id2hrn.containsKey(idChildA); + HeapRegionNode hrnChildB = id2hrn.get(idChildA); + edgeToMerge = edgeA.copy(); + edgeToMerge.setSrc(hrnB); + edgeToMerge.setDst(hrnChildB); + addRefEdge(hrnB, hrnChildB, edgeToMerge); + } + // otherwise, the edge already existed in both graphs + // so merge their reachability sets + else { + // just replace this beta set with the union + assert edgeToMerge != null; + edgeToMerge.setBeta( + Canonical.unionORpreds(edgeToMerge.getBeta(), + edgeA.getBeta() + ) + ); + edgeToMerge.setPreds( + Canonical.join(edgeToMerge.getPreds(), + edgeA.getPreds() + ) + ); + edgeToMerge.setTaints( + Canonical.union(edgeToMerge.getTaints(), + edgeA.getTaints() + ) + ); + } } } @@ -3876,61 +3876,61 @@ public class ReachGraph { Iterator heapRegionsItrA = vnA.iteratorToReferencees(); while( heapRegionsItrA.hasNext() ) { - RefEdge edgeA = heapRegionsItrA.next(); - HeapRegionNode hrnChildA = edgeA.getDst(); - Integer idChildA = hrnChildA.getID(); - - // at this point we know an edge in graph A exists - // tdA -> idChildA, does this exist in B? - assert td2vn.containsKey(tdA); - VariableNode vnB = td2vn.get(tdA); - RefEdge edgeToMerge = null; - - Iterator heapRegionsItrB = vnB.iteratorToReferencees(); - while( heapRegionsItrB.hasNext() && - edgeToMerge == null ) { - - RefEdge edgeB = heapRegionsItrB.next(); - HeapRegionNode hrnChildB = edgeB.getDst(); - Integer idChildB = hrnChildB.getID(); - - // don't use the RefEdge.equals() here because - // we're talking about existence between graphs - if( idChildB.equals(idChildA) && - edgeB.typeAndFieldEquals(edgeA) ) { - - edgeToMerge = edgeB; - } - } - - // if the edge from A was not found in B, - // add it to B. - if( edgeToMerge == null ) { - assert id2hrn.containsKey(idChildA); - HeapRegionNode hrnChildB = id2hrn.get(idChildA); - edgeToMerge = edgeA.copy(); - edgeToMerge.setSrc(vnB); - edgeToMerge.setDst(hrnChildB); - addRefEdge(vnB, hrnChildB, edgeToMerge); - } - // otherwise, the edge already existed in both graphs - // so merge their reachability sets - else { - // just replace this beta set with the union - edgeToMerge.setBeta(Canonical.unionORpreds(edgeToMerge.getBeta(), - edgeA.getBeta() - ) - ); - edgeToMerge.setPreds(Canonical.join(edgeToMerge.getPreds(), - edgeA.getPreds() - ) - ); - edgeToMerge.setTaints( - Canonical.union(edgeToMerge.getTaints(), - edgeA.getTaints() - ) - ); - } + RefEdge edgeA = heapRegionsItrA.next(); + HeapRegionNode hrnChildA = edgeA.getDst(); + Integer idChildA = hrnChildA.getID(); + + // at this point we know an edge in graph A exists + // tdA -> idChildA, does this exist in B? + assert td2vn.containsKey(tdA); + VariableNode vnB = td2vn.get(tdA); + RefEdge edgeToMerge = null; + + Iterator heapRegionsItrB = vnB.iteratorToReferencees(); + while( heapRegionsItrB.hasNext() && + edgeToMerge == null ) { + + RefEdge edgeB = heapRegionsItrB.next(); + HeapRegionNode hrnChildB = edgeB.getDst(); + Integer idChildB = hrnChildB.getID(); + + // don't use the RefEdge.equals() here because + // we're talking about existence between graphs + if( idChildB.equals(idChildA) && + edgeB.typeAndFieldEquals(edgeA) ) { + + edgeToMerge = edgeB; + } + } + + // if the edge from A was not found in B, + // add it to B. + if( edgeToMerge == null ) { + assert id2hrn.containsKey(idChildA); + HeapRegionNode hrnChildB = id2hrn.get(idChildA); + edgeToMerge = edgeA.copy(); + edgeToMerge.setSrc(vnB); + edgeToMerge.setDst(hrnChildB); + addRefEdge(vnB, hrnChildB, edgeToMerge); + } + // otherwise, the edge already existed in both graphs + // so merge their reachability sets + else { + // just replace this beta set with the union + edgeToMerge.setBeta(Canonical.unionORpreds(edgeToMerge.getBeta(), + edgeA.getBeta() + ) + ); + edgeToMerge.setPreds(Canonical.join(edgeToMerge.getPreds(), + edgeA.getPreds() + ) + ); + edgeToMerge.setTaints( + Canonical.union(edgeToMerge.getTaints(), + edgeA.getTaints() + ) + ); + } } } } @@ -3962,28 +3962,28 @@ public class ReachGraph { if( rg == null ) { if( dbgEquals ) { - System.out.println("rg is null"); + System.out.println("rg is null"); } return false; } if( !areHeapRegionNodesEqual(rg) ) { if( dbgEquals ) { - System.out.println("hrn not equal"); + System.out.println("hrn not equal"); } return false; } if( !areVariableNodesEqual(rg) ) { if( dbgEquals ) { - System.out.println("vars not equal"); + System.out.println("vars not equal"); } return false; } if( !areRefEdgesEqual(rg) ) { if( dbgEquals ) { - System.out.println("edges not equal"); + System.out.println("edges not equal"); } return false; } @@ -4024,12 +4024,12 @@ public class ReachGraph { HeapRegionNode hrnA = (HeapRegionNode) meA.getValue(); if( !rgB.id2hrn.containsKey(idA) ) { - return false; + return false; } HeapRegionNode hrnB = rgB.id2hrn.get(idA); if( !hrnA.equalsIncludingAlphaAndPreds(hrnB) ) { - return false; + return false; } } @@ -4058,7 +4058,7 @@ public class ReachGraph { TempDescriptor tdA = (TempDescriptor) meA.getKey(); if( !rgB.td2vn.containsKey(tdA) ) { - return false; + return false; } } @@ -4094,7 +4094,7 @@ public class ReachGraph { assert rgB.id2hrn.containsKey(idA); if( !areallREfromAequaltoB(rgA, hrnA, rgB) ) { - return false; + return false; } // then check every edge in B for presence in A, starting @@ -4102,7 +4102,7 @@ public class ReachGraph { HeapRegionNode hrnB = rgB.id2hrn.get(idA); if( !areallREfromAequaltoB(rgB, hrnB, rgA) ) { - return false; + return false; } } @@ -4119,7 +4119,7 @@ public class ReachGraph { assert rgB.td2vn.containsKey(tdA); if( !areallREfromAequaltoB(rgA, vnA, rgB) ) { - return false; + return false; } // then check every edge in B for presence in A, starting @@ -4127,7 +4127,7 @@ public class ReachGraph { VariableNode vnB = rgB.td2vn.get(tdA); if( !areallREfromAequaltoB(rgB, vnB, rgA) ) { - return false; + return false; } } @@ -4153,34 +4153,34 @@ public class ReachGraph { RefSrcNode rnB = null; if( rnA instanceof HeapRegionNode ) { - HeapRegionNode hrnA = (HeapRegionNode) rnA; - rnB = rgB.id2hrn.get(hrnA.getID() ); + HeapRegionNode hrnA = (HeapRegionNode) rnA; + rnB = rgB.id2hrn.get(hrnA.getID() ); } else { - VariableNode vnA = (VariableNode) rnA; - rnB = rgB.td2vn.get(vnA.getTempDescriptor() ); + VariableNode vnA = (VariableNode) rnA; + rnB = rgB.td2vn.get(vnA.getTempDescriptor() ); } Iterator itrB = rnB.iteratorToReferencees(); while( itrB.hasNext() ) { - RefEdge edgeB = itrB.next(); - HeapRegionNode hrnChildB = edgeB.getDst(); - Integer idChildB = hrnChildB.getID(); - - if( idChildA.equals(idChildB) && - edgeA.typeAndFieldEquals(edgeB) ) { - - // there is an edge in the right place with the right field, - // but do they have the same attributes? - if( edgeA.getBeta().equals(edgeB.getBeta() ) && - edgeA.equalsPreds(edgeB) - ) { - edgeFound = true; - } - } + RefEdge edgeB = itrB.next(); + HeapRegionNode hrnChildB = edgeB.getDst(); + Integer idChildB = hrnChildB.getID(); + + if( idChildA.equals(idChildB) && + edgeA.typeAndFieldEquals(edgeB) ) { + + // there is an edge in the right place with the right field, + // but do they have the same attributes? + if( edgeA.getBeta().equals(edgeB.getBeta() ) && + edgeA.equalsPreds(edgeB) + ) { + edgeFound = true; + } + } } if( !edgeFound ) { - return false; + return false; } } @@ -4202,8 +4202,8 @@ public class ReachGraph { HeapRegionNode hrnA = (HeapRegionNode) meA.getValue(); if( !rgB.id2hrn.containsKey(idA) ) { - System.out.println(" regions smaller"); - return false; + System.out.println(" regions smaller"); + return false; } //HeapRegionNode hrnB = rgB.id2hrn.get( idA ); @@ -4232,39 +4232,39 @@ public class ReachGraph { Iterator reItr = hrnA.iteratorToReferencers(); while( reItr.hasNext() ) { - RefEdge edgeA = reItr.next(); - RefSrcNode rsnA = edgeA.getSrc(); - - // we already checked that nodes were present - HeapRegionNode hrnB = rgB.id2hrn.get(hrnA.getID() ); - assert hrnB != null; - - RefSrcNode rsnB; - if( rsnA instanceof VariableNode ) { - VariableNode vnA = (VariableNode) rsnA; - rsnB = rgB.td2vn.get(vnA.getTempDescriptor() ); - - } else { - HeapRegionNode hrnSrcA = (HeapRegionNode) rsnA; - rsnB = rgB.id2hrn.get(hrnSrcA.getID() ); - } - assert rsnB != null; - - RefEdge edgeB = rsnB.getReferenceTo(hrnB, - edgeA.getType(), - edgeA.getField() - ); - if( edgeB == null ) { - System.out.println(" edges smaller:"); - return false; - } - - // REMEMBER, IS NO SMALLER THAN - /* - System.out.println( " edges smaller" ); - return false; - } - */ + RefEdge edgeA = reItr.next(); + RefSrcNode rsnA = edgeA.getSrc(); + + // we already checked that nodes were present + HeapRegionNode hrnB = rgB.id2hrn.get(hrnA.getID() ); + assert hrnB != null; + + RefSrcNode rsnB; + if( rsnA instanceof VariableNode ) { + VariableNode vnA = (VariableNode) rsnA; + rsnB = rgB.td2vn.get(vnA.getTempDescriptor() ); + + } else { + HeapRegionNode hrnSrcA = (HeapRegionNode) rsnA; + rsnB = rgB.id2hrn.get(hrnSrcA.getID() ); + } + assert rsnB != null; + + RefEdge edgeB = rsnB.getReferenceTo(hrnB, + edgeA.getType(), + edgeA.getField() + ); + if( edgeB == null ) { + System.out.println(" edges smaller:"); + return false; + } + + // REMEMBER, IS NO SMALLER THAN + /* + System.out.println( " edges smaller" ); + return false; + } + */ } } @@ -4340,7 +4340,7 @@ public class ReachGraph { assert tdSrcDeref != null; if( !typeUtil.isSuperorType(tdSrcDeref, td) ) { - return false; + return false; } return edge.getField().equals(DisjointAnalysis.arrayElementFieldName); @@ -4356,12 +4356,12 @@ public class ReachGraph { Iterator fieldItr = cd.getFields(); while( fieldItr.hasNext() ) { - FieldDescriptor fd = (FieldDescriptor) fieldItr.next(); + FieldDescriptor fd = (FieldDescriptor) fieldItr.next(); - if( fd.getType().equals(edge.getType() ) && - fd.getSymbol().equals(edge.getField() ) ) { - return true; - } + if( fd.getType().equals(edge.getType() ) && + fd.getSymbol().equals(edge.getField() ) ) { + return true; + } } cd = cd.getSuperDesc(); @@ -4454,25 +4454,25 @@ public class ReachGraph { // "cut-out" into a DOT cluster for visualization if( callerNodeIDsCopiedToCallee != null ) { - bw.write(" subgraph cluster0 {\n"); - bw.write(" color=blue;\n"); - - Iterator i = id2hrn.entrySet().iterator(); - while( i.hasNext() ) { - Map.Entry me = (Map.Entry)i.next(); - HeapRegionNode hrn = (HeapRegionNode) me.getValue(); - - if( callerNodeIDsCopiedToCallee.contains(hrn.getID() ) ) { - bw.write(" "+ - hrn.toString()+ - hrn.toStringDOT(hideReachability, - hideSubsetReachability, - hidePredicates)+ - ";\n"); - } - } - - bw.write(" }\n"); + bw.write(" subgraph cluster0 {\n"); + bw.write(" color=blue;\n"); + + Iterator i = id2hrn.entrySet().iterator(); + while( i.hasNext() ) { + Map.Entry me = (Map.Entry)i.next(); + HeapRegionNode hrn = (HeapRegionNode) me.getValue(); + + if( callerNodeIDsCopiedToCallee.contains(hrn.getID() ) ) { + bw.write(" "+ + hrn.toString()+ + hrn.toStringDOT(hideReachability, + hideSubsetReachability, + hidePredicates)+ + ";\n"); + } + } + + bw.write(" }\n"); } @@ -4481,29 +4481,29 @@ public class ReachGraph { // then visit every heap region node Iterator i = id2hrn.entrySet().iterator(); while( i.hasNext() ) { - Map.Entry me = (Map.Entry)i.next(); - HeapRegionNode hrn = (HeapRegionNode) me.getValue(); - - // only visit nodes worth writing out--for instance - // not every node at an allocation is referenced - // (think of it as garbage-collected), etc. - if( !pruneGarbage || - hrn.isOutOfContext() || - (hrn.isFlagged() && hrn.getID() > 0 && !hrn.isWiped()) // a non-shadow flagged node - ) { - - if( !visited.contains(hrn) ) { - traverseHeapRegionNodes(hrn, - bw, - null, - visited, - hideReachability, - hideSubsetReachability, - hidePredicates, - hideEdgeTaints, - callerNodeIDsCopiedToCallee); - } - } + Map.Entry me = (Map.Entry)i.next(); + HeapRegionNode hrn = (HeapRegionNode) me.getValue(); + + // only visit nodes worth writing out--for instance + // not every node at an allocation is referenced + // (think of it as garbage-collected), etc. + if( !pruneGarbage || + hrn.isOutOfContext() || + (hrn.isFlagged() && hrn.getID() > 0 && !hrn.isWiped()) // a non-shadow flagged node + ) { + + if( !visited.contains(hrn) ) { + traverseHeapRegionNodes(hrn, + bw, + null, + visited, + hideReachability, + hideSubsetReachability, + hidePredicates, + hideEdgeTaints, + callerNodeIDsCopiedToCallee); + } + } } bw.write(" graphTitle[label=\""+graphName+"\",shape=box];\n"); @@ -4511,49 +4511,49 @@ public class ReachGraph { // then visit every label node, useful for debugging if( writeLabels ) { - i = td2vn.entrySet().iterator(); - while( i.hasNext() ) { - Map.Entry me = (Map.Entry)i.next(); - VariableNode vn = (VariableNode) me.getValue(); - - if( labelSelect ) { - String labelStr = vn.getTempDescriptorString(); - if( labelStr.startsWith("___temp") || - labelStr.startsWith("___dst") || - labelStr.startsWith("___srctmp") || - labelStr.startsWith("___neverused") - ) { - continue; - } - } - - Iterator heapRegionsItr = vn.iteratorToReferencees(); - while( heapRegionsItr.hasNext() ) { - RefEdge edge = heapRegionsItr.next(); - HeapRegionNode hrn = edge.getDst(); - - if( !visited.contains(hrn) ) { - traverseHeapRegionNodes(hrn, - bw, - null, - visited, - hideReachability, - hideSubsetReachability, - hidePredicates, - hideEdgeTaints, - callerNodeIDsCopiedToCallee); - } - - bw.write(" "+vn.toString()+ - " -> "+hrn.toString()+ - edge.toStringDOT(hideReachability, - hideSubsetReachability, - hidePredicates, - hideEdgeTaints, - "")+ - ";\n"); - } - } + i = td2vn.entrySet().iterator(); + while( i.hasNext() ) { + Map.Entry me = (Map.Entry)i.next(); + VariableNode vn = (VariableNode) me.getValue(); + + if( labelSelect ) { + String labelStr = vn.getTempDescriptorString(); + if( labelStr.startsWith("___temp") || + labelStr.startsWith("___dst") || + labelStr.startsWith("___srctmp") || + labelStr.startsWith("___neverused") + ) { + continue; + } + } + + Iterator heapRegionsItr = vn.iteratorToReferencees(); + while( heapRegionsItr.hasNext() ) { + RefEdge edge = heapRegionsItr.next(); + HeapRegionNode hrn = edge.getDst(); + + if( !visited.contains(hrn) ) { + traverseHeapRegionNodes(hrn, + bw, + null, + visited, + hideReachability, + hideSubsetReachability, + hidePredicates, + hideEdgeTaints, + callerNodeIDsCopiedToCallee); + } + + bw.write(" "+vn.toString()+ + " -> "+hrn.toString()+ + edge.toStringDOT(hideReachability, + hideSubsetReachability, + hidePredicates, + hideEdgeTaints, + "")+ + ";\n"); + } + } } bw.write("}\n"); @@ -4602,48 +4602,48 @@ public class ReachGraph { if( callerNodeIDsCopiedToCallee != null && (edge.getSrc() instanceof HeapRegionNode) ) { - HeapRegionNode hrnSrc = (HeapRegionNode) edge.getSrc(); - if( callerNodeIDsCopiedToCallee.contains(hrnSrc.getID() ) && - callerNodeIDsCopiedToCallee.contains(edge.getDst().getID() ) - ) { - bw.write(" "+hrn.toString()+ - " -> "+hrnChild.toString()+ - edge.toStringDOT(hideReachability, - hideSubsetReachability, - hidePredicates, - hideEdgeTaints, - ",color=blue")+ - ";\n"); - } else if( !callerNodeIDsCopiedToCallee.contains(hrnSrc.getID() ) && - callerNodeIDsCopiedToCallee.contains(edge.getDst().getID() ) - ) { - bw.write(" "+hrn.toString()+ - " -> "+hrnChild.toString()+ - edge.toStringDOT(hideReachability, - hideSubsetReachability, - hidePredicates, - hideEdgeTaints, - ",color=blue,style=dashed")+ - ";\n"); - } else { - bw.write(" "+hrn.toString()+ - " -> "+hrnChild.toString()+ - edge.toStringDOT(hideReachability, - hideSubsetReachability, - hidePredicates, - hideEdgeTaints, - "")+ - ";\n"); - } + HeapRegionNode hrnSrc = (HeapRegionNode) edge.getSrc(); + if( callerNodeIDsCopiedToCallee.contains(hrnSrc.getID() ) && + callerNodeIDsCopiedToCallee.contains(edge.getDst().getID() ) + ) { + bw.write(" "+hrn.toString()+ + " -> "+hrnChild.toString()+ + edge.toStringDOT(hideReachability, + hideSubsetReachability, + hidePredicates, + hideEdgeTaints, + ",color=blue")+ + ";\n"); + } else if( !callerNodeIDsCopiedToCallee.contains(hrnSrc.getID() ) && + callerNodeIDsCopiedToCallee.contains(edge.getDst().getID() ) + ) { + bw.write(" "+hrn.toString()+ + " -> "+hrnChild.toString()+ + edge.toStringDOT(hideReachability, + hideSubsetReachability, + hidePredicates, + hideEdgeTaints, + ",color=blue,style=dashed")+ + ";\n"); + } else { + bw.write(" "+hrn.toString()+ + " -> "+hrnChild.toString()+ + edge.toStringDOT(hideReachability, + hideSubsetReachability, + hidePredicates, + hideEdgeTaints, + "")+ + ";\n"); + } } else { - bw.write(" "+hrn.toString()+ - " -> "+hrnChild.toString()+ - edge.toStringDOT(hideReachability, - hideSubsetReachability, - hidePredicates, - hideEdgeTaints, - "")+ - ";\n"); + bw.write(" "+hrn.toString()+ + " -> "+hrnChild.toString()+ + edge.toStringDOT(hideReachability, + hideSubsetReachability, + hidePredicates, + hideEdgeTaints, + "")+ + ";\n"); } traverseHeapRegionNodes(hrnChild, @@ -4677,7 +4677,7 @@ public class ReachGraph { for( int i = 0; i < as.getAllocationDepth(); ++i ) { Integer idI = as.getIthOldest(i); if( id2hrn.containsKey(idI) ) { - out.add(id2hrn.get(idI) ); + out.add(id2hrn.get(idI) ); } } @@ -4700,19 +4700,19 @@ public class ReachGraph { assert !hrn.isOutOfContext(); if( !includeARITY_ZEROORMORE ) { - out.add(ReachTuple.factory(hrn.getID(), - true, // multi-obj region - ReachTuple.ARITY_ZEROORMORE, - false) // ooc? - ); + out.add(ReachTuple.factory(hrn.getID(), + true, // multi-obj region + ReachTuple.ARITY_ZEROORMORE, + false) // ooc? + ); } if( includeARITY_ONE ) { - out.add(ReachTuple.factory(hrn.getID(), - true, // multi-object region - ReachTuple.ARITY_ONE, - false) // ooc? - ); + out.add(ReachTuple.factory(hrn.getID(), + true, // multi-object region + ReachTuple.ARITY_ONE, + false) // ooc? + ); } } @@ -4727,14 +4727,14 @@ public class ReachGraph { Integer idI = as.getIthOldest(i); if( id2hrn.containsKey(idI) ) { - HeapRegionNode hrn = id2hrn.get(idI); - assert !hrn.isOutOfContext(); + HeapRegionNode hrn = id2hrn.get(idI); + assert !hrn.isOutOfContext(); - out.add(ReachTuple.factory(hrn.getID(), - false, // multi-object region - ReachTuple.ARITY_ONE, - false) // ooc? - ); + out.add(ReachTuple.factory(hrn.getID(), + false, // multi-object region + ReachTuple.ARITY_ONE, + false) // ooc? + ); } } @@ -4764,16 +4764,16 @@ public class ReachGraph { Iterator rtItr1 = rtSet1.iterator(); while( rtItr1.hasNext() ) { - ReachTuple rt1 = rtItr1.next(); + ReachTuple rt1 = rtItr1.next(); - Iterator rtItr2 = rtSet2.iterator(); - while( rtItr2.hasNext() ) { - ReachTuple rt2 = rtItr2.next(); + Iterator rtItr2 = rtSet2.iterator(); + while( rtItr2.hasNext() ) { + ReachTuple rt2 = rtItr2.next(); - if( !hrn.getAlpha().getStatesWithBoth(rt1, rt2).isEmpty() ) { - return true; - } - } + if( !hrn.getAlpha().getStatesWithBoth(rt1, rt2).isEmpty() ) { + return true; + } + } } } @@ -4802,30 +4802,30 @@ public class ReachGraph { // if any ZERORMORE tuples are here, TRUE Iterator rtItr = rtSetZOM.iterator(); while( rtItr.hasNext() ) { - ReachTuple rtZOM = rtItr.next(); + ReachTuple rtZOM = rtItr.next(); - if( hrn.getAlpha().containsTuple(rtZOM) ) { - return true; - } + if( hrn.getAlpha().containsTuple(rtZOM) ) { + return true; + } } // otherwise, look for any pair of ONE tuples Iterator rtItr1 = rtSetONE.iterator(); while( rtItr1.hasNext() ) { - ReachTuple rt1 = rtItr1.next(); + ReachTuple rt1 = rtItr1.next(); - Iterator rtItr2 = rtSetONE.iterator(); - while( rtItr2.hasNext() ) { - ReachTuple rt2 = rtItr2.next(); + Iterator rtItr2 = rtSetONE.iterator(); + while( rtItr2.hasNext() ) { + ReachTuple rt2 = rtItr2.next(); - if( rt1 == rt2 ) { - continue; - } + if( rt1 == rt2 ) { + continue; + } - if( !hrn.getAlpha().getStatesWithBoth(rt1, rt2).isEmpty() ) { - return true; - } - } + if( !hrn.getAlpha().getStatesWithBoth(rt1, rt2).isEmpty() ) { + return true; + } + } } } @@ -4851,8 +4851,8 @@ public class ReachGraph { hrn.getAlpha() ); if( !intersection.isEmpty() ) { - assert !hrn.isOutOfContext(); - exhibitProofState.add(hrn); + assert !hrn.isOutOfContext(); + exhibitProofState.add(hrn); } } @@ -4974,7 +4974,7 @@ public class ReachGraph { if( !DISABLE_STRONG_UPDATES && !DISABLE_GLOBAL_SWEEP ) { - assert !common.isEmpty(); + assert !common.isEmpty(); } } @@ -5018,7 +5018,7 @@ public class ReachGraph { if( !DISABLE_STRONG_UPDATES && !DISABLE_GLOBAL_SWEEP ) { - assert !common.isEmpty(); + assert !common.isEmpty(); } } @@ -5134,11 +5134,11 @@ public class ReachGraph { // check sum2 against alloc1 nodes if(hrnSum2!=null) { for (int i = 0; i < as1.getAllocationDepth(); ++i) { - Integer idI1 = as1.getIthOldest(i); - assert id2hrn.containsKey(idI1); - HeapRegionNode hrnI1 = id2hrn.get(idI1); - assert hrnI1 != null; - common.addAll(mayReachSharedObjects(hrnI1, hrnSum2)); + Integer idI1 = as1.getIthOldest(i); + assert id2hrn.containsKey(idI1); + HeapRegionNode hrnI1 = id2hrn.get(idI1); + assert hrnI1 != null; + common.addAll(mayReachSharedObjects(hrnI1, hrnSum2)); } // also ask if objects from this summary share among each other @@ -5153,23 +5153,23 @@ public class ReachGraph { assert hrnI2 != null; if(hrnSum1!=null) { - common.addAll(mayReachSharedObjects(hrnSum1, hrnI2)); + common.addAll(mayReachSharedObjects(hrnSum1, hrnI2)); } // while we're at it, do an inner loop for alloc2 vs alloc1 nodes for (int j = 0; j < as1.getAllocationDepth(); ++j) { - Integer idI1 = as1.getIthOldest(j); + Integer idI1 = as1.getIthOldest(j); - // if these are the same site, don't look for the same token, no - // alias. - // different tokens of the same site could alias together though - if (idI1.equals(idI2)) { - continue; - } + // if these are the same site, don't look for the same token, no + // alias. + // different tokens of the same site could alias together though + if (idI1.equals(idI2)) { + continue; + } - HeapRegionNode hrnI1 = id2hrn.get(idI1); + HeapRegionNode hrnI1 = id2hrn.get(idI1); - common.addAll(mayReachSharedObjects(hrnI1, hrnI2)); + common.addAll(mayReachSharedObjects(hrnI1, hrnI2)); } } diff --git a/Robust/src/Analysis/Disjoint/ReachSet.java b/Robust/src/Analysis/Disjoint/ReachSet.java index a9157859..d821e96c 100644 --- a/Robust/src/Analysis/Disjoint/ReachSet.java +++ b/Robust/src/Analysis/Disjoint/ReachSet.java @@ -70,7 +70,7 @@ public class ReachSet extends Canonical { while( stateItr.hasNext() ) { ReachState stateThis = stateItr.next(); if( stateThis.equalsIgnorePreds(state) ) { - return stateThis; + return stateThis; } } @@ -97,14 +97,14 @@ public class ReachSet extends Canonical { while( itr.hasNext() ) { ReachState stateThis = itr.next(); if( strict ) { - if( !state.equals(stateThis) && - state.isSubset(stateThis) ) { - return true; - } + if( !state.equals(stateThis) && + state.isSubset(stateThis) ) { + return true; + } } else { - if( state.isSubset(stateThis) ) { - return true; - } + if( state.isSubset(stateThis) ) { + return true; + } } } @@ -117,7 +117,7 @@ public class ReachSet extends Canonical { while( itr.hasNext() ) { ReachState state = itr.next(); if( state.containsTuple(rt) ) { - return true; + return true; } } return false; @@ -133,7 +133,7 @@ public class ReachSet extends Canonical { ReachState state = itr.next(); if( state.containsTuple(rt1) && state.containsTuple(rt2) ) { - out.reachStates.add(state); + out.reachStates.add(state); } } @@ -148,12 +148,12 @@ public class ReachSet extends Canonical { for( int i = 0; i < v.size(); ++i ) { ReachState s1 = v.get(i); for( int j = i+1; j < v.size(); ++j ) { - ReachState s2 = v.get(j); - if( s1.equals(s2) ) { - assert s1.isCanonical(); - assert s2.isCanonical(); - return false; - } + ReachState s2 = v.get(j); + if( s1.equals(s2) ) { + assert s1.isCanonical(); + assert s2.isCanonical(); + return false; + } } } return true; @@ -189,12 +189,12 @@ public class ReachSet extends Canonical { // skip this if there is a superset already if( hideSubsetReachability && containsStrictSuperSet(state) ) { - continue; + continue; } s += state; if( i.hasNext() ) { - s += "\\n"; + s += "\\n"; } } @@ -217,13 +217,13 @@ public class ReachSet extends Canonical { Iterator i = this.iterator(); while( i.hasNext() ) { - ReachState state = i.next(); + ReachState state = i.next(); - if( containsStrictSuperSet(state) ) { - continue; - } + if( containsStrictSuperSet(state) ) { + continue; + } - toPrint = Canonical.add(toPrint, state); + toPrint = Canonical.add(toPrint, state); } } @@ -235,7 +235,7 @@ public class ReachSet extends Canonical { s += state; if( i.hasNext() ) { - s += "\n"; + s += "\n"; } } diff --git a/Robust/src/Analysis/Disjoint/ReachState.java b/Robust/src/Analysis/Disjoint/ReachState.java index f69f603a..1ea87ea7 100644 --- a/Robust/src/Analysis/Disjoint/ReachState.java +++ b/Robust/src/Analysis/Disjoint/ReachState.java @@ -100,7 +100,7 @@ public class ReachState extends Canonical { if( hrnID.equals(rt.getHrnID() ) && isOutOfContext == rt.isOutOfContext() ) { - return rt; + return rt; } } diff --git a/Robust/src/Analysis/Disjoint/RefEdge.java b/Robust/src/Analysis/Disjoint/RefEdge.java index 1bd65241..f8d8b0c6 100644 --- a/Robust/src/Analysis/Disjoint/RefEdge.java +++ b/Robust/src/Analysis/Disjoint/RefEdge.java @@ -275,7 +275,7 @@ public class RefEdge { if( !hideEdgeTaints ) { if( !taints.isEmpty() ) { - s += "\\n"+taints.toStringEscNewline(); + s += "\\n"+taints.toStringEscNewline(); } } diff --git a/Robust/src/Analysis/Disjoint/RefSrcNode.java b/Robust/src/Analysis/Disjoint/RefSrcNode.java index b1b4fef5..24ce4bd5 100644 --- a/Robust/src/Analysis/Disjoint/RefSrcNode.java +++ b/Robust/src/Analysis/Disjoint/RefSrcNode.java @@ -50,7 +50,7 @@ public abstract class RefSrcNode { edge.typeEquals(type) && edge.fieldEquals(field) ) { - return edge; + return edge; } } diff --git a/Robust/src/Analysis/Disjoint/SMFEState.java b/Robust/src/Analysis/Disjoint/SMFEState.java index 78508a4e..97cfc145 100644 --- a/Robust/src/Analysis/Disjoint/SMFEState.java +++ b/Robust/src/Analysis/Disjoint/SMFEState.java @@ -162,15 +162,15 @@ public class SMFEState { Iterator eItr = effects.iterator(); while( eItr.hasNext() ) { - Effect e = eItr.next(); - if (conflicts.contains(e)) { - s += "["+e.toString()+"]"; - } else { - s += e.toString(); - } - if( eItr.hasNext() ) { - s += "\\n"; - } + Effect e = eItr.next(); + if (conflicts.contains(e)) { + s += "["+e.toString()+"]"; + } else { + s += e.toString(); + } + if( eItr.hasNext() ) { + s += "\\n"; + } } } @@ -184,14 +184,14 @@ public class SMFEState { Iterator sItr = states.iterator(); while( sItr.hasNext() ) { - SMFEState state = sItr.next(); - - s += "\n "+ - id+" -> "+state.id+ - "[label=\""+e+", RC="+refCount+"\""; - if (conflicts.contains(e)) - s+=",style=dashed"; - s+="];"; + SMFEState state = sItr.next(); + + s += "\n "+ + id+" -> "+state.id+ + "[label=\""+e+", RC="+refCount+"\""; + if (conflicts.contains(e)) + s+=",style=dashed"; + s+="];"; } } diff --git a/Robust/src/Analysis/Disjoint/StateMachineForEffects.java b/Robust/src/Analysis/Disjoint/StateMachineForEffects.java index 780f1275..fea9044a 100644 --- a/Robust/src/Analysis/Disjoint/StateMachineForEffects.java +++ b/Robust/src/Analysis/Disjoint/StateMachineForEffects.java @@ -64,7 +64,7 @@ public class StateMachineForEffects { for(FlatNode fn : fn2state.keySet()) { SMFEState state=fn2state.get(fn); if (!state.getConflicts().isEmpty()) - return false; + return false; } return true; } @@ -143,8 +143,8 @@ public class StateMachineForEffects { Iterator fnItr = fn2state.keySet().iterator(); while( fnItr.hasNext() ) { - SMFEState state = fn2state.get(fnItr.next() ); - bw.write(state.toStringDOT()+"\n"); + SMFEState state = fn2state.get(fnItr.next() ); + bw.write(state.toStringDOT()+"\n"); } bw.write("}\n"); diff --git a/Robust/src/Analysis/Disjoint/TaintSet.java b/Robust/src/Analysis/Disjoint/TaintSet.java index 632987b5..bcbc883b 100644 --- a/Robust/src/Analysis/Disjoint/TaintSet.java +++ b/Robust/src/Analysis/Disjoint/TaintSet.java @@ -42,7 +42,7 @@ public class TaintSet extends Canonical { HashSet taintset=new HashSet(); for(Taint t : taints) { if (t.getWhereDefined()!=fn) { - t=t.reTaint(fn); + t=t.reTaint(fn); } taintset.add(t); } @@ -133,7 +133,7 @@ public class TaintSet extends Canonical { while( tItr.hasNext() ) { Taint tThis = tItr.next(); if( tThis.equalsIgnorePreds(t) ) { - return tThis; + return tThis; } } @@ -166,7 +166,7 @@ public class TaintSet extends Canonical { s += t.toString(); if( tItr.hasNext() ) { - s += ",\\n"; + s += ",\\n"; } } s += "]"; diff --git a/Robust/src/Analysis/FlatIRGraph/FlatIRGraph.java b/Robust/src/Analysis/FlatIRGraph/FlatIRGraph.java index 26f7f34b..7211dd99 100644 --- a/Robust/src/Analysis/FlatIRGraph/FlatIRGraph.java +++ b/Robust/src/Analysis/FlatIRGraph/FlatIRGraph.java @@ -39,9 +39,9 @@ public class FlatIRGraph { for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext(); ) { ClassDescriptor cd = (ClassDescriptor)it_classes.next(); for(Iterator it_methods=cd.getMethods(); it_methods.hasNext(); ) { - MethodDescriptor md = (MethodDescriptor)it_methods.next(); - FlatMethod fm = state.getMethodFlat(md); - writeFlatIRGraph(fm,cd.getSymbol()+"."+md.getSymbol()); + MethodDescriptor md = (MethodDescriptor)it_methods.next(); + FlatMethod fm = state.getMethodFlat(md); + writeFlatIRGraph(fm,cd.getSymbol()+"."+md.getSymbol()); } } } @@ -71,19 +71,19 @@ public class FlatIRGraph { visited.add(fn); if( fn.kind() == FKind.FlatMethod ) { - // FlatMethod does not have toString - flatbw.write(makeDotNodeDec(graphname, flatnodetolabel.get(fn), fn.getClass().getName(), "FlatMethod") ); + // FlatMethod does not have toString + flatbw.write(makeDotNodeDec(graphname, flatnodetolabel.get(fn), fn.getClass().getName(), "FlatMethod") ); } else { - flatbw.write(makeDotNodeDec(graphname, flatnodetolabel.get(fn), fn.getClass().getName(), fn.toString() ) ); + flatbw.write(makeDotNodeDec(graphname, flatnodetolabel.get(fn), fn.getClass().getName(), fn.toString() ) ); } for(int i=0; i node"+flatnodetolabel.get(nn)+";\n"); + FlatNode nn=fn.getNext(i); + flatbw.write(" node"+flatnodetolabel.get(fn)+" -> node"+flatnodetolabel.get(nn)+";\n"); - if( !visited.contains(nn) ) { - toVisit.add(nn); - } + if( !visited.contains(nn) ) { + toVisit.add(nn); + } } } @@ -97,7 +97,7 @@ public class FlatIRGraph { for(int i=0; i exits=getJumps(fn); - output.println("if(RESTOREBRANCH())"); - output.println("goto L"+nodetolabels.get(exits.get(1))+";"); - output.println("else"); - output.println("goto L"+nodetolabels.get(exits.get(0))+";"); + Vector exits=getJumps(fn); + output.println("if(RESTOREBRANCH())"); + output.println("goto L"+nodetolabels.get(exits.get(1))+";"); + output.println("else"); + output.println("goto L"+nodetolabels.get(exits.get(0))+";"); } else { - Vector exits=getJumps(fn); - output.println("switch(RESTOREBRANCH()) {"); - for(int i=0; i exits=getJumps(fn); + output.println("switch(RESTOREBRANCH()) {"); + for(int i=0; i fnit=transset.iterator(); fnit.hasNext(); ) { FlatNode fn=fnit.next(); if ((fn.numNext()>1&&storeset.contains(fn))||fn.kind()==FKind.FlatBackEdge||fn.kind()==FKind.FlatNop) { - FlatNode[] children=fnmap.get(fn); - if (children==null) - continue; - if (!groupmap.containsKey(fn)) { - groupmap.put(fn, new HashSet()); - groupmap.get(fn).add(fn); - } - for(int i=0; i1&&storeset.contains(child))||child.kind()==FKind.FlatBackEdge||child.kind()==FKind.FlatNop) { - mergegroups(fn, child, groupmap); - } - } + FlatNode[] children=fnmap.get(fn); + if (children==null) + continue; + if (!groupmap.containsKey(fn)) { + groupmap.put(fn, new HashSet()); + groupmap.get(fn).add(fn); + } + for(int i=0; i1&&storeset.contains(child))||child.kind()==FKind.FlatBackEdge||child.kind()==FKind.FlatNop) { + mergegroups(fn, child, groupmap); + } + } } } //now we have groupings... @@ -136,17 +136,17 @@ public class BranchAnalysis { Vector exits=new Vector(); table.put(group, exits); for(Iterator fnit=group.iterator(); fnit.hasNext(); ) { - FlatNode fn=fnit.next(); - FlatNode[] nextnodes=fnmap.get(fn); - for(int i=0; i fnit=groupmap.get(fn2).iterator(); fnit.hasNext(); ) { - FlatNode fn3=fnit.next(); - groupmap.put(fn3, groupmap.get(fn1)); + FlatNode fn3=fnit.next(); + groupmap.put(fn3, groupmap.get(fn1)); } } } @@ -180,43 +180,43 @@ public class BranchAnalysis { Set incomingtuples=new HashSet(); for(int i=0; i tuple=fntotuple.get(fprev); - if (tuple!=null) - incomingtuples.addAll(tuple); - } + FlatNode fprev=fn.getPrev(i); + if (nodeset.contains(fprev)||storeset.contains(fprev)) { + for(int j=0; j tuple=fntotuple.get(fprev); + if (tuple!=null) + incomingtuples.addAll(tuple); + } } if (nodeset.contains(fn)||storeset.contains(fn)||fn.kind()==FKind.FlatAtomicExitNode) { - //nodeset contains this node - for(Iterator it=incomingtuples.iterator(); it.hasNext(); ) { - Object[] pair=it.next(); - int index=((Integer)pair[0]).intValue(); - FlatNode node=(FlatNode)pair[1]; - if (!fnmap.containsKey(node)) - fnmap.put(node, new FlatNode[node.numNext()]); - fnmap.get(node)[index]=fn; - } - incomingtuples=new HashSet(); + //nodeset contains this node + for(Iterator it=incomingtuples.iterator(); it.hasNext(); ) { + Object[] pair=it.next(); + int index=((Integer)pair[0]).intValue(); + FlatNode node=(FlatNode)pair[1]; + if (!fnmap.containsKey(node)) + fnmap.put(node, new FlatNode[node.numNext()]); + fnmap.get(node)[index]=fn; + } + incomingtuples=new HashSet(); } //add if we need to update if (!fntotuple.containsKey(fn)|| !fntotuple.get(fn).equals(incomingtuples)) { - fntotuple.put(fn,incomingtuples); - for(int i=0; i0||fn.kind()==FKind.FlatAtomicExitNode) - transset.add(fn); + transset.add(fn); } return transset; } diff --git a/Robust/src/Analysis/Locality/DCWrapper.java b/Robust/src/Analysis/Locality/DCWrapper.java index 9decb4c1..3e0f692a 100644 --- a/Robust/src/Analysis/Locality/DCWrapper.java +++ b/Robust/src/Analysis/Locality/DCWrapper.java @@ -139,33 +139,33 @@ public class DCWrapper { FlatNode fn=fnit.next(); if (fn.kind()==FKind.FlatAtomicEnterNode&& locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0) { - Set transSet=computeTrans(lb, fn); - Set tCheckSet=intersect(checkset, transSet); - Set tRecordSet=intersect(recordset, transSet); - Set tOtherSet=intersect(otherset, transSet); - Set tNotReadySet=intersect(notreadyset, transSet); - HashSet tCannotDelay=intersect(cannotdelay, transSet); - Set tderef=(state.STMARRAY&&!state.DUALVIEW)?intersect(derefset, transSet):null; - - if (checkSet(fn, tCheckSet, tRecordSet, lb)) { - //We will convert this one - nrecordset.addAll(tRecordSet); - notherset.addAll(tOtherSet); - nnotready.addAll(tNotReadySet); - ncannotdelay.addAll(tCannotDelay); - if (state.STMARRAY&&!state.DUALVIEW) - nderef.addAll(tderef); - transmap.get(lb).add(fn); - convset.addAll(transSet); - } else { - ncannotdelay.addAll(transSet); - } - if (!lwmap.containsKey(lb)) - lwmap.put(lb, new HashSet()); - lwmap.get(lb).add(fn); + Set transSet=computeTrans(lb, fn); + Set tCheckSet=intersect(checkset, transSet); + Set tRecordSet=intersect(recordset, transSet); + Set tOtherSet=intersect(otherset, transSet); + Set tNotReadySet=intersect(notreadyset, transSet); + HashSet tCannotDelay=intersect(cannotdelay, transSet); + Set tderef=(state.STMARRAY&&!state.DUALVIEW)?intersect(derefset, transSet):null; + + if (checkSet(fn, tCheckSet, tRecordSet, lb)) { + //We will convert this one + nrecordset.addAll(tRecordSet); + notherset.addAll(tOtherSet); + nnotready.addAll(tNotReadySet); + ncannotdelay.addAll(tCannotDelay); + if (state.STMARRAY&&!state.DUALVIEW) + nderef.addAll(tderef); + transmap.get(lb).add(fn); + convset.addAll(transSet); + } else { + ncannotdelay.addAll(transSet); + } + if (!lwmap.containsKey(lb)) + lwmap.put(lb, new HashSet()); + lwmap.get(lb).add(fn); } else { - if (locality.getAtomic(lb).get(fn).intValue()==0) - ncannotdelay.add(fn); + if (locality.getAtomic(lb).get(fn).intValue()==0) + ncannotdelay.add(fn); } } } @@ -194,10 +194,10 @@ public class DCWrapper { FlatNode fn=fnit.next(); //needs transread if (!state.READSET&&dc.getNeedTrans(lb, fn)||state.READSET&&dc.getNeedWriteTrans(lb, fn)||fn.kind()==FKind.FlatCall) { - System.out.println("False because"+fn); - if (!state.HYBRID) - return true; - return false; + System.out.println("False because"+fn); + if (!state.HYBRID) + return true; + return false; } } optmap.get(lb).add(faen); @@ -213,10 +213,10 @@ public class DCWrapper { toProcess.remove(fn); transSet.add(fn); if (locality.getAtomic(lb).get(fn).intValue()==0) - continue; + continue; for(int i=0; i cannotdelay=cannotdelaymap.get(lb); - HashSet notreadyset=computeNotReadySet(lb, cannotdelay); - HashSet otherset=new HashSet(); - otherset.addAll(fm.getNodeSet()); - otherset.removeAll(notreadyset); - otherset.removeAll(cannotdelay); - if (state.MINIMIZE) { - Hashtable atomicmap=locality.getAtomic(lb); - for(Iterator fnit=otherset.iterator(); fnit.hasNext(); ) { - FlatNode fn=fnit.next(); - if (atomicmap.get(fn).intValue()>0&& - fn.kind()!=FKind.FlatAtomicEnterNode&& - fn.kind()!=FKind.FlatGlobalConvNode) { - //remove non-atomic flatnodes - fnit.remove(); - notreadyset.add(fn); - } - } - } - - notreadymap.put(lb, notreadyset); - othermap.put(lb, otherset); + HashSet cannotdelay=cannotdelaymap.get(lb); + HashSet notreadyset=computeNotReadySet(lb, cannotdelay); + HashSet otherset=new HashSet(); + otherset.addAll(fm.getNodeSet()); + otherset.removeAll(notreadyset); + otherset.removeAll(cannotdelay); + if (state.MINIMIZE) { + Hashtable atomicmap=locality.getAtomic(lb); + for(Iterator fnit=otherset.iterator(); fnit.hasNext(); ) { + FlatNode fn=fnit.next(); + if (atomicmap.get(fn).intValue()>0&& + fn.kind()!=FKind.FlatAtomicEnterNode&& + fn.kind()!=FKind.FlatGlobalConvNode) { + //remove non-atomic flatnodes + fnit.remove(); + notreadyset.add(fn); + } + } + } + + notreadymap.put(lb, notreadyset); + othermap.put(lb, otherset); } //We now have: @@ -117,25 +117,25 @@ public class DelayComputation { FlatNode fn=fnit.next(); Hashtable> tempmap=fnmap.get(fn); if (fn.kind()==FKind.FlatSetElementNode) { - FlatSetElementNode fsen=(FlatSetElementNode) fn; - Set tfpset=tempmap.get(fsen.getDst()); - if (tfpset!=null) { - for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { - TempFlatPair tfp=tfpit.next(); - if (storeset.contains(tfp.f)) - writeset.add(tfp.f); - } - } + FlatSetElementNode fsen=(FlatSetElementNode) fn; + Set tfpset=tempmap.get(fsen.getDst()); + if (tfpset!=null) { + for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { + TempFlatPair tfp=tfpit.next(); + if (storeset.contains(tfp.f)) + writeset.add(tfp.f); + } + } } else if (fn.kind()==FKind.FlatSetFieldNode) { - FlatSetFieldNode fsfn=(FlatSetFieldNode) fn; - Set tfpset=tempmap.get(fsfn.getDst()); - if (tfpset!=null) { - for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { - TempFlatPair tfp=tfpit.next(); - if (storeset.contains(tfp.f)) - writeset.add(tfp.f); - } - } + FlatSetFieldNode fsfn=(FlatSetFieldNode) fn; + Set tfpset=tempmap.get(fsfn.getDst()); + if (tfpset!=null) { + for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { + TempFlatPair tfp=tfpit.next(); + if (storeset.contains(tfp.f)) + writeset.add(tfp.f); + } + } } } return writeset; @@ -175,8 +175,8 @@ public class DelayComputation { List writes=Arrays.asList(fn.writesTemps()); tempset.addAll(writes); if (!recordset.contains(fn)) { - List reads=Arrays.asList(fn.readsTemps()); - tempset.addAll(reads); + List reads=Arrays.asList(fn.readsTemps()); + tempset.addAll(reads); } } @@ -204,19 +204,19 @@ public class DelayComputation { for(Iterator fnit=secondpart.iterator(); fnit.hasNext(); ) { FlatNode fn=fnit.next(); if (recordset.contains(fn)) - continue; + continue; TempDescriptor readset[]=fn.readsTemps(); for(int i=0; i fnset=reachingdefs.get(fn).get(rtmp); - for(Iterator fnit2=fnset.iterator(); fnit2.hasNext(); ) { - FlatNode fn2=fnit2.next(); - if (secondpart.contains(fn2)) - continue; - //otherwise we mark this as live in - liveinto.add(rtmp); - break; - } + TempDescriptor rtmp=readset[i]; + Set fnset=reachingdefs.get(fn).get(rtmp); + for(Iterator fnit2=fnset.iterator(); fnit2.hasNext(); ) { + FlatNode fn2=fnit2.next(); + if (secondpart.contains(fn2)) + continue; + //otherwise we mark this as live in + liveinto.add(rtmp); + break; + } } } return liveinto; @@ -245,23 +245,23 @@ public class DelayComputation { //Look for reaching defs for all live variables that are in the secondpart for(Iterator tmpit=tempset.iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - Set fnset=reachmap.get(tmp); - boolean outsidenode=false; - boolean insidenode=false; - - for(Iterator fnit2=fnset.iterator(); fnit2.hasNext(); ) { - FlatNode fn2=fnit2.next(); - if (secondpart.contains(fn2)) { - insidenode=true; - } else if (!atomicnodes.contains(fn2)) { - outsidenode=true; - } - if (outsidenode&&insidenode) { - liveset.add(tmp); - break; - } - } + TempDescriptor tmp=tmpit.next(); + Set fnset=reachmap.get(tmp); + boolean outsidenode=false; + boolean insidenode=false; + + for(Iterator fnit2=fnset.iterator(); fnit2.hasNext(); ) { + FlatNode fn2=fnit2.next(); + if (secondpart.contains(fn2)) { + insidenode=true; + } else if (!atomicnodes.contains(fn2)) { + outsidenode=true; + } + if (outsidenode&&insidenode) { + liveset.add(tmp); + break; + } + } } } return liveset; @@ -290,19 +290,19 @@ public class DelayComputation { //Look for reaching defs for all live variables that are in the secondpart for(Iterator tmpit=tempset.iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - Set fnset=reachmap.get(tmp); - if (fnset==null) { - System.out.println("null temp set for"+fn+" tmp="+tmp); - System.out.println(fm.printMethod()); - } - for(Iterator fnit2=fnset.iterator(); fnit2.hasNext(); ) { - FlatNode fn2=fnit2.next(); - if (secondpart.contains(fn2)) { - liveset.add(tmp); - break; - } - } + TempDescriptor tmp=tmpit.next(); + Set fnset=reachmap.get(tmp); + if (fnset==null) { + System.out.println("null temp set for"+fn+" tmp="+tmp); + System.out.println(fm.printMethod()); + } + for(Iterator fnit2=fnset.iterator(); fnit2.hasNext(); ) { + FlatNode fn2=fnit2.next(); + if (secondpart.contains(fn2)) { + liveset.add(tmp); + break; + } + } } } return liveset; @@ -338,40 +338,40 @@ public class DelayComputation { for(Iterator fnit=fm.getNodeSet().iterator(); fnit.hasNext(); ) { FlatNode fn=fnit.next(); if (fn.kind()==FKind.FlatAtomicExitNode) { - Set livetemps=livemap.get(fn); - Hashtable> tempmap=reachingdefsmap.get(fn); - - //Iterate over the temps that are live into this node - for(Iterator tmpit=livetemps.iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - Set fnset=tempmap.get(tmp); - boolean inpart1=false; - boolean inpart2=false; - - //iterate over the reaching definitions for the temp - for(Iterator fnit2=fnset.iterator(); fnit2.hasNext(); ) { - FlatNode fn2=fnit2.next(); - if (delayedset.contains(fn2)) { - inpart2=true; - if (inpart1) - break; - } else if (otherset.contains(fn2)||cannotdelayset.contains(fn2)) { - inpart1=true; - if (inpart2) - break; - } - } - if (inpart1&&inpart2) { - for(Iterator fnit2=fnset.iterator(); fnit2.hasNext(); ) { - FlatNode fn2=fnit2.next(); - if ((otherset.contains(fn2)||cannotdelayset.contains(fn2))&& - locality.getAtomic(lb).get(fn2).intValue()>0) { - unionset.add(fn2); - livenodes.add(fn2); - } - } - } - } + Set livetemps=livemap.get(fn); + Hashtable> tempmap=reachingdefsmap.get(fn); + + //Iterate over the temps that are live into this node + for(Iterator tmpit=livetemps.iterator(); tmpit.hasNext(); ) { + TempDescriptor tmp=tmpit.next(); + Set fnset=tempmap.get(tmp); + boolean inpart1=false; + boolean inpart2=false; + + //iterate over the reaching definitions for the temp + for(Iterator fnit2=fnset.iterator(); fnit2.hasNext(); ) { + FlatNode fn2=fnit2.next(); + if (delayedset.contains(fn2)) { + inpart2=true; + if (inpart1) + break; + } else if (otherset.contains(fn2)||cannotdelayset.contains(fn2)) { + inpart1=true; + if (inpart2) + break; + } + } + if (inpart1&&inpart2) { + for(Iterator fnit2=fnset.iterator(); fnit2.hasNext(); ) { + FlatNode fn2=fnit2.next(); + if ((otherset.contains(fn2)||cannotdelayset.contains(fn2))&& + locality.getAtomic(lb).get(fn2).intValue()>0) { + unionset.add(fn2); + livenodes.add(fn2); + } + } + } + } } } @@ -385,86 +385,86 @@ public class DelayComputation { //Don't process non-atomic nodes if (locality.getAtomic(lb).get(fn).intValue()==0) { - if (!map.containsKey(fn)) { - map.put(fn, new Hashtable>()); - //enqueue next nodes - for(int i=0; i>()); + //enqueue next nodes + for(int i=0; i liveset=livemap.get(fn); //Do merge on incoming edges for(int i=0; i> prevmap=map.get(fnprev); - if (prevmap!=null) - for(Iterator tmpit=prevmap.keySet().iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - if (!liveset.contains(tmp)) //skip dead temps - continue; - if (!tmptofn.containsKey(tmp)) - tmptofn.put(tmp, new HashSet()); - tmptofn.get(tmp).addAll(prevmap.get(tmp)); - } + FlatNode fnprev=fn.getPrev(i); + Hashtable> prevmap=map.get(fnprev); + if (prevmap!=null) + for(Iterator tmpit=prevmap.keySet().iterator(); tmpit.hasNext(); ) { + TempDescriptor tmp=tmpit.next(); + if (!liveset.contains(tmp)) //skip dead temps + continue; + if (!tmptofn.containsKey(tmp)) + tmptofn.put(tmp, new HashSet()); + tmptofn.get(tmp).addAll(prevmap.get(tmp)); + } } if (delayedset.contains(fn)) { - if(state.STMARRAY&&!state.DUALVIEW&&derefset.contains(fn)) { - //FlatElementNodes don't read anything... - if (fn.kind()==FKind.FlatSetElementNode) { - //check only the source read tmp - TempDescriptor tmp=((FlatSetElementNode)fn).getSrc(); - if (tmptofn.containsKey(tmp)) { - livenodes.addAll(tmptofn.get(tmp)); //Add live nodes - unionset.addAll(tmptofn.get(tmp)); - } - } - } else { - //If the node is in the second set, check our readset - TempDescriptor readset[]=fn.readsTemps(); - for(int i=0; i set=new HashSet(); - tmptofn.put(tmp,set); - set.add(fn); - } - if (fn.numNext()>1) { - Set branchset=branchmap.get((FlatCondBranch)fn); - for(Iterator brit=branchset.iterator(); brit.hasNext(); ) { - FlatNode brfn=brit.next(); - if (unionset.contains(brfn)) { - //This branch is important--need to remember how it goes - livenodes.add(fn); - unionset.add(fn); - } - } - } + //If the node is in the first set, search over what we write + //We write -- our reads are done + TempDescriptor writeset[]=fn.writesTemps(); + for(int i=0; i set=new HashSet(); + tmptofn.put(tmp,set); + set.add(fn); + } + if (fn.numNext()>1) { + Set branchset=branchmap.get((FlatCondBranch)fn); + for(Iterator brit=branchset.iterator(); brit.hasNext(); ) { + FlatNode brfn=brit.next(); + if (unionset.contains(brfn)) { + //This branch is important--need to remember how it goes + livenodes.add(fn); + unionset.add(fn); + } + } + } } if (!map.containsKey(fn)||!map.get(fn).equals(tmptofn)) { - map.put(fn, tmptofn); - //enqueue next ndoes - for(int i=0; i0; if (!isatomic) - continue; + continue; boolean isnodelay=false; /* Compute incoming nodelay sets */ @@ -550,234 +550,234 @@ public class DelayComputation { HashSet nodelayfieldrdset=new HashSet(); HashSet nodelayarrayrdset=new HashSet(); for(int i=0; i branchset=revbranchmap.get((FlatCondBranch)fn); - for(Iterator brit=branchset.iterator(); brit.hasNext(); ) { - FlatNode branchnode=brit.next(); - if (cannotdelay.contains(branchnode)||(state.STMARRAY&&!state.DUALVIEW&&derefset.contains(branchnode))) { - isnodelay=true; - break; - } - } + Set branchset=revbranchmap.get((FlatCondBranch)fn); + for(Iterator brit=branchset.iterator(); brit.hasNext(); ) { + FlatNode branchnode=brit.next(); + if (cannotdelay.contains(branchnode)||(state.STMARRAY&&!state.DUALVIEW&&derefset.contains(branchnode))) { + isnodelay=true; + break; + } + } } //Check for field conflicts if (fn.kind()==FKind.FlatSetFieldNode) { - FieldDescriptor fd=((FlatSetFieldNode)fn).getField(); - //write conflicts - if (nodelayfieldwrset.contains(fd)) - isnodelay=true; - //read - if (nodelayfieldrdset.contains(fd)) - isnodelay=true; + FieldDescriptor fd=((FlatSetFieldNode)fn).getField(); + //write conflicts + if (nodelayfieldwrset.contains(fd)) + isnodelay=true; + //read + if (nodelayfieldrdset.contains(fd)) + isnodelay=true; } if (fn.kind()==FKind.FlatFieldNode) { - FieldDescriptor fd=((FlatFieldNode)fn).getField(); - //write conflicts - if (nodelayfieldwrset.contains(fd)) - isnodelay=true; + FieldDescriptor fd=((FlatFieldNode)fn).getField(); + //write conflicts + if (nodelayfieldwrset.contains(fd)) + isnodelay=true; } //Check for array conflicts if (fn.kind()==FKind.FlatSetElementNode) { - TypeDescriptor td=((FlatSetElementNode)fn).getDst().getType(); - //check for write conflicts - if (nodelayarraywrset.contains(td)) - isnodelay=true; - //check for read conflicts - if (nodelayarrayrdset.contains(td)) - isnodelay=true; + TypeDescriptor td=((FlatSetElementNode)fn).getDst().getType(); + //check for write conflicts + if (nodelayarraywrset.contains(td)) + isnodelay=true; + //check for read conflicts + if (nodelayarrayrdset.contains(td)) + isnodelay=true; } if (fn.kind()==FKind.FlatElementNode) { - TypeDescriptor td=((FlatElementNode)fn).getSrc().getType(); - //check for write conflicts - if (nodelayarraywrset.contains(td)) - isnodelay=true; + TypeDescriptor td=((FlatElementNode)fn).getSrc().getType(); + //check for write conflicts + if (nodelayarraywrset.contains(td)) + isnodelay=true; } //If we are no delay, then the temps we read are no delay if (isnodelay) { - /* Add our read set */ - TempDescriptor readset[]=fn.readsTemps(); - for(int i=0; i fcbset=branchmap.get(fn); - for(Iterator fcbit=fcbset.iterator(); fcbit.hasNext(); ) { - FlatCondBranch fcb=fcbit.next(); - //enqueue flatcondbranch node for reanalysis - if (!cannotdelay.contains(fcb)) { - cannotdelay.add(fcb); - toanalyze.add(fcb); - } - } - } - /* Do we write to fields */ - if (fn.kind()==FKind.FlatSetFieldNode) { - nodelayfieldwrset.add(((FlatSetFieldNode)fn).getField()); - } - /* Do we read from fields */ - if (fn.kind()==FKind.FlatFieldNode) { - nodelayfieldrdset.add(((FlatFieldNode)fn).getField()); - } - /* Do we write to arrays */ - if (fn.kind()==FKind.FlatSetElementNode) { - //have to do expansion - nodelayarraywrset.addAll(typeanalysis.expand(((FlatSetElementNode)fn).getDst().getType())); - } - /* Do we read from arrays */ - if (fn.kind()==FKind.FlatElementNode) { - //have to do expansion - nodelayarrayrdset.addAll(typeanalysis.expand(((FlatElementNode)fn).getSrc().getType())); - } - - //See if flatnode is definitely no delay - if (fn.kind()==FKind.FlatCall) { - //Have to deal with fields/arrays - FlatCall fcall=(FlatCall)fn; - MethodDescriptor mdcall=fcall.getMethod(); - nodelayfieldwrset.addAll(gft.getFieldsAll(mdcall)); - nodelayarraywrset.addAll(typeanalysis.expandSet(gft.getArraysAll(mdcall))); - //Have to deal with field/array reads - nodelayfieldrdset.addAll(gft.getFieldsRdAll(mdcall)); - nodelayarrayrdset.addAll(typeanalysis.expandSet(gft.getArraysRdAll(mdcall))); - } + /* Add our read set */ + TempDescriptor readset[]=fn.readsTemps(); + for(int i=0; i fcbset=branchmap.get(fn); + for(Iterator fcbit=fcbset.iterator(); fcbit.hasNext(); ) { + FlatCondBranch fcb=fcbit.next(); + //enqueue flatcondbranch node for reanalysis + if (!cannotdelay.contains(fcb)) { + cannotdelay.add(fcb); + toanalyze.add(fcb); + } + } + } + /* Do we write to fields */ + if (fn.kind()==FKind.FlatSetFieldNode) { + nodelayfieldwrset.add(((FlatSetFieldNode)fn).getField()); + } + /* Do we read from fields */ + if (fn.kind()==FKind.FlatFieldNode) { + nodelayfieldrdset.add(((FlatFieldNode)fn).getField()); + } + /* Do we write to arrays */ + if (fn.kind()==FKind.FlatSetElementNode) { + //have to do expansion + nodelayarraywrset.addAll(typeanalysis.expand(((FlatSetElementNode)fn).getDst().getType())); + } + /* Do we read from arrays */ + if (fn.kind()==FKind.FlatElementNode) { + //have to do expansion + nodelayarrayrdset.addAll(typeanalysis.expand(((FlatElementNode)fn).getSrc().getType())); + } + + //See if flatnode is definitely no delay + if (fn.kind()==FKind.FlatCall) { + //Have to deal with fields/arrays + FlatCall fcall=(FlatCall)fn; + MethodDescriptor mdcall=fcall.getMethod(); + nodelayfieldwrset.addAll(gft.getFieldsAll(mdcall)); + nodelayarraywrset.addAll(typeanalysis.expandSet(gft.getArraysAll(mdcall))); + //Have to deal with field/array reads + nodelayfieldrdset.addAll(gft.getFieldsRdAll(mdcall)); + nodelayarrayrdset.addAll(typeanalysis.expandSet(gft.getArraysRdAll(mdcall))); + } } else { - //Need to know which objects to lock on - Set oldtemps=oldtempmap.get(fn); - switch(fn.kind()) { - case FKind.FlatSetFieldNode: { - FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; - if (oldtemps.contains(fsfn.getDst())) { - nodelaytempset.add(fsfn.getDst()); - } - break; - } - - case FKind.FlatSetElementNode: { - FlatSetElementNode fsen=(FlatSetElementNode)fn; - if (oldtemps.contains(fsen.getDst())) { - nodelaytempset.add(fsen.getDst()); - //Word Array support requires index - if (state.STMARRAY&&!state.DUALVIEW) { - nodelaytempset.add(fsen.getIndex()); - derefset.add(fsen); - } - } - break; - } - - case FKind.FlatFieldNode: { - FlatFieldNode ffn=(FlatFieldNode)fn; - if (oldtemps.contains(ffn.getSrc())&& - dcopts.getFields().contains(ffn.getField())) { - nodelaytempset.add(ffn.getSrc()); - } - break; - } - - case FKind.FlatElementNode: { - FlatElementNode fen=(FlatElementNode)fn; - if (oldtemps.contains(fen.getSrc())&& - dcopts.getArrays().contains(fen.getSrc().getType())) { - nodelaytempset.add(fen.getSrc()); - //Word Array support requires index - if (state.STMARRAY&&!state.DUALVIEW) { - nodelaytempset.add(fen.getIndex()); - derefset.add(fen); - } - } - break; - } - } + //Need to know which objects to lock on + Set oldtemps=oldtempmap.get(fn); + switch(fn.kind()) { + case FKind.FlatSetFieldNode: { + FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; + if (oldtemps.contains(fsfn.getDst())) { + nodelaytempset.add(fsfn.getDst()); + } + break; + } + + case FKind.FlatSetElementNode: { + FlatSetElementNode fsen=(FlatSetElementNode)fn; + if (oldtemps.contains(fsen.getDst())) { + nodelaytempset.add(fsen.getDst()); + //Word Array support requires index + if (state.STMARRAY&&!state.DUALVIEW) { + nodelaytempset.add(fsen.getIndex()); + derefset.add(fsen); + } + } + break; + } + + case FKind.FlatFieldNode: { + FlatFieldNode ffn=(FlatFieldNode)fn; + if (oldtemps.contains(ffn.getSrc())&& + dcopts.getFields().contains(ffn.getField())) { + nodelaytempset.add(ffn.getSrc()); + } + break; + } + + case FKind.FlatElementNode: { + FlatElementNode fen=(FlatElementNode)fn; + if (oldtemps.contains(fen.getSrc())&& + dcopts.getArrays().contains(fen.getSrc().getType())) { + nodelaytempset.add(fen.getSrc()); + //Word Array support requires index + if (state.STMARRAY&&!state.DUALVIEW) { + nodelaytempset.add(fen.getIndex()); + derefset.add(fen); + } + } + break; + } + } } boolean changed=false; //See if we need to propagate changes if (!nodelaytemps.containsKey(fn)|| !nodelaytemps.get(fn).equals(nodelaytempset)) { - nodelaytemps.put(fn, nodelaytempset); - changed=true; + nodelaytemps.put(fn, nodelaytempset); + changed=true; } //See if we need to propagate changes if (!nodelayfieldswr.containsKey(fn)|| !nodelayfieldswr.get(fn).equals(nodelayfieldwrset)) { - nodelayfieldswr.put(fn, nodelayfieldwrset); - changed=true; + nodelayfieldswr.put(fn, nodelayfieldwrset); + changed=true; } //See if we need to propagate changes if (!nodelayfieldsrd.containsKey(fn)|| !nodelayfieldsrd.get(fn).equals(nodelayfieldrdset)) { - nodelayfieldsrd.put(fn, nodelayfieldrdset); - changed=true; + nodelayfieldsrd.put(fn, nodelayfieldrdset); + changed=true; } //See if we need to propagate changes if (!nodelayarrayswr.containsKey(fn)|| !nodelayarrayswr.get(fn).equals(nodelayarraywrset)) { - nodelayarrayswr.put(fn, nodelayarraywrset); - changed=true; + nodelayarrayswr.put(fn, nodelayarraywrset); + changed=true; } //See if we need to propagate changes if (!nodelayarraysrd.containsKey(fn)|| !nodelayarraysrd.get(fn).equals(nodelayarrayrdset)) { - nodelayarraysrd.put(fn, nodelayarrayrdset); - changed=true; + nodelayarraysrd.put(fn, nodelayarrayrdset); + changed=true; } if (changed) - for(int i=0; i0; if (!isatomic) - continue; + continue; //Compute initial notready set HashSet notreadyset=new HashSet(); for(int i=0; i tfpset=dcopts.getMap(lb).get(fn).get(tmp); - if (tfpset!=null) { - for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { - TempFlatPair tfp=tfpit.next(); - if (!dcopts.getNeedSrcTrans(lb, tfp.f)) { - //if a source didn't need a translation and we are - //accessing it, it did...so therefore we are note - //ready - notready=true; - break; - } - } - } - break; - } - - case FKind.FlatSetFieldNode: { - FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; - TempDescriptor tmp=fsfn.getDst(); - Hashtable> tmpmap=dcopts.getMap(lb).get(fn); - Set tfpset=tmpmap!=null?tmpmap.get(tmp):null; - - if (tfpset!=null) { - for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { - TempFlatPair tfp=tfpit.next(); - if (!dcopts.getNeedSrcTrans(lb, tfp.f)) { - //if a source didn't need a translation and we are - //accessing it, it did...so therefore we are note - //ready - notready=true; - break; - } - } - } - break; - } - - case FKind.FlatElementNode: { - FlatElementNode fen=(FlatElementNode)fn; - if (!dcopts.getArrays().contains(fen.getSrc().getType())) { - break; - } - TempDescriptor tmp=fen.getSrc(); - Set tfpset=dcopts.getMap(lb).get(fn).get(tmp); - if (tfpset!=null) { - for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { - TempFlatPair tfp=tfpit.next(); - if (!dcopts.getNeedSrcTrans(lb, tfp.f)) { - //if a source didn't need a translation and we are - //accessing it, it did...so therefore we are note - //ready - notready=true; - break; - } - } - } - break; - } - - case FKind.FlatSetElementNode: { - FlatSetElementNode fsen=(FlatSetElementNode)fn; - TempDescriptor tmp=fsen.getDst(); - Set tfpset=dcopts.getMap(lb).get(fn).get(tmp); - if (tfpset!=null) { - for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { - TempFlatPair tfp=tfpit.next(); - if (!dcopts.getNeedSrcTrans(lb, tfp.f)) { - //if a source didn't need a translation and we are - //accessing it, it did...so therefore we are note - //ready - notready=true; - break; - } - } - } - break; - } - } + switch(fn.kind()) { + case FKind.FlatFieldNode: { + FlatFieldNode ffn=(FlatFieldNode)fn; + if (!dcopts.getFields().contains(ffn.getField())) { + break; + } + TempDescriptor tmp=ffn.getSrc(); + Set tfpset=dcopts.getMap(lb).get(fn).get(tmp); + if (tfpset!=null) { + for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { + TempFlatPair tfp=tfpit.next(); + if (!dcopts.getNeedSrcTrans(lb, tfp.f)) { + //if a source didn't need a translation and we are + //accessing it, it did...so therefore we are note + //ready + notready=true; + break; + } + } + } + break; + } + + case FKind.FlatSetFieldNode: { + FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; + TempDescriptor tmp=fsfn.getDst(); + Hashtable> tmpmap=dcopts.getMap(lb).get(fn); + Set tfpset=tmpmap!=null?tmpmap.get(tmp):null; + + if (tfpset!=null) { + for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { + TempFlatPair tfp=tfpit.next(); + if (!dcopts.getNeedSrcTrans(lb, tfp.f)) { + //if a source didn't need a translation and we are + //accessing it, it did...so therefore we are note + //ready + notready=true; + break; + } + } + } + break; + } + + case FKind.FlatElementNode: { + FlatElementNode fen=(FlatElementNode)fn; + if (!dcopts.getArrays().contains(fen.getSrc().getType())) { + break; + } + TempDescriptor tmp=fen.getSrc(); + Set tfpset=dcopts.getMap(lb).get(fn).get(tmp); + if (tfpset!=null) { + for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { + TempFlatPair tfp=tfpit.next(); + if (!dcopts.getNeedSrcTrans(lb, tfp.f)) { + //if a source didn't need a translation and we are + //accessing it, it did...so therefore we are note + //ready + notready=true; + break; + } + } + } + break; + } + + case FKind.FlatSetElementNode: { + FlatSetElementNode fsen=(FlatSetElementNode)fn; + TempDescriptor tmp=fsen.getDst(); + Set tfpset=dcopts.getMap(lb).get(fn).get(tmp); + if (tfpset!=null) { + for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { + TempFlatPair tfp=tfpit.next(); + if (!dcopts.getNeedSrcTrans(lb, tfp.f)) { + //if a source didn't need a translation and we are + //accessing it, it did...so therefore we are note + //ready + notready=true; + break; + } + } + } + break; + } + } } if (!notready) { - //See if we depend on a conditional branch that is not ready - Set branchset=branchmap.get(fn); - if (branchset!=null) - for(Iterator branchit=branchset.iterator(); branchit.hasNext(); ) { - FlatCondBranch fcb=branchit.next(); - if (notreadynodes.contains(fcb)) { - //if we depend on a branch that isn't ready, we aren't ready - notready=true; - break; - } - } + //See if we depend on a conditional branch that is not ready + Set branchset=branchmap.get(fn); + if (branchset!=null) + for(Iterator branchit=branchset.iterator(); branchit.hasNext(); ) { + FlatCondBranch fcb=branchit.next(); + if (notreadynodes.contains(fcb)) { + //if we depend on a branch that isn't ready, we aren't ready + notready=true; + break; + } + } } //Fix up things based on our status if (notready) { - if (fn.kind()==FKind.FlatCondBranch&&!notreadynodes.contains(fn)) { - //enqueue everything in our dependence set - Set branchdepset=revbranchmap.get((FlatCondBranch)fn); - toanalyze.addAll(branchdepset); - } - - //add us to the list - notreadynodes.add(fn); - - //Add our writes - TempDescriptor writeset[]=fn.writesTemps(); - for(int i=0; i branchdepset=revbranchmap.get((FlatCondBranch)fn); + toanalyze.addAll(branchdepset); + } + + //add us to the list + notreadynodes.add(fn); + + //Add our writes + TempDescriptor writeset[]=fn.writesTemps(); + for(int i=0; i fnit=fm.getNodeSet().iterator(); fnit.hasNext(); ) { FlatNode fn=fnit.next(); if (fn.kind()!=FKind.FlatCondBranch) - continue; + continue; FlatCondBranch fcb=(FlatCondBranch)fn; //only worry about fcb inside of transactions if (locality.getAtomic(lb).get(fcb).intValue()==0) - continue; + continue; FlatNode postdom=postdt.idom(fcb); //Reverse the mapping @@ -1003,20 +1003,20 @@ public class DelayComputation { for(Iterator fnit=fm.getNodeSet().iterator(); fnit.hasNext(); ) { FlatNode fn=fnit.next(); if (fn.kind()!=FKind.FlatCondBranch) - continue; + continue; FlatCondBranch fcb=(FlatCondBranch)fn; //only worry about fcb inside of transactions if (locality.getAtomic(lb).get(fcb).intValue()==0) - continue; + continue; FlatNode postdom=postdt.idom(fcb); //Reverse the mapping Set fnset=computeBranchSet(lb, fcb, postdom); for(Iteratorfnit2=fnset.iterator(); fnit2.hasNext(); ) { - FlatNode fn2=fnit2.next(); - if (!condmap.containsKey(fn2)) - condmap.put(fn2,new HashSet()); - condmap.get(fn2).add(fcb); + FlatNode fn2=fnit2.next(); + if (!condmap.containsKey(fn2)) + condmap.put(fn2,new HashSet()); + condmap.get(fn2).add(fcb); } } return condmap; @@ -1033,16 +1033,16 @@ public class DelayComputation { //already examined or exit node if (visited.contains(fn)||fn==last) - continue; + continue; //out of transaction if (locality.getAtomic(lb).get(fn).intValue()==0) - continue; + continue; visited.add(fn); for(int i=0; i(); for(Iterator it=writemap.get(lb).iterator(); it.hasNext(); ) { - TempFlatPair tfp=it.next(); - set.add(tfp.f); + TempFlatPair tfp=it.next(); + set.add(tfp.f); } twritemap.put(lb, set); } @@ -126,8 +126,8 @@ public class DiscoverConflicts { // Set gwriteset=(state.READSET&&gft!=null)?twritemap.get(lb):treadmap.get(lb); if (state.READSET&&gft!=null) { if (twritemap.get(lb).size()==0) { - getmap.put(lb, new HashSet()); - return; + getmap.put(lb, new HashSet()); + return; } } @@ -138,17 +138,17 @@ public class DiscoverConflicts { FlatNode fn=fnit.next(); Hashtable atomictable=locality.getAtomic(lb); if (atomictable.get(fn).intValue()>0&&fn.kind()==FKind.FlatElementNode) { - FlatElementNode fen=(FlatElementNode)fn; - Set tfpset=fnmap.get(fen).get(fen.getSrc()); - if (tfpset!=null) { - for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { - TempFlatPair tfp=tfpit.next(); - if (gwriteset.contains(tfp.f)) { - needsget.add(fen); - break; - } - } - } + FlatElementNode fen=(FlatElementNode)fn; + Set tfpset=fnmap.get(fen).get(fen.getSrc()); + if (tfpset!=null) { + for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { + TempFlatPair tfp=tfpit.next(); + if (gwriteset.contains(tfp.f)) { + needsget.add(fen); + break; + } + } + } } } getmap.put(lb, needsget); @@ -171,13 +171,13 @@ public class DiscoverConflicts { FlatNode fprev=fn.getPrev(i); Hashtable> tabset=tmptofnset.get(fprev); if (tabset!=null) { - for(Iterator tmpit=tabset.keySet().iterator(); tmpit.hasNext(); ) { - TempDescriptor td=tmpit.next(); - Set fnset=tabset.get(td); - if (!table.containsKey(td)) - table.put(td, new HashSet()); - table.get(td).addAll(fnset); - } + for(Iterator tmpit=tabset.keySet().iterator(); tmpit.hasNext(); ) { + TempDescriptor td=tmpit.next(); + Set fnset=tabset.get(td); + if (!table.containsKey(td)) + table.put(td, new HashSet()); + table.get(td).addAll(fnset); + } } } return table; @@ -248,113 +248,113 @@ public class DiscoverConflicts { FlatNode fn=fnit.next(); Hashtable atomictable=locality.getAtomic(lb); if (atomictable.get(fn).intValue()>0) { - Hashtable> tmap=fnmap.get(fn); - switch(fn.kind()) { - //We might need to translate arguments to pointer comparison - - case FKind.FlatOpNode: { - FlatOpNode fon=(FlatOpNode)fn; - if (fon.getOp().getOp()==Operation.EQUAL|| - fon.getOp().getOp()==Operation.NOTEQUAL) { - if (!fon.getLeft().getType().isPtr()) - break; - Set lefttfpset=tmap.get(fon.getLeft()); - Set righttfpset=tmap.get(fon.getRight()); - //handle left operand - if (lefttfpset!=null) { - for(Iterator tfpit=lefttfpset.iterator(); tfpit.hasNext(); ) { - TempFlatPair tfp=tfpit.next(); - if (tfset.contains(tfp)||outofscope(tfp)) { - leftsrctrans.add(fon); - break; - } - } - } - //handle right operand - if (righttfpset!=null) { - for(Iterator tfpit=righttfpset.iterator(); tfpit.hasNext(); ) { - TempFlatPair tfp=tfpit.next(); - if (tfset.contains(tfp)||outofscope(tfp)) { - rightsrctrans.add(fon); - break; - } - } - } - } - break; - } - - case FKind.FlatGlobalConvNode: { - //need to translate these if the value we read from may be a - //shadow... check this by seeing if any of the values we - //may read are in the transread set or came from our caller - //or a method we called - - FlatGlobalConvNode fgcn=(FlatGlobalConvNode)fn; - if (fgcn.getLocality()!=lb|| - fgcn.getMakePtr()) - break; - - Set tfpset=tmap.get(fgcn.getSrc()); - - if (tfpset!=null) { - for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { - TempFlatPair tfp=tfpit.next(); - if (tfset.contains(tfp)||outofscope(tfp)) { - srctrans.add(fgcn); - break; - } - } - } - break; - } - - case FKind.FlatSetFieldNode: { - //need to translate these if the value we read from may be a - //shadow... check this by seeing if any of the values we - //may read are in the transread set or came from our caller - //or a method we called - - FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; - if (!fsfn.getField().getType().isPtr()) - break; - Set tfpset=tmap.get(fsfn.getSrc()); - if (tfpset!=null) { - for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { - TempFlatPair tfp=tfpit.next(); - if (tfset.contains(tfp)||outofscope(tfp)) { - srctrans.add(fsfn); - break; - } - } - } - break; - } - - case FKind.FlatSetElementNode: { - //need to translate these if the value we read from may be a - //shadow... check this by seeing if any of the values we - //may read are in the transread set or came from our caller - //or a method we called - - FlatSetElementNode fsen=(FlatSetElementNode)fn; - if (!fsen.getSrc().getType().isPtr()) - break; - Set tfpset=tmap.get(fsen.getSrc()); - if (tfpset!=null) { - for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { - TempFlatPair tfp=tfpit.next(); - if (tfset.contains(tfp)||outofscope(tfp)) { - srctrans.add(fsen); - break; - } - } - } - break; - } - - default: - } + Hashtable> tmap=fnmap.get(fn); + switch(fn.kind()) { + //We might need to translate arguments to pointer comparison + + case FKind.FlatOpNode: { + FlatOpNode fon=(FlatOpNode)fn; + if (fon.getOp().getOp()==Operation.EQUAL|| + fon.getOp().getOp()==Operation.NOTEQUAL) { + if (!fon.getLeft().getType().isPtr()) + break; + Set lefttfpset=tmap.get(fon.getLeft()); + Set righttfpset=tmap.get(fon.getRight()); + //handle left operand + if (lefttfpset!=null) { + for(Iterator tfpit=lefttfpset.iterator(); tfpit.hasNext(); ) { + TempFlatPair tfp=tfpit.next(); + if (tfset.contains(tfp)||outofscope(tfp)) { + leftsrctrans.add(fon); + break; + } + } + } + //handle right operand + if (righttfpset!=null) { + for(Iterator tfpit=righttfpset.iterator(); tfpit.hasNext(); ) { + TempFlatPair tfp=tfpit.next(); + if (tfset.contains(tfp)||outofscope(tfp)) { + rightsrctrans.add(fon); + break; + } + } + } + } + break; + } + + case FKind.FlatGlobalConvNode: { + //need to translate these if the value we read from may be a + //shadow... check this by seeing if any of the values we + //may read are in the transread set or came from our caller + //or a method we called + + FlatGlobalConvNode fgcn=(FlatGlobalConvNode)fn; + if (fgcn.getLocality()!=lb|| + fgcn.getMakePtr()) + break; + + Set tfpset=tmap.get(fgcn.getSrc()); + + if (tfpset!=null) { + for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { + TempFlatPair tfp=tfpit.next(); + if (tfset.contains(tfp)||outofscope(tfp)) { + srctrans.add(fgcn); + break; + } + } + } + break; + } + + case FKind.FlatSetFieldNode: { + //need to translate these if the value we read from may be a + //shadow... check this by seeing if any of the values we + //may read are in the transread set or came from our caller + //or a method we called + + FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; + if (!fsfn.getField().getType().isPtr()) + break; + Set tfpset=tmap.get(fsfn.getSrc()); + if (tfpset!=null) { + for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { + TempFlatPair tfp=tfpit.next(); + if (tfset.contains(tfp)||outofscope(tfp)) { + srctrans.add(fsfn); + break; + } + } + } + break; + } + + case FKind.FlatSetElementNode: { + //need to translate these if the value we read from may be a + //shadow... check this by seeing if any of the values we + //may read are in the transread set or came from our caller + //or a method we called + + FlatSetElementNode fsen=(FlatSetElementNode)fn; + if (!fsen.getSrc().getType().isPtr()) + break; + Set tfpset=tmap.get(fsen.getSrc()); + if (tfpset!=null) { + for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { + TempFlatPair tfp=tfpit.next(); + if (tfset.contains(tfp)||outofscope(tfp)) { + srctrans.add(fsen); + break; + } + } + } + break; + } + + default: + } } } //Update results @@ -384,57 +384,57 @@ public class DiscoverConflicts { //Stop if we aren't in a transaction if (atomictable.get(fn).intValue()==0) - continue; + continue; //Do merge of all exits for(int i=0; i fields=gft.getFieldsAll(mdfc); - updatefieldset.addAll(fields); - - //get modified arrays - Set arrays=gft.getArraysAll(mdfc); - updatetypeset.addAll(typeanalysis.expandSet(arrays)); - break; - } - } + switch(fn.kind()) { + case FKind.FlatSetFieldNode: { + FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; + updatefieldset.add(fsfn.getField()); + break; + } + + case FKind.FlatSetElementNode: { + FlatSetElementNode fsen=(FlatSetElementNode)fn; + updatetypeset.addAll(typeanalysis.expand(fsen.getDst().getType())); + break; + } + + case FKind.FlatCall: { + FlatCall fcall=(FlatCall)fn; + MethodDescriptor mdfc=fcall.getMethod(); + + //get modified fields + Set fields=gft.getFieldsAll(mdfc); + updatefieldset.addAll(fields); + + //get modified arrays + Set arrays=gft.getArraysAll(mdfc); + updatetypeset.addAll(typeanalysis.expandSet(arrays)); + break; + } + } } if (!updatedtypemap.containsKey(fn)||!updatedfieldmap.containsKey(fn)|| !updatedtypemap.get(fn).equals(updatetypeset)||!updatedfieldmap.get(fn).equals(updatefieldset)) { - updatedtypemap.put(fn, updatetypeset); - updatedfieldmap.put(fn, updatefieldset); - for(int i=0; i atomictable=locality.getAtomic(lb); if (atomictable.get(fn).intValue()>0) { - Hashtable> tmap=fnmap.get(fn); - switch(fn.kind()) { - case FKind.FlatElementNode: { - FlatElementNode fen=(FlatElementNode)fn; - if (arrays.contains(fen.getSrc().getType())) { - //this could cause conflict...figure out conflict set - Set tfpset=tmap.get(fen.getSrc()); - if (tfpset!=null) - tfset.addAll(tfpset); - } - if (updatedtypemap!=null&&updatedtypemap.get(fen).contains(fen.getSrc().getType())) { - //this could cause conflict...figure out conflict set - Set tfpset=tmap.get(fen.getSrc()); - if (tfpset!=null) - tfset.addAll(tfpset); - } - break; - } - - case FKind.FlatFieldNode: { - FlatFieldNode ffn=(FlatFieldNode)fn; - if (fields.contains(ffn.getField())) { - //this could cause conflict...figure out conflict set - Set tfpset=tmap.get(ffn.getSrc()); - if (tfpset!=null) - tfset.addAll(tfpset); - } - if (updatedfieldmap!=null&&updatedfieldmap.get(ffn).contains(ffn.getField())) { - //this could cause conflict...figure out conflict set - Set tfpset=tmap.get(ffn.getSrc()); - if (tfpset!=null) - tfset.addAll(tfpset); - } - break; - } - - case FKind.FlatSetFieldNode: { - //definitely need to translate these - FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; - Set tfpset=tmap.get(fsfn.getDst()); - if (tfpset!=null) - tfset.addAll(tfpset); - if (writeset!=null) { - if (tfpset!=null) - writeset.addAll(tfpset); - } - break; - } - - case FKind.FlatSetElementNode: { - //definitely need to translate these - FlatSetElementNode fsen=(FlatSetElementNode)fn; - Set tfpset=tmap.get(fsen.getDst()); - if (tfpset!=null) - tfset.addAll(tfpset); - if (writeset!=null) { - if (tfpset!=null) - writeset.addAll(tfpset); - } - break; - } - - case FKind.FlatCall: //assume pessimistically that calls do bad things - case FKind.FlatReturnNode: { - TempDescriptor [] readarray=fn.readsTemps(); - for(int i=0; i tfpset=tmap.get(rtmp); - if (tfpset!=null) - tfset.addAll(tfpset); - if (writeset!=null) { - if (tfpset!=null) - writeset.addAll(tfpset); - } - } - break; - } - - default: - //do nothing - } + Hashtable> tmap=fnmap.get(fn); + switch(fn.kind()) { + case FKind.FlatElementNode: { + FlatElementNode fen=(FlatElementNode)fn; + if (arrays.contains(fen.getSrc().getType())) { + //this could cause conflict...figure out conflict set + Set tfpset=tmap.get(fen.getSrc()); + if (tfpset!=null) + tfset.addAll(tfpset); + } + if (updatedtypemap!=null&&updatedtypemap.get(fen).contains(fen.getSrc().getType())) { + //this could cause conflict...figure out conflict set + Set tfpset=tmap.get(fen.getSrc()); + if (tfpset!=null) + tfset.addAll(tfpset); + } + break; + } + + case FKind.FlatFieldNode: { + FlatFieldNode ffn=(FlatFieldNode)fn; + if (fields.contains(ffn.getField())) { + //this could cause conflict...figure out conflict set + Set tfpset=tmap.get(ffn.getSrc()); + if (tfpset!=null) + tfset.addAll(tfpset); + } + if (updatedfieldmap!=null&&updatedfieldmap.get(ffn).contains(ffn.getField())) { + //this could cause conflict...figure out conflict set + Set tfpset=tmap.get(ffn.getSrc()); + if (tfpset!=null) + tfset.addAll(tfpset); + } + break; + } + + case FKind.FlatSetFieldNode: { + //definitely need to translate these + FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; + Set tfpset=tmap.get(fsfn.getDst()); + if (tfpset!=null) + tfset.addAll(tfpset); + if (writeset!=null) { + if (tfpset!=null) + writeset.addAll(tfpset); + } + break; + } + + case FKind.FlatSetElementNode: { + //definitely need to translate these + FlatSetElementNode fsen=(FlatSetElementNode)fn; + Set tfpset=tmap.get(fsen.getDst()); + if (tfpset!=null) + tfset.addAll(tfpset); + if (writeset!=null) { + if (tfpset!=null) + writeset.addAll(tfpset); + } + break; + } + + case FKind.FlatCall: //assume pessimistically that calls do bad things + case FKind.FlatReturnNode: { + TempDescriptor [] readarray=fn.readsTemps(); + for(int i=0; i tfpset=tmap.get(rtmp); + if (tfpset!=null) + tfset.addAll(tfpset); + if (writeset!=null) { + if (tfpset!=null) + writeset.addAll(tfpset); + } + } + break; + } + + default: + //do nothing + } } } return tfset; @@ -576,105 +576,105 @@ public class DiscoverConflicts { FlatNode fn=tovisit.iterator().next(); tovisit.remove(fn); for(int i=0; i> ttofn=null; if (atomictable.get(fn).intValue()!=0) { - if ((fn.numPrev()>0)&&atomictable.get(fn.getPrev(0)).intValue()==0) { - //atomic node, start with new set - ttofn=new Hashtable>(); - } else { - ttofn=doMerge(fn, tmptofnset); - switch(fn.kind()) { - case FKind.FlatGlobalConvNode: { - FlatGlobalConvNode fgcn=(FlatGlobalConvNode)fn; - if (lb==fgcn.getLocality()&& - fgcn.getMakePtr()) { - TempDescriptor[] writes=fn.writesTemps(); - for(int i=0; i set=new HashSet(); - set.add(new TempFlatPair(wtmp, fn)); - ttofn.put(wtmp, set); - } - } - break; - } - - case FKind.FlatFieldNode: - case FKind.FlatElementNode: { - TempDescriptor[] writes=fn.writesTemps(); - for(int i=0; i set=new HashSet(); - set.add(new TempFlatPair(wtmp, fn)); - ttofn.put(wtmp, set); - } - break; - } - - case FKind.FlatCall: - case FKind.FlatMethod: { - TempDescriptor[] writes=fn.writesTemps(); - for(int i=0; i set=new HashSet(); - set.add(new TempFlatPair(wtmp, fn)); - ttofn.put(wtmp, set); - } - break; - } - - case FKind.FlatCastNode: - case FKind.FlatOpNode: - if (fn.kind()==FKind.FlatCastNode) { - FlatCastNode fcn=(FlatCastNode)fn; - if (fcn.getDst().getType().isPtr()) { - HashSet set=new HashSet(); - if (ttofn.containsKey(fcn.getSrc())) - set.addAll(ttofn.get(fcn.getSrc())); - if (normalassign) - set.add(new TempFlatPair(fcn.getDst(), fn)); - ttofn.put(fcn.getDst(), set); - break; - } - } else if (fn.kind()==FKind.FlatOpNode) { - FlatOpNode fon=(FlatOpNode)fn; - if (fon.getOp().getOp()==Operation.ASSIGN&&fon.getDest().getType().isPtr()) { - HashSet set=new HashSet(); - if (ttofn.containsKey(fon.getLeft())) - set.addAll(ttofn.get(fon.getLeft())); - if (normalassign) - set.add(new TempFlatPair(fon.getDest(), fn)); - ttofn.put(fon.getDest(), set); - break; - } - } - - default: - //Do kill computation - TempDescriptor[] writes=fn.writesTemps(); - for(int i=0; i0)&&atomictable.get(fn.getPrev(0)).intValue()==0) { + //atomic node, start with new set + ttofn=new Hashtable>(); + } else { + ttofn=doMerge(fn, tmptofnset); + switch(fn.kind()) { + case FKind.FlatGlobalConvNode: { + FlatGlobalConvNode fgcn=(FlatGlobalConvNode)fn; + if (lb==fgcn.getLocality()&& + fgcn.getMakePtr()) { + TempDescriptor[] writes=fn.writesTemps(); + for(int i=0; i set=new HashSet(); + set.add(new TempFlatPair(wtmp, fn)); + ttofn.put(wtmp, set); + } + } + break; + } + + case FKind.FlatFieldNode: + case FKind.FlatElementNode: { + TempDescriptor[] writes=fn.writesTemps(); + for(int i=0; i set=new HashSet(); + set.add(new TempFlatPair(wtmp, fn)); + ttofn.put(wtmp, set); + } + break; + } + + case FKind.FlatCall: + case FKind.FlatMethod: { + TempDescriptor[] writes=fn.writesTemps(); + for(int i=0; i set=new HashSet(); + set.add(new TempFlatPair(wtmp, fn)); + ttofn.put(wtmp, set); + } + break; + } + + case FKind.FlatCastNode: + case FKind.FlatOpNode: + if (fn.kind()==FKind.FlatCastNode) { + FlatCastNode fcn=(FlatCastNode)fn; + if (fcn.getDst().getType().isPtr()) { + HashSet set=new HashSet(); + if (ttofn.containsKey(fcn.getSrc())) + set.addAll(ttofn.get(fcn.getSrc())); + if (normalassign) + set.add(new TempFlatPair(fcn.getDst(), fn)); + ttofn.put(fcn.getDst(), set); + break; + } + } else if (fn.kind()==FKind.FlatOpNode) { + FlatOpNode fon=(FlatOpNode)fn; + if (fon.getOp().getOp()==Operation.ASSIGN&&fon.getDest().getType().isPtr()) { + HashSet set=new HashSet(); + if (ttofn.containsKey(fon.getLeft())) + set.addAll(ttofn.get(fon.getLeft())); + if (normalassign) + set.add(new TempFlatPair(fon.getDest(), fn)); + ttofn.put(fon.getDest(), set); + break; + } + } + + default: + //Do kill computation + TempDescriptor[] writes=fn.writesTemps(); + for(int i=0; i atomictable=locality.getAtomic(lb); if (atomictable.get(fn).intValue()>0) { - Set oldtemp=oldtemps.get(fn); - switch (fn.kind()) { - case FKind.FlatSetFieldNode: - FlatSetFieldNode fsfn=(FlatSetFieldNode) fn; - if (oldtemp.contains(fsfn.getDst())) - fields.add(fsfn.getField()); - break; - - case FKind.FlatSetElementNode: - FlatSetElementNode fsen=(FlatSetElementNode) fn; - if (oldtemp.contains(fsen.getDst())) - arrays.add(fsen.getDst().getType()); - break; - - default: - } + Set oldtemp=oldtemps.get(fn); + switch (fn.kind()) { + case FKind.FlatSetFieldNode: + FlatSetFieldNode fsfn=(FlatSetFieldNode) fn; + if (oldtemp.contains(fsfn.getDst())) + fields.add(fsfn.getField()); + break; + + case FKind.FlatSetElementNode: + FlatSetElementNode fsen=(FlatSetElementNode) fn; + if (oldtemp.contains(fsen.getDst())) + arrays.add(fsen.getDst().getType()); + break; + + default: + } } } } @@ -734,82 +734,82 @@ public class DiscoverConflicts { FlatNode fn=tovisit.iterator().next(); tovisit.remove(fn); for(int i=0; i oldtemps=null; if (atomictable.get(fn).intValue()!=0) { - if ((fn.numPrev()>0)&&atomictable.get(fn.getPrev(0)).intValue()==0) { - //Everything live is old - Set lives=livetemps.get(fn); - oldtemps=new HashSet(); - - for(Iterator it=lives.iterator(); it.hasNext(); ) { - TempDescriptor tmp=it.next(); - if (tmp.getType().isPtr()) { - oldtemps.add(tmp); - } - } - } else { - oldtemps=new HashSet(); - //Compute union of old temporaries - for(int i=0; i pset=fntooldtmp.get(fn.getPrev(i)); - if (pset!=null) - oldtemps.addAll(pset); - } - - switch (fn.kind()) { - case FKind.FlatNew: - oldtemps.removeAll(Arrays.asList(fn.readsTemps())); - break; - - case FKind.FlatOpNode: - case FKind.FlatCastNode: - if (fn.kind()==FKind.FlatCastNode) { - FlatCastNode fcn=(FlatCastNode)fn; - if (fcn.getDst().getType().isPtr()) { - if (oldtemps.contains(fcn.getSrc())) - oldtemps.add(fcn.getDst()); - else - oldtemps.remove(fcn.getDst()); - break; - } - } else if (fn.kind()==FKind.FlatOpNode) { - FlatOpNode fon=(FlatOpNode)fn; - if (fon.getOp().getOp()==Operation.ASSIGN&&fon.getDest().getType().isPtr()) { - if (oldtemps.contains(fon.getLeft())) - oldtemps.add(fon.getDest()); - else - oldtemps.remove(fon.getDest()); - break; - } - } - - default: { - TempDescriptor[] writes=fn.writesTemps(); - for(int i=0; i0)&&atomictable.get(fn.getPrev(0)).intValue()==0) { + //Everything live is old + Set lives=livetemps.get(fn); + oldtemps=new HashSet(); + + for(Iterator it=lives.iterator(); it.hasNext(); ) { + TempDescriptor tmp=it.next(); + if (tmp.getType().isPtr()) { + oldtemps.add(tmp); + } + } + } else { + oldtemps=new HashSet(); + //Compute union of old temporaries + for(int i=0; i pset=fntooldtmp.get(fn.getPrev(i)); + if (pset!=null) + oldtemps.addAll(pset); + } + + switch (fn.kind()) { + case FKind.FlatNew: + oldtemps.removeAll(Arrays.asList(fn.readsTemps())); + break; + + case FKind.FlatOpNode: + case FKind.FlatCastNode: + if (fn.kind()==FKind.FlatCastNode) { + FlatCastNode fcn=(FlatCastNode)fn; + if (fcn.getDst().getType().isPtr()) { + if (oldtemps.contains(fcn.getSrc())) + oldtemps.add(fcn.getDst()); + else + oldtemps.remove(fcn.getDst()); + break; + } + } else if (fn.kind()==FKind.FlatOpNode) { + FlatOpNode fon=(FlatOpNode)fn; + if (fon.getOp().getOp()==Operation.ASSIGN&&fon.getDest().getType().isPtr()) { + if (oldtemps.contains(fon.getLeft())) + oldtemps.add(fon.getDest()); + else + oldtemps.remove(fon.getDest()); + break; + } + } + + default: { + TempDescriptor[] writes=fn.writesTemps(); + for(int i=0; i()); - nodetoconvs2.put(fn, new HashSet()); + nodetoconvs.put(fn, new HashSet()); + nodetoconvs2.put(fn, new HashSet()); } HashSet tempset=new HashSet(); for(int i=0; i prevset=nodetotnpair.get(fnprev); - for(Iterator it=prevset.iterator(); it.hasNext(); ) { - TempNodePair tnp=it.next(); - if (fn.kind()==FKind.FlatGlobalConvNode&& - ((FlatGlobalConvNode)fn).getLocality()!=lb) { - //ignore this node - tempset.add(tnp); - continue; - } - if (reads.contains(tnp.getTemp())&&tnp.getNode()!=null) { - //Value actually is read... - nodetoconvs.get(tnp.getNode()).add(tnp.getTemp()); - } - - if (writes.contains(tnp.getTemp())) //value overwritten - continue; - if (!isatomic&&fn.kind()==FKind.FlatAtomicExitNode) { - //Create new node and tag it with this exit - if (tnp.getNode()==null) { - TempNodePair tnp2=new TempNodePair(tnp.getTemp()); - tnp2.setNode(fn); - tempset.add(tnp2); - nodetoconvs2.get(fn).add(tnp.getTemp()); //have to hide cached copies from gc -- add unused converted temps - } else - tempset.add(tnp); - } else - tempset.add(tnp); - } + FlatNode fnprev=fn.getPrev(i); + if (!nodetotnpair.containsKey(fnprev)) + continue; + + Set prevset=nodetotnpair.get(fnprev); + for(Iterator it=prevset.iterator(); it.hasNext(); ) { + TempNodePair tnp=it.next(); + if (fn.kind()==FKind.FlatGlobalConvNode&& + ((FlatGlobalConvNode)fn).getLocality()!=lb) { + //ignore this node + tempset.add(tnp); + continue; + } + if (reads.contains(tnp.getTemp())&&tnp.getNode()!=null) { + //Value actually is read... + nodetoconvs.get(tnp.getNode()).add(tnp.getTemp()); + } + + if (writes.contains(tnp.getTemp())) //value overwritten + continue; + if (!isatomic&&fn.kind()==FKind.FlatAtomicExitNode) { + //Create new node and tag it with this exit + if (tnp.getNode()==null) { + TempNodePair tnp2=new TempNodePair(tnp.getTemp()); + tnp2.setNode(fn); + tempset.add(tnp2); + nodetoconvs2.get(fn).add(tnp.getTemp()); //have to hide cached copies from gc -- add unused converted temps + } else + tempset.add(tnp); + } else + tempset.add(tnp); + } } if (isatomic) { - /* If this is in an atomic block, record temps that - * are written to.*/ - - /* NOTE: If this compiler is changed to maintain - * OID/Ptr's in variables, then we need to use all - * global temps that could be read and not just the - * ones converted by globalconvnode*/ - - if (fn.kind()!=FKind.FlatGlobalConvNode|| - ((FlatGlobalConvNode)fn).getLocality()==lb) { - /*If globalconvnode, make sure we have the right - * locality. */ - for(Iterator writeit=writes.iterator(); writeit.hasNext(); ) { - TempDescriptor wrtmp=writeit.next(); - if (state.SINGLETM) { - if (wrtmp.getType().isPtr()&& - (nodetemptab.get(wrtmp)!=LocalityAnalysis.SCRATCH)) { - TempNodePair tnp=new TempNodePair(wrtmp); - tempset.add(tnp); - } - } else if (nodetemptab.get(wrtmp)==LocalityAnalysis.GLOBAL) { - TempNodePair tnp=new TempNodePair(wrtmp); - tempset.add(tnp); - } - } - } + /* If this is in an atomic block, record temps that + * are written to.*/ + + /* NOTE: If this compiler is changed to maintain + * OID/Ptr's in variables, then we need to use all + * global temps that could be read and not just the + * ones converted by globalconvnode*/ + + if (fn.kind()!=FKind.FlatGlobalConvNode|| + ((FlatGlobalConvNode)fn).getLocality()==lb) { + /*If globalconvnode, make sure we have the right + * locality. */ + for(Iterator writeit=writes.iterator(); writeit.hasNext(); ) { + TempDescriptor wrtmp=writeit.next(); + if (state.SINGLETM) { + if (wrtmp.getType().isPtr()&& + (nodetemptab.get(wrtmp)!=LocalityAnalysis.SCRATCH)) { + TempNodePair tnp=new TempNodePair(wrtmp); + tempset.add(tnp); + } + } else if (nodetemptab.get(wrtmp)==LocalityAnalysis.GLOBAL) { + TempNodePair tnp=new TempNodePair(wrtmp); + tempset.add(tnp); + } + } + } } if (!nodetotnpair.containsKey(fn)||!nodetotnpair.get(fn).equals(tempset)) { - //changes to set, so enqueue next nodes - nodetotnpair.put(fn, tempset); //update set - for(int i=0; i0&& atomictab.get(fn.getPrev(0)).intValue()>0) { - //sanity check - assert(fn.kind()==FKind.FlatAtomicExitNode); - //insert calls here... - Set tempset=nodetoconvs2.get(fn); - for(Iterator tempit=tempset.iterator(); tempit.hasNext(); ) { - TempDescriptor tmpd=tempit.next(); - FlatGlobalConvNode fgcn=new FlatGlobalConvNode(tmpd, lb, false, nodetoconvs.get(fn).contains(tmpd)); - - //This loop makes sure that we have accurate atomic information for the new node - for(Iterator lbit=locality.getMethodBindings(lb.getMethod()).iterator(); lbit.hasNext(); ) { - LocalityBinding fixlb=lbit.next(); - locality.getAtomic(fixlb).put(fgcn, locality.getAtomic(fixlb).get(fn.getPrev(0))); - locality.getNodeTempInfo(fixlb).put(fgcn, (Hashtable)locality.getNodeTempInfo(fixlb).get(fn).clone()); - } - - fgcn.setAtomicEnter(((FlatAtomicExitNode)fn).getAtomicEnter()); - - FlatNode[] prevarray=new FlatNode[fn.numPrev()]; - for(int i=0; i tempset=nodetoconvs2.get(fn); + for(Iterator tempit=tempset.iterator(); tempit.hasNext(); ) { + TempDescriptor tmpd=tempit.next(); + FlatGlobalConvNode fgcn=new FlatGlobalConvNode(tmpd, lb, false, nodetoconvs.get(fn).contains(tmpd)); + + //This loop makes sure that we have accurate atomic information for the new node + for(Iterator lbit=locality.getMethodBindings(lb.getMethod()).iterator(); lbit.hasNext(); ) { + LocalityBinding fixlb=lbit.next(); + locality.getAtomic(fixlb).put(fgcn, locality.getAtomic(fixlb).get(fn.getPrev(0))); + locality.getNodeTempInfo(fixlb).put(fgcn, (Hashtable)locality.getNodeTempInfo(fixlb).get(fn).clone()); + } + + fgcn.setAtomicEnter(((FlatAtomicExitNode)fn).getAtomicEnter()); + + FlatNode[] prevarray=new FlatNode[fn.numPrev()]; + for(int i=0; i0) { - //build set of transaction temps use by next nodes - HashSet transtemps=new HashSet(); - for(int i=0; i pretemptab=locality.getNodePreTempInfo(lb, fn); - if (state.SINGLETM) { - TempDescriptor [] readtemps=fn.readsTemps(); - for(int i=0; i transtemps=new HashSet(); + for(int i=0; i pretemptab=locality.getNodePreTempInfo(lb, fn); + if (state.SINGLETM) { + TempDescriptor [] readtemps=fn.readsTemps(); + for(int i=0; i0&& atomictab.get(fn.getPrev(0)).intValue()==0) { - //sanity check - assert(fn.kind()==FKind.FlatAtomicEnterNode); - - //insert calls here... - Set tempset=nodetotranstemps.get(fn); - for(Iterator tempit=tempset.iterator(); tempit.hasNext(); ) { - FlatGlobalConvNode fgcn=new FlatGlobalConvNode(tempit.next(), lb, true); - fgcn.setAtomicEnter((FlatAtomicEnterNode)fn); - //This loop makes sure that we have accurate atomic information for the new node - for(Iterator lbit=locality.getMethodBindings(lb.getMethod()).iterator(); lbit.hasNext(); ) { - LocalityBinding fixlb=lbit.next(); - locality.getAtomic(fixlb).put(fgcn, locality.getAtomic(fixlb).get(fn)); - locality.getNodeTempInfo(fixlb).put(fgcn, (Hashtable)locality.getNodeTempInfo(fixlb).get(fn).clone()); - } - fgcn.addNext(fn.getNext(0)); - fn.setNext(0, fgcn); - } + //sanity check + assert(fn.kind()==FKind.FlatAtomicEnterNode); + + //insert calls here... + Set tempset=nodetotranstemps.get(fn); + for(Iterator tempit=tempset.iterator(); tempit.hasNext(); ) { + FlatGlobalConvNode fgcn=new FlatGlobalConvNode(tempit.next(), lb, true); + fgcn.setAtomicEnter((FlatAtomicEnterNode)fn); + //This loop makes sure that we have accurate atomic information for the new node + for(Iterator lbit=locality.getMethodBindings(lb.getMethod()).iterator(); lbit.hasNext(); ) { + LocalityBinding fixlb=lbit.next(); + locality.getAtomic(fixlb).put(fgcn, locality.getAtomic(fixlb).get(fn)); + locality.getNodeTempInfo(fixlb).put(fgcn, (Hashtable)locality.getNodeTempInfo(fixlb).get(fn).clone()); + } + fgcn.addNext(fn.getNext(0)); + fn.setNext(0, fgcn); + } } } } diff --git a/Robust/src/Analysis/Locality/LocalityAnalysis.java b/Robust/src/Analysis/Locality/LocalityAnalysis.java index fd9efa01..04418984 100644 --- a/Robust/src/Analysis/Locality/LocalityAnalysis.java +++ b/Robust/src/Analysis/Locality/LocalityAnalysis.java @@ -78,12 +78,12 @@ public class LocalityAnalysis { if (state.DSM&&fc.getThis()!=null) { Integer thistype=currtable.get(fc.getThis()); if (thistype==null) - thistype=EITHER; + thistype=EITHER; lb.setGlobalThis(thistype); } else if (state.SINGLETM&&fc.getThis()!=null) { Integer thistype=currtable.get(fc.getThis()); if (thistype==null) - thistype=STMEITHER; + thistype=STMEITHER; lb.setGlobalThis(thistype); } // else @@ -139,11 +139,11 @@ public class LocalityAnalysis { FlatNode prevnode=fn.getPrev(i); Hashtable prevtable=temptable.get(prevnode); for(Iterator tempit=prevtable.keySet().iterator(); tempit.hasNext(); ) { - TempDescriptor temp=tempit.next(); - Integer tmpint=prevtable.get(temp); - Integer oldint=currtable.containsKey(temp)?currtable.get(temp):(state.DSM?EITHER:STMEITHER); - Integer newint=state.DSM?merge(tmpint, oldint):mergestm(tmpint, oldint); - currtable.put(temp, newint); + TempDescriptor temp=tempit.next(); + Integer tmpint=prevtable.get(temp); + Integer oldint=currtable.containsKey(temp)?currtable.get(temp):(state.DSM?EITHER:STMEITHER); + Integer newint=state.DSM?merge(tmpint, oldint):mergestm(tmpint, oldint); + currtable.put(temp, newint); } } return currtable; @@ -173,8 +173,8 @@ public class LocalityAnalysis { Hashtable> table=getTemps(lb); if (table!=null) for(Iterator faenit=table.keySet().iterator(); faenit.hasNext(); ) { - FlatAtomicEnterNode faen=faenit.next(); - set.addAll(table.get(faen)); + FlatAtomicEnterNode faen=faenit.next(); + set.addAll(table.get(faen)); } return set; } @@ -204,19 +204,19 @@ public class LocalityAnalysis { while(!lbstack.isEmpty()) { LocalityBinding lb=lbstack.pop(); if (calldep.containsKey(lb)) { - Set set=new HashSet(); - set.addAll(calldep.get(lb)); - set.removeAll(lbset); - lbstack.addAll(set); - lbset.addAll(set); + Set set=new HashSet(); + set.addAll(calldep.get(lb)); + set.removeAll(lbset); + lbstack.addAll(set); + lbset.addAll(set); } } for(Iterator lbit=discovered.keySet().iterator(); lbit.hasNext(); ) { LocalityBinding lb=lbit.next(); if (!lbset.contains(lb)) { - lbit.remove(); - classtolb.get(lb.getMethod().getClassDesc()).remove(lb); - methodtolb.get(lb.getMethod()).remove(lb); + lbit.remove(); + classtolb.get(lb.getMethod().getClassDesc()).remove(lb); + methodtolb.get(lb.getMethod()).remove(lb); } } } @@ -227,7 +227,7 @@ public class LocalityAnalysis { .hasNext(); ) { MethodDescriptor md=(MethodDescriptor) methodit.next(); if (md.numParameters()!=1||!md.getModifiers().isStatic()||!md.getParamType(0).getSymbol().equals(TypeUtil.ThreadClass)) - continue; + continue; return md; } throw new Error("Can't find Thread.run"); @@ -274,19 +274,19 @@ public class LocalityAnalysis { Hashtable atomictable=new Hashtable(); calldep.remove(lb); try { - computeCallsFlagsSTM(md, lb, temptable, atomictable); + computeCallsFlagsSTM(md, lb, temptable, atomictable); } catch (Error e) { - System.out.println("Error in "+md+" context "+lb); - e.printStackTrace(); - System.exit(-1); + System.out.println("Error in "+md+" context "+lb); + e.printStackTrace(); + System.exit(-1); } temptab.put(lb, temptable); atomictab.put(lb, atomictable); if (md.getReturnType()!=null&&md.getReturnType().isPtr()&&!returnglobal.equals(lb.getGlobalReturn())) { - //return type is more precise now - //rerun everything that call us - lbtovisit.addAll(dependence.get(lb)); + //return type is more precise now + //rerun everything that call us + lbtovisit.addAll(dependence.get(lb)); } } } @@ -313,13 +313,13 @@ public class LocalityAnalysis { atomictable.put(fm, lb.isAtomic()?1:0); int offset=md.isStatic()?0:1; if (!md.isStatic()) { - table.put(fm.getParameter(0), lb.getGlobalThis()); + table.put(fm.getParameter(0), lb.getGlobalThis()); } for(int i=offset; i currtable=new Hashtable(); int atomicstate=0; for(int i=0; i prevtable=temptable.get(prevnode); - for(Iterator tempit=prevtable.keySet().iterator(); tempit.hasNext(); ) { - TempDescriptor temp=tempit.next(); - if (!liveset.contains(temp)) - continue; - Integer tmpint=prevtable.get(temp); - Integer oldint=currtable.containsKey(temp)?currtable.get(temp):STMEITHER; - Integer newint=mergestm(tmpint, oldint); - currtable.put(temp, newint); - } + FlatNode prevnode=fn.getPrev(i); + if (atomictable.containsKey(prevnode)) { + atomicstate=atomictable.get(prevnode).intValue(); + } + if (!temptable.containsKey(prevnode)) + continue; + Hashtable prevtable=temptable.get(prevnode); + for(Iterator tempit=prevtable.keySet().iterator(); tempit.hasNext(); ) { + TempDescriptor temp=tempit.next(); + if (!liveset.contains(temp)) + continue; + Integer tmpint=prevtable.get(temp); + Integer oldint=currtable.containsKey(temp)?currtable.get(temp):STMEITHER; + Integer newint=mergestm(tmpint, oldint); + currtable.put(temp, newint); + } } atomictable.put(fn, atomicstate); // Process this node switch(fn.kind()) { case FKind.FlatAtomicEnterNode: - processAtomicEnterNode((FlatAtomicEnterNode)fn, atomictable); - if (!lb.isAtomic()) - lb.setHasAtomic(); - break; + processAtomicEnterNode((FlatAtomicEnterNode)fn, atomictable); + if (!lb.isAtomic()) + lb.setHasAtomic(); + break; case FKind.FlatAtomicExitNode: - processAtomicExitNode((FlatAtomicExitNode)fn, atomictable); - break; + processAtomicExitNode((FlatAtomicExitNode)fn, atomictable); + break; case FKind.FlatCall: - processCallNodeSTM(lb, (FlatCall)fn, isAtomic(atomictable, fn), currtable, temptable.get(fn)); - break; + processCallNodeSTM(lb, (FlatCall)fn, isAtomic(atomictable, fn), currtable, temptable.get(fn)); + break; case FKind.FlatNew: - processNewSTM(lb, (FlatNew) fn, currtable); - break; + processNewSTM(lb, (FlatNew) fn, currtable); + break; case FKind.FlatFieldNode: - processFieldNodeSTM(lb, (FlatFieldNode) fn, currtable); - break; + processFieldNodeSTM(lb, (FlatFieldNode) fn, currtable); + break; case FKind.FlatSetFieldNode: - processSetFieldNodeSTM(lb, (FlatSetFieldNode) fn, currtable); - break; + processSetFieldNodeSTM(lb, (FlatSetFieldNode) fn, currtable); + break; case FKind.FlatSetElementNode: - processSetElementNodeSTM(lb, (FlatSetElementNode) fn, currtable); - break; + processSetElementNodeSTM(lb, (FlatSetElementNode) fn, currtable); + break; case FKind.FlatElementNode: - processElementNodeSTM(lb, (FlatElementNode) fn, currtable); - break; + processElementNodeSTM(lb, (FlatElementNode) fn, currtable); + break; case FKind.FlatOpNode: - processOpNodeSTM(lb, (FlatOpNode)fn, currtable); - break; + processOpNodeSTM(lb, (FlatOpNode)fn, currtable); + break; case FKind.FlatCastNode: - processCastNodeSTM((FlatCastNode)fn, currtable); - break; + processCastNodeSTM((FlatCastNode)fn, currtable); + break; case FKind.FlatReturnNode: - processReturnNodeSTM(lb, (FlatReturnNode)fn, currtable); - break; + processReturnNodeSTM(lb, (FlatReturnNode)fn, currtable); + break; case FKind.FlatLiteralNode: - processLiteralNodeSTM((FlatLiteralNode)fn, currtable); - break; + processLiteralNodeSTM((FlatLiteralNode)fn, currtable); + break; case FKind.FlatMethod: case FKind.FlatOffsetNode: @@ -411,27 +411,27 @@ public class LocalityAnalysis { case FKind.FlatNop: case FKind.FlatPrefetchNode: case FKind.FlatExit: - //No action needed for these - break; + //No action needed for these + break; case FKind.FlatFlagActionNode: case FKind.FlatCheckNode: case FKind.FlatTagDeclaration: - throw new Error("Incompatible with tasks!"); + throw new Error("Incompatible with tasks!"); default: - throw new Error("In finding fn.kind()= " + fn.kind()); + throw new Error("In finding fn.kind()= " + fn.kind()); } Hashtable oldtable=temptable.get(fn); if (oldtable==null||!oldtable.equals(currtable)) { - // Update table for this node - temptable.put(fn, currtable); - for(int i=0; i()); - classtolb.get(lb.getMethod().getClassDesc()).add(lb); - if (!methodtolb.containsKey(lb.getMethod())) - methodtolb.put(lb.getMethod(), new HashSet()); - methodtolb.get(lb.getMethod()).add(lb); + if (isnative) { + if (nodemd.getReturnType()!=null&&nodemd.getReturnType().isPtr()) + lb.setGlobalReturn(NORMAL); + } else + lb.setGlobalReturn(STMEITHER); + + lb.setParent(currlb); + lbtovisit.add(lb); + System.out.println("New lb:"+lb); + discovered.put(lb, lb); + if (!classtolb.containsKey(lb.getMethod().getClassDesc())) + classtolb.put(lb.getMethod().getClassDesc(), new HashSet()); + classtolb.get(lb.getMethod().getClassDesc()).add(lb); + if (!methodtolb.containsKey(lb.getMethod())) + methodtolb.put(lb.getMethod(), new HashSet()); + methodtolb.get(lb.getMethod()).add(lb); } else - lb=discovered.get(lb); + lb=discovered.get(lb); Integer returnval=lb.getGlobalReturn(); currreturnval=mergestm(returnval, currreturnval); if (!dependence.containsKey(lb)) - dependence.put(lb, new HashSet()); + dependence.put(lb, new HashSet()); dependence.get(lb).add(currlb); if (!calldep.containsKey(currlb)) - calldep.put(currlb, new HashSet()); + calldep.put(currlb, new HashSet()); calldep.get(currlb).add(lb); } if (fc.getReturnTemp()!=null&&fc.getReturnTemp().getType().isPtr()) { @@ -579,14 +579,14 @@ public class LocalityAnalysis { System.out.println(fsfn); if (dsttype.equals(SCRATCH)) { if (!(srctype.equals(SCRATCH)||srctype.equals(STMEITHER))) - throw new Error("Writing possible normal reference to scratch object in context: \n"+lb.getExplanation()); + throw new Error("Writing possible normal reference to scratch object in context: \n"+lb.getExplanation()); } else if (dsttype.equals(NORMAL)) { //okay to store primitives in global object if (!(srctype.equals(NORMAL)||srctype.equals(STMEITHER))) - throw new Error("Writing possible scratch reference to normal object in context:\n"+lb.getExplanation()+" for FlatFieldNode "+fsfn); + throw new Error("Writing possible scratch reference to normal object in context:\n"+lb.getExplanation()+" for FlatFieldNode "+fsfn); } else if (dsttype.equals(STMEITHER)) { if (srctype.equals(STMCONFLICT)) - throw new Error("Using reference that could be scratch or normal in context:\n"+lb.getExplanation()); + throw new Error("Using reference that could be scratch or normal in context:\n"+lb.getExplanation()); } else if (dsttype.equals(STMCONFLICT)) { throw new Error("Access to object that could be either scratch or normal in context:\n"+lb.getExplanation()); } @@ -600,13 +600,13 @@ public class LocalityAnalysis { if (dsttype.equals(SCRATCH)) { if (!(srctype.equals(SCRATCH)||srctype.equals(STMEITHER))) - throw new Error("Writing possible normal reference to scratch object in context:\n"+lb.getExplanation()+fsen); + throw new Error("Writing possible normal reference to scratch object in context:\n"+lb.getExplanation()+fsen); } else if (dsttype.equals(NORMAL)) { if (!(srctype.equals(NORMAL)||srctype.equals(STMEITHER))) - throw new Error("Writing possible scratch reference to normal object in context:\n"+lb.getExplanation()); + throw new Error("Writing possible scratch reference to normal object in context:\n"+lb.getExplanation()); } else if (dsttype.equals(STMEITHER)) { if (srctype.equals(STMCONFLICT)) - throw new Error("Using reference that could be scratch or normal in context:\n"+lb.getExplanation()); + throw new Error("Using reference that could be scratch or normal in context:\n"+lb.getExplanation()); } else if (dsttype.equals(STMCONFLICT)) { throw new Error("Access to object that could be either normal or scratch in context:\n"+lb.getExplanation()); } @@ -707,11 +707,11 @@ public class LocalityAnalysis { lbtovisit.add(lbexecute); discovered.put(lbexecute, lbexecute); if (!classtolb.containsKey(lbexecute.getMethod().getClassDesc())) - classtolb.put(lbexecute.getMethod().getClassDesc(), new HashSet()); + classtolb.put(lbexecute.getMethod().getClassDesc(), new HashSet()); classtolb.get(lbexecute.getMethod().getClassDesc()).add(lbexecute); if (!methodtolb.containsKey(lbexecute.getMethod())) - methodtolb.put(lbexecute.getMethod(), new HashSet()); + methodtolb.put(lbexecute.getMethod(), new HashSet()); methodtolb.get(lbexecute.getMethod()).add(lbexecute); } @@ -726,19 +726,19 @@ public class LocalityAnalysis { Hashtable atomictable=new Hashtable(); calldep.remove(lb); try { - computeCallsFlags(md, lb, temptable, atomictable); + computeCallsFlags(md, lb, temptable, atomictable); } catch (Error e) { - System.out.println("Error in "+md+" context "+lb); - e.printStackTrace(); - System.exit(-1); + System.out.println("Error in "+md+" context "+lb); + e.printStackTrace(); + System.exit(-1); } temptab.put(lb, temptable); atomictab.put(lb, atomictable); if (md.getReturnType()!=null&&!returnglobal.equals(lb.getGlobalReturn())) { - //return type is more precise now - //rerun everything that call us - lbtovisit.addAll(dependence.get(lb)); + //return type is more precise now + //rerun everything that call us + lbtovisit.addAll(dependence.get(lb)); } } } @@ -757,12 +757,12 @@ public class LocalityAnalysis { atomictable.put(fm, lb.isAtomic()?1:0); int offset=md.isStatic()?0:1; if (!md.isStatic()) { - table.put(fm.getParameter(0), lb.getGlobalThis()); + table.put(fm.getParameter(0), lb.getGlobalThis()); } for(int i=offset; i currtable=new Hashtable(); int atomicstate=0; for(int i=0; i prevtable=temptable.get(prevnode); - for(Iterator tempit=prevtable.keySet().iterator(); tempit.hasNext(); ) { - TempDescriptor temp=tempit.next(); - Integer tmpint=prevtable.get(temp); - Integer oldint=currtable.containsKey(temp)?currtable.get(temp):EITHER; - Integer newint=merge(tmpint, oldint); - currtable.put(temp, newint); - } + FlatNode prevnode=fn.getPrev(i); + if (atomictable.containsKey(prevnode)) { + atomicstate=atomictable.get(prevnode).intValue(); + } + if (!temptable.containsKey(prevnode)) + continue; + Hashtable prevtable=temptable.get(prevnode); + for(Iterator tempit=prevtable.keySet().iterator(); tempit.hasNext(); ) { + TempDescriptor temp=tempit.next(); + Integer tmpint=prevtable.get(temp); + Integer oldint=currtable.containsKey(temp)?currtable.get(temp):EITHER; + Integer newint=merge(tmpint, oldint); + currtable.put(temp, newint); + } } atomictable.put(fn, atomicstate); // Process this node switch(fn.kind()) { case FKind.FlatAtomicEnterNode: - processAtomicEnterNode((FlatAtomicEnterNode)fn, atomictable); - if (!lb.isAtomic()) - lb.setHasAtomic(); - break; + processAtomicEnterNode((FlatAtomicEnterNode)fn, atomictable); + if (!lb.isAtomic()) + lb.setHasAtomic(); + break; case FKind.FlatAtomicExitNode: - processAtomicExitNode((FlatAtomicExitNode)fn, atomictable); - break; + processAtomicExitNode((FlatAtomicExitNode)fn, atomictable); + break; case FKind.FlatCall: - processCallNode(lb, (FlatCall)fn, currtable, isAtomic(atomictable, fn), temptable.get(fn)); - break; + processCallNode(lb, (FlatCall)fn, currtable, isAtomic(atomictable, fn), temptable.get(fn)); + break; case FKind.FlatFieldNode: - processFieldNode(lb, (FlatFieldNode)fn, isAtomic(atomictable, fn), currtable); - break; + processFieldNode(lb, (FlatFieldNode)fn, isAtomic(atomictable, fn), currtable); + break; case FKind.FlatSetFieldNode: - processSetFieldNode(lb, (FlatSetFieldNode)fn, isAtomic(atomictable,fn), currtable); - break; + processSetFieldNode(lb, (FlatSetFieldNode)fn, isAtomic(atomictable,fn), currtable); + break; case FKind.FlatNew: - processNew(lb, (FlatNew)fn, isAtomic(atomictable, fn), currtable); - break; + processNew(lb, (FlatNew)fn, isAtomic(atomictable, fn), currtable); + break; case FKind.FlatOpNode: - processOpNode((FlatOpNode)fn, currtable); - break; + processOpNode((FlatOpNode)fn, currtable); + break; case FKind.FlatCastNode: - processCastNode((FlatCastNode)fn, currtable); - break; + processCastNode((FlatCastNode)fn, currtable); + break; case FKind.FlatLiteralNode: - processLiteralNode((FlatLiteralNode)fn, currtable); - break; + processLiteralNode((FlatLiteralNode)fn, currtable); + break; case FKind.FlatReturnNode: - processReturnNode(lb, (FlatReturnNode)fn, currtable); - break; + processReturnNode(lb, (FlatReturnNode)fn, currtable); + break; case FKind.FlatSetElementNode: - processSetElementNode(lb, (FlatSetElementNode)fn, currtable, isAtomic(atomictable, fn)); - break; + processSetElementNode(lb, (FlatSetElementNode)fn, currtable, isAtomic(atomictable, fn)); + break; case FKind.FlatElementNode: - processElementNode(lb, (FlatElementNode)fn, currtable, isAtomic(atomictable, fn)); - break; + processElementNode(lb, (FlatElementNode)fn, currtable, isAtomic(atomictable, fn)); + break; case FKind.FlatInstanceOfNode: case FKind.FlatCondBranch: @@ -847,31 +847,31 @@ public class LocalityAnalysis { case FKind.FlatNop: case FKind.FlatExit: case FKind.FlatPrefetchNode: - //No action needed for these - break; + //No action needed for these + break; case FKind.FlatFlagActionNode: case FKind.FlatCheckNode: case FKind.FlatTagDeclaration: - throw new Error("Incompatible with tasks!"); + throw new Error("Incompatible with tasks!"); case FKind.FlatMethod: - break; + break; case FKind.FlatOffsetNode: - processOffsetNode((FlatOffsetNode)fn, currtable); - break; + processOffsetNode((FlatOffsetNode)fn, currtable); + break; default: - throw new Error("In finding fn.kind()= " + fn.kind()); + throw new Error("In finding fn.kind()= " + fn.kind()); } Hashtable oldtable=temptable.get(fn); if (oldtable==null||!oldtable.equals(currtable)) { - // Update table for this node - temptable.put(fn, currtable); - for(int i=0; i()); - classtolb.get(lb.getMethod().getClassDesc()).add(lb); - if (!methodtolb.containsKey(lb.getMethod())) - methodtolb.put(lb.getMethod(), new HashSet()); - methodtolb.get(lb.getMethod()).add(lb); + if (isnative) + lb.setGlobalReturn(LOCAL); + else + lb.setGlobalReturn(EITHER); + lb.setParent(currlb); + lbtovisit.add(lb); + discovered.put(lb, lb); + if (!classtolb.containsKey(lb.getMethod().getClassDesc())) + classtolb.put(lb.getMethod().getClassDesc(), new HashSet()); + classtolb.get(lb.getMethod().getClassDesc()).add(lb); + if (!methodtolb.containsKey(lb.getMethod())) + methodtolb.put(lb.getMethod(), new HashSet()); + methodtolb.get(lb.getMethod()).add(lb); } else - lb=discovered.get(lb); + lb=discovered.get(lb); Integer returnval=lb.getGlobalReturn(); currreturnval=merge(returnval, currreturnval); if (!dependence.containsKey(lb)) - dependence.put(lb, new HashSet()); + dependence.put(lb, new HashSet()); dependence.get(lb).add(currlb); if (!calldep.containsKey(currlb)) - calldep.put(currlb, new HashSet()); + calldep.put(currlb, new HashSet()); calldep.get(currlb).add(lb); } if (fc.getReturnTemp()!=null) { @@ -1035,23 +1035,23 @@ public class LocalityAnalysis { TempDescriptor dst=ffn.getDst(); if (type.equals(LOCAL)) { if (ffn.getField().isGlobal()) - currtable.put(dst,GLOBAL); + currtable.put(dst,GLOBAL); else - currtable.put(dst,LOCAL); + currtable.put(dst,LOCAL); } else if (type.equals(GLOBAL)) { if (!transaction) - throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation()); + throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation()); if (ffn.getField().getType().isPrimitive()&&!ffn.getField().getType().isArray()) - currtable.put(dst, LOCAL); // primitives are local + currtable.put(dst, LOCAL); // primitives are local else - currtable.put(dst, GLOBAL); + currtable.put(dst, GLOBAL); } else if (type.equals(EITHER)) { if (ffn.getField().getType().isPrimitive()&&!ffn.getField().getType().isArray()) - currtable.put(dst, LOCAL); // primitives are local + currtable.put(dst, LOCAL); // primitives are local else if (ffn.getField().isGlobal()) - currtable.put(dst, GLOBAL); + currtable.put(dst, GLOBAL); else - currtable.put(dst, EITHER); + currtable.put(dst, EITHER); } else if (type.equals(CONFLICT)) { throw new Error("Access to object that could be either global or local in context:\n"+lb.getExplanation()); } @@ -1064,24 +1064,24 @@ public class LocalityAnalysis { if (dsttype.equals(LOCAL)) { if (fsfn.getField().isGlobal()) { - if (!(srctype.equals(GLOBAL)||srctype.equals(EITHER))) - throw new Error("Writing possible local reference to global field in context: \n"+lb.getExplanation()); + if (!(srctype.equals(GLOBAL)||srctype.equals(EITHER))) + throw new Error("Writing possible local reference to global field in context: \n"+lb.getExplanation()); } else { - if (!(srctype.equals(LOCAL)||srctype.equals(EITHER))) { - throw new Error("Writing possible global reference to local object in context: \n"+lb.getExplanation()); - } + if (!(srctype.equals(LOCAL)||srctype.equals(EITHER))) { + throw new Error("Writing possible global reference to local object in context: \n"+lb.getExplanation()); + } } } else if (dsttype.equals(GLOBAL)) { if (!transaction) - throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation()); + throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation()); //okay to store primitives in global object if (srctype.equals(LOCAL) && fsfn.getField().getType().isPrimitive() && !fsfn.getField().getType().isArray()) - return; + return; if (!(srctype.equals(GLOBAL)||srctype.equals(EITHER))) - throw new Error("Writing possible local reference to global object in context:\n"+lb.getExplanation()+" for FlatFieldNode "+fsfn); + throw new Error("Writing possible local reference to global object in context:\n"+lb.getExplanation()+" for FlatFieldNode "+fsfn); } else if (dsttype.equals(EITHER)) { if (srctype.equals(CONFLICT)) - throw new Error("Using reference that could be local or global in context:\n"+lb.getExplanation()); + throw new Error("Using reference that could be local or global in context:\n"+lb.getExplanation()); } else if (dsttype.equals(CONFLICT)) { throw new Error("Access to object that could be either global or local in context:\n"+lb.getExplanation()); } @@ -1103,9 +1103,9 @@ public class LocalityAnalysis { if (srcvalue==null) { if (!fon.getLeft().getType().isPtr()) { - srcvalue=LOCAL; + srcvalue=LOCAL; } else - throw new Error(fon.getLeft()+" is undefined!"); + throw new Error(fon.getLeft()+" is undefined!"); } currtable.put(fon.getDest(), srcvalue); } @@ -1139,18 +1139,18 @@ public class LocalityAnalysis { if (dsttype.equals(LOCAL)) { if (!(srctype.equals(LOCAL)||srctype.equals(EITHER))) { - throw new Error("Writing possible global reference to local object in context:\n"+lb.getExplanation()+fsen); + throw new Error("Writing possible global reference to local object in context:\n"+lb.getExplanation()+fsen); } } else if (dsttype.equals(GLOBAL)) { if (srctype.equals(LOCAL) && fsen.getDst().getType().dereference().isPrimitive() && !fsen.getDst().getType().dereference().isArray()) - return; + return; if (!(srctype.equals(GLOBAL)||srctype.equals(EITHER))) - throw new Error("Writing possible local reference to global object in context:\n"+lb.getExplanation()); + throw new Error("Writing possible local reference to global object in context:\n"+lb.getExplanation()); if (!isatomic) - throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation()); + throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation()); } else if (dsttype.equals(EITHER)) { if (srctype.equals(CONFLICT)) - throw new Error("Using reference that could be local or global in context:\n"+lb.getExplanation()); + throw new Error("Using reference that could be local or global in context:\n"+lb.getExplanation()); } else if (dsttype.equals(CONFLICT)) { throw new Error("Access to object that could be either global or local in context:\n"+lb.getExplanation()); } @@ -1163,18 +1163,18 @@ public class LocalityAnalysis { currtable.put(dst,LOCAL); } else if (type.equals(GLOBAL)) { if (!isatomic) - throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation()); + throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation()); if(fen.getSrc().getType().dereference().isPrimitive()&& !fen.getSrc().getType().dereference().isArray()) - currtable.put(dst, LOCAL); + currtable.put(dst, LOCAL); else - currtable.put(dst, GLOBAL); + currtable.put(dst, GLOBAL); } else if (type.equals(EITHER)) { if(fen.getSrc().getType().dereference().isPrimitive()&& !fen.getSrc().getType().dereference().isArray()) - currtable.put(dst, LOCAL); + currtable.put(dst, LOCAL); else - currtable.put(dst, EITHER); + currtable.put(dst, EITHER); } else if (type.equals(CONFLICT)) { throw new Error("Access to object that could be either global or local in context:\n"+lb.getExplanation()); } @@ -1227,39 +1227,39 @@ public class LocalityAnalysis { boolean isatomic=atomictab.get(fn).intValue()>0; if (isatomic&& atomictab.get(fn.getPrev(0)).intValue()==0) { - assert(fn.kind()==FKind.FlatAtomicEnterNode); - nodemap.put(fn, (FlatAtomicEnterNode)fn); - nodetosavetemps.put((FlatAtomicEnterNode)fn, new HashSet()); + assert(fn.kind()==FKind.FlatAtomicEnterNode); + nodemap.put(fn, (FlatAtomicEnterNode)fn); + nodetosavetemps.put((FlatAtomicEnterNode)fn, new HashSet()); } else if (isatomic) { - FlatAtomicEnterNode atomicnode=nodemap.get(fn); - Set livetemps=nodetotemps.get(atomicnode); - List reads=Arrays.asList(fn.readsTemps()); - List writes=Arrays.asList(fn.writesTemps()); - - for(Iterator tempit=livetemps.iterator(); tempit.hasNext(); ) { - TempDescriptor tmp=tempit.next(); - if (writes.contains(tmp)) { - nodetosavetemps.get(atomicnode).add(tmp); - } else if (state.DSM) { - if (reads.contains(tmp)&&temptab.get(fn).get(tmp)==GLOBAL) { - nodetosavetemps.get(atomicnode).add(tmp); - } - } else if (state.SINGLETM) { - if (reads.contains(tmp)&&tmp.getType().isPtr()&&temptab.get(fn).get(tmp)==NORMAL) { - nodetosavetemps.get(atomicnode).add(tmp); - } - } - } + FlatAtomicEnterNode atomicnode=nodemap.get(fn); + Set livetemps=nodetotemps.get(atomicnode); + List reads=Arrays.asList(fn.readsTemps()); + List writes=Arrays.asList(fn.writesTemps()); + + for(Iterator tempit=livetemps.iterator(); tempit.hasNext(); ) { + TempDescriptor tmp=tempit.next(); + if (writes.contains(tmp)) { + nodetosavetemps.get(atomicnode).add(tmp); + } else if (state.DSM) { + if (reads.contains(tmp)&&temptab.get(fn).get(tmp)==GLOBAL) { + nodetosavetemps.get(atomicnode).add(tmp); + } + } else if (state.SINGLETM) { + if (reads.contains(tmp)&&tmp.getType().isPtr()&&temptab.get(fn).get(tmp)==NORMAL) { + nodetosavetemps.get(atomicnode).add(tmp); + } + } + } } for(int i=0; i set=transmap.get(td); for(Iterator it2=set.iterator(); it2.hasNext(); ) { - TypeDescriptor type=it2.next(); - if (!namemap.containsKey(type)) - namemap.put(type, new HashSet()); - namemap.get(type).addAll(set); + TypeDescriptor type=it2.next(); + if (!namemap.containsKey(type)) + namemap.put(type, new HashSet()); + namemap.get(type).addAll(set); } } } @@ -73,17 +73,17 @@ public class TypeAnalysis { transmap.get(td).add(td); while(!tovisit.isEmpty()) { - TypeDescriptor type=tovisit.iterator().next(); - tovisit.remove(type); - //Is type a supertype of td...if not skip along - if (!typeutil.isSuperorType(type,td)) - continue; - //Check if we have seen it before - if (!transmap.get(td).contains(type)) { - //If not, add to set and continue processing - transmap.get(td).add(type); - tovisit.add(type); - } + TypeDescriptor type=tovisit.iterator().next(); + tovisit.remove(type); + //Is type a supertype of td...if not skip along + if (!typeutil.isSuperorType(type,td)) + continue; + //Check if we have seen it before + if (!transmap.get(td).contains(type)) { + //If not, add to set and continue processing + transmap.get(td).add(type); + tovisit.add(type); + } } } } @@ -99,9 +99,9 @@ public class TypeAnalysis { TypeDescriptor td=it.next(); Set etdset=expand(td); if (etdset==null) - expandedSet.add(td); + expandedSet.add(td); else - expandedSet.addAll(etdset); + expandedSet.addAll(etdset); } return expandedSet; } @@ -122,82 +122,82 @@ public class TypeAnalysis { FlatNode fn=fnit.next(); switch(fn.kind()) { case FKind.FlatOpNode: { - FlatOpNode fon=(FlatOpNode)fn; - if(fon.getOp().getOp()==Operation.ASSIGN) { - addMapping(fon.getLeft().getType(),fon.getDest().getType()); - } - break; + FlatOpNode fon=(FlatOpNode)fn; + if(fon.getOp().getOp()==Operation.ASSIGN) { + addMapping(fon.getLeft().getType(),fon.getDest().getType()); + } + break; } case FKind.FlatNew: { - FlatNew fnew=(FlatNew)fn; - roottypes.add(fnew.getType()); - break; + FlatNew fnew=(FlatNew)fn; + roottypes.add(fnew.getType()); + break; } case FKind.FlatCastNode: { - FlatCastNode fcn=(FlatCastNode)fn; - addMapping(fcn.getSrc().getType(), fcn.getDst().getType()); - break; + FlatCastNode fcn=(FlatCastNode)fn; + addMapping(fcn.getSrc().getType(), fcn.getDst().getType()); + break; } case FKind.FlatFieldNode: { - FlatFieldNode ffn=(FlatFieldNode)fn; - addMapping(ffn.getField().getType(), ffn.getDst().getType()); - break; + FlatFieldNode ffn=(FlatFieldNode)fn; + addMapping(ffn.getField().getType(), ffn.getDst().getType()); + break; } case FKind.FlatSetFieldNode: { - FlatSetFieldNode fsfn=(FlatSetFieldNode) fn; - addMapping(fsfn.getSrc().getType(), fsfn.getField().getType()); - break; + FlatSetFieldNode fsfn=(FlatSetFieldNode) fn; + addMapping(fsfn.getSrc().getType(), fsfn.getField().getType()); + break; } case FKind.FlatElementNode: { - FlatElementNode fen=(FlatElementNode)fn; - addMapping(fen.getSrc().getType().dereference(), fen.getDst().getType()); - break; + FlatElementNode fen=(FlatElementNode)fn; + addMapping(fen.getSrc().getType().dereference(), fen.getDst().getType()); + break; } case FKind.FlatSetElementNode: { - FlatSetElementNode fsen=(FlatSetElementNode)fn; - addMapping(fsen.getSrc().getType(), fsen.getDst().getType().dereference()); - break; + FlatSetElementNode fsen=(FlatSetElementNode)fn; + addMapping(fsen.getSrc().getType(), fsen.getDst().getType().dereference()); + break; } case FKind.FlatCall: { - FlatCall fc=(FlatCall)fn; - if (fc.getReturnTemp()!=null) { - addMapping(fc.getMethod().getReturnType(), fc.getReturnTemp().getType()); - } - MethodDescriptor callmd=fc.getMethod(); - if (fc.getThis()!=null) { - //complicated...need to deal with virtual dispatch here - Set methods=cg.getMethods(callmd); - for(Iterator mdit=methods.iterator(); mdit.hasNext(); ) { - MethodDescriptor md2=(MethodDescriptor)mdit.next(); - if (fc.getThis()!=null) { - TypeDescriptor ttype=new TypeDescriptor(md2.getClassDesc()); - if (!typeutil.isSuperorType(fc.getThis().getType(),ttype)&& - !typeutil.isSuperorType(ttype,fc.getThis().getType())) - continue; - addMapping(fc.getThis().getType(), ttype); - } - } - } - for(int i=0; i tab=computeIntersection(fn, availexpr); //Do kills of expression/variable mappings TempDescriptor[] write=fn.writesTemps(); for(int i=0; i fields=gft.getFieldsAll(md); - Set arrays=gft.getArraysAll(md); - killexpressions(tab, fields, arrays, gft.containsAtomicAll(md)||gft.containsBarrierAll(md)); - break; + FlatCall fc=(FlatCall) fn; + MethodDescriptor md=fc.getMethod(); + Set fields=gft.getFieldsAll(md); + Set arrays=gft.getArraysAll(md); + killexpressions(tab, fields, arrays, gft.containsAtomicAll(md)||gft.containsBarrierAll(md)); + break; } case FKind.FlatOpNode: { - FlatOpNode fon=(FlatOpNode) fn; - Expression e=new Expression(fon.getLeft(), fon.getRight(), fon.getOp()); - tab.put(e, fon.getDest()); - break; + FlatOpNode fon=(FlatOpNode) fn; + Expression e=new Expression(fon.getLeft(), fon.getRight(), fon.getOp()); + tab.put(e, fon.getDest()); + break; } case FKind.FlatSetFieldNode: { - FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; - Set fields=new HashSet(); - fields.add(fsfn.getField()); - killexpressions(tab, fields, null, false); - Expression e=new Expression(fsfn.getDst(), fsfn.getField()); - tab.put(e, fsfn.getSrc()); - break; + FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; + Set fields=new HashSet(); + fields.add(fsfn.getField()); + killexpressions(tab, fields, null, false); + Expression e=new Expression(fsfn.getDst(), fsfn.getField()); + tab.put(e, fsfn.getSrc()); + break; } case FKind.FlatFieldNode: { - FlatFieldNode ffn=(FlatFieldNode)fn; - Expression e=new Expression(ffn.getSrc(), ffn.getField()); - tab.put(e, ffn.getDst()); - break; + FlatFieldNode ffn=(FlatFieldNode)fn; + Expression e=new Expression(ffn.getSrc(), ffn.getField()); + tab.put(e, ffn.getDst()); + break; } case FKind.FlatSetElementNode: { - FlatSetElementNode fsen=(FlatSetElementNode)fn; - Expression e=new Expression(fsen.getDst(),fsen.getIndex()); - tab.put(e, fsen.getSrc()); - break; + FlatSetElementNode fsen=(FlatSetElementNode)fn; + Expression e=new Expression(fsen.getDst(),fsen.getIndex()); + tab.put(e, fsen.getSrc()); + break; } case FKind.FlatElementNode: { - FlatElementNode fen=(FlatElementNode)fn; - Expression e=new Expression(fen.getSrc(),fen.getIndex()); - tab.put(e, fen.getDst()); - break; + FlatElementNode fen=(FlatElementNode)fn; + Expression e=new Expression(fen.getSrc(),fen.getIndex()); + tab.put(e, fen.getDst()); + break; } default: } if (write.length==1) { - TempDescriptor w=write[0]; - for(Iterator it=tab.entrySet().iterator(); it.hasNext(); ) { - Map.Entry m=(Map.Entry)it.next(); - Expression e=(Expression)m.getKey(); - if (e.a==w||e.b==w) - it.remove(); - } + TempDescriptor w=write[0]; + for(Iterator it=tab.entrySet().iterator(); it.hasNext(); ) { + Map.Entry m=(Map.Entry)it.next(); + Expression e=(Expression)m.getKey(); + if (e.a==w||e.b==w) + it.remove(); + } } if (!availexpr.containsKey(fn)||!availexpr.get(fn).equals(tab)) { - availexpr.put(fn, tab); - for(int i=0; i table=availexpr.get(prev); - for(Iterator mapit=tab.entrySet().iterator(); mapit.hasNext(); ) { - Object entry=mapit.next(); - if (!table.contains(entry)) - mapit.remove(); - } - } + if (availexpr.containsKey(prev)) { + Hashtable table=availexpr.get(prev); + for(Iterator mapit=tab.entrySet().iterator(); mapit.hasNext(); ) { + Object entry=mapit.next(); + if (!table.contains(entry)) + mapit.remove(); + } + } } } return tab; @@ -212,18 +212,18 @@ public class CSE { Map.Entry m=(Map.Entry)it.next(); Expression e=(Expression)m.getKey(); if (killall&&(e.f!=null||e.a!=null)) - it.remove(); + it.remove(); else if (e.f!=null&&fields!=null&&fields.contains(e.f)) - it.remove(); + it.remove(); else if ((e.a!=null)&&(arrays!=null)) { - for(Iterator arit=arrays.iterator(); arit.hasNext(); ) { - TypeDescriptor artd=arit.next(); - if (typeutil.isSuperorType(artd,e.a.getType())|| - typeutil.isSuperorType(e.a.getType(),artd)) { - it.remove(); - break; - } - } + for(Iterator arit=arrays.iterator(); arit.hasNext(); ) { + TypeDescriptor artd=arit.next(); + if (typeutil.isSuperorType(artd,e.a.getType())|| + typeutil.isSuperorType(e.a.getType(),artd)) { + it.remove(); + break; + } + } } } } diff --git a/Robust/src/Analysis/Loops/CopyPropagation.java b/Robust/src/Analysis/Loops/CopyPropagation.java index e8e60502..c4eead83 100644 --- a/Robust/src/Analysis/Loops/CopyPropagation.java +++ b/Robust/src/Analysis/Loops/CopyPropagation.java @@ -23,103 +23,103 @@ public class CopyPropagation { HashSet tovisit=new HashSet(); tovisit.add(fm); while(!tovisit.isEmpty()) { - FlatNode fn=(FlatNode) tovisit.iterator().next(); - tovisit.remove(fn); + FlatNode fn=(FlatNode) tovisit.iterator().next(); + tovisit.remove(fn); - Hashtable tab; - if (fn.numPrev()>=1&&table.containsKey(fn.getPrev(0))) - tab=new Hashtable(table.get(fn.getPrev(0))); - else - tab=new Hashtable(); - //Compute intersection + Hashtable tab; + if (fn.numPrev()>=1&&table.containsKey(fn.getPrev(0))) + tab=new Hashtable(table.get(fn.getPrev(0))); + else + tab=new Hashtable(); + //Compute intersection - Set liveset=livetemps.get(fn); - for(int i=1; i tp=table.get(fn.getPrev(i)); - if (tp==null) - continue; - for(Iterator tmpit=tp.entrySet().iterator(); tmpit.hasNext(); ) { - Map.Entry t=(Map.Entry)tmpit.next(); - TempDescriptor tmp=(TempDescriptor)t.getKey(); - if (!liveset.contains(tmp)) - continue; - TempDescriptor dsttmp=tp.get(tmp); - if (!tab.containsKey(tmp)) { - tab.put(tmp, dsttmp); - } else if (tab.get(tmp)!=dsttmp) { - tab.put(tmp, bogustd); - } - } - } + Set liveset=livetemps.get(fn); + for(int i=1; i tp=table.get(fn.getPrev(i)); + if (tp==null) + continue; + for(Iterator tmpit=tp.entrySet().iterator(); tmpit.hasNext(); ) { + Map.Entry t=(Map.Entry)tmpit.next(); + TempDescriptor tmp=(TempDescriptor)t.getKey(); + if (!liveset.contains(tmp)) + continue; + TempDescriptor dsttmp=tp.get(tmp); + if (!tab.containsKey(tmp)) { + tab.put(tmp, dsttmp); + } else if (tab.get(tmp)!=dsttmp) { + tab.put(tmp, bogustd); + } + } + } - HashSet toremove=new HashSet(); - TempDescriptor[] writes=fn.writesTemps(); - for(int i=0; i tmpit=tab.keySet().iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp2=tmpit.next(); - if (tmp==tab.get(tmp2)) - toremove.add(tmp2); - } - } + HashSet toremove=new HashSet(); + TempDescriptor[] writes=fn.writesTemps(); + for(int i=0; i tmpit=tab.keySet().iterator(); tmpit.hasNext(); ) { + TempDescriptor tmp2=tmpit.next(); + if (tmp==tab.get(tmp2)) + toremove.add(tmp2); + } + } - for(Iterator tmpit=toremove.iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - tab.put(tmp, bogustd); - } + for(Iterator tmpit=toremove.iterator(); tmpit.hasNext(); ) { + TempDescriptor tmp=tmpit.next(); + tab.put(tmp, bogustd); + } - if (fn.kind()==FKind.FlatOpNode) { - FlatOpNode fon=(FlatOpNode)fn; - if (fon.getOp().getOp()==Operation.ASSIGN) { - tab.put(fon.getDest(), fon.getLeft()); - } - } - if (!table.containsKey(fn)||!table.get(fn).equals(tab)) { - table.put(fn,tab); - changed=true; - for(int i=0; i nodeset=fm.getNodeSet(); for(Iterator it=fm.getNodeSet().iterator(); it.hasNext(); ) { - FlatNode fn=it.next(); - if (fn.numPrev()==0) - continue; + FlatNode fn=it.next(); + if (fn.numPrev()==0) + continue; - Hashtable tab=new Hashtable(); + Hashtable tab=new Hashtable(); - for(int i=0; i tp=table.get(fn.getPrev(i)); - for(Iterator tmpit=tp.entrySet().iterator(); tmpit.hasNext(); ) { - Map.Entry t=(Map.Entry)tmpit.next(); - TempDescriptor tmp=(TempDescriptor)t.getKey(); + for(int i=0; i tp=table.get(fn.getPrev(i)); + for(Iterator tmpit=tp.entrySet().iterator(); tmpit.hasNext(); ) { + Map.Entry t=(Map.Entry)tmpit.next(); + TempDescriptor tmp=(TempDescriptor)t.getKey(); - if (!tab.containsKey(tmp)) - tab.put(tmp, tp.get(tmp)); - else if (tab.get(tmp)!=tp.get(tmp)) { - tab.put(tmp, bogustd); - } - } - } + if (!tab.containsKey(tmp)) + tab.put(tmp, tp.get(tmp)); + else if (tab.get(tmp)!=tp.get(tmp)) { + tab.put(tmp, bogustd); + } + } + } - TempMap tmap=null; - TempDescriptor[] reads=fn.readsTemps(); - for(int i=0; i it=fm.getNodeSet().iterator(); it.hasNext(); ) { - FlatNode fn=it.next(); - switch(fn.kind()) { - case FKind.FlatCall: - case FKind.FlatFieldNode: - case FKind.FlatSetFieldNode: - case FKind.FlatNew: - case FKind.FlatCastNode: - case FKind.FlatReturnNode: - case FKind.FlatCondBranch: - case FKind.FlatSetElementNode: - case FKind.FlatElementNode: - case FKind.FlatFlagActionNode: - case FKind.FlatCheckNode: - case FKind.FlatBackEdge: - case FKind.FlatExit: - case FKind.FlatTagDeclaration: - case FKind.FlatMethod: - case FKind.FlatAtomicEnterNode: - case FKind.FlatAtomicExitNode: - case FKind.FlatPrefetchNode: - case FKind.FlatSESEEnterNode: - case FKind.FlatSESEExitNode: - case FKind.FlatGenReachNode: - if (!useful.contains(fn)) { - useful.add(fn); - changed=true; - } - break; + FlatNode fn=it.next(); + switch(fn.kind()) { + case FKind.FlatCall: + case FKind.FlatFieldNode: + case FKind.FlatSetFieldNode: + case FKind.FlatNew: + case FKind.FlatCastNode: + case FKind.FlatReturnNode: + case FKind.FlatCondBranch: + case FKind.FlatSetElementNode: + case FKind.FlatElementNode: + case FKind.FlatFlagActionNode: + case FKind.FlatCheckNode: + case FKind.FlatBackEdge: + case FKind.FlatExit: + case FKind.FlatTagDeclaration: + case FKind.FlatMethod: + case FKind.FlatAtomicEnterNode: + case FKind.FlatAtomicExitNode: + case FKind.FlatPrefetchNode: + case FKind.FlatSESEEnterNode: + case FKind.FlatSESEExitNode: + case FKind.FlatGenReachNode: + if (!useful.contains(fn)) { + useful.add(fn); + changed=true; + } + break; - case FKind.FlatOpNode: - FlatOpNode fon=(FlatOpNode)fn; - if (fon.getOp().getOp()==Operation.DIV|| - fon.getOp().getOp()==Operation.MOD) { - if (!useful.contains(fn)) { - useful.add(fn); - changed=true; - } - break; - } + case FKind.FlatOpNode: + FlatOpNode fon=(FlatOpNode)fn; + if (fon.getOp().getOp()==Operation.DIV|| + fon.getOp().getOp()==Operation.MOD) { + if (!useful.contains(fn)) { + useful.add(fn); + changed=true; + } + break; + } - default: - TempDescriptor[] writes=fn.writesTemps(); - if (!useful.contains(fn)) - for(int i=0; i uit=ud.useMap(fn,writes[i]).iterator(); uit.hasNext(); ) { - FlatNode ufn=uit.next(); - if (useful.contains(ufn)) { - //we are useful - useful.add(fn); - changed=true; - continue nextfn; - } - } - } - } + default: + TempDescriptor[] writes=fn.writesTemps(); + if (!useful.contains(fn)) + for(int i=0; i uit=ud.useMap(fn,writes[i]).iterator(); uit.hasNext(); ) { + FlatNode ufn=uit.next(); + if (useful.contains(ufn)) { + //we are useful + useful.add(fn); + changed=true; + continue nextfn; + } + } + } + } } } //get rid of useless nodes for(Iterator it=fm.getNodeSet().iterator(); it.hasNext(); ) { FlatNode fn=it.next(); if (!useful.contains(fn)||isuseless(fn)) { - //We have a useless node - FlatNode fnnext=fn.getNext(0); - for(int i=0; i fnodes=fm.getNodeSet(); Vector v=new Vector(); for(Iterator fit=fnodes.iterator(); fit.hasNext(); ) { - FlatNode fn=fit.next(); - if (fn.numNext()==0) { - v.add(fn); - } + FlatNode fn=fit.next(); + if (fn.numNext()==0) { + v.add(fn); + } } FlatNode[] fnarray=new FlatNode[v.size()]; for(int i=0; i set=new HashSet (); - set.add(fnarray[i]); - childtree.put(fnarray[i],set); + fnarray[i]=v.elementAt(i); + domtable.put(fnarray[i],fnarray[i]); + HashSet set=new HashSet (); + set.add(fnarray[i]); + childtree.put(fnarray[i],set); } DFS(fnarray, postdominator); } else { @@ -59,26 +59,26 @@ public class DomTree { while(changed) { changed=false; for(int i=vec.size()-2; i>=0; i--) { - FlatNode fn=vec.elementAt(i); - FlatNode dom=null; - for(int j=0; j<(postdominator?fn.numNext():fn.numPrev()); j++) { - FlatNode np=postdominator?fn.getNext(j):fn.getPrev(j); - FlatNode ndom=domtable.get(np); - if (ndom!=null) { - if (dom==null) - dom=np; - else - dom=intersect(dom,np); - } - } - if (!domtable.containsKey(fn)|| - !domtable.get(fn).equals(dom)) { - domtable.put(fn,dom); - if (!childtree.containsKey(dom)) - childtree.put(dom, new HashSet()); - childtree.get(dom).add(fn); - changed=true; - } + FlatNode fn=vec.elementAt(i); + FlatNode dom=null; + for(int j=0; j<(postdominator?fn.numNext():fn.numPrev()); j++) { + FlatNode np=postdominator?fn.getNext(j):fn.getPrev(j); + FlatNode ndom=domtable.get(np); + if (ndom!=null) { + if (dom==null) + dom=np; + else + dom=intersect(dom,np); + } + } + if (!domtable.containsKey(fn)|| + !domtable.get(fn).equals(dom)) { + domtable.put(fn,dom); + if (!childtree.containsKey(dom)) + childtree.put(dom, new HashSet()); + childtree.get(dom).add(fn); + changed=true; + } } } } @@ -88,12 +88,12 @@ public class DomTree { int ifb=vecindex.get(fb).intValue(); while(ifa!=ifb) { while (ifa run link - MethodDescriptor runmd=null; - for(Iterator methodit=md.getClassDesc().getMethodTable().getSet("run").iterator(); methodit.hasNext(); ) { - MethodDescriptor mdrun=(MethodDescriptor) methodit.next(); - if (mdrun.numParameters()!=0||mdrun.getModifiers().isStatic()) - continue; - runmd=mdrun; - break; - } - if (runmd!=null) { - Set runmethodset=cg.getMethods(runmd); - for(Iterator it=runmethodset.iterator(); it.hasNext(); ) { - MethodDescriptor md2=(MethodDescriptor)it.next(); - if (!discovered.contains(md2)) { - discovered.add(md2); - toprocess.add(md2); - } - } - } else throw new Error("Can't find run method"); + //start -> run link + MethodDescriptor runmd=null; + for(Iterator methodit=md.getClassDesc().getMethodTable().getSet("run").iterator(); methodit.hasNext(); ) { + MethodDescriptor mdrun=(MethodDescriptor) methodit.next(); + if (mdrun.numParameters()!=0||mdrun.getModifiers().isStatic()) + continue; + runmd=mdrun; + break; + } + if (runmd!=null) { + Set runmethodset=cg.getMethods(runmd); + for(Iterator it=runmethodset.iterator(); it.hasNext(); ) { + MethodDescriptor md2=(MethodDescriptor)it.next(); + if (!discovered.contains(md2)) { + discovered.add(md2); + toprocess.add(md2); + } + } + } else throw new Error("Can't find run method"); } } boolean changed=true; while(changed) { changed=false; for(Iterator it=discovered.iterator(); it.hasNext(); ) { - MethodDescriptor md=(MethodDescriptor)it.next(); - Set callees=cg.getCalleeSet(md); - for(Iterator cit=callees.iterator(); cit.hasNext(); ) { - MethodDescriptor md2=(MethodDescriptor)cit.next(); - if (fields.get(md).addAll(fields.get(md2))) - changed=true; - if (arrays.get(md).addAll(arrays.get(md2))) - changed=true; - if (fieldsrd.get(md).addAll(fieldsrd.get(md2))) - changed=true; - if (arraysrd.get(md).addAll(arraysrd.get(md2))) - changed=true; - if (containsAtomic.contains(md2)) { - if (containsAtomic.add(md)) - changed=true; - } - if (containsBarrier.contains(md2)) { - if (containsBarrier.add(md)) - changed=true; - } - } + MethodDescriptor md=(MethodDescriptor)it.next(); + Set callees=cg.getCalleeSet(md); + for(Iterator cit=callees.iterator(); cit.hasNext(); ) { + MethodDescriptor md2=(MethodDescriptor)cit.next(); + if (fields.get(md).addAll(fields.get(md2))) + changed=true; + if (arrays.get(md).addAll(arrays.get(md2))) + changed=true; + if (fieldsrd.get(md).addAll(fieldsrd.get(md2))) + changed=true; + if (arraysrd.get(md).addAll(arraysrd.get(md2))) + changed=true; + if (containsAtomic.contains(md2)) { + if (containsAtomic.add(md)) + changed=true; + } + if (containsBarrier.contains(md2)) { + if (containsBarrier.add(md)) + changed=true; + } + } } } } @@ -134,7 +134,7 @@ public class GlobalFieldType { for(Iterator it=methodset.iterator(); it.hasNext(); ) { MethodDescriptor md2=(MethodDescriptor)it.next(); if (containsAtomic.contains(md2)) - return true; + return true; } return false; } @@ -144,7 +144,7 @@ public class GlobalFieldType { for(Iterator it=methodset.iterator(); it.hasNext(); ) { MethodDescriptor md2=(MethodDescriptor)it.next(); if (containsBarrier.contains(md2)) - return true; + return true; } return false; } @@ -155,7 +155,7 @@ public class GlobalFieldType { for(Iterator it=methodset.iterator(); it.hasNext(); ) { MethodDescriptor md2=(MethodDescriptor)it.next(); if (fields.containsKey(md2)) - s.addAll(fields.get(md2)); + s.addAll(fields.get(md2)); } return s; } @@ -166,7 +166,7 @@ public class GlobalFieldType { for(Iterator it=methodset.iterator(); it.hasNext(); ) { MethodDescriptor md2=(MethodDescriptor)it.next(); if (arrays.containsKey(md2)) - s.addAll(arrays.get(md2)); + s.addAll(arrays.get(md2)); } return s; } @@ -177,7 +177,7 @@ public class GlobalFieldType { for(Iterator it=methodset.iterator(); it.hasNext(); ) { MethodDescriptor md2=(MethodDescriptor)it.next(); if (fieldsrd.containsKey(md2)) - s.addAll(fieldsrd.get(md2)); + s.addAll(fieldsrd.get(md2)); } return s; } @@ -188,7 +188,7 @@ public class GlobalFieldType { for(Iterator it=methodset.iterator(); it.hasNext(); ) { MethodDescriptor md2=(MethodDescriptor)it.next(); if (arraysrd.containsKey(md2)) - s.addAll(arraysrd.get(md2)); + s.addAll(arraysrd.get(md2)); } return s; } @@ -203,32 +203,32 @@ public class GlobalFieldType { for(Iterator it=fm.getNodeSet().iterator(); it.hasNext(); ) { FlatNode fn=(FlatNode)it.next(); if (fn.kind()==FKind.FlatSetElementNode) { - FlatSetElementNode fsen=(FlatSetElementNode)fn; - arrays.get(md).add(fsen.getDst().getType()); + FlatSetElementNode fsen=(FlatSetElementNode)fn; + arrays.get(md).add(fsen.getDst().getType()); } else if (fn.kind()==FKind.FlatElementNode) { - FlatElementNode fen=(FlatElementNode)fn; - arraysrd.get(md).add(fen.getSrc().getType()); + FlatElementNode fen=(FlatElementNode)fn; + arraysrd.get(md).add(fen.getSrc().getType()); } else if (fn.kind()==FKind.FlatSetFieldNode) { - FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; - fields.get(md).add(fsfn.getField()); + FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; + fields.get(md).add(fsfn.getField()); } else if (fn.kind()==FKind.FlatFieldNode) { - FlatFieldNode ffn=(FlatFieldNode)fn; - fieldsrd.get(md).add(ffn.getField()); + FlatFieldNode ffn=(FlatFieldNode)fn; + fieldsrd.get(md).add(ffn.getField()); } else if (fn.kind()==FKind.FlatAtomicEnterNode) { - containsAtomic.add(md); + containsAtomic.add(md); } else if (fn.kind()==FKind.FlatCall) { - MethodDescriptor mdcall=((FlatCall)fn).getMethod(); - if (mdcall.getSymbol().equals("enterBarrier")&& - mdcall.getClassDesc().getSymbol().equals("Barrier")) { - containsBarrier.add(md); - containsBarrier.add(mdcall); - } - //treat lock acquire the same as a barrier - if ((mdcall.getSymbol().equals("MonitorEnter")||mdcall.getSymbol().equals("MonitorExit")||mdcall.getSymbol().equals("wait"))&& - mdcall.getClassDesc().getSymbol().equals("Object")) { - containsBarrier.add(md); - containsBarrier.add(mdcall); - } + MethodDescriptor mdcall=((FlatCall)fn).getMethod(); + if (mdcall.getSymbol().equals("enterBarrier")&& + mdcall.getClassDesc().getSymbol().equals("Barrier")) { + containsBarrier.add(md); + containsBarrier.add(mdcall); + } + //treat lock acquire the same as a barrier + if ((mdcall.getSymbol().equals("MonitorEnter")||mdcall.getSymbol().equals("MonitorExit")||mdcall.getSymbol().equals("wait"))&& + mdcall.getClassDesc().getSymbol().equals("Object")) { + containsBarrier.add(md); + containsBarrier.add(mdcall); + } } } } diff --git a/Robust/src/Analysis/Loops/LoopFinder.java b/Robust/src/Analysis/Loops/LoopFinder.java index 8ba27e8b..9794a650 100755 --- a/Robust/src/Analysis/Loops/LoopFinder.java +++ b/Robust/src/Analysis/Loops/LoopFinder.java @@ -15,7 +15,7 @@ import java.util.Iterator; * LoopFinder implements Dominator Tree Loop detection. * * @author Brian Demsky - * @version $Id: LoopFinder.java,v 1.4 2011/04/27 20:34:22 bdemsky Exp $ + * @version $Id: LoopFinder.java,v 1.5 2011/04/27 20:51:36 bdemsky Exp $ */ public class LoopFinder implements Loops { @@ -173,7 +173,7 @@ public class LoopFinder implements Loops { //Add it to the tree, complain if oddness if (addnode(A, root)!=1) - System.out.println("Evil Error in LoopFinder while building tree."); + System.out.println("Evil Error in LoopFinder while building tree."); } } @@ -186,70 +186,70 @@ public class LoopFinder implements Loops { //Do we share headers? if (treenode.header!=A.header) { - //No... Loop through our children to see if they want this - //node. + //No... Loop through our children to see if they want this + //node. - //Use integers for tri-state: - //0=not stored here, 1=stored and everything is good - //2=combined 2 natural loops with same header...need cleanup + //Use integers for tri-state: + //0=not stored here, 1=stored and everything is good + //2=combined 2 natural loops with same header...need cleanup - int stored=0; - Iterator iterate=treenode.children.iterator(); - Loop temp=new Loop(); - while (iterate.hasNext()) { - temp=(Loop) iterate.next(); - stored=addnode(A,temp); - if (stored!=0) break; - } + int stored=0; + Iterator iterate=treenode.children.iterator(); + Loop temp=new Loop(); + while (iterate.hasNext()) { + temp=(Loop) iterate.next(); + stored=addnode(A,temp); + if (stored!=0) break; + } - //See what our children did for us + //See what our children did for us - if (stored==0) { - //We get a new child... - treenode.children.add(A); - temp=A; - } + if (stored==0) { + //We get a new child... + treenode.children.add(A); + temp=A; + } - //Need to do cleanup for case 0 or 2 - //temp points to the new child + //Need to do cleanup for case 0 or 2 + //temp points to the new child - if (stored!=1) { + if (stored!=1) { - //Have to make sure that none of the nodes under this one - //are children of the new node + //Have to make sure that none of the nodes under this one + //are children of the new node - Iterator iterate2=treenode.children.iterator(); - temp.parent=treenode; + Iterator iterate2=treenode.children.iterator(); + temp.parent=treenode; - //Loop through the children - while (iterate2.hasNext()) { - Loop temp2=(Loop)iterate2.next(); + //Loop through the children + while (iterate2.hasNext()) { + Loop temp2=(Loop)iterate2.next(); - //Don't look at the new node...otherwise we will create - //a unreachable subtree + //Don't look at the new node...otherwise we will create + //a unreachable subtree - if (temp2!=temp) - //If the new node has a childs header - //give the child up to it... + if (temp2!=temp) + //If the new node has a childs header + //give the child up to it... - if (temp.entries.contains(temp2.header)) { - temp.children.add(temp2); - iterate2.remove(); - } - } - } + if (temp.entries.contains(temp2.header)) { + temp.children.add(temp2); + iterate2.remove(); + } + } + } - //We fixed everything...let our parents know - return 1; + //We fixed everything...let our parents know + return 1; } else { - //need to combine loops - while (!A.entries.isEmpty()) { - FlatNode node=(FlatNode)A.entries.iterator().next(); - A.entries.remove(node); - treenode.entries.add(node); - } - //let the previous caller know that they have stuff todo - return 2; + //need to combine loops + while (!A.entries.isEmpty()) { + FlatNode node=(FlatNode)A.entries.iterator().next(); + A.entries.remove(node); + treenode.entries.add(node); + } + //let the previous caller know that they have stuff todo + return 2; } //We aren't adopting the new node else return 0; @@ -270,11 +270,11 @@ public class LoopFinder implements Loops { Set children=dominator.children(current_node); if (children!=null) { - for(Iterator it=children.iterator(); it.hasNext(); ) { - FlatNode fn=it.next(); - if (fn!=current_node) - stk.push(fn); - } + for(Iterator it=children.iterator(); it.hasNext(); ) { + FlatNode fn=it.next(); + if (fn!=current_node) + stk.push(fn); + } } } } @@ -293,7 +293,7 @@ public class LoopFinder implements Loops { //find the node we jump back too while ((temp!=hc)&& (temp_to!=temp)) { - temp=dominator.idom(temp); + temp=dominator.idom(temp); } //If we found the node we jumped back to @@ -301,33 +301,33 @@ public class LoopFinder implements Loops { if (temp_to==temp) { - //found a loop - A.entries.add(temp); //Push the header - A.header=temp; - B.add(q); //Put the backedge in the todo list - - //Starting with the backedge, work on the incoming edges - //until we get back to the loop header... - //Then we have the entire natural loop - - while(!B.isEmpty()) { - FlatNode newnode=(FlatNode)B.iterator().next(); - B.remove(newnode); - - //Add all of the new incoming edges that we haven't already - //visited - for (int j=0; j f=gft.getFieldsAll(md); - Set t=gft.getArraysAll(md); - if (f!=null) - fields.addAll(f); - if (t!=null) - types.addAll(t); - if (gft.containsAtomicAll(md)||gft.containsBarrierAll(md)) { - unsafe=true; - } - } else if (fn.kind()==FKind.FlatSetFieldNode) { - FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; - fields.add(fsfn.getField()); - } else if (fn.kind()==FKind.FlatSetElementNode) { - FlatSetElementNode fsen=(FlatSetElementNode)fn; - types.add(fsen.getDst().getType()); - } + FlatNode fn=(FlatNode)elit.next(); + if (fn.kind()==FKind.FlatAtomicEnterNode|| + fn.kind()==FKind.FlatAtomicExitNode) { + unsafe=true; + break; + } else if (fn.kind()==FKind.FlatCall) { + FlatCall fcall=(FlatCall)fn; + MethodDescriptor md=fcall.getMethod(); + Set f=gft.getFieldsAll(md); + Set t=gft.getArraysAll(md); + if (f!=null) + fields.addAll(f); + if (t!=null) + types.addAll(t); + if (gft.containsAtomicAll(md)||gft.containsBarrierAll(md)) { + unsafe=true; + } + } else if (fn.kind()==FKind.FlatSetFieldNode) { + FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; + fields.add(fsfn.getField()); + } else if (fn.kind()==FKind.FlatSetElementNode) { + FlatSetElementNode fsen=(FlatSetElementNode)fn; + types.add(fsen.getDst().getType()); + } } } @@ -99,59 +99,59 @@ public class LoopInvariant { changed=false; nextfn: for(Iterator tpit=toprocess.iterator(); tpit.hasNext(); ) { - FlatNode fn=(FlatNode)tpit.next(); - switch(fn.kind()) { - case FKind.FlatOpNode: - int op=((FlatOpNode)fn).getOp().getOp(); - if (op==Operation.DIV||op==Operation.MOD|| - checkNode(fn,elements)|| - !unsafe&&!dominatorset.contains(fn)) { - continue nextfn; - } - break; + FlatNode fn=(FlatNode)tpit.next(); + switch(fn.kind()) { + case FKind.FlatOpNode: + int op=((FlatOpNode)fn).getOp().getOp(); + if (op==Operation.DIV||op==Operation.MOD|| + checkNode(fn,elements)|| + !unsafe&&!dominatorset.contains(fn)) { + continue nextfn; + } + break; - case FKind.FlatInstanceOfNode: - if (checkNode(fn,elements)|| - !unsafe&&!dominatorset.contains(fn)) { - continue nextfn; - } - break; + case FKind.FlatInstanceOfNode: + if (checkNode(fn,elements)|| + !unsafe&&!dominatorset.contains(fn)) { + continue nextfn; + } + break; - case FKind.FlatElementNode: - if (unsafe||dominatorset==null|| - !dominatorset.contains(fn)|| - checkNode(fn,elements)) - continue nextfn; - TypeDescriptor td=((FlatElementNode)fn).getSrc().getType(); - for(Iterator tdit=types.iterator(); tdit.hasNext(); ) { - TypeDescriptor td2=tdit.next(); - if (typeutil.isSuperorType(td,td2)|| - typeutil.isSuperorType(td2,td)) { - continue nextfn; - } - } - if (isLeaf) - tounroll.add(entrance); - break; + case FKind.FlatElementNode: + if (unsafe||dominatorset==null|| + !dominatorset.contains(fn)|| + checkNode(fn,elements)) + continue nextfn; + TypeDescriptor td=((FlatElementNode)fn).getSrc().getType(); + for(Iterator tdit=types.iterator(); tdit.hasNext(); ) { + TypeDescriptor td2=tdit.next(); + if (typeutil.isSuperorType(td,td2)|| + typeutil.isSuperorType(td2,td)) { + continue nextfn; + } + } + if (isLeaf) + tounroll.add(entrance); + break; - case FKind.FlatFieldNode: - if (unsafe||dominatorset==null|| - !dominatorset.contains(fn)|| - fields.contains(((FlatFieldNode)fn).getField())|| - checkNode(fn,elements)) { - continue nextfn; - } - if (isLeaf) - tounroll.add(entrance); - break; + case FKind.FlatFieldNode: + if (unsafe||dominatorset==null|| + !dominatorset.contains(fn)|| + fields.contains(((FlatFieldNode)fn).getField())|| + checkNode(fn,elements)) { + continue nextfn; + } + if (isLeaf) + tounroll.add(entrance); + break; - default: - continue nextfn; - } - //mark to hoist - if (hoisted.add(fn)) - changed=true; - table.get(entrance).add(fn); + default: + continue nextfn; + } + //mark to hoist + if (hoisted.add(fn)) + changed=true; + table.get(entrance).add(fn); } } } @@ -168,23 +168,23 @@ nextfn: for (int i=0; i defset=usedef.defMap(fn, t); for(Iterator defit=defset.iterator(); defit.hasNext(); ) { - FlatNode def=defit.next(); - if (elements.contains(def)&&defset.size()>1) - return true; - if (elements.contains(def)&&!hoisted.contains(def)) - return true; + FlatNode def=defit.next(); + if (elements.contains(def)&&defset.size()>1) + return true; + if (elements.contains(def)&&!hoisted.contains(def)) + return true; } } return false; diff --git a/Robust/src/Analysis/Loops/LoopOptimize.java b/Robust/src/Analysis/Loops/LoopOptimize.java index d23b1707..3571704d 100644 --- a/Robust/src/Analysis/Loops/LoopOptimize.java +++ b/Robust/src/Analysis/Loops/LoopOptimize.java @@ -81,12 +81,12 @@ public class LoopOptimize { //deal with the possiblity we already hoisted this node if (clonemap.containsKey(fn)) { - FlatNode fnnew=clonemap.get(fn); - TempDescriptor writenew[]=fnnew.writesTemps(); - t.addPair(writes[0],writenew[0]); - if (fn==entrance) - entrance=map.get(fn); - continue; + FlatNode fnnew=clonemap.get(fn); + TempDescriptor writenew[]=fnnew.writesTemps(); + t.addPair(writes[0],writenew[0]); + if (fn==entrance) + entrance=map.get(fn); + continue; } //build hoisted version @@ -94,10 +94,10 @@ public class LoopOptimize { fnnew.rewriteUse(t); for(int j=0; j1) { - throw new Error(); + throw new Error(); } } /* If the chain is empty, we can exit now */ @@ -136,11 +136,11 @@ public class LoopOptimize { FlatNode prev=prevarray[i]; if (!lelements.contains(ntooremap(prev))) { - //need to fix this edge - for(int j=0; j s=new HashSet(); Set liveset=livemap.get(fn); for(int i=0; i prevs=tmp.get(prev); - if (prevs!=null) { + FlatNode prev=fn.getPrev(i); + Set prevs=tmp.get(prev); + if (prevs!=null) { nexttfp: - for(Iterator tfit=prevs.iterator(); tfit.hasNext(); ) { - TempFlatPair tfp=tfit.next(); - if (!liveset.contains(tfp.t)) - continue; - for(int j=0; j tfit=prevs.iterator(); tfit.hasNext(); ) { + TempFlatPair tfp=tfit.next(); + if (!liveset.contains(tfp.t)) + continue; + for(int j=0; j fset=fm.getNodeSet(); @@ -85,20 +85,20 @@ nexttfp: Set tfpset=tmp.get(fn); for(int i=0; i tfpit=tfpset.iterator(); tfpit.hasNext(); ) { - TempFlatPair tfp=tfpit.next(); - if (tfp.t==readt) { - //have use - if (!uses.containsKey(tfp)) - uses.put(tfp,new HashSet()); - uses.get(tfp).add(fn); - TempFlatPair readtfp=new TempFlatPair(readt,fn); - if (!defs.containsKey(readtfp)) - defs.put(readtfp,new HashSet()); - defs.get(readtfp).add(tfp.f); - } - } + TempDescriptor readt=fnreads[i]; + for(Iterator tfpit=tfpset.iterator(); tfpit.hasNext(); ) { + TempFlatPair tfp=tfpit.next(); + if (tfp.t==readt) { + //have use + if (!uses.containsKey(tfp)) + uses.put(tfp,new HashSet()); + uses.get(tfp).add(fn); + TempFlatPair readtfp=new TempFlatPair(readt,fn); + if (!defs.containsKey(readtfp)) + defs.put(readtfp,new HashSet()); + defs.get(readtfp).add(tfp.f); + } + } } } } diff --git a/Robust/src/Analysis/Loops/WriteBarrier.java b/Robust/src/Analysis/Loops/WriteBarrier.java index 464e03e3..4ff0ee3e 100644 --- a/Robust/src/Analysis/Loops/WriteBarrier.java +++ b/Robust/src/Analysis/Loops/WriteBarrier.java @@ -73,65 +73,65 @@ public class WriteBarrier { FlatNode fn=(FlatNode)toprocess.iterator().next(); toprocess.remove(fn); for(int i=0; i nb=computeIntersection(fn); TempDescriptor[] writes=fn.writesTemps(); for(int i=0; i0&& - atomic.get(fn.getPrev(0)).intValue()==0) { - nb=new HashSet(); - } + //If we enter a transaction toss everything + if (atomic.get(fn).intValue()>0&& + atomic.get(fn.getPrev(0)).intValue()==0) { + nb=new HashSet(); + } } if (!needbarrier.containsKey(fn)|| !needbarrier.get(fn).equals(nb)) { - for(int i=0; i hs=needbarrier.get(fprev); if (hs!=null) { - if (first) { - tab.addAll(hs); - first=false; - } else { - //Intersect sets - for(Iterator it=tab.iterator(); it.hasNext(); ) { - TempDescriptor t=it.next(); - if (!hs.contains(t)) - it.remove(); - } - } + if (first) { + tab.addAll(hs); + first=false; + } else { + //Intersect sets + for(Iterator it=tab.iterator(); it.hasNext(); ) { + TempDescriptor t=it.next(); + if (!hs.contains(t)) + it.remove(); + } + } } } return tab; diff --git a/Robust/src/Analysis/Loops/localCSE.java b/Robust/src/Analysis/Loops/localCSE.java index 7ca5681b..34bed0c9 100644 --- a/Robust/src/Analysis/Loops/localCSE.java +++ b/Robust/src/Analysis/Loops/localCSE.java @@ -38,7 +38,7 @@ public class localCSE { for(Iterator it=g.set.iterator(); it.hasNext(); ) { LocalExpression e=(LocalExpression)it.next(); if (e.t!=null) - return e.t; + return e.t; } return null; } @@ -49,129 +49,129 @@ public class localCSE { for(Iterator it=nodes.iterator(); it.hasNext(); ) { FlatNode fn=(FlatNode)it.next(); if (fn.numPrev()>1) - toanalyze.add(fn); + toanalyze.add(fn); } for(Iterator it=toanalyze.iterator(); it.hasNext(); ) { FlatNode fn=it.next(); Hashtable table=new Hashtable(); do { - index=0; - switch(fn.kind()) { - case FKind.FlatOpNode: { - FlatOpNode fon=(FlatOpNode)fn; - Group left=getGroup(table, fon.getLeft()); - Group right=getGroup(table, fon.getRight()); - LocalExpression dst=new LocalExpression(fon.getDest()); - if (fon.getOp().getOp()==Operation.ASSIGN) { - left.set.add(dst); - kill(table, fon.getDest()); - table.put(dst, left); - } else { - LocalExpression e=new LocalExpression(left, right, fon.getOp()); - Group g=getGroup(table,e); - TempDescriptor td=getTemp(g); - if (td!=null) { - FlatNode nfon=new FlatOpNode(fon.getDest(),td,null,new Operation(Operation.ASSIGN)); - fn.replace(nfon); - } - g.set.add(dst); - kill(table, fon.getDest()); - table.put(dst,g); - } - break; - } + index=0; + switch(fn.kind()) { + case FKind.FlatOpNode: { + FlatOpNode fon=(FlatOpNode)fn; + Group left=getGroup(table, fon.getLeft()); + Group right=getGroup(table, fon.getRight()); + LocalExpression dst=new LocalExpression(fon.getDest()); + if (fon.getOp().getOp()==Operation.ASSIGN) { + left.set.add(dst); + kill(table, fon.getDest()); + table.put(dst, left); + } else { + LocalExpression e=new LocalExpression(left, right, fon.getOp()); + Group g=getGroup(table,e); + TempDescriptor td=getTemp(g); + if (td!=null) { + FlatNode nfon=new FlatOpNode(fon.getDest(),td,null,new Operation(Operation.ASSIGN)); + fn.replace(nfon); + } + g.set.add(dst); + kill(table, fon.getDest()); + table.put(dst,g); + } + break; + } - case FKind.FlatLiteralNode: { - FlatLiteralNode fln=(FlatLiteralNode)fn; - LocalExpression e=new LocalExpression(fln.getValue()); - Group src=getGroup(table, e); - LocalExpression dst=new LocalExpression(fln.getDst()); - src.set.add(dst); - kill(table, fln.getDst()); - table.put(dst, src); - break; - } + case FKind.FlatLiteralNode: { + FlatLiteralNode fln=(FlatLiteralNode)fn; + LocalExpression e=new LocalExpression(fln.getValue()); + Group src=getGroup(table, e); + LocalExpression dst=new LocalExpression(fln.getDst()); + src.set.add(dst); + kill(table, fln.getDst()); + table.put(dst, src); + break; + } - case FKind.FlatFieldNode: { - FlatFieldNode ffn=(FlatFieldNode) fn; - Group src=getGroup(table, ffn.getSrc()); - LocalExpression e=new LocalExpression(src, ffn.getField()); - Group srcf=getGroup(table, e); - LocalExpression dst=new LocalExpression(ffn.getDst()); - TempDescriptor td=getTemp(srcf); - if (td!=null) { - FlatOpNode fon=new FlatOpNode(ffn.getDst(),td,null,new Operation(Operation.ASSIGN)); - fn.replace(fon); - } - srcf.set.add(dst); - kill(table, ffn.getDst()); - table.put(dst, srcf); - break; - } + case FKind.FlatFieldNode: { + FlatFieldNode ffn=(FlatFieldNode) fn; + Group src=getGroup(table, ffn.getSrc()); + LocalExpression e=new LocalExpression(src, ffn.getField()); + Group srcf=getGroup(table, e); + LocalExpression dst=new LocalExpression(ffn.getDst()); + TempDescriptor td=getTemp(srcf); + if (td!=null) { + FlatOpNode fon=new FlatOpNode(ffn.getDst(),td,null,new Operation(Operation.ASSIGN)); + fn.replace(fon); + } + srcf.set.add(dst); + kill(table, ffn.getDst()); + table.put(dst, srcf); + break; + } - case FKind.FlatElementNode: { - FlatElementNode fen=(FlatElementNode) fn; - Group src=getGroup(table, fen.getSrc()); - Group index=getGroup(table, fen.getIndex()); - LocalExpression e=new LocalExpression(src, fen.getSrc().getType(), index); - Group srcf=getGroup(table, e); - LocalExpression dst=new LocalExpression(fen.getDst()); - TempDescriptor td=getTemp(srcf); - if (td!=null) { - FlatOpNode fon=new FlatOpNode(fen.getDst(),td,null,new Operation(Operation.ASSIGN)); - fn.replace(fon); - } - srcf.set.add(dst); - kill(table, fen.getDst()); - table.put(dst, srcf); - break; - } + case FKind.FlatElementNode: { + FlatElementNode fen=(FlatElementNode) fn; + Group src=getGroup(table, fen.getSrc()); + Group index=getGroup(table, fen.getIndex()); + LocalExpression e=new LocalExpression(src, fen.getSrc().getType(), index); + Group srcf=getGroup(table, e); + LocalExpression dst=new LocalExpression(fen.getDst()); + TempDescriptor td=getTemp(srcf); + if (td!=null) { + FlatOpNode fon=new FlatOpNode(fen.getDst(),td,null,new Operation(Operation.ASSIGN)); + fn.replace(fon); + } + srcf.set.add(dst); + kill(table, fen.getDst()); + table.put(dst, srcf); + break; + } - case FKind.FlatSetFieldNode: { - FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; - Group dst=getGroup(table, fsfn.getDst()); - LocalExpression e=new LocalExpression(dst, fsfn.getField()); - Group dstf=getGroup(table, e); - LocalExpression src=new LocalExpression(fsfn.getSrc()); - dstf.set.add(src); - HashSet fields=new HashSet(); - fields.add(fsfn.getField()); - kill(table, fields, null, false, false); - table.put(src, dstf); - break; - } + case FKind.FlatSetFieldNode: { + FlatSetFieldNode fsfn=(FlatSetFieldNode)fn; + Group dst=getGroup(table, fsfn.getDst()); + LocalExpression e=new LocalExpression(dst, fsfn.getField()); + Group dstf=getGroup(table, e); + LocalExpression src=new LocalExpression(fsfn.getSrc()); + dstf.set.add(src); + HashSet fields=new HashSet(); + fields.add(fsfn.getField()); + kill(table, fields, null, false, false); + table.put(src, dstf); + break; + } - case FKind.FlatSetElementNode: { - FlatSetElementNode fsen=(FlatSetElementNode)fn; - Group dst=getGroup(table, fsen.getDst()); - Group index=getGroup(table, fsen.getIndex()); - LocalExpression e=new LocalExpression(dst, fsen.getDst().getType(), index); - Group dstf=getGroup(table, e); - LocalExpression src=new LocalExpression(fsen.getSrc()); - dstf.set.add(src); - HashSet arrays=new HashSet(); - arrays.add(fsen.getDst().getType()); - kill(table, null, arrays, false, false); - table.put(src, dstf); - break; - } + case FKind.FlatSetElementNode: { + FlatSetElementNode fsen=(FlatSetElementNode)fn; + Group dst=getGroup(table, fsen.getDst()); + Group index=getGroup(table, fsen.getIndex()); + LocalExpression e=new LocalExpression(dst, fsen.getDst().getType(), index); + Group dstf=getGroup(table, e); + LocalExpression src=new LocalExpression(fsen.getSrc()); + dstf.set.add(src); + HashSet arrays=new HashSet(); + arrays.add(fsen.getDst().getType()); + kill(table, null, arrays, false, false); + table.put(src, dstf); + break; + } - case FKind.FlatCall: { - //do side effects - FlatCall fc=(FlatCall)fn; - MethodDescriptor md=fc.getMethod(); - Set fields=gft.getFieldsAll(md); - Set arrays=gft.getArraysAll(md); - kill(table, fields, arrays, gft.containsAtomicAll(md), gft.containsBarrierAll(md)); - } + case FKind.FlatCall: { + //do side effects + FlatCall fc=(FlatCall)fn; + MethodDescriptor md=fc.getMethod(); + Set fields=gft.getFieldsAll(md); + Set arrays=gft.getArraysAll(md); + kill(table, fields, arrays, gft.containsAtomicAll(md), gft.containsBarrierAll(md)); + } - default: { - TempDescriptor[] writes=fn.writesTemps(); - for(int i=0; i it=eset.iterator(); it.hasNext(); ) { LocalExpression e=it.next(); if (isBarrier) { - //make Barriers kill everything - it.remove(); + //make Barriers kill everything + it.remove(); } else if (isAtomic&&(e.td!=null||e.f!=null)) { - Group g=tab.get(e); - g.set.remove(e); - it.remove(); + Group g=tab.get(e); + g.set.remove(e); + it.remove(); } else if (e.td!=null) { - //have array - TypeDescriptor artd=e.td; - for(Iterator arit=arrays.iterator(); arit.hasNext(); ) { - TypeDescriptor td=arit.next(); - if (typeutil.isSuperorType(artd,td)|| - typeutil.isSuperorType(td,artd)) { - Group g=tab.get(e); - g.set.remove(e); - it.remove(); - break; - } - } + //have array + TypeDescriptor artd=e.td; + for(Iterator arit=arrays.iterator(); arit.hasNext(); ) { + TypeDescriptor td=arit.next(); + if (typeutil.isSuperorType(artd,td)|| + typeutil.isSuperorType(td,artd)) { + Group g=tab.get(e); + g.set.remove(e); + it.remove(); + break; + } + } } else if (e.f!=null) { - if (fields.contains(e.f)) { - Group g=tab.get(e); - g.set.remove(e); - it.remove(); - } + if (fields.contains(e.f)) { + Group g=tab.get(e); + g.set.remove(e); + it.remove(); + } } } } diff --git a/Robust/src/Analysis/OoOJava/Accessible.java b/Robust/src/Analysis/OoOJava/Accessible.java index 244da173..6861f7db 100644 --- a/Robust/src/Analysis/OoOJava/Accessible.java +++ b/Robust/src/Analysis/OoOJava/Accessible.java @@ -28,7 +28,7 @@ public class Accessible { for(int i=0; i inAccessibleSet=new HashSet(); for(int i=0; i inAccess=inAccessible.get(fn.getPrev(i)); - if (inAccess!=null) - inAccessibleSet.addAll(inAccess); + Set inAccess=inAccessible.get(fn.getPrev(i)); + if (inAccess!=null) + inAccessibleSet.addAll(inAccess); } switch(fn.kind()) { @@ -53,94 +53,94 @@ nextNode: case FKind.FlatSetFieldNode: case FKind.FlatSetElementNode: { - TempDescriptor[] rdtmps=fn.readsTemps(); - for(int i=0; i> callset=methodmap.get(pairmd); - for(Pair fcallpair : callset) { - FlatCall fcall=fcallpair.getFirst(); - Set inAccess=inAccessible.get(fcall); - if (fcall.getReturnTemp()!=null&&!inAccess.contains(fcall.getReturnTemp())) { - inAccess.add(fcall.getReturnTemp()); - for(int i=0; i(fcall.getNext(i), fcallpair.getSecond())); - } - } - } - } + FlatReturnNode fr=(FlatReturnNode)fn; + if (fr.getReturnTemp()!=null&&inAccessibleSet.contains(fr.getReturnTemp())) { + //Need to inform callers + Set> callset=methodmap.get(pairmd); + for(Pair fcallpair : callset) { + FlatCall fcall=fcallpair.getFirst(); + Set inAccess=inAccessible.get(fcall); + if (fcall.getReturnTemp()!=null&&!inAccess.contains(fcall.getReturnTemp())) { + inAccess.add(fcall.getReturnTemp()); + for(int i=0; i(fcall.getNext(i), fcallpair.getSecond())); + } + } + } + } } - continue nextNode; + continue nextNode; case FKind.FlatSESEEnterNode: case FKind.FlatSESEExitNode: - continue nextNode; + continue nextNode; case FKind.FlatCall: { - FlatCall fcall=(FlatCall)fn; - MethodDescriptor calledmethod=fcall.getMethod(); - Set methodsthatcouldbecalled=fcall.getThis()==null?callGraph.getMethods(calledmethod): - callGraph.getMethods(calledmethod, fcall.getThis().getType()); - for(Object o : methodsthatcouldbecalled) { - MethodDescriptor md=(MethodDescriptor)o; - FlatMethod fm=state.getMethodFlat(md); - - if (!methodmap.containsKey(md)) - methodmap.put(md, new HashSet>()); - - methodmap.get(md).add(new Pair(fcall, pairmd)); - - HashSet tmpinaccess=new HashSet(); - for(int i=0; i(fm.getNext(i),md)); - if (!inAccessible.containsKey(fm)) - inAccessible.put(fm, new HashSet()); - inAccessible.get(fm).addAll(tmpinaccess); - } - } - //be sure not to wipe out return value or other inaccessible temps - Set oldtemps=inAccessible.get(fcall); - if (oldtemps!=null) - inAccessibleSet.addAll(oldtemps); + FlatCall fcall=(FlatCall)fn; + MethodDescriptor calledmethod=fcall.getMethod(); + Set methodsthatcouldbecalled=fcall.getThis()==null?callGraph.getMethods(calledmethod): + callGraph.getMethods(calledmethod, fcall.getThis().getType()); + for(Object o : methodsthatcouldbecalled) { + MethodDescriptor md=(MethodDescriptor)o; + FlatMethod fm=state.getMethodFlat(md); + + if (!methodmap.containsKey(md)) + methodmap.put(md, new HashSet>()); + + methodmap.get(md).add(new Pair(fcall, pairmd)); + + HashSet tmpinaccess=new HashSet(); + for(int i=0; i(fm.getNext(i),md)); + if (!inAccessible.containsKey(fm)) + inAccessible.put(fm, new HashSet()); + inAccessible.get(fm).addAll(tmpinaccess); + } + } + //be sure not to wipe out return value or other inaccessible temps + Set oldtemps=inAccessible.get(fcall); + if (oldtemps!=null) + inAccessibleSet.addAll(oldtemps); } break; default: } if (!inAccessibleSet.isEmpty()&&(!inAccessible.containsKey(fn)||!inAccessible.get(fn).equals(inAccessibleSet))) { - inAccessible.put(fn, inAccessibleSet); - for(int i=0; i(fn.getNext(i),pairmd)); + inAccessible.put(fn, inAccessibleSet); + for(int i=0; i(fn.getNext(i),pairmd)); } } } @@ -150,13 +150,13 @@ nextNode: FlatSESEExitNode seseexit=sese.getFlatExit(); HashSet liveout=new HashSet(liveness.getLiveOutTemps(sese.getfmEnclosing(), seseexit)); for(Iterator tmpit=liveout.iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - if (!tmp.getType().isPtr()) - tmpit.remove(); + TempDescriptor tmp=tmpit.next(); + if (!tmp.getType().isPtr()) + tmpit.remove(); } inAccessible.put(seseexit, liveout); for(int i=0; i(seseexit.getNext(i),sese.getmdEnclosing())); + toprocess.add(new Pair(seseexit.getNext(i),sese.getmdEnclosing())); } Set methodSet=taskAnalysis.getMethodsWithSESEs(); @@ -168,12 +168,12 @@ nextNode: MethodDescriptor md=methodStack.pop(); Set callers=callGraph.getCallerSet(md); for(Object o : callers) { - MethodDescriptor callermd=(MethodDescriptor)o; - if (!canCallSESE.contains(callermd)) { - //new method descriptor - canCallSESE.add(callermd); - methodStack.add(callermd); - } + MethodDescriptor callermd=(MethodDescriptor)o; + if (!canCallSESE.contains(callermd)) { + //new method descriptor + canCallSESE.add(callermd); + methodStack.add(callermd); + } } } @@ -181,36 +181,36 @@ nextNode: for(MethodDescriptor md : canCallSESE) { FlatMethod fm=state.getMethodFlat(md); for(FlatNode fn : fm.getNodeSet()) { - if (fn.kind()==FKind.FlatCall) { - FlatCall fcall=(FlatCall)fn; - MethodDescriptor calledmethod=fcall.getMethod(); - Set methodsthatcouldbecalled=fcall.getThis()==null?callGraph.getMethods(calledmethod): - callGraph.getMethods(calledmethod, fcall.getThis().getType()); - boolean specialcall=false; - for(Object o : methodsthatcouldbecalled) { - MethodDescriptor callermd=(MethodDescriptor)o; - if (canCallSESE.contains(callermd)) { - //TODO: NEED TO BUILD MAP FROM MD -> CALLS - specialcall=true; - if (!methodmap.containsKey(callermd)) - methodmap.put(callermd, new HashSet>()); - methodmap.get(callermd).add(new Pair(fcall,md)); - } - } - if (specialcall) { - Set liveout=new HashSet(liveness.getLiveOutTemps(fm, fcall)); - TempDescriptor returntmp=fcall.getReturnTemp(); - liveout.remove(returntmp); - for(Iterator tmpit=liveout.iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - if (!tmp.getType().isPtr()) - tmpit.remove(); - } - inAccessible.put(fcall, liveout); - for(int i=0; i(fcall.getNext(i),md)); - } - } + if (fn.kind()==FKind.FlatCall) { + FlatCall fcall=(FlatCall)fn; + MethodDescriptor calledmethod=fcall.getMethod(); + Set methodsthatcouldbecalled=fcall.getThis()==null?callGraph.getMethods(calledmethod): + callGraph.getMethods(calledmethod, fcall.getThis().getType()); + boolean specialcall=false; + for(Object o : methodsthatcouldbecalled) { + MethodDescriptor callermd=(MethodDescriptor)o; + if (canCallSESE.contains(callermd)) { + //TODO: NEED TO BUILD MAP FROM MD -> CALLS + specialcall=true; + if (!methodmap.containsKey(callermd)) + methodmap.put(callermd, new HashSet>()); + methodmap.get(callermd).add(new Pair(fcall,md)); + } + } + if (specialcall) { + Set liveout=new HashSet(liveness.getLiveOutTemps(fm, fcall)); + TempDescriptor returntmp=fcall.getReturnTemp(); + liveout.remove(returntmp); + for(Iterator tmpit=liveout.iterator(); tmpit.hasNext(); ) { + TempDescriptor tmp=tmpit.next(); + if (!tmp.getType().isPtr()) + tmpit.remove(); + } + inAccessible.put(fcall, liveout); + for(int i=0; i(fcall.getNext(i),md)); + } + } } } computeFixPoint(); diff --git a/Robust/src/Analysis/OoOJava/ConflictGraph.java b/Robust/src/Analysis/OoOJava/ConflictGraph.java index 07f62a6e..bf8802d7 100644 --- a/Robust/src/Analysis/OoOJava/ConflictGraph.java +++ b/Robust/src/Analysis/OoOJava/ConflictGraph.java @@ -66,11 +66,11 @@ public class ConflictGraph { Taint taint = (Taint) entry.getKey(); Set effectSet = (Set)entry.getValue(); if (!effectSet.isEmpty()) { - Iterator effectIter = effectSet.iterator(); - while (effectIter.hasNext()) { - Effect effect = (Effect) effectIter.next(); - addLiveInNodeEffect(taint, effect); - } + Iterator effectIter = effectSet.iterator(); + while (effectIter.hasNext()) { + Effect effect = (Effect) effectIter.next(); + addLiveInNodeEffect(taint, effect); + } } } } @@ -86,13 +86,13 @@ public class ConflictGraph { Taint taint = (Taint) entry.getKey(); Set effectSet = (Set)entry.getValue(); if (!effectSet.isEmpty()) { - Iterator effectIter = effectSet.iterator(); - while (effectIter.hasNext()) { - Effect effect = (Effect) effectIter.next(); - if (taint.getVar().equals(var)) { - addStallSiteEffect(taint, effect, cd); - } - } + Iterator effectIter = effectSet.iterator(); + while (effectIter.hasNext()) { + Effect effect = (Effect) effectIter.next(); + if (taint.getVar().equals(var)) { + addStallSiteEffect(taint, effect, cd); + } + } } } } @@ -141,15 +141,15 @@ public class ConflictGraph { if ((conflictEdge.getVertexU().equals(nodeU) && conflictEdge.getVertexV().equals(nodeV)) || (conflictEdge.getVertexU().equals(nodeV) && conflictEdge.getVertexV().equals(nodeU))) { - if (conflictEdge.getType() == ConflictGraph.FINE_GRAIN_EDGE - && type == ConflictGraph.COARSE_GRAIN_EDGE) { - toBeRemoved = conflictEdge; - break; - } else if (conflictEdge.getType() == ConflictGraph.COARSE_GRAIN_EDGE - && type == ConflictGraph.FINE_GRAIN_EDGE) { - // ignore - return; - } + if (conflictEdge.getType() == ConflictGraph.FINE_GRAIN_EDGE + && type == ConflictGraph.COARSE_GRAIN_EDGE) { + toBeRemoved = conflictEdge; + break; + } else if (conflictEdge.getType() == ConflictGraph.COARSE_GRAIN_EDGE + && type == ConflictGraph.FINE_GRAIN_EDGE) { + // ignore + return; + } } } @@ -186,10 +186,10 @@ public class ConflictGraph { if (currentNode.isInVarNode()) { conflictType = calculateConflictType(currentNode, useReachInfo); if (conflictType > ConflictGraph.NON_WRITE_CONFLICT) { - addConflictEdge(conflictType, currentNode, currentNode); - if (sitesToFlag != null) { - sitesToFlag.addAll(currentNode.getFlatNewSet()); - } + addConflictEdge(conflictType, currentNode, currentNode); + if (sitesToFlag != null) { + sitesToFlag.addAll(currentNode.getFlatNewSet()); + } } } @@ -201,28 +201,28 @@ public class ConflictGraph { ConflictNode entryNode = entry.getValue(); if (currentNode.isStallSiteNode() && entryNode.isStallSiteNode()) { - continue; + continue; } if ((currentNode.isInVarNode() && entryNode.isInVarNode()) && (currentNode.getSESEIdentifier() == entryNode.getSESEIdentifier()) && (currentNode.getVar().equals(entryNode.getVar()))) { - continue; + continue; } if ((!currentNode.getID().equals(entryNodeID)) && !(analyzedIDSet.contains(currentNode.getID() + entryNodeID) || analyzedIDSet .contains(entryNodeID + currentNode.getID()))) { - conflictType = calculateConflictType(currentNode, entryNode, useReachInfo); - if (conflictType > ConflictGraph.NON_WRITE_CONFLICT) { - addConflictEdge(conflictType, currentNode, entryNode); - if (sitesToFlag != null) { - sitesToFlag.addAll(currentNode.getFlatNewSet()); - sitesToFlag.addAll(entryNode.getFlatNewSet()); - } - } - analyzedIDSet.add(currentNode.getID() + entryNodeID); + conflictType = calculateConflictType(currentNode, entryNode, useReachInfo); + if (conflictType > ConflictGraph.NON_WRITE_CONFLICT) { + addConflictEdge(conflictType, currentNode, entryNode); + if (sitesToFlag != null) { + sitesToFlag.addAll(currentNode.getFlatNewSet()); + sitesToFlag.addAll(entryNode.getFlatNewSet()); + } + } + analyzedIDSet.add(currentNode.getID() + entryNodeID); } } @@ -318,79 +318,79 @@ public class ConflictGraph { Iterator effectItrB = readTableB.entrySet().iterator(); while (effectItrB.hasNext()) { - Map.Entry meB = (Map.Entry)effectItrB.next(); - Alloc asB = (Alloc) meB.getKey(); - Set esB = (Set)meB.getValue(); - - for (Iterator iterator = strongUpdateSetA.iterator(); iterator.hasNext(); ) { - Effect strongUpdateA = (Effect) iterator.next(); - for (Iterator iterator2 = esB.iterator(); iterator2.hasNext(); ) { - Effect effectB = (Effect) iterator2.next(); - - if (strongUpdateA.getAffectedAllocSite().equals(effectB.getAffectedAllocSite()) - && strongUpdateA.getField().equals(effectB.getField())) { - if (useReachInfo) { - FlatNew fnRoot1 = asA.getFlatNew(); - FlatNew fnRoot2 = asB.getFlatNew(); - FlatNew fnTarget = strongUpdateA.getAffectedAllocSite().getFlatNew(); - if (da.mayBothReachTarget(fmEnclosing, fnRoot1, fnRoot2, fnTarget)) { - addCoarseEffect(nodeA, asA, strongUpdateA); - if (!nodeA.equals(nodeB)) { - addCoarseEffect(nodeB, asB, effectB); - } - conflictType = updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE); - } - } else { - if (state.RCR) { - // need coarse effects for RCR from just one pass - addCoarseEffect(nodeA, asA, strongUpdateA); - if (!nodeA.equals(nodeB)) { - addCoarseEffect(nodeB, asB, effectB); - } - conflictType = ConflictGraph.COARSE_GRAIN_EDGE; - } else { - return ConflictGraph.COARSE_GRAIN_EDGE; - } - } - - } - - } - } + Map.Entry meB = (Map.Entry)effectItrB.next(); + Alloc asB = (Alloc) meB.getKey(); + Set esB = (Set)meB.getValue(); + + for (Iterator iterator = strongUpdateSetA.iterator(); iterator.hasNext(); ) { + Effect strongUpdateA = (Effect) iterator.next(); + for (Iterator iterator2 = esB.iterator(); iterator2.hasNext(); ) { + Effect effectB = (Effect) iterator2.next(); + + if (strongUpdateA.getAffectedAllocSite().equals(effectB.getAffectedAllocSite()) + && strongUpdateA.getField().equals(effectB.getField())) { + if (useReachInfo) { + FlatNew fnRoot1 = asA.getFlatNew(); + FlatNew fnRoot2 = asB.getFlatNew(); + FlatNew fnTarget = strongUpdateA.getAffectedAllocSite().getFlatNew(); + if (da.mayBothReachTarget(fmEnclosing, fnRoot1, fnRoot2, fnTarget)) { + addCoarseEffect(nodeA, asA, strongUpdateA); + if (!nodeA.equals(nodeB)) { + addCoarseEffect(nodeB, asB, effectB); + } + conflictType = updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE); + } + } else { + if (state.RCR) { + // need coarse effects for RCR from just one pass + addCoarseEffect(nodeA, asA, strongUpdateA); + if (!nodeA.equals(nodeB)) { + addCoarseEffect(nodeB, asB, effectB); + } + conflictType = ConflictGraph.COARSE_GRAIN_EDGE; + } else { + return ConflictGraph.COARSE_GRAIN_EDGE; + } + } + + } + + } + } } effectItrB = writeTableB.entrySet().iterator(); while (effectItrB.hasNext()) { - Map.Entry meB = (Map.Entry)effectItrB.next(); - Alloc asB = (Alloc) meB.getKey(); - Set esB = (Set)meB.getValue(); - - for (Iterator iterator = strongUpdateSetA.iterator(); iterator.hasNext(); ) { - Effect strongUpdateA = (Effect) iterator.next(); - for (Iterator iterator2 = esB.iterator(); iterator2.hasNext(); ) { - Effect effectB = (Effect) iterator2.next(); - - if (strongUpdateA.getAffectedAllocSite().equals(effectB.getAffectedAllocSite()) - && strongUpdateA.getField().equals(effectB.getField())) { - - if (useReachInfo) { - FlatNew fnRoot1 = asA.getFlatNew(); - FlatNew fnRoot2 = asB.getFlatNew(); - FlatNew fnTarget = strongUpdateA.getAffectedAllocSite().getFlatNew(); - if (da.mayBothReachTarget(fmEnclosing, fnRoot1, fnRoot2, fnTarget)) { - addCoarseEffect(nodeA, asA, strongUpdateA); - if (!nodeA.equals(nodeB)) { - addCoarseEffect(nodeB, asB, effectB); - } - conflictType = updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE); - } - } else { - return ConflictGraph.COARSE_GRAIN_EDGE; - } - } - - } - } + Map.Entry meB = (Map.Entry)effectItrB.next(); + Alloc asB = (Alloc) meB.getKey(); + Set esB = (Set)meB.getValue(); + + for (Iterator iterator = strongUpdateSetA.iterator(); iterator.hasNext(); ) { + Effect strongUpdateA = (Effect) iterator.next(); + for (Iterator iterator2 = esB.iterator(); iterator2.hasNext(); ) { + Effect effectB = (Effect) iterator2.next(); + + if (strongUpdateA.getAffectedAllocSite().equals(effectB.getAffectedAllocSite()) + && strongUpdateA.getField().equals(effectB.getField())) { + + if (useReachInfo) { + FlatNew fnRoot1 = asA.getFlatNew(); + FlatNew fnRoot2 = asB.getFlatNew(); + FlatNew fnTarget = strongUpdateA.getAffectedAllocSite().getFlatNew(); + if (da.mayBothReachTarget(fmEnclosing, fnRoot1, fnRoot2, fnTarget)) { + addCoarseEffect(nodeA, asA, strongUpdateA); + if (!nodeA.equals(nodeB)) { + addCoarseEffect(nodeB, asB, effectB); + } + conflictType = updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE); + } + } else { + return ConflictGraph.COARSE_GRAIN_EDGE; + } + } + + } + } } } @@ -412,63 +412,63 @@ public class ConflictGraph { Iterator effectItrB = nodeBtable.entrySet().iterator(); while (effectItrB.hasNext()) { - Map.Entry meB = (Map.Entry)effectItrB.next(); - Alloc asB = (Alloc) meB.getKey(); - Set esB = (Set)meB.getValue(); - - for (Iterator iterator = esA.iterator(); iterator.hasNext(); ) { - Effect effectA = (Effect) iterator.next(); - for (Iterator iterator2 = esB.iterator(); iterator2.hasNext(); ) { - Effect effectB = (Effect) iterator2.next(); - - if (effectA.getAffectedAllocSite().equals(effectB.getAffectedAllocSite()) - && ((effectA.getField() != null && effectB.getField() != null && effectA.getField() - .equals(effectB.getField())) || (effectA.getField() == null && effectB - .getField() == null))) { - - if (useReachInfo) { - FlatNew fnRoot1 = asA.getFlatNew(); - FlatNew fnRoot2 = asB.getFlatNew(); - FlatNew fnTarget = effectA.getAffectedAllocSite().getFlatNew(); - if (fnRoot1.equals(fnRoot2)) { - if (!da.mayManyReachTarget(fmEnclosing, fnRoot1, fnTarget)) { - // fine-grained conflict case - conflictType = updateConflictType(conflictType, ConflictGraph.FINE_GRAIN_EDGE); - } else { - // coarse-grained conflict case - addCoarseEffect(nodeA, asA, effectA); - if (!nodeA.equals(nodeB)) { - addCoarseEffect(nodeB, asB, effectB); - } - conflictType = - updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE); - } - } else { - if (da.mayBothReachTarget(fmEnclosing, fnRoot1, fnRoot2, fnTarget)) { - addCoarseEffect(nodeA, asA, effectA); - if (!nodeA.equals(nodeB)) { - addCoarseEffect(nodeB, asB, effectB); - } - conflictType = - updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE); - } else { - } - } - } else { - if (state.RCR) { - // need coarse effects for RCR from just one pass - addCoarseEffect(nodeA, asA, effectA); - if (!nodeA.equals(nodeB)) { - addCoarseEffect(nodeB, asB, effectB); - } - conflictType = ConflictGraph.COARSE_GRAIN_EDGE; - } else { - return ConflictGraph.COARSE_GRAIN_EDGE; - } - } - } - } - } + Map.Entry meB = (Map.Entry)effectItrB.next(); + Alloc asB = (Alloc) meB.getKey(); + Set esB = (Set)meB.getValue(); + + for (Iterator iterator = esA.iterator(); iterator.hasNext(); ) { + Effect effectA = (Effect) iterator.next(); + for (Iterator iterator2 = esB.iterator(); iterator2.hasNext(); ) { + Effect effectB = (Effect) iterator2.next(); + + if (effectA.getAffectedAllocSite().equals(effectB.getAffectedAllocSite()) + && ((effectA.getField() != null && effectB.getField() != null && effectA.getField() + .equals(effectB.getField())) || (effectA.getField() == null && effectB + .getField() == null))) { + + if (useReachInfo) { + FlatNew fnRoot1 = asA.getFlatNew(); + FlatNew fnRoot2 = asB.getFlatNew(); + FlatNew fnTarget = effectA.getAffectedAllocSite().getFlatNew(); + if (fnRoot1.equals(fnRoot2)) { + if (!da.mayManyReachTarget(fmEnclosing, fnRoot1, fnTarget)) { + // fine-grained conflict case + conflictType = updateConflictType(conflictType, ConflictGraph.FINE_GRAIN_EDGE); + } else { + // coarse-grained conflict case + addCoarseEffect(nodeA, asA, effectA); + if (!nodeA.equals(nodeB)) { + addCoarseEffect(nodeB, asB, effectB); + } + conflictType = + updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE); + } + } else { + if (da.mayBothReachTarget(fmEnclosing, fnRoot1, fnRoot2, fnTarget)) { + addCoarseEffect(nodeA, asA, effectA); + if (!nodeA.equals(nodeB)) { + addCoarseEffect(nodeB, asB, effectB); + } + conflictType = + updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE); + } else { + } + } + } else { + if (state.RCR) { + // need coarse effects for RCR from just one pass + addCoarseEffect(nodeA, asA, effectA); + if (!nodeA.equals(nodeB)) { + addCoarseEffect(nodeB, asB, effectB); + } + conflictType = ConflictGraph.COARSE_GRAIN_EDGE; + } else { + return ConflictGraph.COARSE_GRAIN_EDGE; + } + } + } + } + } } } @@ -540,7 +540,7 @@ public class ConflictGraph { String key = (String) iterator.next(); ConflictNode node = id2cn.get(key); if (node.getEdgeSet().size() > 0) { - return true; + return true; } } return false; @@ -566,32 +566,32 @@ public class ConflictGraph { ConflictNode node = (ConflictNode) entry.getValue(); if (node.isInVarNode()) { - if (node.getSESEIdentifier() == seseID) { - - Set edgeSet = node.getEdgeSet(); - for (Iterator iterator = edgeSet.iterator(); iterator.hasNext(); ) { - ConflictEdge conflictEdge = (ConflictEdge) iterator.next(); - - for (Iterator seseLockIter = seseLockSet.iterator(); seseLockIter.hasNext(); ) { - SESELock seseLock = seseLockIter.next(); - if (seseLock.containsConflictNode(node) - && seseLock.containsConflictEdge(conflictEdge)) { - WaitingElement newElement = new WaitingElement(); - newElement.setQueueID(seseLock.getID()); - newElement.setStatus(seseLock.getNodeType(node)); - newElement.setTempDesc(node.getVar()); - if (isFineElement(newElement.getStatus())) { - newElement.setDynID(node.getVar().toString()); - } - if (!waitingElementSet.contains(newElement)) { - waitingElementSet.add(newElement); - } - - } - } - } - - } + if (node.getSESEIdentifier() == seseID) { + + Set edgeSet = node.getEdgeSet(); + for (Iterator iterator = edgeSet.iterator(); iterator.hasNext(); ) { + ConflictEdge conflictEdge = (ConflictEdge) iterator.next(); + + for (Iterator seseLockIter = seseLockSet.iterator(); seseLockIter.hasNext(); ) { + SESELock seseLock = seseLockIter.next(); + if (seseLock.containsConflictNode(node) + && seseLock.containsConflictEdge(conflictEdge)) { + WaitingElement newElement = new WaitingElement(); + newElement.setQueueID(seseLock.getID()); + newElement.setStatus(seseLock.getNodeType(node)); + newElement.setTempDesc(node.getVar()); + if (isFineElement(newElement.getStatus())) { + newElement.setDynID(node.getVar().toString()); + } + if (!waitingElementSet.contains(newElement)) { + waitingElementSet.add(newElement); + } + + } + } + } + + } } } @@ -612,7 +612,7 @@ public class ConflictGraph { WaitingElement waitingElement = (WaitingElement) iterator.next(); Set set = map.get(new Integer(waitingElement.getQueueID())); if (set == null) { - set = new HashSet(); + set = new HashSet(); } set.add(waitingElement); map.put(new Integer(waitingElement.getQueueID()), set); @@ -643,62 +643,62 @@ public class ConflictGraph { WaitingElement coarseElement = null; for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) { - WaitingElement waitingElement = (WaitingElement) iterator.next(); - if (waitingElement.getStatus() == ConflictNode.FINE_READ) { - numRead++; - } else if (waitingElement.getStatus() == ConflictNode.FINE_WRITE) { - numWrite++; - } else if (waitingElement.getStatus() == ConflictNode.COARSE) { - numCoarse++; - coarseElement = waitingElement; - } else if (waitingElement.getStatus() == ConflictNode.SCC) { - SCCelement = waitingElement; - } + WaitingElement waitingElement = (WaitingElement) iterator.next(); + if (waitingElement.getStatus() == ConflictNode.FINE_READ) { + numRead++; + } else if (waitingElement.getStatus() == ConflictNode.FINE_WRITE) { + numWrite++; + } else if (waitingElement.getStatus() == ConflictNode.COARSE) { + numCoarse++; + coarseElement = waitingElement; + } else if (waitingElement.getStatus() == ConflictNode.SCC) { + SCCelement = waitingElement; + } } if (SCCelement != null) { - // if there is at lease one SCC element, just enqueue SCC and - // ignore others. - if (state.RCR) { - // for rcr, we need to label all of coarse tempdescriptors - // here assume that all waiting elements are coarse - for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) { - WaitingElement waitingElement = (WaitingElement) iterator.next(); - SCCelement.addTempDesc(waitingElement.getTempDesc()); - if (waitingElement != SCCelement) { - waitingElement.setBogus(true); - refinedSet.add(waitingElement); - } - } - } - refinedSet.add(SCCelement); + // if there is at lease one SCC element, just enqueue SCC and + // ignore others. + if (state.RCR) { + // for rcr, we need to label all of coarse tempdescriptors + // here assume that all waiting elements are coarse + for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) { + WaitingElement waitingElement = (WaitingElement) iterator.next(); + SCCelement.addTempDesc(waitingElement.getTempDesc()); + if (waitingElement != SCCelement) { + waitingElement.setBogus(true); + refinedSet.add(waitingElement); + } + } + } + refinedSet.add(SCCelement); } else if (numCoarse == 1 && (numRead + numWrite == total)) { - // if one is a coarse, the othere are reads/write, enqueue SCC. - WaitingElement we = new WaitingElement(); - we.setQueueID(queueID); - we.setStatus(ConflictNode.SCC); - refinedSet.add(we); + // if one is a coarse, the othere are reads/write, enqueue SCC. + WaitingElement we = new WaitingElement(); + we.setQueueID(queueID); + we.setStatus(ConflictNode.SCC); + refinedSet.add(we); } else if (numCoarse == total) { - // if there are multiple coarses, enqueue just one coarse. - if (state.RCR) { - // for rcr, we need to label all of coarse tempdescriptors - for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) { - WaitingElement waitingElement = (WaitingElement) iterator.next(); - if (waitingElement != coarseElement) { - coarseElement.addTempDesc(waitingElement.getTempDesc()); - waitingElement.setBogus(true); - refinedSet.add(waitingElement); - } - } - } - refinedSet.add(coarseElement); + // if there are multiple coarses, enqueue just one coarse. + if (state.RCR) { + // for rcr, we need to label all of coarse tempdescriptors + for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) { + WaitingElement waitingElement = (WaitingElement) iterator.next(); + if (waitingElement != coarseElement) { + coarseElement.addTempDesc(waitingElement.getTempDesc()); + waitingElement.setBogus(true); + refinedSet.add(waitingElement); + } + } + } + refinedSet.add(coarseElement); } else if (numWrite == total || (numRead + numWrite) == total) { - // code generator is going to handle the case for multiple writes & - // read/writes. - seseDS.setType(queueID, SESEWaitingQueue.EXCEPTION); - refinedSet.addAll(waitingElementSet); + // code generator is going to handle the case for multiple writes & + // read/writes. + seseDS.setType(queueID, SESEWaitingQueue.EXCEPTION); + refinedSet.addAll(waitingElementSet); } else { - // otherwise, enqueue everything. - refinedSet.addAll(waitingElementSet); + // otherwise, enqueue everything. + refinedSet.addAll(waitingElementSet); } seseDS.setWaitingElementSet(queueID, refinedSet); } else { @@ -718,25 +718,25 @@ public class ConflictGraph { ConflictNode node = (ConflictNode) entry.getValue(); if (node.isStallSiteNode() && node.getStallSiteFlatNode().equals(stallSite)) { - Set edgeSet = node.getEdgeSet(); - for (Iterator iter2 = edgeSet.iterator(); iter2.hasNext(); ) { - ConflictEdge conflictEdge = (ConflictEdge) iter2.next(); - - for (Iterator seseLockIter = seseLockSet.iterator(); seseLockIter.hasNext(); ) { - SESELock seseLock = seseLockIter.next(); - if (seseLock.containsConflictNode(node) && seseLock.containsConflictEdge(conflictEdge)) { - WaitingElement newElement = new WaitingElement(); - newElement.setQueueID(seseLock.getID()); - newElement.setStatus(seseLock.getNodeType(node)); - if (isFineElement(newElement.getStatus())) { - newElement.setDynID(node.getVar().toString()); - } - newElement.setTempDesc(node.getVar()); - waitingElementSet.add(newElement); - } - } - - } + Set edgeSet = node.getEdgeSet(); + for (Iterator iter2 = edgeSet.iterator(); iter2.hasNext(); ) { + ConflictEdge conflictEdge = (ConflictEdge) iter2.next(); + + for (Iterator seseLockIter = seseLockSet.iterator(); seseLockIter.hasNext(); ) { + SESELock seseLock = seseLockIter.next(); + if (seseLock.containsConflictNode(node) && seseLock.containsConflictEdge(conflictEdge)) { + WaitingElement newElement = new WaitingElement(); + newElement.setQueueID(seseLock.getID()); + newElement.setStatus(seseLock.getNodeType(node)); + if (isFineElement(newElement.getStatus())) { + newElement.setDynID(node.getVar().toString()); + } + newElement.setTempDesc(node.getVar()); + waitingElementSet.add(newElement); + } + } + + } } @@ -767,15 +767,15 @@ public class ConflictGraph { ConflictNode node = entry.getValue(); if (filter) { - if (node.getID().startsWith("___dst") || node.getID().startsWith("___srctmp") - || node.getID().startsWith("___neverused") || node.getID().startsWith("___temp")) { + if (node.getID().startsWith("___dst") || node.getID().startsWith("___srctmp") + || node.getID().startsWith("___neverused") || node.getID().startsWith("___temp")) { - continue; - } + continue; + } - if (node.getEdgeSet().isEmpty()) { - continue; - } + if (node.getEdgeSet().isEmpty()) { + continue; + } } @@ -784,43 +784,43 @@ public class ConflictGraph { attributes += "label=\"" + node.getID() + "\\n"; if (node.isStallSiteNode()) { - String srcFileName = node.getSourceFileName(); - int separatorIdx = srcFileName.lastIndexOf(File.separator); - if (separatorIdx > 0) { - srcFileName = srcFileName.substring(separatorIdx + 1); - } - node.stallSite.getNumLine(); - attributes += - "STALL SITE" + "\\n" + srcFileName + ":" + node.getStallSiteFlatNode().getNumLine() - + "\\n" + "\"]"; + String srcFileName = node.getSourceFileName(); + int separatorIdx = srcFileName.lastIndexOf(File.separator); + if (separatorIdx > 0) { + srcFileName = srcFileName.substring(separatorIdx + 1); + } + node.stallSite.getNumLine(); + attributes += + "STALL SITE" + "\\n" + srcFileName + ":" + node.getStallSiteFlatNode().getNumLine() + + "\\n" + "\"]"; } else { - attributes += "LIVE-IN" + "\\n" + "\"]"; + attributes += "LIVE-IN" + "\\n" + "\"]"; } bw.write(entry.getKey() + attributes + ";\n"); Set edgeSet = node.getEdgeSet(); for (Iterator iterator = edgeSet.iterator(); iterator.hasNext(); ) { - ConflictEdge conflictEdge = (ConflictEdge) iterator.next(); - - ConflictNode u = conflictEdge.getVertexU(); - ConflictNode v = conflictEdge.getVertexV(); - - if (filter) { - String uID = u.getID(); - String vID = v.getID(); - if (uID.startsWith("___dst") || uID.startsWith("___srctmp") - || uID.startsWith("___neverused") || uID.startsWith("___temp") - || vID.startsWith("___dst") || vID.startsWith("___srctmp") - || vID.startsWith("___neverused") || vID.startsWith("___temp")) { - continue; - } - } - - if (!addedSet.contains(conflictEdge)) { - bw.write("" + u.getID() + "--" + v.getID() + "[label=" + conflictEdge.toGraphEdgeString() - + ",decorate];\n"); - addedSet.add(conflictEdge); - } + ConflictEdge conflictEdge = (ConflictEdge) iterator.next(); + + ConflictNode u = conflictEdge.getVertexU(); + ConflictNode v = conflictEdge.getVertexV(); + + if (filter) { + String uID = u.getID(); + String vID = v.getID(); + if (uID.startsWith("___dst") || uID.startsWith("___srctmp") + || uID.startsWith("___neverused") || uID.startsWith("___temp") + || vID.startsWith("___dst") || vID.startsWith("___srctmp") + || vID.startsWith("___neverused") || vID.startsWith("___temp")) { + continue; + } + } + + if (!addedSet.contains(conflictEdge)) { + bw.write("" + u.getID() + "--" + v.getID() + "[label=" + conflictEdge.toGraphEdgeString() + + ",decorate];\n"); + addedSet.add(conflictEdge); + } } } diff --git a/Robust/src/Analysis/OoOJava/ConflictNode.java b/Robust/src/Analysis/OoOJava/ConflictNode.java index d7eceefd..479ce47a 100644 --- a/Robust/src/Analysis/OoOJava/ConflictNode.java +++ b/Robust/src/Analysis/OoOJava/ConflictNode.java @@ -89,7 +89,7 @@ public class ConflictNode { for (Iterator iterator = taintSet.iterator(); iterator.hasNext(); ) { Taint t = (Taint) iterator.next(); if (t.getAllocSite().equals(as)) { - return t; + return t; } } return null; @@ -244,21 +244,21 @@ public class ConflictNode { ConflictEdge edge = (ConflictEdge) iterator.next(); if (edge.getVertexU() == edge.getVertexV()) { - // self-conflict, need to generate traverser - return false; + // self-conflict, need to generate traverser + return false; } else { - if (edge.getVertexU() == this) { - if (edge.getVertexV().isInVarNode()) { - // has a conflict with invar, need to generate traverser - return false; - } - } else { - if (edge.getVertexU().isInVarNode()) { - // has a conflict with invar, need to generate traverser - return false; - } - } + if (edge.getVertexU() == this) { + if (edge.getVertexV().isInVarNode()) { + // has a conflict with invar, need to generate traverser + return false; + } + } else { + if (edge.getVertexU().isInVarNode()) { + // has a conflict with invar, need to generate traverser + return false; + } + } } } return true; diff --git a/Robust/src/Analysis/OoOJava/OoOJavaAnalysis.java b/Robust/src/Analysis/OoOJava/OoOJavaAnalysis.java index 89fb06e8..495b0e4e 100644 --- a/Robust/src/Analysis/OoOJava/OoOJavaAnalysis.java +++ b/Robust/src/Analysis/OoOJava/OoOJavaAnalysis.java @@ -262,9 +262,9 @@ public class OoOJavaAnalysis { if (state.OOODEBUG) { try { - writeReports(""); - disjointAnalysisTaints.getEffectsAnalysis().writeEffects("effects.txt"); - writeConflictGraph(); + writeReports(""); + disjointAnalysisTaints.getEffectsAnalysis().writeEffects("effects.txt"); + writeConflictGraph(); } catch (IOException e) { } } @@ -285,10 +285,10 @@ public class OoOJavaAnalysis { fn2fm.put(fn, fm); for (int i = 0; i < fn.numNext(); i++) { - FlatNode nn = fn.getNext(i); - if (!flatNodesVisited.contains(nn)) { - flatNodesToVisit.add(nn); - } + FlatNode nn = fn.getNext(i); + if (!flatNodesVisited.contains(nn)) { + flatNodesToVisit.add(nn); + } } } } @@ -312,8 +312,8 @@ public class OoOJavaAnalysis { BufferedWriter bw = new BufferedWriter(new FileWriter("sitesToFlag.txt")); for (Iterator iterator = sitesToFlag.iterator(); iterator.hasNext(); ) { - FlatNew fn = (FlatNew) iterator.next(); - bw.write(fn + "\n"); + FlatNew fn = (FlatNew) iterator.next(); + bw.write(fn + "\n"); } bw.close(); } catch (IOException e) { @@ -340,11 +340,11 @@ public class OoOJavaAnalysis { // merge sets from control flow joins Set livein = new HashSet(); for (int i = 0; i < fn.numNext(); i++) { - FlatNode nn = fn.getNext(i); - Set s = livenessGlobalView.get(nn); - if (s != null) { - livein.addAll(s); - } + FlatNode nn = fn.getNext(i); + Set s = livenessGlobalView.get(nn); + if (s != null) { + livein.addAll(s); + } } Set curr = liveness_nodeActions(fn, livein); @@ -352,13 +352,13 @@ public class OoOJavaAnalysis { // if a new result, schedule backward nodes for analysis if (!curr.equals(prev)) { - if (fn != fsen) { - livenessGlobalView.put(fn, curr); - for (int i = 0; i < fn.numPrev(); i++) { - FlatNode nn = fn.getPrev(i); - flatNodesToVisit.add(nn); - } - } + if (fn != fsen) { + livenessGlobalView.put(fn, curr); + for (int i = 0; i < fn.numPrev(); i++) { + FlatNode nn = fn.getPrev(i); + flatNodesToVisit.add(nn); + } + } } } } @@ -371,7 +371,7 @@ public class OoOJavaAnalysis { // task's in-var set FlatSESEEnterNode fsen = (FlatSESEEnterNode) fn; if (liveIn != null) { - fsen.addInVarSet(liveIn); + fsen.addInVarSet(liveIn); } // no break, should also execute default actions } @@ -380,31 +380,31 @@ public class OoOJavaAnalysis { // handle effects of statement in reverse, writes then reads TempDescriptor[] writeTemps = fn.writesTemps(); for (int i = 0; i < writeTemps.length; ++i) { - liveIn.remove(writeTemps[i]); - - // if we are analyzing code declared directly in a task, - FlatSESEEnterNode fsen = rblockRel.getLocalInnerRBlock(fn); - if (fsen != null) { - // check to see if we are writing to variables that will - // be live-out at the task's exit (and therefore should - // go in the task's out-var set) - FlatSESEExitNode fsexn = fsen.getFlatExit(); - // note: liveness analysis can have corresponding decisions - Set livetemps = liveness.getLiveInTemps(fsen.getfmEnclosing(), fsexn); - if (livetemps != null && livetemps.contains(writeTemps[i])) { - fsen.addOutVar(writeTemps[i]); - } - } + liveIn.remove(writeTemps[i]); + + // if we are analyzing code declared directly in a task, + FlatSESEEnterNode fsen = rblockRel.getLocalInnerRBlock(fn); + if (fsen != null) { + // check to see if we are writing to variables that will + // be live-out at the task's exit (and therefore should + // go in the task's out-var set) + FlatSESEExitNode fsexn = fsen.getFlatExit(); + // note: liveness analysis can have corresponding decisions + Set livetemps = liveness.getLiveInTemps(fsen.getfmEnclosing(), fsexn); + if (livetemps != null && livetemps.contains(writeTemps[i])) { + fsen.addOutVar(writeTemps[i]); + } + } } TempDescriptor[] readTemps = fn.readsTemps(); for (int i = 0; i < readTemps.length; ++i) { - liveIn.add(readTemps[i]); + liveIn.add(readTemps[i]); } Set virtualReadTemps = livenessVirtualReads.get(fn); if (virtualReadTemps != null) { - liveIn.addAll(virtualReadTemps); + liveIn.addAll(virtualReadTemps); } } break; @@ -428,26 +428,26 @@ public class OoOJavaAnalysis { // merge sets from control flow joins VarSrcTokTable curr = new VarSrcTokTable(); for (int i = 0; i < fn.numPrev(); i++) { - FlatNode nn = fn.getPrev(i); - VarSrcTokTable incoming = variableResults.get(nn); - curr.merge(incoming); + FlatNode nn = fn.getPrev(i); + VarSrcTokTable incoming = variableResults.get(nn); + curr.merge(incoming); } FlatSESEEnterNode currentSESE = rblockRel.getLocalInnerRBlock(fn); if (currentSESE == null) { - currentSESE = rblockRel.getCallerProxySESE(); + currentSESE = rblockRel.getCallerProxySESE(); } variable_nodeActions(fn, curr, currentSESE); // if a new result, schedule forward nodes for analysis if (!curr.equals(prev)) { - variableResults.put(fn, curr); + variableResults.put(fn, curr); - for (int i = 0; i < fn.numNext(); i++) { - FlatNode nn = fn.getNext(i); - flatNodesToVisit.add(nn); - } + for (int i = 0; i < fn.numNext(); i++) { + FlatNode nn = fn.getNext(i); + flatNodesToVisit.add(nn); + } } } } @@ -487,7 +487,7 @@ public class OoOJavaAnalysis { Set fsenVirtReadsOld = livenessVirtualReads.get(fn); if (fsenVirtReadsOld != null) { - fsenVirtReads.addAll(fsenVirtReadsOld); + fsenVirtReads.addAll(fsenVirtReadsOld); } livenessVirtualReads.put(fn, fsenVirtReads); @@ -499,12 +499,12 @@ public class OoOJavaAnalysis { // the latest, clean sources Iterator outVarItr = fsen.getOutVarSet().iterator(); while (outVarItr.hasNext()) { - TempDescriptor outVar = outVarItr.next(); - HashSet ts = new HashSet(); - ts.add(outVar); - VariableSourceToken vst = new VariableSourceToken(ts, fsen, new Integer(0), outVar); - vstTable.remove(outVar); - vstTable.add(vst); + TempDescriptor outVar = outVarItr.next(); + HashSet ts = new HashSet(); + ts.add(outVar); + VariableSourceToken vst = new VariableSourceToken(ts, fsen, new Integer(0), outVar); + vstTable.remove(outVar); + vstTable.add(vst); } vstTable.assertConsistency(); } @@ -514,47 +514,47 @@ public class OoOJavaAnalysis { FlatOpNode fon = (FlatOpNode) fn; if (fon.getOp().getOp() == Operation.ASSIGN) { - TempDescriptor lhs = fon.getDest(); - TempDescriptor rhs = fon.getLeft(); - - vstTable.remove(lhs); - - Set forAddition = new HashSet(); - - Iterator itr = vstTable.get(rhs).iterator(); - while (itr.hasNext()) { - VariableSourceToken vst = itr.next(); - - HashSet ts = new HashSet(); - ts.add(lhs); - - // when we do x = y for variables, just copy over from a child, - // there are two cases: - // 1. if the current task is the caller proxy, any local root is a - // child - boolean case1 = - currentSESE.getIsCallerProxySESE() - && rblockRel.getLocalRootSESEs().contains(vst.getSESE()); - - // 2. if the child task is a locally-defined child of the current task - boolean case2 = currentSESE.getLocalChildren().contains(vst.getSESE()); - - if (case1 || case2) { - // if the source comes from a child, copy it over - forAddition.add(new VariableSourceToken(ts, vst.getSESE(), vst.getAge(), vst - .getAddrVar())); - } else { - // otherwise, stamp it as us as the source - forAddition.add(new VariableSourceToken(ts, currentSESE, new Integer(0), lhs)); - } - } - - vstTable.addAll(forAddition); - - // only break if this is an ASSIGN op node, - // otherwise fall through to default case - vstTable.assertConsistency(); - break; + TempDescriptor lhs = fon.getDest(); + TempDescriptor rhs = fon.getLeft(); + + vstTable.remove(lhs); + + Set forAddition = new HashSet(); + + Iterator itr = vstTable.get(rhs).iterator(); + while (itr.hasNext()) { + VariableSourceToken vst = itr.next(); + + HashSet ts = new HashSet(); + ts.add(lhs); + + // when we do x = y for variables, just copy over from a child, + // there are two cases: + // 1. if the current task is the caller proxy, any local root is a + // child + boolean case1 = + currentSESE.getIsCallerProxySESE() + && rblockRel.getLocalRootSESEs().contains(vst.getSESE()); + + // 2. if the child task is a locally-defined child of the current task + boolean case2 = currentSESE.getLocalChildren().contains(vst.getSESE()); + + if (case1 || case2) { + // if the source comes from a child, copy it over + forAddition.add(new VariableSourceToken(ts, vst.getSESE(), vst.getAge(), vst + .getAddrVar())); + } else { + // otherwise, stamp it as us as the source + forAddition.add(new VariableSourceToken(ts, currentSESE, new Integer(0), lhs)); + } + } + + vstTable.addAll(forAddition); + + // only break if this is an ASSIGN op node, + // otherwise fall through to default case + vstTable.assertConsistency(); + break; } } @@ -564,20 +564,20 @@ public class OoOJavaAnalysis { TempDescriptor[] writeTemps = fn.writesTemps(); if (writeTemps.length > 0) { - // for now, when writeTemps > 1, make sure - // its a call node, programmer enforce only - // doing stuff like calling a print routine - if (writeTemps.length > 1) { - assert fn.kind() == FKind.FlatCall || fn.kind() == FKind.FlatMethod; - break; - } + // for now, when writeTemps > 1, make sure + // its a call node, programmer enforce only + // doing stuff like calling a print routine + if (writeTemps.length > 1) { + assert fn.kind() == FKind.FlatCall || fn.kind() == FKind.FlatMethod; + break; + } - vstTable.remove(writeTemps[0]); + vstTable.remove(writeTemps[0]); - HashSet ts = new HashSet(); - ts.add(writeTemps[0]); + HashSet ts = new HashSet(); + ts.add(writeTemps[0]); - vstTable.add(new VariableSourceToken(ts, currentSESE, new Integer(0), writeTemps[0])); + vstTable.add(new VariableSourceToken(ts, currentSESE, new Integer(0), writeTemps[0])); } vstTable.assertConsistency(); @@ -600,28 +600,28 @@ public class OoOJavaAnalysis { Set curr = new HashSet(); for (int i = 0; i < fn.numPrev(); i++) { - FlatNode nn = fn.getPrev(i); - Set notAvailIn = notAvailableResults.get(nn); - if (notAvailIn != null) { - curr.addAll(notAvailIn); - } + FlatNode nn = fn.getPrev(i); + Set notAvailIn = notAvailableResults.get(nn); + if (notAvailIn != null) { + curr.addAll(notAvailIn); + } } FlatSESEEnterNode currentSESE = rblockRel.getLocalInnerRBlock(fn); if (currentSESE == null) { - currentSESE = rblockRel.getCallerProxySESE(); + currentSESE = rblockRel.getCallerProxySESE(); } notAvailable_nodeActions(fn, curr, currentSESE); // if a new result, schedule forward nodes for analysis if (!curr.equals(prev)) { - notAvailableResults.put(fn, curr); + notAvailableResults.put(fn, curr); - for (int i = 0; i < fn.numNext(); i++) { - FlatNode nn = fn.getNext(i); - flatNodesToVisit.add(nn); - } + for (int i = 0; i < fn.numNext(); i++) { + FlatNode nn = fn.getNext(i); + flatNodesToVisit.add(nn); + } } } } @@ -643,7 +643,7 @@ public class OoOJavaAnalysis { Set notAvailCopy = new HashSet(); Iterator tdItr = notAvailSet.iterator(); while (tdItr.hasNext()) { - notAvailCopy.add(tdItr.next()); + notAvailCopy.add(tdItr.next()); } notAvailableIntoSESE.put(fsen, notAvailCopy); @@ -672,19 +672,19 @@ public class OoOJavaAnalysis { FlatOpNode fon = (FlatOpNode) fn; if (fon.getOp().getOp() == Operation.ASSIGN) { - TempDescriptor lhs = fon.getDest(); - TempDescriptor rhs = fon.getLeft(); - - // copy makes lhs same availability as rhs - if (notAvailSet.contains(rhs)) { - notAvailSet.add(lhs); - } else { - notAvailSet.remove(lhs); - } - - // only break if this is an ASSIGN op node, - // otherwise fall through to default case - break; + TempDescriptor lhs = fon.getDest(); + TempDescriptor rhs = fon.getLeft(); + + // copy makes lhs same availability as rhs + if (notAvailSet.contains(rhs)) { + notAvailSet.add(lhs); + } else { + notAvailSet.remove(lhs); + } + + // only break if this is an ASSIGN op node, + // otherwise fall through to default case + break; } } @@ -693,47 +693,47 @@ public class OoOJavaAnalysis { default: { TempDescriptor[] writeTemps = fn.writesTemps(); for (int i = 0; i < writeTemps.length; i++) { - TempDescriptor wTemp = writeTemps[i]; - notAvailSet.remove(wTemp); + TempDescriptor wTemp = writeTemps[i]; + notAvailSet.remove(wTemp); } TempDescriptor[] readTemps = fn.readsTemps(); for (int i = 0; i < readTemps.length; i++) { - TempDescriptor rTemp = readTemps[i]; - notAvailSet.remove(rTemp); - - // if this variable has exactly one source, potentially - // get other things from this source as well - VarSrcTokTable vstTable = variableResults.get(fn); - - VSTWrapper vstIfStatic = new VSTWrapper(); - Integer srcType = vstTable.getRefVarSrcType(rTemp, currentSESE, vstIfStatic); - - if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) { - - VariableSourceToken vst = vstIfStatic.vst; - - Iterator availItr = - vstTable.get(vst.getSESE(), vst.getAge()).iterator(); - - // look through things that are also available from same source - while (availItr.hasNext()) { - VariableSourceToken vstAlsoAvail = availItr.next(); - - Iterator refVarItr = vstAlsoAvail.getRefVars().iterator(); - while (refVarItr.hasNext()) { - TempDescriptor refVarAlso = refVarItr.next(); - - // if a variable is available from the same source, AND it ALSO - // only comes from one statically known source, mark it available - VSTWrapper vstIfStaticNotUsed = new VSTWrapper(); - Integer srcTypeAlso = - vstTable.getRefVarSrcType(refVarAlso, currentSESE, vstIfStaticNotUsed); - if (srcTypeAlso.equals(VarSrcTokTable.SrcType_STATIC)) { - notAvailSet.remove(refVarAlso); - } - } - } - } + TempDescriptor rTemp = readTemps[i]; + notAvailSet.remove(rTemp); + + // if this variable has exactly one source, potentially + // get other things from this source as well + VarSrcTokTable vstTable = variableResults.get(fn); + + VSTWrapper vstIfStatic = new VSTWrapper(); + Integer srcType = vstTable.getRefVarSrcType(rTemp, currentSESE, vstIfStatic); + + if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) { + + VariableSourceToken vst = vstIfStatic.vst; + + Iterator availItr = + vstTable.get(vst.getSESE(), vst.getAge()).iterator(); + + // look through things that are also available from same source + while (availItr.hasNext()) { + VariableSourceToken vstAlsoAvail = availItr.next(); + + Iterator refVarItr = vstAlsoAvail.getRefVars().iterator(); + while (refVarItr.hasNext()) { + TempDescriptor refVarAlso = refVarItr.next(); + + // if a variable is available from the same source, AND it ALSO + // only comes from one statically known source, mark it available + VSTWrapper vstIfStaticNotUsed = new VSTWrapper(); + Integer srcTypeAlso = + vstTable.getRefVarSrcType(refVarAlso, currentSESE, vstIfStaticNotUsed); + if (srcTypeAlso.equals(VarSrcTokTable.SrcType_STATIC)) { + notAvailSet.remove(refVarAlso); + } + } + } + } } } break; @@ -761,35 +761,35 @@ public class OoOJavaAnalysis { // before the current statement VarSrcTokTable dotSTtable = new VarSrcTokTable(); for (int i = 0; i < fn.numPrev(); i++) { - FlatNode nn = fn.getPrev(i); - dotSTtable.merge(variableResults.get(nn)); + FlatNode nn = fn.getPrev(i); + dotSTtable.merge(variableResults.get(nn)); } // find dt-st notAvailableSet also Set dotSTnotAvailSet = new HashSet(); for (int i = 0; i < fn.numPrev(); i++) { - FlatNode nn = fn.getPrev(i); - Set notAvailIn = notAvailableResults.get(nn); - if (notAvailIn != null) { - dotSTnotAvailSet.addAll(notAvailIn); - } + FlatNode nn = fn.getPrev(i); + Set notAvailIn = notAvailableResults.get(nn); + if (notAvailIn != null) { + dotSTnotAvailSet.addAll(notAvailIn); + } } Set dotSTlive = livenessGlobalView.get(fn); FlatSESEEnterNode currentSESE = rblockRel.getLocalInnerRBlock(fn); if (currentSESE == null) { - currentSESE = rblockRel.getCallerProxySESE(); + currentSESE = rblockRel.getCallerProxySESE(); } codePlans_nodeActions(fm, fn, dotSTtable, dotSTnotAvailSet, currentSESE); for (int i = 0; i < fn.numNext(); i++) { - FlatNode nn = fn.getNext(i); + FlatNode nn = fn.getNext(i); - if (!visited.contains(nn)) { - flatNodesToVisit.add(nn); - } + if (!visited.contains(nn)) { + flatNodesToVisit.add(nn); + } } } } @@ -809,38 +809,38 @@ public class OoOJavaAnalysis { // dependencies properly Iterator inVarItr = fsen.getInVarSet().iterator(); while (inVarItr.hasNext()) { - TempDescriptor inVar = inVarItr.next(); - - // when we get to an SESE enter node we change the - // currentSESE variable of this analysis to the - // child that is declared by the enter node, so - // in order to classify in-vars correctly, pass - // the parent SESE in--at other FlatNode types just - // use the currentSESE - FlatSESEEnterNode parent = rblockRel.getLocalInnerRBlock(fn); - if (parent == null) { - parent = rblockRel.getCallerProxySESE(); - } - - VSTWrapper vstIfStatic = new VSTWrapper(); - Integer srcType = vstTableIn.getRefVarSrcType(inVar, parent, vstIfStatic); - - // the current SESE needs a local space to track the dynamic - // variable and the child needs space in its SESE record - if (srcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) { - fsen.addDynamicInVar(inVar); - addDynamicVar(parent, fm, inVar); - - } else if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) { - fsen.addStaticInVar(inVar); - VariableSourceToken vst = vstIfStatic.vst; - fsen.putStaticInVar2src(inVar, vst); - fsen.addStaticInVarSrc(new SESEandAgePair(vst.getSESE(), vst.getAge())); - - } else { - assert srcType.equals(VarSrcTokTable.SrcType_READY); - fsen.addReadyInVar(inVar); - } + TempDescriptor inVar = inVarItr.next(); + + // when we get to an SESE enter node we change the + // currentSESE variable of this analysis to the + // child that is declared by the enter node, so + // in order to classify in-vars correctly, pass + // the parent SESE in--at other FlatNode types just + // use the currentSESE + FlatSESEEnterNode parent = rblockRel.getLocalInnerRBlock(fn); + if (parent == null) { + parent = rblockRel.getCallerProxySESE(); + } + + VSTWrapper vstIfStatic = new VSTWrapper(); + Integer srcType = vstTableIn.getRefVarSrcType(inVar, parent, vstIfStatic); + + // the current SESE needs a local space to track the dynamic + // variable and the child needs space in its SESE record + if (srcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) { + fsen.addDynamicInVar(inVar); + addDynamicVar(parent, fm, inVar); + + } else if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) { + fsen.addStaticInVar(inVar); + VariableSourceToken vst = vstIfStatic.vst; + fsen.putStaticInVar2src(inVar, vst); + fsen.addStaticInVarSrc(new SESEandAgePair(vst.getSESE(), vst.getAge())); + + } else { + assert srcType.equals(VarSrcTokTable.SrcType_READY); + fsen.addReadyInVar(inVar); + } } } break; @@ -855,28 +855,28 @@ public class OoOJavaAnalysis { Iterator outVarItr = exiter.getOutVarSet().iterator(); while (outVarItr.hasNext()) { - TempDescriptor outVar = outVarItr.next(); - - VSTWrapper vstIfStatic = new VSTWrapper(); - Integer srcType = vstTableIn.getRefVarSrcType(outVar, exiter, vstIfStatic); - - if (srcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) { - // if the out-var is dynamic, put it in the set of dyn out vars - // so exiting code gen knows to look for the value, but also put - // it in the set of dynamic vars the exiter must track! - exiter.addDynamicOutVar(outVar); - addDynamicVar(exiter, fm, outVar); - - } else if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) { - exiter.addStaticOutVar(outVar); - VariableSourceToken vst = vstIfStatic.vst; - exiter.putStaticOutVar2src(outVar, vst); - exiter.addStaticOutVarSrc(new SESEandAgePair(vst.getSESE(), vst.getAge())); - - } else { - assert srcType.equals(VarSrcTokTable.SrcType_READY); - exiter.addReadyOutVar(outVar); - } + TempDescriptor outVar = outVarItr.next(); + + VSTWrapper vstIfStatic = new VSTWrapper(); + Integer srcType = vstTableIn.getRefVarSrcType(outVar, exiter, vstIfStatic); + + if (srcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) { + // if the out-var is dynamic, put it in the set of dyn out vars + // so exiting code gen knows to look for the value, but also put + // it in the set of dynamic vars the exiter must track! + exiter.addDynamicOutVar(outVar); + addDynamicVar(exiter, fm, outVar); + + } else if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) { + exiter.addStaticOutVar(outVar); + VariableSourceToken vst = vstIfStatic.vst; + exiter.putStaticOutVar2src(outVar, vst); + exiter.addStaticOutVarSrc(new SESEandAgePair(vst.getSESE(), vst.getAge())); + + } else { + assert srcType.equals(VarSrcTokTable.SrcType_READY); + exiter.addReadyOutVar(outVar); + } } } break; @@ -885,33 +885,33 @@ public class OoOJavaAnalysis { FlatOpNode fon = (FlatOpNode) fn; if (fon.getOp().getOp() == Operation.ASSIGN) { - TempDescriptor lhs = fon.getDest(); - TempDescriptor rhs = fon.getLeft(); - - // if this is an op node, don't stall, copy - // source and delay until we need to use value - - // ask whether lhs and rhs sources are dynamic, static, etc. - VSTWrapper vstIfStatic = new VSTWrapper(); - Integer lhsSrcType = vstTableIn.getRefVarSrcType(lhs, currentSESE, vstIfStatic); - Integer rhsSrcType = vstTableIn.getRefVarSrcType(rhs, currentSESE, vstIfStatic); - - if (rhsSrcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) { - // if rhs is dynamic going in, lhs will definitely be dynamic - // going out of this node, so track that here - plan.addDynAssign(lhs, rhs); - addDynamicVar(currentSESE, fm, lhs); - addDynamicVar(currentSESE, fm, rhs); - - } else if (lhsSrcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) { - // otherwise, if the lhs is dynamic, but the rhs is not, we - // need to update the variable's dynamic source as "current SESE" - plan.addDynAssign(lhs); - } - - // only break if this is an ASSIGN op node, - // otherwise fall through to default case - break; + TempDescriptor lhs = fon.getDest(); + TempDescriptor rhs = fon.getLeft(); + + // if this is an op node, don't stall, copy + // source and delay until we need to use value + + // ask whether lhs and rhs sources are dynamic, static, etc. + VSTWrapper vstIfStatic = new VSTWrapper(); + Integer lhsSrcType = vstTableIn.getRefVarSrcType(lhs, currentSESE, vstIfStatic); + Integer rhsSrcType = vstTableIn.getRefVarSrcType(rhs, currentSESE, vstIfStatic); + + if (rhsSrcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) { + // if rhs is dynamic going in, lhs will definitely be dynamic + // going out of this node, so track that here + plan.addDynAssign(lhs, rhs); + addDynamicVar(currentSESE, fm, lhs); + addDynamicVar(currentSESE, fm, rhs); + + } else if (lhsSrcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) { + // otherwise, if the lhs is dynamic, but the rhs is not, we + // need to update the variable's dynamic source as "current SESE" + plan.addDynAssign(lhs); + } + + // only break if this is an ASSIGN op node, + // otherwise fall through to default case + break; } } @@ -927,66 +927,66 @@ public class OoOJavaAnalysis { TempDescriptor[] readarray = fn.readsTemps(); for (int i = 0; i < readarray.length; i++) { - TempDescriptor readtmp = readarray[i]; - - // ignore temps that are definitely available - // when considering to stall on it - if (!notAvailSetIn.contains(readtmp)) { - continue; - } - - // check the source type of this variable - VSTWrapper vstIfStatic = new VSTWrapper(); - Integer srcType = vstTableIn.getRefVarSrcType(readtmp, currentSESE, vstIfStatic); - - if (srcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) { - // 1) It is not clear statically where this variable will - // come from, so dynamically we must keep track - // along various control paths, and therefore when we stall, - // just stall for the exact thing we need and move on - plan.addDynamicStall(readtmp); - addDynamicVar(currentSESE, fm, readtmp); - - } else if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) { - // 2) Single token/age pair: Stall for token/age pair, and copy - // all live variables with same token/age pair at the same - // time. This is the same stuff that the notavaialable analysis - // marks as now available. - VariableSourceToken vst = vstIfStatic.vst; - - Iterator availItr = - vstTableIn.get(vst.getSESE(), vst.getAge()).iterator(); - - while (availItr.hasNext()) { - VariableSourceToken vstAlsoAvail = availItr.next(); - - // only grab additional stuff that is live - Set copySet = new HashSet(); - - Iterator refVarItr = vstAlsoAvail.getRefVars().iterator(); - - while (refVarItr.hasNext()) { - TempDescriptor refVar = refVarItr.next(); - // note: this should just use normal liveness in...only want to - // copy live variables... - if (liveness.getLiveInTemps(fm, fn).contains(refVar)) { - copySet.add(refVar); - } - } - - if (!copySet.isEmpty()) { - plan.addStall2CopySet(vstAlsoAvail, copySet); - } - } - - } else { - // the other case for srcs is READY, so do nothing - } - - // assert that everything being stalled for is in the - // "not available" set coming into this flat node and - // that every VST identified is in the possible "stall set" - // that represents VST's from children SESE's + TempDescriptor readtmp = readarray[i]; + + // ignore temps that are definitely available + // when considering to stall on it + if (!notAvailSetIn.contains(readtmp)) { + continue; + } + + // check the source type of this variable + VSTWrapper vstIfStatic = new VSTWrapper(); + Integer srcType = vstTableIn.getRefVarSrcType(readtmp, currentSESE, vstIfStatic); + + if (srcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) { + // 1) It is not clear statically where this variable will + // come from, so dynamically we must keep track + // along various control paths, and therefore when we stall, + // just stall for the exact thing we need and move on + plan.addDynamicStall(readtmp); + addDynamicVar(currentSESE, fm, readtmp); + + } else if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) { + // 2) Single token/age pair: Stall for token/age pair, and copy + // all live variables with same token/age pair at the same + // time. This is the same stuff that the notavaialable analysis + // marks as now available. + VariableSourceToken vst = vstIfStatic.vst; + + Iterator availItr = + vstTableIn.get(vst.getSESE(), vst.getAge()).iterator(); + + while (availItr.hasNext()) { + VariableSourceToken vstAlsoAvail = availItr.next(); + + // only grab additional stuff that is live + Set copySet = new HashSet(); + + Iterator refVarItr = vstAlsoAvail.getRefVars().iterator(); + + while (refVarItr.hasNext()) { + TempDescriptor refVar = refVarItr.next(); + // note: this should just use normal liveness in...only want to + // copy live variables... + if (liveness.getLiveInTemps(fm, fn).contains(refVar)) { + copySet.add(refVar); + } + } + + if (!copySet.isEmpty()) { + plan.addStall2CopySet(vstAlsoAvail, copySet); + } + } + + } else { + // the other case for srcs is READY, so do nothing + } + + // assert that everything being stalled for is in the + // "not available" set coming into this flat node and + // that every VST identified is in the possible "stall set" + // that represents VST's from children SESE's } } @@ -1007,7 +1007,7 @@ public class OoOJavaAnalysis { // never need to generate another name for it in code (it is // ALWAYS the task executing the local method context) if (vst.getSESE().getIsCallerProxySESE()) { - continue; + continue; } SESEandAgePair sap = new SESEandAgePair(vst.getSESE(), vst.getAge()); @@ -1015,8 +1015,8 @@ public class OoOJavaAnalysis { FlatSESEEnterNode sese = currentSESE; while (sese != null) { - addNeededStaticName(sese, fm, sap); - sese = sese.getLocalParent(); + addNeededStaticName(sese, fm, sap); + sese = sese.getLocalParent(); } } @@ -1035,17 +1035,17 @@ public class OoOJavaAnalysis { fsenDoingTracking = currentSESE.getLocalParent(); if (fsenDoingTracking == null) { - // if there is no local parent, there are one of two cases - // 1) the current task is main, in which case this FlatNode - // is the main's exit, and doesn't need to do any of the - // following dynamic tracking - // 2) the current task is defined in a method, so use the - // caller proxy in the variable source calcs below - if (currentSESE.equals(rblockRel.getMainSESE())) { - return; - } else { - fsenDoingTracking = rblockRel.getCallerProxySESE(); - } + // if there is no local parent, there are one of two cases + // 1) the current task is main, in which case this FlatNode + // is the main's exit, and doesn't need to do any of the + // following dynamic tracking + // 2) the current task is defined in a method, so use the + // caller proxy in the variable source calcs below + if (currentSESE.equals(rblockRel.getMainSESE())) { + return; + } else { + fsenDoingTracking = rblockRel.getCallerProxySESE(); + } } } else { fsenDoingTracking = currentSESE; @@ -1063,24 +1063,24 @@ public class OoOJavaAnalysis { // completely outside of the root SESE scope if (nextVstTable != null && nextLiveIn != null) { - Hashtable readyOrStatic2dynamicSet = - thisVstTable.getReadyOrStatic2DynamicSet(nextVstTable, nextLiveIn, fsenDoingTracking); + Hashtable readyOrStatic2dynamicSet = + thisVstTable.getReadyOrStatic2DynamicSet(nextVstTable, nextLiveIn, fsenDoingTracking); - if (!readyOrStatic2dynamicSet.isEmpty()) { + if (!readyOrStatic2dynamicSet.isEmpty()) { - // either add these results to partial fixed-point result - // or make a new one if we haven't made any here yet - FlatEdge fe = new FlatEdge(fn, nn); - FlatWriteDynamicVarNode fwdvn = wdvNodesToSpliceIn.get(fe); + // either add these results to partial fixed-point result + // or make a new one if we haven't made any here yet + FlatEdge fe = new FlatEdge(fn, nn); + FlatWriteDynamicVarNode fwdvn = wdvNodesToSpliceIn.get(fe); - if (fwdvn == null) { - fwdvn = - new FlatWriteDynamicVarNode(fn, nn, readyOrStatic2dynamicSet, fsenDoingTracking); - wdvNodesToSpliceIn.put(fe, fwdvn); - } else { - fwdvn.addMoreVar2Src(readyOrStatic2dynamicSet); - } - } + if (fwdvn == null) { + fwdvn = + new FlatWriteDynamicVarNode(fn, nn, readyOrStatic2dynamicSet, fsenDoingTracking); + wdvNodesToSpliceIn.put(fe, fwdvn); + } else { + fwdvn.addMoreVar2Src(readyOrStatic2dynamicSet); + } + } } } } @@ -1143,7 +1143,7 @@ public class OoOJavaAnalysis { FlatSESEEnterNode parent = (FlatSESEEnterNode) iterator.next(); if (parent.getIsLeafSESE()) { - continue; + continue; } EffectsAnalysis effectsAnalysis = disjointAnalysisTaints.getEffectsAnalysis(); @@ -1153,9 +1153,9 @@ public class OoOJavaAnalysis { Set children = parent.getChildren(); for (Iterator iterator2 = children.iterator(); iterator2.hasNext(); ) { - FlatSESEEnterNode child = (FlatSESEEnterNode) iterator2.next(); - Hashtable> taint2Effects = effectsAnalysis.get(child); - conflictGraph.addLiveIn(taint2Effects); + FlatSESEEnterNode child = (FlatSESEEnterNode) iterator2.next(); + Hashtable> taint2Effects = effectsAnalysis.get(child); + conflictGraph.addLiveIn(taint2Effects); } sese2conflictGraph.put(parent, conflictGraph); @@ -1169,7 +1169,7 @@ public class OoOJavaAnalysis { MethodDescriptor md = descItr.next(); FlatMethod fm = state.getMethodFlat(md); if (fm != null) { - addStallSitesToConflictGraphs(fm); + addStallSitesToConflictGraphs(fm); } } } @@ -1192,10 +1192,10 @@ public class OoOJavaAnalysis { // schedule forward nodes for analysis for (int i = 0; i < fn.numNext(); i++) { - FlatNode nn = fn.getNext(i); - if (!visited.contains(nn)) { - flatNodesToVisit.add(nn); - } + FlatNode nn = fn.getNext(i); + if (!visited.contains(nn)) { + flatNodesToVisit.add(nn); + } } } } @@ -1215,8 +1215,8 @@ public class OoOJavaAnalysis { ConflictGraph conflictGraph = sese2conflictGraph.get(currentSESE); if (conflictGraph == null) { - assert currentSESE.getIsLeafSESE(); - continue; + assert currentSESE.getIsLeafSESE(); + continue; } TempDescriptor lhs; @@ -1227,48 +1227,48 @@ public class OoOJavaAnalysis { case FKind.FlatFieldNode: case FKind.FlatElementNode: { - if (fn instanceof FlatFieldNode) { - FlatFieldNode ffn = (FlatFieldNode) fn; - rhs = ffn.getSrc(); - } else { - FlatElementNode fen = (FlatElementNode) fn; - rhs = fen.getSrc(); - } + if (fn instanceof FlatFieldNode) { + FlatFieldNode ffn = (FlatFieldNode) fn; + rhs = ffn.getSrc(); + } else { + FlatElementNode fen = (FlatElementNode) fn; + rhs = fen.getSrc(); + } - conflictGraph.addStallSite(taint2Effects, rhs, cd); + conflictGraph.addStallSite(taint2Effects, rhs, cd); } break; case FKind.FlatSetFieldNode: case FKind.FlatSetElementNode: { - if (fn instanceof FlatSetFieldNode) { - FlatSetFieldNode fsfn = (FlatSetFieldNode) fn; - lhs = fsfn.getDst(); - rhs = fsfn.getSrc(); - } else { - FlatSetElementNode fsen = (FlatSetElementNode) fn; - lhs = fsen.getDst(); - rhs = fsen.getSrc(); - } - - conflictGraph.addStallSite(taint2Effects, rhs, cd); - conflictGraph.addStallSite(taint2Effects, lhs, cd); + if (fn instanceof FlatSetFieldNode) { + FlatSetFieldNode fsfn = (FlatSetFieldNode) fn; + lhs = fsfn.getDst(); + rhs = fsfn.getSrc(); + } else { + FlatSetElementNode fsen = (FlatSetElementNode) fn; + lhs = fsen.getDst(); + rhs = fsen.getSrc(); + } + + conflictGraph.addStallSite(taint2Effects, rhs, cd); + conflictGraph.addStallSite(taint2Effects, lhs, cd); } break; case FKind.FlatCall: { - FlatCall fc = (FlatCall) fn; - lhs = fc.getThis(); + FlatCall fc = (FlatCall) fn; + lhs = fc.getThis(); - conflictGraph.addStallSite(taint2Effects, lhs, cd); + conflictGraph.addStallSite(taint2Effects, lhs, cd); } break; } if (conflictGraph.id2cn.size() > 0) { - sese2conflictGraph.put(currentSESE, conflictGraph); + sese2conflictGraph.put(currentSESE, conflictGraph); } } } @@ -1283,10 +1283,10 @@ public class OoOJavaAnalysis { ConflictGraph conflictGraph = sese2conflictGraph.get(sese); if (useReachInfo) { - // clear current conflict before recalculating with reachability info - conflictGraph.clearAllConflictEdge(); - conflictGraph.setDisJointAnalysis(disjointAnalysisReach); - conflictGraph.setFMEnclosing(sese.getfmEnclosing()); + // clear current conflict before recalculating with reachability info + conflictGraph.clearAllConflictEdge(); + conflictGraph.setDisJointAnalysis(disjointAnalysisReach); + conflictGraph.setFMEnclosing(sese.getfmEnclosing()); } conflictGraph.analyzeConflicts(sitesToFlag, useReachInfo); sese2conflictGraph.put(sese, conflictGraph); @@ -1299,12 +1299,12 @@ public class OoOJavaAnalysis { FlatNode key = (FlatNode) keyEnum.nextElement(); ConflictGraph cg = sese2conflictGraph.get(key); try { - if (cg.hasConflictEdge()) { - cg.writeGraph("ConflictGraphFor" + key, false); - } + if (cg.hasConflictEdge()) { + cg.writeGraph("ConflictGraphFor" + key, false); + } } catch (IOException e) { - System.out.println("Error writing"); - System.exit(0); + System.out.println("Error writing"); + System.exit(0); } } } @@ -1342,9 +1342,9 @@ public class OoOJavaAnalysis { for (Iterator iterator = tempCover.iterator(); iterator.hasNext(); ) { ConflictEdge conflictEdge = (ConflictEdge) iterator.next(); if (conflictEdge.isCoarseEdge()) { - coarseToCover.add(conflictEdge); + coarseToCover.add(conflictEdge); } else { - fineToCover.add(conflictEdge); + fineToCover.add(conflictEdge); } } @@ -1361,250 +1361,250 @@ public class OoOJavaAnalysis { do { // fine-grained edge - changed = false; - - for (Iterator iterator = fineToCover.iterator(); iterator.hasNext(); ) { - - int type; - ConflictEdge edge = (ConflictEdge) iterator.next(); - if (seseLock.getConflictNodeSet().size() == 0) { - // initial setup - if (seseLock.isWriteNode(edge.getVertexU())) { - // mark as fine_write - if (edge.getVertexU().isStallSiteNode()) { - type = ConflictNode.PARENT_WRITE; - } else { - type = ConflictNode.FINE_WRITE; - } - seseLock.addConflictNode(edge.getVertexU(), type); - } else { - // mark as fine_read - if (edge.getVertexU().isStallSiteNode()) { - type = ConflictNode.PARENT_READ; - } else { - type = ConflictNode.FINE_READ; - } - seseLock.addConflictNode(edge.getVertexU(), type); - } - if (edge.getVertexV() != edge.getVertexU()) { - if (seseLock.isWriteNode(edge.getVertexV())) { - // mark as fine_write - if (edge.getVertexV().isStallSiteNode()) { - type = ConflictNode.PARENT_WRITE; - } else { - type = ConflictNode.FINE_WRITE; - } - seseLock.addConflictNode(edge.getVertexV(), type); - } else { - // mark as fine_read - if (edge.getVertexV().isStallSiteNode()) { - type = ConflictNode.PARENT_READ; - } else { - type = ConflictNode.FINE_READ; - } - seseLock.addConflictNode(edge.getVertexV(), type); - } - } - changed = true; - seseLock.addConflictEdge(edge); - fineToCover.remove(edge); - break; // exit iterator loop - } // end of initial setup - - ConflictNode newNode; - if ((newNode = seseLock.getNewNodeConnectedWithGroup(edge)) != null) { - // new node has a fine-grained edge to all current node - // If there is a coarse grained edge where need a fine edge, it's - // okay to add the node - // but the edge must remain uncovered. - - changed = true; - - if (seseLock.containsConflictNode(newNode)) { - seseLock.addEdge(edge); - fineToCover.remove(edge); - break; - } - - if (seseLock.isWriteNode(newNode)) { - if (newNode.isStallSiteNode()) { - type = ConflictNode.PARENT_WRITE; - } else { - type = ConflictNode.FINE_WRITE; - } - seseLock.setNodeType(newNode, type); - } else { - if (newNode.isStallSiteNode()) { - type = ConflictNode.PARENT_READ; - } else { - type = ConflictNode.FINE_READ; - } - seseLock.setNodeType(newNode, type); - } - - seseLock.addEdge(edge); - Set edgeSet = newNode.getEdgeSet(); - for (Iterator iterator2 = edgeSet.iterator(); iterator2.hasNext(); ) { - ConflictEdge conflictEdge = (ConflictEdge) iterator2.next(); - - // mark all fine edges between new node and nodes in the group as - // covered - if (!conflictEdge.getVertexU().equals(newNode)) { - if (seseLock.containsConflictNode(conflictEdge.getVertexU())) { - changed = true; - seseLock.addConflictEdge(conflictEdge); - fineToCover.remove(conflictEdge); - } - } else if (!conflictEdge.getVertexV().equals(newNode)) { - if (seseLock.containsConflictNode(conflictEdge.getVertexV())) { - changed = true; - seseLock.addConflictEdge(conflictEdge); - fineToCover.remove(conflictEdge); - } - } - - } - - break; // exit iterator loop - } - } + changed = false; + + for (Iterator iterator = fineToCover.iterator(); iterator.hasNext(); ) { + + int type; + ConflictEdge edge = (ConflictEdge) iterator.next(); + if (seseLock.getConflictNodeSet().size() == 0) { + // initial setup + if (seseLock.isWriteNode(edge.getVertexU())) { + // mark as fine_write + if (edge.getVertexU().isStallSiteNode()) { + type = ConflictNode.PARENT_WRITE; + } else { + type = ConflictNode.FINE_WRITE; + } + seseLock.addConflictNode(edge.getVertexU(), type); + } else { + // mark as fine_read + if (edge.getVertexU().isStallSiteNode()) { + type = ConflictNode.PARENT_READ; + } else { + type = ConflictNode.FINE_READ; + } + seseLock.addConflictNode(edge.getVertexU(), type); + } + if (edge.getVertexV() != edge.getVertexU()) { + if (seseLock.isWriteNode(edge.getVertexV())) { + // mark as fine_write + if (edge.getVertexV().isStallSiteNode()) { + type = ConflictNode.PARENT_WRITE; + } else { + type = ConflictNode.FINE_WRITE; + } + seseLock.addConflictNode(edge.getVertexV(), type); + } else { + // mark as fine_read + if (edge.getVertexV().isStallSiteNode()) { + type = ConflictNode.PARENT_READ; + } else { + type = ConflictNode.FINE_READ; + } + seseLock.addConflictNode(edge.getVertexV(), type); + } + } + changed = true; + seseLock.addConflictEdge(edge); + fineToCover.remove(edge); + break; // exit iterator loop + } // end of initial setup + + ConflictNode newNode; + if ((newNode = seseLock.getNewNodeConnectedWithGroup(edge)) != null) { + // new node has a fine-grained edge to all current node + // If there is a coarse grained edge where need a fine edge, it's + // okay to add the node + // but the edge must remain uncovered. + + changed = true; + + if (seseLock.containsConflictNode(newNode)) { + seseLock.addEdge(edge); + fineToCover.remove(edge); + break; + } + + if (seseLock.isWriteNode(newNode)) { + if (newNode.isStallSiteNode()) { + type = ConflictNode.PARENT_WRITE; + } else { + type = ConflictNode.FINE_WRITE; + } + seseLock.setNodeType(newNode, type); + } else { + if (newNode.isStallSiteNode()) { + type = ConflictNode.PARENT_READ; + } else { + type = ConflictNode.FINE_READ; + } + seseLock.setNodeType(newNode, type); + } + + seseLock.addEdge(edge); + Set edgeSet = newNode.getEdgeSet(); + for (Iterator iterator2 = edgeSet.iterator(); iterator2.hasNext(); ) { + ConflictEdge conflictEdge = (ConflictEdge) iterator2.next(); + + // mark all fine edges between new node and nodes in the group as + // covered + if (!conflictEdge.getVertexU().equals(newNode)) { + if (seseLock.containsConflictNode(conflictEdge.getVertexU())) { + changed = true; + seseLock.addConflictEdge(conflictEdge); + fineToCover.remove(conflictEdge); + } + } else if (!conflictEdge.getVertexV().equals(newNode)) { + if (seseLock.containsConflictNode(conflictEdge.getVertexV())) { + changed = true; + seseLock.addConflictEdge(conflictEdge); + fineToCover.remove(conflictEdge); + } + } + + } + + break; // exit iterator loop + } + } } while (changed); HashSet notCovered = new HashSet(); do { // coarse - changed = false; - int type; - for (Iterator iterator = coarseToCover.iterator(); iterator.hasNext(); ) { - - ConflictEdge edge = (ConflictEdge) iterator.next(); - if (seseLock.getConflictNodeSet().size() == 0) { - // initial setup - if (seseLock.hasSelfCoarseEdge(edge.getVertexU())) { - // node has a coarse-grained edge with itself - if (!(edge.getVertexU().isStallSiteNode())) { - // and it is not parent - type = ConflictNode.SCC; - } else { - if (state.RCR) { - type = ConflictNode.PARENT_COARSE; - } else { - type = ConflictNode.PARENT_WRITE; - } - } - seseLock.addConflictNode(edge.getVertexU(), type); - } else { - if (edge.getVertexU().isStallSiteNode()) { - if (state.RCR) { - type = ConflictNode.PARENT_COARSE; - } else { - if (edge.getVertexU().getWriteEffectSet().isEmpty()) { - type = ConflictNode.PARENT_READ; - } else { - type = ConflictNode.PARENT_WRITE; - } - } - } else { - type = ConflictNode.COARSE; - } - seseLock.addConflictNode(edge.getVertexU(), type); - } - if (seseLock.hasSelfCoarseEdge(edge.getVertexV())) { - // node has a coarse-grained edge with itself - if (!(edge.getVertexV().isStallSiteNode())) { - // and it is not parent - type = ConflictNode.SCC; - } else { - if (state.RCR) { - type = ConflictNode.PARENT_COARSE; - } else { - type = ConflictNode.PARENT_WRITE; - } - } - seseLock.addConflictNode(edge.getVertexV(), type); - } else { - if (edge.getVertexV().isStallSiteNode()) { - if (state.RCR) { - type = ConflictNode.PARENT_COARSE; - } else { - if (edge.getVertexV().getWriteEffectSet().isEmpty()) { - type = ConflictNode.PARENT_READ; - } else { - type = ConflictNode.PARENT_WRITE; - } - } - } else { - type = ConflictNode.COARSE; - } - seseLock.addConflictNode(edge.getVertexV(), type); - } - changed = true; - coarseToCover.remove(edge); - seseLock.addConflictEdge(edge); - break; // exit iterator loop - } // end of initial setup - - ConflictNode newNode; - if ((newNode = seseLock.getNewNodeConnectedWithGroup(edge)) != null) { - // new node has a coarse-grained edge to all fine-read, fine-write, - // parent - changed = true; - - if (newNode.isInVarNode() && (!seseLock.hasSelfCoarseEdge(newNode)) - && seseLock.hasCoarseEdgeWithParentCoarse(newNode)) { - // this case can't be covered by this queue - coarseToCover.remove(edge); - notCovered.add(edge); - break; - } - - if (seseLock.containsConflictNode(newNode)) { - seseLock.addEdge(edge); - coarseToCover.remove(edge); - break; - } - - if (seseLock.hasSelfCoarseEdge(newNode)) { - // SCC - if (newNode.isStallSiteNode()) { - type = ConflictNode.PARENT_COARSE; - } else { - type = ConflictNode.SCC; - } - seseLock.setNodeType(newNode, type); - } else { - if (newNode.isStallSiteNode()) { - type = ConflictNode.PARENT_COARSE; - } else { - type = ConflictNode.COARSE; - } - seseLock.setNodeType(newNode, type); - } - - seseLock.addEdge(edge); - Set edgeSet = newNode.getEdgeSet(); - for (Iterator iterator2 = edgeSet.iterator(); iterator2.hasNext(); ) { - ConflictEdge conflictEdge = (ConflictEdge) iterator2.next(); - // mark all coarse edges between new node and nodes in the group - // as covered - if (!conflictEdge.getVertexU().equals(newNode)) { - if (seseLock.containsConflictNode(conflictEdge.getVertexU())) { - changed = true; - seseLock.addConflictEdge(conflictEdge); - coarseToCover.remove(conflictEdge); - } - } else if (!conflictEdge.getVertexV().equals(newNode)) { - if (seseLock.containsConflictNode(conflictEdge.getVertexV())) { - changed = true; - seseLock.addConflictEdge(conflictEdge); - coarseToCover.remove(conflictEdge); - } - } - - } - break; // exit iterator loop - } - - } + changed = false; + int type; + for (Iterator iterator = coarseToCover.iterator(); iterator.hasNext(); ) { + + ConflictEdge edge = (ConflictEdge) iterator.next(); + if (seseLock.getConflictNodeSet().size() == 0) { + // initial setup + if (seseLock.hasSelfCoarseEdge(edge.getVertexU())) { + // node has a coarse-grained edge with itself + if (!(edge.getVertexU().isStallSiteNode())) { + // and it is not parent + type = ConflictNode.SCC; + } else { + if (state.RCR) { + type = ConflictNode.PARENT_COARSE; + } else { + type = ConflictNode.PARENT_WRITE; + } + } + seseLock.addConflictNode(edge.getVertexU(), type); + } else { + if (edge.getVertexU().isStallSiteNode()) { + if (state.RCR) { + type = ConflictNode.PARENT_COARSE; + } else { + if (edge.getVertexU().getWriteEffectSet().isEmpty()) { + type = ConflictNode.PARENT_READ; + } else { + type = ConflictNode.PARENT_WRITE; + } + } + } else { + type = ConflictNode.COARSE; + } + seseLock.addConflictNode(edge.getVertexU(), type); + } + if (seseLock.hasSelfCoarseEdge(edge.getVertexV())) { + // node has a coarse-grained edge with itself + if (!(edge.getVertexV().isStallSiteNode())) { + // and it is not parent + type = ConflictNode.SCC; + } else { + if (state.RCR) { + type = ConflictNode.PARENT_COARSE; + } else { + type = ConflictNode.PARENT_WRITE; + } + } + seseLock.addConflictNode(edge.getVertexV(), type); + } else { + if (edge.getVertexV().isStallSiteNode()) { + if (state.RCR) { + type = ConflictNode.PARENT_COARSE; + } else { + if (edge.getVertexV().getWriteEffectSet().isEmpty()) { + type = ConflictNode.PARENT_READ; + } else { + type = ConflictNode.PARENT_WRITE; + } + } + } else { + type = ConflictNode.COARSE; + } + seseLock.addConflictNode(edge.getVertexV(), type); + } + changed = true; + coarseToCover.remove(edge); + seseLock.addConflictEdge(edge); + break; // exit iterator loop + } // end of initial setup + + ConflictNode newNode; + if ((newNode = seseLock.getNewNodeConnectedWithGroup(edge)) != null) { + // new node has a coarse-grained edge to all fine-read, fine-write, + // parent + changed = true; + + if (newNode.isInVarNode() && (!seseLock.hasSelfCoarseEdge(newNode)) + && seseLock.hasCoarseEdgeWithParentCoarse(newNode)) { + // this case can't be covered by this queue + coarseToCover.remove(edge); + notCovered.add(edge); + break; + } + + if (seseLock.containsConflictNode(newNode)) { + seseLock.addEdge(edge); + coarseToCover.remove(edge); + break; + } + + if (seseLock.hasSelfCoarseEdge(newNode)) { + // SCC + if (newNode.isStallSiteNode()) { + type = ConflictNode.PARENT_COARSE; + } else { + type = ConflictNode.SCC; + } + seseLock.setNodeType(newNode, type); + } else { + if (newNode.isStallSiteNode()) { + type = ConflictNode.PARENT_COARSE; + } else { + type = ConflictNode.COARSE; + } + seseLock.setNodeType(newNode, type); + } + + seseLock.addEdge(edge); + Set edgeSet = newNode.getEdgeSet(); + for (Iterator iterator2 = edgeSet.iterator(); iterator2.hasNext(); ) { + ConflictEdge conflictEdge = (ConflictEdge) iterator2.next(); + // mark all coarse edges between new node and nodes in the group + // as covered + if (!conflictEdge.getVertexU().equals(newNode)) { + if (seseLock.containsConflictNode(conflictEdge.getVertexU())) { + changed = true; + seseLock.addConflictEdge(conflictEdge); + coarseToCover.remove(conflictEdge); + } + } else if (!conflictEdge.getVertexV().equals(newNode)) { + if (seseLock.containsConflictNode(conflictEdge.getVertexV())) { + changed = true; + seseLock.addConflictEdge(conflictEdge); + coarseToCover.remove(conflictEdge); + } + } + + } + break; // exit iterator loop + } + + } } while (changed); lockSet.add(seseLock); @@ -1658,20 +1658,20 @@ public class OoOJavaAnalysis { MethodDescriptor md = methItr.next(); FlatMethod fm = state.getMethodFlat(md); if (fm != null) { - bw = - new BufferedWriter(new FileWriter("ooojReport_" + md.getClassMethodName() - + md.getSafeMethodDescriptor() + ".txt")); - bw.write("OoOJava Results for " + md + "\n-------------------\n"); - - bw.write("Dynamic vars to manage:\n " + getContextTaskNames(fm).getDynamicVarSet()); - - bw.write("\n\nLive-In, Root View\n------------------\n" - + fm.printMethod(livenessGlobalView)); - bw.write("\n\nVariable Results-Out\n----------------\n" + fm.printMethod(variableResults)); - bw.write("\n\nNot Available Results-Out\n---------------------\n" - + fm.printMethod(notAvailableResults)); - bw.write("\n\nCode Plans\n----------\n" + fm.printMethod(codePlans)); - bw.close(); + bw = + new BufferedWriter(new FileWriter("ooojReport_" + md.getClassMethodName() + + md.getSafeMethodDescriptor() + ".txt")); + bw.write("OoOJava Results for " + md + "\n-------------------\n"); + + bw.write("Dynamic vars to manage:\n " + getContextTaskNames(fm).getDynamicVarSet()); + + bw.write("\n\nLive-In, Root View\n------------------\n" + + fm.printMethod(livenessGlobalView)); + bw.write("\n\nVariable Results-Out\n----------------\n" + fm.printMethod(variableResults)); + bw.write("\n\nNot Available Results-Out\n---------------------\n" + + fm.printMethod(notAvailableResults)); + bw.write("\n\nCode Plans\n----------\n" + fm.printMethod(codePlans)); + bw.close(); } } } @@ -1707,23 +1707,23 @@ public class OoOJavaAnalysis { bw.write("SESE " + fsen.getPrettyIdentifier()); if (fsen.getIsLeafSESE()) { - bw.write(" (leaf)"); + bw.write(" (leaf)"); } bw.write(" {\n"); bw.write(" in-set: " + fsen.getInVarSet() + "\n"); Iterator tItr = fsen.getInVarSet().iterator(); while (tItr.hasNext()) { - TempDescriptor inVar = tItr.next(); - if (fsen.getReadyInVarSet().contains(inVar)) { - bw.write(" (ready) " + inVar + "\n"); - } - if (fsen.getStaticInVarSet().contains(inVar)) { - bw.write(" (static) " + inVar + " from " + fsen.getStaticInVarSrc(inVar) + "\n"); - } - if (fsen.getDynamicInVarSet().contains(inVar)) { - bw.write(" (dynamic)" + inVar + "\n"); - } + TempDescriptor inVar = tItr.next(); + if (fsen.getReadyInVarSet().contains(inVar)) { + bw.write(" (ready) " + inVar + "\n"); + } + if (fsen.getStaticInVarSet().contains(inVar)) { + bw.write(" (static) " + inVar + " from " + fsen.getStaticInVarSrc(inVar) + "\n"); + } + if (fsen.getDynamicInVarSet().contains(inVar)) { + bw.write(" (dynamic)" + inVar + "\n"); + } } bw.write(" Dynamic vars to manage: " + getContextTaskNames(fsen).getDynamicVarSet() + "\n"); @@ -1731,16 +1731,16 @@ public class OoOJavaAnalysis { bw.write(" out-set: " + fsen.getOutVarSet() + "\n"); tItr = fsen.getOutVarSet().iterator(); while (tItr.hasNext()) { - TempDescriptor outVar = tItr.next(); - if (fsen.getReadyOutVarSet().contains(outVar)) { - bw.write(" (ready) " + outVar + "\n"); - } - if (fsen.getStaticOutVarSet().contains(outVar)) { - bw.write(" (static) " + outVar + " from " + fsen.getStaticOutVarSrc(outVar) + "\n"); - } - if (fsen.getDynamicOutVarSet().contains(outVar)) { - bw.write(" (dynamic)" + outVar + "\n"); - } + TempDescriptor outVar = tItr.next(); + if (fsen.getReadyOutVarSet().contains(outVar)) { + bw.write(" (ready) " + outVar + "\n"); + } + if (fsen.getStaticOutVarSet().contains(outVar)) { + bw.write(" (static) " + outVar + " from " + fsen.getStaticOutVarSrc(outVar) + "\n"); + } + if (fsen.getDynamicOutVarSet().contains(outVar)) { + bw.write(" (dynamic)" + outVar + "\n"); + } } bw.write(" local parent: " + fsen.getLocalParent() + "\n"); diff --git a/Robust/src/Analysis/OoOJava/RBlockRelationAnalysis.java b/Robust/src/Analysis/OoOJava/RBlockRelationAnalysis.java index 331b141a..9b38bdff 100644 --- a/Robust/src/Analysis/OoOJava/RBlockRelationAnalysis.java +++ b/Robust/src/Analysis/OoOJava/RBlockRelationAnalysis.java @@ -160,12 +160,12 @@ public class RBlockRelationAnalysis { FlatNode curr=toprocess.pop(); Set callers=fn2currentSESEs.get(curr); if (callers!=null) { - for(FlatSESEEnterNode sese : callers) { - if (!seseSet.contains(sese)) { - seseSet.add(sese); - toprocess.add(fn); - } - } + for(FlatSESEEnterNode sese : callers) { + if (!seseSet.contains(sese)) { + seseSet.add(sese); + toprocess.add(fn); + } + } } } return seseSet; @@ -277,31 +277,31 @@ public class RBlockRelationAnalysis { seseStacks.put(fm, seseStackFirst); while( !flatNodesToVisit.isEmpty() ) { - Iterator fnItr = flatNodesToVisit.iterator(); - FlatNode fn = fnItr.next(); + Iterator fnItr = flatNodesToVisit.iterator(); + FlatNode fn = fnItr.next(); - Stack seseStack = seseStacks.get(fn); - assert seseStack != null; + Stack seseStack = seseStacks.get(fn); + assert seseStack != null; - flatNodesToVisit.remove(fn); - visited.add(fn); + flatNodesToVisit.remove(fn); + visited.add(fn); - if( !seseStack.isEmpty() ) { - fn2localInnerSESE.put(fn, seseStack.peek() ); - } + if( !seseStack.isEmpty() ) { + fn2localInnerSESE.put(fn, seseStack.peek() ); + } - nodeActions(fn, seseStack, fm); + nodeActions(fn, seseStack, fm); - for( int i = 0; i < fn.numNext(); i++ ) { - FlatNode nn = fn.getNext(i); + for( int i = 0; i < fn.numNext(); i++ ) { + FlatNode nn = fn.getNext(i); - if( !visited.contains(nn) ) { - flatNodesToVisit.add(nn); + if( !visited.contains(nn) ) { + flatNodesToVisit.add(nn); - // clone stack and send along each control path - seseStacks.put(nn, (Stack)seseStack.clone() ); - } - } + // clone stack and send along each control path + seseStacks.put(nn, (Stack)seseStack.clone() ); + } + } } } } @@ -322,27 +322,27 @@ public class RBlockRelationAnalysis { fsen.setcdEnclosing(fm.getMethod().getClassDesc() ); if( seseStack.empty() ) { - // no local parent - fsen.setLocalParent(null); + // no local parent + fsen.setLocalParent(null); - allLocalRootSESEs.add(fsen); + allLocalRootSESEs.add(fsen); - Set seseSet = md2localRootSESEs.get(fm.getMethod() ); - if( seseSet == null ) { - seseSet = new HashSet(); - } - seseSet.add(fsen); - md2localRootSESEs.put(fm.getMethod(), seseSet); + Set seseSet = md2localRootSESEs.get(fm.getMethod() ); + if( seseSet == null ) { + seseSet = new HashSet(); + } + seseSet.add(fsen); + md2localRootSESEs.put(fm.getMethod(), seseSet); } else { - // otherwise a local parent/child relation - // which is also the broader parent/child - // relation as well - seseStack.peek().addLocalChild(fsen); - fsen.setLocalParent(seseStack.peek() ); - - seseStack.peek().addChild(fsen); - fsen.addParent(seseStack.peek() ); + // otherwise a local parent/child relation + // which is also the broader parent/child + // relation as well + seseStack.peek().addLocalChild(fsen); + fsen.setLocalParent(seseStack.peek() ); + + seseStack.peek().addChild(fsen); + fsen.addParent(seseStack.peek() ); } seseStack.push(fsen); @@ -357,8 +357,8 @@ public class RBlockRelationAnalysis { case FKind.FlatReturnNode: { FlatReturnNode frn = (FlatReturnNode) fn; if( !seseStack.empty() ) { - throw new Error("Error: return statement enclosed within SESE "+ - seseStack.peek().getPrettyIdentifier() ); + throw new Error("Error: return statement enclosed within SESE "+ + seseStack.peek().getPrettyIdentifier() ); } } break; @@ -398,48 +398,48 @@ public class RBlockRelationAnalysis { visited.add(fn); if( fn.kind() == FKind.FlatCall ) { - FlatCall fc = (FlatCall) fn; - MethodDescriptor mdCallee = fc.getMethod(); - Set reachable = new HashSet(); - - reachable.add(mdCallee); - reachable.addAll(callGraph.getAllMethods(mdCallee) ); - reachable.retainAll(methodsContainingSESEs); - - if( !reachable.isEmpty() ) { - hasChildrenByCall = true; - - Set reachableSESEMethodSet = - callGraph.getFirstReachableMethodContainingSESE(mdCallee, methodsContainingSESEs); - - reachableSESEMethodSet.add(mdCallee); - reachableSESEMethodSet.retainAll(methodsContainingSESEs); - - for( Iterator iterator = reachableSESEMethodSet.iterator(); iterator.hasNext(); ) { - MethodDescriptor md = (MethodDescriptor) iterator.next(); - Set seseSet = md2localRootSESEs.get(md); - if( seseSet != null ) { - fsen.addChildren(seseSet); - for( Iterator iterator2 = seseSet.iterator(); iterator2.hasNext(); ) { - FlatSESEEnterNode child = (FlatSESEEnterNode) iterator2.next(); - child.addParent(fsen); - } - } - } - } + FlatCall fc = (FlatCall) fn; + MethodDescriptor mdCallee = fc.getMethod(); + Set reachable = new HashSet(); + + reachable.add(mdCallee); + reachable.addAll(callGraph.getAllMethods(mdCallee) ); + reachable.retainAll(methodsContainingSESEs); + + if( !reachable.isEmpty() ) { + hasChildrenByCall = true; + + Set reachableSESEMethodSet = + callGraph.getFirstReachableMethodContainingSESE(mdCallee, methodsContainingSESEs); + + reachableSESEMethodSet.add(mdCallee); + reachableSESEMethodSet.retainAll(methodsContainingSESEs); + + for( Iterator iterator = reachableSESEMethodSet.iterator(); iterator.hasNext(); ) { + MethodDescriptor md = (MethodDescriptor) iterator.next(); + Set seseSet = md2localRootSESEs.get(md); + if( seseSet != null ) { + fsen.addChildren(seseSet); + for( Iterator iterator2 = seseSet.iterator(); iterator2.hasNext(); ) { + FlatSESEEnterNode child = (FlatSESEEnterNode) iterator2.next(); + child.addParent(fsen); + } + } + } + } } if( fn == fsen.getFlatExit() ) { - // don't enqueue any futher nodes - continue; + // don't enqueue any futher nodes + continue; } for( int i = 0; i < fn.numNext(); i++ ) { - FlatNode nn = fn.getNext(i); + FlatNode nn = fn.getNext(i); - if( !visited.contains(nn) ) { - flatNodesToVisit.add(nn); - } + if( !visited.contains(nn) ) { + flatNodesToVisit.add(nn); + } } } @@ -458,135 +458,135 @@ public class RBlockRelationAnalysis { new Hashtable(); for( int i = 0; i < fsen.numNext(); i++ ) { - FlatNode nn = fsen.getNext(i); - flatNodesToVisit.put(nn, fsen.getfmEnclosing() ); + FlatNode nn = fsen.getNext(i); + flatNodesToVisit.put(nn, fsen.getfmEnclosing() ); } Set visited = new HashSet(); while (!flatNodesToVisit.isEmpty()) { - Map.Entry me = (Map.Entry)flatNodesToVisit.entrySet().iterator().next(); - FlatNode fn = (FlatNode) me.getKey(); - FlatMethod fm = (FlatMethod) me.getValue(); - - flatNodesToVisit.remove(fn); - visited.add(fn); - - // the "is potential stall site" strategy is to propagate - // "false" from the beginning of a task until you hit a - // child, then from the child's exit propagate "true" for - // the parent statements after children. When you pull a node - // out of the bag for traversal and it happens to be an - // enter or an exit node, fix the dumb propagation that - // your IR predecessor pushed on you - Boolean isPotentialStallSite = isPotentialStallSite(fn); - - if (fn == fsen.getFlatExit()) { - // don't enqueue any further nodes when you find your exit, - // NOR mark your own flat as a statement you are currently - // executing, your parent(s) will mark it - continue; - } - - if (fn instanceof FlatSESEExitNode) { - setIsPotentialStallSite(fn, false); - isPotentialStallSite = true; - } - - // the purpose of this traversal is to find program - // points where rblock 'fsen' might be executing - addPossibleExecutingRBlock(fn, fsen); - - if (fn instanceof FlatSESEEnterNode) { - // don't visit internal nodes of child, - // just enqueue the exit node - FlatSESEEnterNode child = (FlatSESEEnterNode) fn; - assert fsen.getChildren().contains(child); - assert child.getParents().contains(fsen); - flatNodesToVisit.put(child.getFlatExit(), fm); - setIsPotentialStallSite(fn, false); - - // explicitly do this to handle the case that you - // should mark yourself as possibly executing at - // your own exit, because one instance can - // recursively invoke another - addPossibleExecutingRBlock(child.getFlatExit(), fsen); - - continue; - } - - // if previous flat nodes have any changes,, - // propagate predecessor's status of stall site potential - - if (fn instanceof FlatCall) { - - // start visiting nodes in other contexts - FlatCall fc = (FlatCall) fn; - MethodDescriptor mdCallee = fc.getMethod(); - - Set implementations = new HashSet(); - - if (mdCallee.isStatic()) { - implementations.add(mdCallee); - } else { - TypeDescriptor typeDesc = fc.getThis().getType(); - implementations.addAll(callGraph.getMethods(mdCallee, typeDesc)); - } - - for (Iterator imps = implementations.iterator(); imps.hasNext(); ) { - MethodDescriptor mdImp = (MethodDescriptor) imps.next(); - FlatMethod fmImp = state.getMethodFlat(mdImp); - - // keep mapping from fc's md to - // later, when return node of callee becomes a potential stall site, - // following flat nodes of fc should be re-analyzied - if(!methodmap.containsKey(fmImp)) { - methodmap.put(mdImp, new HashSet>()); - } - methodmap.get(mdImp).add(new Pair(fc,fm.getMethod())); - - if ((isPotentialStallSite && !isPotentialStallSite(fmImp)) || !visited.contains(fmImp)) { - flatNodesToVisit.put(fmImp, fmImp); - - // propagate your IR graph predecessor's stall site potential - mergeIsPotentialStallSite(fmImp, isPotentialStallSite); - } - - } - // don't 'continue' out of this loop, also enqueue - // flat nodes that flow in the current method context - } - - if (fn instanceof FlatReturnNode) { - // if return node is potential stall site, need to inform its caller - if (isPotentialStallSite) { - Set> callset = methodmap.get(fm.getMethod()); - if (callset != null) { - for (Pair fcallpair : callset) { - FlatCall fcall = fcallpair.getFirst(); - MethodDescriptor mdcaller = fcallpair.getSecond(); - for (int i = 0; i < fcall.numNext(); i++) { - FlatNode nn = fcall.getNext(i); - if ( visited.contains(nn) && (!isPotentialStallSite(nn)) ) { - mergeIsPotentialStallSite(nn, isPotentialStallSite); - FlatMethod fmcaller = state.getMethodFlat(mdcaller); - flatNodesToVisit.put(nn, fmcaller); - } - } - } - } - } - } - - // note: only when current flat node has a change on the status of potential - // stall site, need to visit following flat nodes - for (int i = 0; i < fn.numNext(); i++) { - FlatNode nn = fn.getNext(i); - if ((isPotentialStallSite && !isPotentialStallSite(nn)) || !visited.contains(nn)) { - flatNodesToVisit.put(nn, fm); - mergeIsPotentialStallSite(nn, isPotentialStallSite); - } - } + Map.Entry me = (Map.Entry)flatNodesToVisit.entrySet().iterator().next(); + FlatNode fn = (FlatNode) me.getKey(); + FlatMethod fm = (FlatMethod) me.getValue(); + + flatNodesToVisit.remove(fn); + visited.add(fn); + + // the "is potential stall site" strategy is to propagate + // "false" from the beginning of a task until you hit a + // child, then from the child's exit propagate "true" for + // the parent statements after children. When you pull a node + // out of the bag for traversal and it happens to be an + // enter or an exit node, fix the dumb propagation that + // your IR predecessor pushed on you + Boolean isPotentialStallSite = isPotentialStallSite(fn); + + if (fn == fsen.getFlatExit()) { + // don't enqueue any further nodes when you find your exit, + // NOR mark your own flat as a statement you are currently + // executing, your parent(s) will mark it + continue; + } + + if (fn instanceof FlatSESEExitNode) { + setIsPotentialStallSite(fn, false); + isPotentialStallSite = true; + } + + // the purpose of this traversal is to find program + // points where rblock 'fsen' might be executing + addPossibleExecutingRBlock(fn, fsen); + + if (fn instanceof FlatSESEEnterNode) { + // don't visit internal nodes of child, + // just enqueue the exit node + FlatSESEEnterNode child = (FlatSESEEnterNode) fn; + assert fsen.getChildren().contains(child); + assert child.getParents().contains(fsen); + flatNodesToVisit.put(child.getFlatExit(), fm); + setIsPotentialStallSite(fn, false); + + // explicitly do this to handle the case that you + // should mark yourself as possibly executing at + // your own exit, because one instance can + // recursively invoke another + addPossibleExecutingRBlock(child.getFlatExit(), fsen); + + continue; + } + + // if previous flat nodes have any changes,, + // propagate predecessor's status of stall site potential + + if (fn instanceof FlatCall) { + + // start visiting nodes in other contexts + FlatCall fc = (FlatCall) fn; + MethodDescriptor mdCallee = fc.getMethod(); + + Set implementations = new HashSet(); + + if (mdCallee.isStatic()) { + implementations.add(mdCallee); + } else { + TypeDescriptor typeDesc = fc.getThis().getType(); + implementations.addAll(callGraph.getMethods(mdCallee, typeDesc)); + } + + for (Iterator imps = implementations.iterator(); imps.hasNext(); ) { + MethodDescriptor mdImp = (MethodDescriptor) imps.next(); + FlatMethod fmImp = state.getMethodFlat(mdImp); + + // keep mapping from fc's md to + // later, when return node of callee becomes a potential stall site, + // following flat nodes of fc should be re-analyzied + if(!methodmap.containsKey(fmImp)) { + methodmap.put(mdImp, new HashSet>()); + } + methodmap.get(mdImp).add(new Pair(fc,fm.getMethod())); + + if ((isPotentialStallSite && !isPotentialStallSite(fmImp)) || !visited.contains(fmImp)) { + flatNodesToVisit.put(fmImp, fmImp); + + // propagate your IR graph predecessor's stall site potential + mergeIsPotentialStallSite(fmImp, isPotentialStallSite); + } + + } + // don't 'continue' out of this loop, also enqueue + // flat nodes that flow in the current method context + } + + if (fn instanceof FlatReturnNode) { + // if return node is potential stall site, need to inform its caller + if (isPotentialStallSite) { + Set> callset = methodmap.get(fm.getMethod()); + if (callset != null) { + for (Pair fcallpair : callset) { + FlatCall fcall = fcallpair.getFirst(); + MethodDescriptor mdcaller = fcallpair.getSecond(); + for (int i = 0; i < fcall.numNext(); i++) { + FlatNode nn = fcall.getNext(i); + if ( visited.contains(nn) && (!isPotentialStallSite(nn)) ) { + mergeIsPotentialStallSite(nn, isPotentialStallSite); + FlatMethod fmcaller = state.getMethodFlat(mdcaller); + flatNodesToVisit.put(nn, fmcaller); + } + } + } + } + } + } + + // note: only when current flat node has a change on the status of potential + // stall site, need to visit following flat nodes + for (int i = 0; i < fn.numNext(); i++) { + FlatNode nn = fn.getNext(i); + if ((isPotentialStallSite && !isPotentialStallSite(nn)) || !visited.contains(nn)) { + flatNodesToVisit.put(nn, fm); + mergeIsPotentialStallSite(nn, isPotentialStallSite); + } + } } } } @@ -657,11 +657,11 @@ public class RBlockRelationAnalysis { System.out.println(fn+"[["+isPotentialStallSite(fn)+"]]"); for (int i = 0; i < fn.numNext(); i++) { - FlatNode nn = fn.getNext(i); + FlatNode nn = fn.getNext(i); - if (!visited.contains(nn)) { - flatNodesToVisit.add(nn); - } + if (!visited.contains(nn)) { + flatNodesToVisit.add(nn); + } } } } diff --git a/Robust/src/Analysis/OoOJava/SESELock.java b/Robust/src/Analysis/OoOJava/SESELock.java index d36eeec8..8e3fd6aa 100644 --- a/Robust/src/Analysis/OoOJava/SESELock.java +++ b/Robust/src/Analysis/OoOJava/SESELock.java @@ -58,7 +58,7 @@ public class SESELock { ConflictEdge conflictEdge = (ConflictEdge) iterator.next(); if (conflictEdge.isCoarseEdge() && conflictEdge.getVertexU() == conflictEdge.getVertexV()) { - return true; + return true; } } return false; @@ -71,7 +71,7 @@ public class SESELock { ConflictEdge conflictEdge = (ConflictEdge) iterator.next(); if ((!conflictEdge.isCoarseEdge()) && conflictEdge.getVertexU() == conflictEdge.getVertexV()) { - return true; + return true; } } return false; @@ -85,13 +85,13 @@ public class SESELock { ConflictNode cNode; if (conflictEdge.getVertexU() == node) { - cNode = conflictEdge.getVertexV(); + cNode = conflictEdge.getVertexV(); } else { - cNode = conflictEdge.getVertexU(); + cNode = conflictEdge.getVertexU(); } Integer cNodeTypeIn = nodeTypeMap.get(cNode); if (cNodeTypeIn != null && cNodeTypeIn.intValue() == ConflictNode.PARENT_COARSE) { - return true; + return true; } } return false; @@ -118,10 +118,10 @@ public class SESELock { ConflictEdge conflictEdge = (ConflictEdge) iterator.next(); if (!conflictEdge.getVertexU().equals(newNode) && conflictNodeSet.contains(conflictEdge.getVertexU())) { - count++; + count++; } else if (!conflictEdge.getVertexV().equals(newNode) && conflictNodeSet.contains(conflictEdge.getVertexV())) { - count++; + count++; } } @@ -131,21 +131,21 @@ public class SESELock { if(isWriteNode(newNode)) { if (count == conflictNodeSet.size()) { - // connected to all current nodes in group - return newNode; + // connected to all current nodes in group + return newNode; } } else { // it is read node int writeNodeCount=0; for (Iterator iterator = conflictNodeSet.iterator(); iterator.hasNext(); ) { - ConflictNode node = (ConflictNode) iterator.next(); - if(isWriteNode(node)) { - writeNodeCount++; - } + ConflictNode node = (ConflictNode) iterator.next(); + if(isWriteNode(node)) { + writeNodeCount++; + } } if (count == writeNodeCount) { - // connected to all current write nodes in group - return newNode; + // connected to all current write nodes in group + return newNode; } } @@ -180,16 +180,16 @@ public class SESELock { } ConflictNode nodeToAdd = conflictNodeSet.contains(newEdge.getVertexU())?newEdge.getVertexV() - :newEdge.getVertexU(); + :newEdge.getVertexU(); HashSet nodeSet = new HashSet(conflictNodeSet); for (Iterator edgeIter = nodeToAdd.getEdgeSet().iterator(); edgeIter.hasNext(); ) { ConflictEdge edge = (ConflictEdge) edgeIter.next(); if (nodeSet.contains(edge.getVertexU())) { - nodeSet.remove(edge.getVertexU()); + nodeSet.remove(edge.getVertexU()); } else if (nodeSet.contains(edge.getVertexV())) { - nodeSet.remove(edge.getVertexV()); + nodeSet.remove(edge.getVertexV()); } } diff --git a/Robust/src/Analysis/OoOJava/SESEWaitingQueue.java b/Robust/src/Analysis/OoOJava/SESEWaitingQueue.java index 1bf0795f..7fa001ed 100644 --- a/Robust/src/Analysis/OoOJava/SESEWaitingQueue.java +++ b/Robust/src/Analysis/OoOJava/SESEWaitingQueue.java @@ -39,7 +39,7 @@ public class SESEWaitingQueue { WaitingElement we=wit.next(); TempDescriptor tmp=we.getTempDesc(); if (!tmp2WaitingElement.containsKey(tmp)) - tmp2WaitingElement.put(tmp, new HashSet()); + tmp2WaitingElement.put(tmp, new HashSet()); tmp2WaitingElement.get(tmp).add(we); } } diff --git a/Robust/src/Analysis/OoOJava/VarSrcTokTable.java b/Robust/src/Analysis/OoOJava/VarSrcTokTable.java index c4220c95..e977db08 100644 --- a/Robust/src/Analysis/OoOJava/VarSrcTokTable.java +++ b/Robust/src/Analysis/OoOJava/VarSrcTokTable.java @@ -73,11 +73,11 @@ public class VarSrcTokTable { VariableSourceToken vstAlready = trueSet.get(vst); if (vstAlready!=null) { - removePrivate(vstAlready); - HashSet toAddSet=new HashSet(); - toAddSet.addAll(vstAlready.getRefVars()); - toAddSet.addAll(vst.getRefVars()); - vst.setRefVars(toAddSet); + removePrivate(vstAlready); + HashSet toAddSet=new HashSet(); + toAddSet.addAll(vstAlready.getRefVars()); + toAddSet.addAll(vst.getRefVars()); + vst.setRefVars(toAddSet); } } @@ -95,16 +95,16 @@ public class VarSrcTokTable { TempDescriptor refVar = refVarItr.next(); s = var2vst.get(refVar); if( s == null ) { - s = new HashSet(); - var2vst.put(refVar, s); + s = new HashSet(); + var2vst.put(refVar, s); } s.add(vst); SVKey key = new SVKey(vst.getSESE(), refVar); s = sv2vst.get(key); if( s == null ) { - s = new HashSet(); - sv2vst.put(key, s); + s = new HashSet(); + sv2vst.put(key, s); } s.add(vst); } @@ -166,7 +166,7 @@ public class VarSrcTokTable { while( sItr.hasNext() ) { VariableSourceToken vst = sItr.next(); if( !vst.getAge().equals(age) ) { - s.remove(vst); + s.remove(vst); } } @@ -216,18 +216,18 @@ public class VarSrcTokTable { s = get(refVar); if( s != null ) { - s.remove(vst); - if( s.isEmpty() ) { - var2vst.remove(refVar); - } + s.remove(vst); + if( s.isEmpty() ) { + var2vst.remove(refVar); + } } s = get(vst.getSESE(), refVar); if( s != null ) { - s.remove(vst); - if( s.isEmpty() ) { - sv2vst.remove(new SVKey(vst.getSESE(), refVar) ); - } + s.remove(vst); + if( s.isEmpty() ) { + sv2vst.remove(new SVKey(vst.getSESE(), refVar) ); + } } } } @@ -288,7 +288,7 @@ public class VarSrcTokTable { // referencing this token, just take it // out of the table all together if( refVars.size() == 1 ) { - removePrivate(vst); + removePrivate(vst); } sv2vst.remove(new SVKey(vst.getSESE(), refVar) ); @@ -329,18 +329,18 @@ public class VarSrcTokTable { if( vst.getSESE().equals(curr) ) { - // only age if the token isn't already the maximum age - if( vst.getAge() < MAX_AGE ) { + // only age if the token isn't already the maximum age + if( vst.getAge() < MAX_AGE ) { - forRemoval.add(vst); + forRemoval.add(vst); - forAddition.add(new VariableSourceToken(vst.getRefVars(), - curr, - vst.getAge() + 1, - vst.getAddrVar() - ) - ); - } + forAddition.add(new VariableSourceToken(vst.getRefVars(), + curr, + vst.getAge() + 1, + vst.getAddrVar() + ) + ); + } } } @@ -397,28 +397,28 @@ public class VarSrcTokTable { Iterator vstItr = get(child).iterator(); while( vstItr.hasNext() ) { - VariableSourceToken vst = vstItr.next(); - removalSet.add(vst); - - additionSet.add(new VariableSourceToken(vst.getRefVars(), - curr, - new Integer(0), - vst.getAddrVar() - ) - ); + VariableSourceToken vst = vstItr.next(); + removalSet.add(vst); + + additionSet.add(new VariableSourceToken(vst.getRefVars(), + curr, + new Integer(0), + vst.getAddrVar() + ) + ); } // remove( eah item in forremoval ) vstItr = removalSet.iterator(); while( vstItr.hasNext() ) { - VariableSourceToken vst = vstItr.next(); - remove(vst); + VariableSourceToken vst = vstItr.next(); + remove(vst); } // add( each ite inm for additon _ vstItr = additionSet.iterator(); while( vstItr.hasNext() ) { - VariableSourceToken vst = vstItr.next(); - add(vst); + VariableSourceToken vst = vstItr.next(); + add(vst); } } @@ -460,26 +460,26 @@ public class VarSrcTokTable { Iterator childItr; if( ancestor == null ) { - // when some caller task is the next parent, the siblings - // of the current task are other local root tasks - ancestor = rblockRel.getCallerProxySESE(); - childItr = rblockRel.getLocalRootSESEs(exiter.getfmEnclosing() ).iterator(); - findMore = false; + // when some caller task is the next parent, the siblings + // of the current task are other local root tasks + ancestor = rblockRel.getCallerProxySESE(); + childItr = rblockRel.getLocalRootSESEs(exiter.getfmEnclosing() ).iterator(); + findMore = false; } else { - // otherwise, the siblings are locally-defined - childItr = ancestor.getLocalChildren().iterator(); + // otherwise, the siblings are locally-defined + childItr = ancestor.getLocalChildren().iterator(); - // and there is no further ancestry beyond the main task - if( ancestor.equals(rblockRel.getMainSESE() ) ) { - findMore = false; - } + // and there is no further ancestry beyond the main task + if( ancestor.equals(rblockRel.getMainSESE() ) ) { + findMore = false; + } } // this ancestor and its children are valid alternate sources alternateSESEs.add(ancestor); while( childItr.hasNext() ) { - FlatSESEEnterNode sibling = childItr.next(); - alternateSESEs.add(sibling); + FlatSESEEnterNode sibling = childItr.next(); + alternateSESEs.add(sibling); } } @@ -495,48 +495,48 @@ public class VarSrcTokTable { // only interested in sources from our current instance if( vstExiterSrc.getAge() != 0 ) { - continue; + continue; } // for each variable that might come from those sources... Iterator refVarItr = vstExiterSrc.getRefVars().iterator(); while( refVarItr.hasNext() ) { - TempDescriptor refVar = refVarItr.next(); - - // only matters for live variables at SESE exit program point - if( !liveVars.contains(refVar) ) { - continue; - } - - // examine other sources for a variable... - Iterator srcItr = get(refVar).iterator(); - while( srcItr.hasNext() ) { - VariableSourceToken vstPossibleOtherSrc = srcItr.next(); - - if( vstPossibleOtherSrc.getSESE().equals(exiter) && - vstPossibleOtherSrc.getAge() > 0 - ) { - // this is an alternate source if its - // an older instance of this SESE - virtReadSet.add(refVar); - forRemoval.add(vstPossibleOtherSrc); - - } else if( alternateSESEs.contains(vstPossibleOtherSrc.getSESE() ) ) { - // this is an alternate source from ancestor or ancestor's sibling - virtReadSet.add(refVar); - forRemoval.add(vstPossibleOtherSrc); - - } else { - if( !(vstPossibleOtherSrc.getSESE().equals(exiter) && - vstPossibleOtherSrc.getAge().equals(0) - ) - ) { - System.out.println("For refVar="+refVar+" at exit of "+exiter+ - ", unexpected possible variable source "+vstPossibleOtherSrc); - assert false; - } - } - } + TempDescriptor refVar = refVarItr.next(); + + // only matters for live variables at SESE exit program point + if( !liveVars.contains(refVar) ) { + continue; + } + + // examine other sources for a variable... + Iterator srcItr = get(refVar).iterator(); + while( srcItr.hasNext() ) { + VariableSourceToken vstPossibleOtherSrc = srcItr.next(); + + if( vstPossibleOtherSrc.getSESE().equals(exiter) && + vstPossibleOtherSrc.getAge() > 0 + ) { + // this is an alternate source if its + // an older instance of this SESE + virtReadSet.add(refVar); + forRemoval.add(vstPossibleOtherSrc); + + } else if( alternateSESEs.contains(vstPossibleOtherSrc.getSESE() ) ) { + // this is an alternate source from ancestor or ancestor's sibling + virtReadSet.add(refVar); + forRemoval.add(vstPossibleOtherSrc); + + } else { + if( !(vstPossibleOtherSrc.getSESE().equals(exiter) && + vstPossibleOtherSrc.getAge().equals(0) + ) + ) { + System.out.println("For refVar="+refVar+" at exit of "+exiter+ + ", unexpected possible variable source "+vstPossibleOtherSrc); + assert false; + } + } + } } } @@ -572,21 +572,21 @@ public class VarSrcTokTable { // only worth tracking if live if( nextLiveIn.contains(var) ) { - VSTWrapper vstIfStaticBefore = new VSTWrapper(); - VSTWrapper vstIfStaticAfter = new VSTWrapper(); - - Integer srcTypeBefore = this.getRefVarSrcType(var, current, vstIfStaticBefore); - Integer srcTypeAfter = nextTable.getRefVarSrcType(var, current, vstIfStaticAfter); - - if( !srcTypeBefore.equals(SrcType_DYNAMIC) && - srcTypeAfter.equals(SrcType_DYNAMIC) - ) { - // remember the variable and a source - // it had before crossing the transition - // 1) if it was ready, vstIfStatic.vst is null - // 2) if is was static, use vstIfStatic.vst - out.put(var, vstIfStaticBefore); - } + VSTWrapper vstIfStaticBefore = new VSTWrapper(); + VSTWrapper vstIfStaticAfter = new VSTWrapper(); + + Integer srcTypeBefore = this.getRefVarSrcType(var, current, vstIfStaticBefore); + Integer srcTypeAfter = nextTable.getRefVarSrcType(var, current, vstIfStaticAfter); + + if( !srcTypeBefore.equals(SrcType_DYNAMIC) && + srcTypeAfter.equals(SrcType_DYNAMIC) + ) { + // remember the variable and a source + // it had before crossing the transition + // 1) if it was ready, vstIfStatic.vst is null + // 2) if is was static, use vstIfStatic.vst + out.put(var, vstIfStaticBefore); + } } } @@ -639,21 +639,21 @@ public class VarSrcTokTable { if( case1 || case2 ) { - // if we ever have at least one child source with an - // unknown age, have to treat var as dynamic - if( vst.getAge().equals(OoOJavaAnalysis.maxSESEage) ) { - return SrcType_DYNAMIC; - } - - // if we have a known-age child source, this var is - // either static or dynamic now: it's static if this - // source is the only source, otherwise dynamic - if( srcs.size() > 1 ) { - return SrcType_DYNAMIC; - } - - vstIfStatic.vst = vst; - return SrcType_STATIC; + // if we ever have at least one child source with an + // unknown age, have to treat var as dynamic + if( vst.getAge().equals(OoOJavaAnalysis.maxSESEage) ) { + return SrcType_DYNAMIC; + } + + // if we have a known-age child source, this var is + // either static or dynamic now: it's static if this + // source is the only source, otherwise dynamic + if( srcs.size() > 1 ) { + return SrcType_DYNAMIC; + } + + vstIfStatic.vst = vst; + return SrcType_STATIC; } } @@ -876,7 +876,7 @@ public class VarSrcTokTable { vstItr = s1.iterator(); while( vstItr.hasNext() ) { - str += " "+tokHighlighter+" "+vstItr.next()+"\n"; + str += " "+tokHighlighter+" "+vstItr.next()+"\n"; } } @@ -892,7 +892,7 @@ public class VarSrcTokTable { vstItr = s1.iterator(); while( vstItr.hasNext() ) { - str += " "+tokHighlighter+" "+vstItr.next()+"\n"; + str += " "+tokHighlighter+" "+vstItr.next()+"\n"; } } @@ -908,7 +908,7 @@ public class VarSrcTokTable { vstItr = s1.iterator(); while( vstItr.hasNext() ) { - str += " "+tokHighlighter+" "+vstItr.next()+"\n"; + str += " "+tokHighlighter+" "+vstItr.next()+"\n"; } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/AllocationSite.java b/Robust/src/Analysis/OwnershipAnalysis/AllocationSite.java index e08df8bc..08930fdb 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/AllocationSite.java +++ b/Robust/src/Analysis/OwnershipAnalysis/AllocationSite.java @@ -132,7 +132,7 @@ public class AllocationSite { for( int i = 0; i < allocationDepth - 1; ++i ) { if( id.equals(ithOldest.get(i) ) ) { - return AGE_in_I; + return AGE_in_I; } } @@ -142,7 +142,7 @@ public class AllocationSite { public Integer getAge(Integer id) { for( int i = 0; i < allocationDepth - 1; ++i ) { if( id.equals(ithOldest.get(i) ) ) { - return new Integer(i); + return new Integer(i); } } @@ -160,7 +160,7 @@ public class AllocationSite { for( int i = 0; i < allocationDepth - 1; ++i ) { if( id.equals(getIthOldestShadow(i) ) ) { - return SHADOWAGE_in_I; + return SHADOWAGE_in_I; } } @@ -170,7 +170,7 @@ public class AllocationSite { public Integer getShadowAge(Integer id) { for( int i = 0; i < allocationDepth - 1; ++i ) { if( id.equals(getIthOldestShadow(i) ) ) { - return new Integer(-i); + return new Integer(-i); } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/ChangeTuple.java b/Robust/src/Analysis/OwnershipAnalysis/ChangeTuple.java index 3b107fa0..1617850b 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/ChangeTuple.java +++ b/Robust/src/Analysis/OwnershipAnalysis/ChangeTuple.java @@ -60,9 +60,9 @@ public class ChangeTuple extends Canonical oldHashSet = true; } else { if( oldHash != currentHash ) { - System.out.println("IF YOU SEE THIS A CANONICAL ChangeTuple CHANGED"); - Integer x = null; - x.toString(); + System.out.println("IF YOU SEE THIS A CANONICAL ChangeTuple CHANGED"); + Integer x = null; + x.toString(); } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/ChangeTupleSet.java b/Robust/src/Analysis/OwnershipAnalysis/ChangeTupleSet.java index 15b28751..12c03b30 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/ChangeTupleSet.java +++ b/Robust/src/Analysis/OwnershipAnalysis/ChangeTupleSet.java @@ -84,9 +84,9 @@ public class ChangeTupleSet extends Canonical { oldHashSet = true; } else { if( oldHash != currentHash ) { - System.out.println("IF YOU SEE THIS A CANONICAL ChangeTupleSet CHANGED"); - Integer x = null; - x.toString(); + System.out.println("IF YOU SEE THIS A CANONICAL ChangeTupleSet CHANGED"); + Integer x = null; + x.toString(); } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/EffectsSet.java b/Robust/src/Analysis/OwnershipAnalysis/EffectsSet.java index 20ec8c8c..aafb9c47 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/EffectsSet.java +++ b/Robust/src/Analysis/OwnershipAnalysis/EffectsSet.java @@ -32,7 +32,7 @@ public class EffectsSet { if (newSet != null) { HashSet aSet = readTable.get(idx); if (aSet == null) { - aSet = new HashSet(); + aSet = new HashSet(); } aSet.addAll(newSet); readTable.put(idx, aSet); @@ -45,7 +45,7 @@ public class EffectsSet { if (newSet != null) { HashSet aSet = writeTable.get(idx); if (aSet == null) { - aSet = new HashSet(); + aSet = new HashSet(); } aSet.addAll(newSet); writeTable.put(idx, aSet); @@ -58,7 +58,7 @@ public class EffectsSet { if (newSet != null) { HashSet aSet = strongUpdateTable.get(idx); if (aSet == null) { - aSet = new HashSet(); + aSet = new HashSet(); } aSet.addAll(newSet); strongUpdateTable.put(idx, aSet); @@ -119,13 +119,13 @@ public class EffectsSet { Set effectSet = readTable.get(idx); String keyStr = "{"; if (effectSet != null) { - Iterator effectIter = effectSet.iterator(); - while (effectIter.hasNext()) { - EffectsKey key = effectIter.next(); - keyStr += " " + key; - } + Iterator effectIter = effectSet.iterator(); + while (effectIter.hasNext()) { + EffectsKey key = effectIter.next(); + keyStr += " " + key; + } } else { - keyStr = "null"; + keyStr = "null"; } System.out.println("param" + idx + " R=" + keyStr); } @@ -138,13 +138,13 @@ public class EffectsSet { Set effectSet = writeTable.get(idx); String keyStr = "{"; if (effectSet != null) { - Iterator effectIter = effectSet.iterator(); - while (effectIter.hasNext()) { - EffectsKey key = effectIter.next(); - keyStr += " " + key; - } + Iterator effectIter = effectSet.iterator(); + while (effectIter.hasNext()) { + EffectsKey key = effectIter.next(); + keyStr += " " + key; + } } else { - keyStr = "null"; + keyStr = "null"; } System.out.println("param" + idx + " W=" + keyStr); } diff --git a/Robust/src/Analysis/OwnershipAnalysis/HeapRegionNode.java b/Robust/src/Analysis/OwnershipAnalysis/HeapRegionNode.java index cbc12465..95be7fda 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/HeapRegionNode.java +++ b/Robust/src/Analysis/OwnershipAnalysis/HeapRegionNode.java @@ -162,7 +162,7 @@ public class HeapRegionNode extends OwnershipNode { if( edge.getSrc().equals(on) && edge.typeEquals(type) && edge.fieldEquals(field) ) { - return edge; + return edge; } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/MethodContext.java b/Robust/src/Analysis/OwnershipAnalysis/MethodContext.java index e50fa5b1..1efb30a0 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/MethodContext.java +++ b/Robust/src/Analysis/OwnershipAnalysis/MethodContext.java @@ -62,7 +62,7 @@ public class MethodContext { while( i.hasNext() ) { s += i.next(); if( i.hasNext() ) { - s += "a"; + s += "a"; } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/MethodEffects.java b/Robust/src/Analysis/OwnershipAnalysis/MethodEffects.java index 6d1cdc18..e1006104 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/MethodEffects.java +++ b/Robust/src/Analysis/OwnershipAnalysis/MethodEffects.java @@ -28,39 +28,39 @@ public class MethodEffects { Iterator heapRegionsItr = ln.iteratorToReferencees(); while (heapRegionsItr.hasNext()) { - ReferenceEdge edge = heapRegionsItr.next(); - HeapRegionNode hrn = edge.getDst(); + ReferenceEdge edge = heapRegionsItr.next(); + HeapRegionNode hrn = edge.getDst(); - if (hrn.isParameter()) { - Set paramSet = og.idPrimary2paramIndexSet.get(hrn - .getID()); + if (hrn.isParameter()) { + Set paramSet = og.idPrimary2paramIndexSet.get(hrn + .getID()); - if (paramSet != null) { - Iterator paramIter = paramSet.iterator(); - while (paramIter.hasNext()) { - Integer paramID = paramIter.next(); - effectsSet.addReadingVar(paramID, new EffectsKey( - fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0)); + if (paramSet != null) { + Iterator paramIter = paramSet.iterator(); + while (paramIter.hasNext()) { + Integer paramID = paramIter.next(); + effectsSet.addReadingVar(paramID, new EffectsKey( + fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0)); - } - } + } + } - // check weather this heap region is parameter - // reachable... + // check weather this heap region is parameter + // reachable... - paramSet = og.idSecondary2paramIndexSet.get(hrn.getID()); - if (paramSet != null) { - Iterator paramIter = paramSet.iterator(); + paramSet = og.idSecondary2paramIndexSet.get(hrn.getID()); + if (paramSet != null) { + Iterator paramIter = paramSet.iterator(); - while (paramIter.hasNext()) { - Integer paramID = paramIter.next(); - effectsSet.addReadingVar(paramID, new EffectsKey( - fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1)); + while (paramIter.hasNext()) { + Integer paramID = paramIter.next(); + effectsSet.addReadingVar(paramID, new EffectsKey( + fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1)); - } - } + } + } - } + } } } @@ -74,37 +74,37 @@ public class MethodEffects { Iterator heapRegionsItr = ln.iteratorToReferencees(); while (heapRegionsItr.hasNext()) { - ReferenceEdge edge = heapRegionsItr.next(); - HeapRegionNode hrn = edge.getDst(); - - if (hrn.isParameter()) { - Set paramSet = og.idPrimary2paramIndexSet.get(hrn - .getID()); - - if (paramSet != null) { - Iterator paramIter = paramSet.iterator(); - while (paramIter.hasNext()) { - Integer paramID = paramIter.next(); - effectsSet.addReadingVar(paramID, new EffectsKey( - fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0)); - } - } - - // check weather this heap region is parameter - // reachable... - - paramSet = og.idSecondary2paramIndexSet.get(hrn.getID()); - if (paramSet != null) { - Iterator paramIter = paramSet.iterator(); - - while (paramIter.hasNext()) { - Integer paramID = paramIter.next(); - effectsSet.addReadingVar(paramID, new EffectsKey( - fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1)); - } - } - - } + ReferenceEdge edge = heapRegionsItr.next(); + HeapRegionNode hrn = edge.getDst(); + + if (hrn.isParameter()) { + Set paramSet = og.idPrimary2paramIndexSet.get(hrn + .getID()); + + if (paramSet != null) { + Iterator paramIter = paramSet.iterator(); + while (paramIter.hasNext()) { + Integer paramID = paramIter.next(); + effectsSet.addReadingVar(paramID, new EffectsKey( + fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0)); + } + } + + // check weather this heap region is parameter + // reachable... + + paramSet = og.idSecondary2paramIndexSet.get(hrn.getID()); + if (paramSet != null) { + Iterator paramIter = paramSet.iterator(); + + while (paramIter.hasNext()) { + Integer paramID = paramIter.next(); + effectsSet.addReadingVar(paramID, new EffectsKey( + fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1)); + } + } + + } } } @@ -123,69 +123,69 @@ public class MethodEffects { boolean strongUpdate = false; if (!fieldDesc.getType().isImmutable() || fieldDesc.getType().isArray()) { - Iterator itrXhrn = ln.iteratorToReferencees(); - while (itrXhrn.hasNext()) { - ReferenceEdge edgeX = itrXhrn.next(); - HeapRegionNode hrnX = edgeX.getDst(); - - if (fieldDesc != null - && fieldDesc != OwnershipAnalysis - .getArrayField(fieldDesc.getType()) - && ((hrnX.getNumReferencers() == 1) || // case 1 - (hrnX.isSingleObject() && ln.getNumReferencees() == 1) // case - // 2 - )) { - strongUpdate = true; - } - } + Iterator itrXhrn = ln.iteratorToReferencees(); + while (itrXhrn.hasNext()) { + ReferenceEdge edgeX = itrXhrn.next(); + HeapRegionNode hrnX = edgeX.getDst(); + + if (fieldDesc != null + && fieldDesc != OwnershipAnalysis + .getArrayField(fieldDesc.getType()) + && ((hrnX.getNumReferencers() == 1) || // case 1 + (hrnX.isSingleObject() && ln.getNumReferencees() == 1) // case + // 2 + )) { + strongUpdate = true; + } + } } // // Iterator heapRegionsItr = ln.iteratorToReferencees(); while (heapRegionsItr.hasNext()) { - ReferenceEdge edge = heapRegionsItr.next(); - HeapRegionNode hrn = edge.getDst(); - - if (hrn.isParameter()) { - Set paramSet = og.idPrimary2paramIndexSet.get(hrn - .getID()); - - if (paramSet != null) { - Iterator paramIter = paramSet.iterator(); - while (paramIter.hasNext()) { - Integer paramID = paramIter.next(); - effectsSet.addWritingVar(paramID, new EffectsKey( - fieldDesc.getSymbol(), dstDesc.getType(), - hrn.getID(), hrn - .getGloballyUniqueIdentifier(), 0)); - if(strongUpdate) { - effectsSet.addStrongUpdateVar(paramID, new EffectsKey( - fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0)); - } - } - } - - // check weather this heap region is parameter - // reachable... - - paramSet = og.idSecondary2paramIndexSet.get(hrn.getID()); - if (paramSet != null) { - Iterator paramIter = paramSet.iterator(); - - while (paramIter.hasNext()) { - Integer paramID = paramIter.next(); - effectsSet.addWritingVar(paramID, new EffectsKey( - fieldDesc.getSymbol(), dstDesc.getType(), - hrn.getID(), hrn - .getGloballyUniqueIdentifier(), 1)); - if(strongUpdate) { - effectsSet.addStrongUpdateVar(paramID, new EffectsKey( - fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0)); - } - } - } - - } + ReferenceEdge edge = heapRegionsItr.next(); + HeapRegionNode hrn = edge.getDst(); + + if (hrn.isParameter()) { + Set paramSet = og.idPrimary2paramIndexSet.get(hrn + .getID()); + + if (paramSet != null) { + Iterator paramIter = paramSet.iterator(); + while (paramIter.hasNext()) { + Integer paramID = paramIter.next(); + effectsSet.addWritingVar(paramID, new EffectsKey( + fieldDesc.getSymbol(), dstDesc.getType(), + hrn.getID(), hrn + .getGloballyUniqueIdentifier(), 0)); + if(strongUpdate) { + effectsSet.addStrongUpdateVar(paramID, new EffectsKey( + fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0)); + } + } + } + + // check weather this heap region is parameter + // reachable... + + paramSet = og.idSecondary2paramIndexSet.get(hrn.getID()); + if (paramSet != null) { + Iterator paramIter = paramSet.iterator(); + + while (paramIter.hasNext()) { + Integer paramID = paramIter.next(); + effectsSet.addWritingVar(paramID, new EffectsKey( + fieldDesc.getSymbol(), dstDesc.getType(), + hrn.getID(), hrn + .getGloballyUniqueIdentifier(), 1)); + if(strongUpdate) { + effectsSet.addStrongUpdateVar(paramID, new EffectsKey( + fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0)); + } + } + } + + } } } @@ -200,68 +200,68 @@ public class MethodEffects { /// check possible strong updates boolean strongUpdate = false; if( !fieldDesc.getType().isImmutable() || fieldDesc.getType().isArray() ) { - Iterator itrXhrn = ln.iteratorToReferencees(); - while( itrXhrn.hasNext() ) { - ReferenceEdge edgeX = itrXhrn.next(); - HeapRegionNode hrnX = edgeX.getDst(); - - if( fieldDesc != null && - fieldDesc != OwnershipAnalysis.getArrayField(fieldDesc.getType() ) && - ( (hrnX.getNumReferencers() == 1) || // case 1 - (hrnX.isSingleObject() && ln.getNumReferencees() == 1) // case 2 - ) - ) { - strongUpdate = true; - } - } + Iterator itrXhrn = ln.iteratorToReferencees(); + while( itrXhrn.hasNext() ) { + ReferenceEdge edgeX = itrXhrn.next(); + HeapRegionNode hrnX = edgeX.getDst(); + + if( fieldDesc != null && + fieldDesc != OwnershipAnalysis.getArrayField(fieldDesc.getType() ) && + ( (hrnX.getNumReferencers() == 1) || // case 1 + (hrnX.isSingleObject() && ln.getNumReferencees() == 1) // case 2 + ) + ) { + strongUpdate = true; + } + } } //// Iterator heapRegionsItr = ln.iteratorToReferencees(); while (heapRegionsItr.hasNext()) { - ReferenceEdge edge = heapRegionsItr.next(); - HeapRegionNode hrn = edge.getDst(); - - if (hrn.isParameter()) { - - Set paramSet = og.idPrimary2paramIndexSet.get(hrn - .getID()); - - if (paramSet != null) { - Iterator paramIter = paramSet.iterator(); - while (paramIter.hasNext()) { - Integer paramID = paramIter.next(); - effectsSet.addWritingVar(paramID, new EffectsKey( - fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0)); - if(strongUpdate) { - effectsSet.addStrongUpdateVar(paramID, new EffectsKey( - fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0)); - } - - } - } - - // check weather this heap region is parameter - // reachable... - - paramSet = og.idSecondary2paramIndexSet.get(hrn.getID()); - if (paramSet != null) { - Iterator paramIter = paramSet.iterator(); - - while (paramIter.hasNext()) { - Integer paramID = paramIter.next(); - effectsSet.addWritingVar(paramID, new EffectsKey( - fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1)); - if(strongUpdate) { - effectsSet.addStrongUpdateVar(paramID, new EffectsKey( - fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1)); - } - - } - } - - } + ReferenceEdge edge = heapRegionsItr.next(); + HeapRegionNode hrn = edge.getDst(); + + if (hrn.isParameter()) { + + Set paramSet = og.idPrimary2paramIndexSet.get(hrn + .getID()); + + if (paramSet != null) { + Iterator paramIter = paramSet.iterator(); + while (paramIter.hasNext()) { + Integer paramID = paramIter.next(); + effectsSet.addWritingVar(paramID, new EffectsKey( + fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0)); + if(strongUpdate) { + effectsSet.addStrongUpdateVar(paramID, new EffectsKey( + fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0)); + } + + } + } + + // check weather this heap region is parameter + // reachable... + + paramSet = og.idSecondary2paramIndexSet.get(hrn.getID()); + if (paramSet != null) { + Iterator paramIter = paramSet.iterator(); + + while (paramIter.hasNext()) { + Integer paramID = paramIter.next(); + effectsSet.addWritingVar(paramID, new EffectsKey( + fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1)); + if(strongUpdate) { + effectsSet.addStrongUpdateVar(paramID, new EffectsKey( + fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1)); + } + + } + } + + } } } @@ -278,40 +278,40 @@ public class MethodEffects { Iterator heapRegionsItr = ln.iteratorToReferencees(); while (heapRegionsItr.hasNext()) { - ReferenceEdge edge = heapRegionsItr.next(); - HeapRegionNode hrn = edge.getDst(); + ReferenceEdge edge = heapRegionsItr.next(); + HeapRegionNode hrn = edge.getDst(); - if (hrn.isParameter()) { + if (hrn.isParameter()) { - Set paramSet = og.idPrimary2paramIndexSet.get(hrn - .getID()); + Set paramSet = og.idPrimary2paramIndexSet.get(hrn + .getID()); - if (paramSet != null) { - Iterator paramIter = paramSet.iterator(); - while (paramIter.hasNext()) { - Integer paramID = paramIter.next(); + if (paramSet != null) { + Iterator paramIter = paramSet.iterator(); + while (paramIter.hasNext()) { + Integer paramID = paramIter.next(); - resultSet.add(paramID); + resultSet.add(paramID); - } - } + } + } - // check weather this heap region is parameter - // reachable... + // check weather this heap region is parameter + // reachable... - paramSet = og.idSecondary2paramIndexSet.get(hrn.getID()); - if (paramSet != null) { - Iterator paramIter = paramSet.iterator(); + paramSet = og.idSecondary2paramIndexSet.get(hrn.getID()); + if (paramSet != null) { + Iterator paramIter = paramSet.iterator(); - while (paramIter.hasNext()) { - Integer paramID = paramIter.next(); + while (paramIter.hasNext()) { + Integer paramID = paramIter.next(); - resultSet.add(paramID); + resultSet.add(paramID); - } - } + } + } - } + } } } @@ -333,122 +333,122 @@ public class MethodEffects { // handle read effects Iterator paramIter = paramIDs.iterator(); while (paramIter.hasNext()) { - Integer paramIdx = paramIter.next(); - HashSet newSet = callee.getEffects().getReadTable() - .get(calleeParamIdx); - - - if(newSet!=null) { - HashSet thisSet=new HashSet(); - HeapRegionNode priHRN=og.id2hrn.get(og.paramIndex2idPrimary.get(paramIdx)); - Integer secIdx=og.paramIndex2idSecondary.get(paramIdx); - HeapRegionNode secHRN=null; - if(secIdx!=null) { - secHRN=og.id2hrn.get(secIdx); - } else { - secHRN=priHRN; - } - - for (Iterator iterator = newSet.iterator(); iterator.hasNext(); ) { - EffectsKey effectsKey = (EffectsKey) iterator.next(); - HeapRegionNode hrnTemp; - if(effectsKey.getParamIden()==0) { //primary - hrnTemp=priHRN; - } else { //secondary - hrnTemp=secHRN; - } - EffectsKey newEffectsKey; - if(secIdx==null) { - newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),0); - } else { - newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),effectsKey.getParamIden()); - } - thisSet.add(newEffectsKey); - } - - effectsSet.addReadingEffectsSet(paramIdx, thisSet); - } + Integer paramIdx = paramIter.next(); + HashSet newSet = callee.getEffects().getReadTable() + .get(calleeParamIdx); + + + if(newSet!=null) { + HashSet thisSet=new HashSet(); + HeapRegionNode priHRN=og.id2hrn.get(og.paramIndex2idPrimary.get(paramIdx)); + Integer secIdx=og.paramIndex2idSecondary.get(paramIdx); + HeapRegionNode secHRN=null; + if(secIdx!=null) { + secHRN=og.id2hrn.get(secIdx); + } else { + secHRN=priHRN; + } + + for (Iterator iterator = newSet.iterator(); iterator.hasNext(); ) { + EffectsKey effectsKey = (EffectsKey) iterator.next(); + HeapRegionNode hrnTemp; + if(effectsKey.getParamIden()==0) { //primary + hrnTemp=priHRN; + } else { //secondary + hrnTemp=secHRN; + } + EffectsKey newEffectsKey; + if(secIdx==null) { + newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),0); + } else { + newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),effectsKey.getParamIden()); + } + thisSet.add(newEffectsKey); + } + + effectsSet.addReadingEffectsSet(paramIdx, thisSet); + } } // handle write effects paramIter = paramIDs.iterator(); while (paramIter.hasNext()) { - Integer paramIdx = paramIter.next(); - HashSet newSet = callee.getEffects() - .getWriteTable().get(calleeParamIdx); - - if(newSet!=null) { - - HashSet thisSet=new HashSet(); - HeapRegionNode priHRN=og.id2hrn.get(og.paramIndex2idPrimary.get(paramIdx)); - Integer secIdx=og.paramIndex2idSecondary.get(paramIdx); - HeapRegionNode secHRN=null; - if(secIdx!=null) { - secHRN=og.id2hrn.get(secIdx); - } else { - secHRN=priHRN; - } - - for (Iterator iterator = newSet.iterator(); iterator.hasNext(); ) { - EffectsKey effectsKey = (EffectsKey) iterator.next(); - HeapRegionNode hrnTemp; - if(effectsKey.getParamIden()==0) { //primary - hrnTemp=priHRN; - } else { //secondary - hrnTemp=secHRN; - } - EffectsKey newEffectsKey; - if(secIdx==null) { - newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),0); - } else { - newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),effectsKey.getParamIden()); - } - thisSet.add(newEffectsKey); - } - - effectsSet.addWritingEffectsSet(paramIdx, thisSet); - } + Integer paramIdx = paramIter.next(); + HashSet newSet = callee.getEffects() + .getWriteTable().get(calleeParamIdx); + + if(newSet!=null) { + + HashSet thisSet=new HashSet(); + HeapRegionNode priHRN=og.id2hrn.get(og.paramIndex2idPrimary.get(paramIdx)); + Integer secIdx=og.paramIndex2idSecondary.get(paramIdx); + HeapRegionNode secHRN=null; + if(secIdx!=null) { + secHRN=og.id2hrn.get(secIdx); + } else { + secHRN=priHRN; + } + + for (Iterator iterator = newSet.iterator(); iterator.hasNext(); ) { + EffectsKey effectsKey = (EffectsKey) iterator.next(); + HeapRegionNode hrnTemp; + if(effectsKey.getParamIden()==0) { //primary + hrnTemp=priHRN; + } else { //secondary + hrnTemp=secHRN; + } + EffectsKey newEffectsKey; + if(secIdx==null) { + newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),0); + } else { + newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),effectsKey.getParamIden()); + } + thisSet.add(newEffectsKey); + } + + effectsSet.addWritingEffectsSet(paramIdx, thisSet); + } } // handle strong update effects paramIter = paramIDs.iterator(); while (paramIter.hasNext()) { - Integer paramIdx = paramIter.next(); - HashSet newSet = callee.getEffects() - .getStrongUpdateTable().get(calleeParamIdx); - if(newSet!=null) { - - HashSet thisSet=new HashSet(); - HeapRegionNode priHRN=og.id2hrn.get(og.paramIndex2idPrimary.get(paramIdx)); - Integer secIdx=og.paramIndex2idSecondary.get(paramIdx); - HeapRegionNode secHRN=null; - if(secIdx!=null) { - secHRN=og.id2hrn.get(secIdx); - } else { - secHRN=priHRN; - } - - for (Iterator iterator = newSet.iterator(); iterator.hasNext(); ) { - EffectsKey effectsKey = (EffectsKey) iterator.next(); - HeapRegionNode hrnTemp; - if(effectsKey.getParamIden()==0) { //primary - hrnTemp=priHRN; - } else { //secondary - hrnTemp=secHRN; - } - EffectsKey newEffectsKey; - if(secIdx==null) { - newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),0); - } else { - newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),effectsKey.getParamIden()); - } - thisSet.add(newEffectsKey); - } - - effectsSet.addStrongUpdateEffectsSet(paramIdx, thisSet); - } + Integer paramIdx = paramIter.next(); + HashSet newSet = callee.getEffects() + .getStrongUpdateTable().get(calleeParamIdx); + if(newSet!=null) { + + HashSet thisSet=new HashSet(); + HeapRegionNode priHRN=og.id2hrn.get(og.paramIndex2idPrimary.get(paramIdx)); + Integer secIdx=og.paramIndex2idSecondary.get(paramIdx); + HeapRegionNode secHRN=null; + if(secIdx!=null) { + secHRN=og.id2hrn.get(secIdx); + } else { + secHRN=priHRN; + } + + for (Iterator iterator = newSet.iterator(); iterator.hasNext(); ) { + EffectsKey effectsKey = (EffectsKey) iterator.next(); + HeapRegionNode hrnTemp; + if(effectsKey.getParamIden()==0) { //primary + hrnTemp=priHRN; + } else { //secondary + hrnTemp=secHRN; + } + EffectsKey newEffectsKey; + if(secIdx==null) { + newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),0); + } else { + newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),effectsKey.getParamIden()); + } + thisSet.add(newEffectsKey); + } + + effectsSet.addStrongUpdateEffectsSet(paramIdx, thisSet); + } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/MethodEffectsAnalysis.java b/Robust/src/Analysis/OwnershipAnalysis/MethodEffectsAnalysis.java index 99d2a73c..c86b5efd 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/MethodEffectsAnalysis.java +++ b/Robust/src/Analysis/OwnershipAnalysis/MethodEffectsAnalysis.java @@ -88,51 +88,51 @@ public class MethodEffectsAnalysis { Set mcSet = mapMethodContextToMethodEffects.keySet(); Iterator mcIter = mcSet.iterator(); while (mcIter.hasNext()) { - MethodContext mc = mcIter.next(); - MethodDescriptor md = (MethodDescriptor) mc.getDescriptor(); - - int startIdx = 0; - if (!md.isStatic()) { - startIdx = 1; - } - - MethodEffects me = mapMethodContextToMethodEffects.get(mc); - EffectsSet effectsSet = me.getEffects(); - - bw.write("Method " + mc + " :\n"); - for (int i = startIdx; i < md.numParameters() + startIdx; i++) { - - String paramName = md.getParamName(i - startIdx); - - Set effectSet = effectsSet.getReadingSet(i); - String keyStr = "{"; - if (effectSet != null) { - Iterator effectIter = effectSet.iterator(); - while (effectIter.hasNext()) { - EffectsKey key = effectIter.next(); - keyStr += " " + key; - } - } - keyStr += " }"; - bw.write(" Paramter " + paramName + " ReadingSet=" - + keyStr + "\n"); - - effectSet = effectsSet.getWritingSet(new Integer(i)); - keyStr = "{"; - if (effectSet != null) { - Iterator effectIter = effectSet.iterator(); - while (effectIter.hasNext()) { - EffectsKey key = effectIter.next(); - keyStr += " " + key; - } - } - - keyStr += " }"; - bw.write(" Paramter " + paramName + " WritingngSet=" - + keyStr + "\n"); - - } - bw.write("\n"); + MethodContext mc = mcIter.next(); + MethodDescriptor md = (MethodDescriptor) mc.getDescriptor(); + + int startIdx = 0; + if (!md.isStatic()) { + startIdx = 1; + } + + MethodEffects me = mapMethodContextToMethodEffects.get(mc); + EffectsSet effectsSet = me.getEffects(); + + bw.write("Method " + mc + " :\n"); + for (int i = startIdx; i < md.numParameters() + startIdx; i++) { + + String paramName = md.getParamName(i - startIdx); + + Set effectSet = effectsSet.getReadingSet(i); + String keyStr = "{"; + if (effectSet != null) { + Iterator effectIter = effectSet.iterator(); + while (effectIter.hasNext()) { + EffectsKey key = effectIter.next(); + keyStr += " " + key; + } + } + keyStr += " }"; + bw.write(" Paramter " + paramName + " ReadingSet=" + + keyStr + "\n"); + + effectSet = effectsSet.getWritingSet(new Integer(i)); + keyStr = "{"; + if (effectSet != null) { + Iterator effectIter = effectSet.iterator(); + while (effectIter.hasNext()) { + EffectsKey key = effectIter.next(); + keyStr += " " + key; + } + } + + keyStr += " }"; + bw.write(" Paramter " + paramName + " WritingngSet=" + + keyStr + "\n"); + + } + bw.write("\n"); } diff --git a/Robust/src/Analysis/OwnershipAnalysis/OwnershipAnalysis.java b/Robust/src/Analysis/OwnershipAnalysis/OwnershipAnalysis.java index 8dd9f34e..cfdfb17c 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/OwnershipAnalysis.java +++ b/Robust/src/Analysis/OwnershipAnalysis/OwnershipAnalysis.java @@ -107,9 +107,9 @@ public class OwnershipAnalysis { AllocationSite as = n.getAllocationSite(); if( as == null ) { - out += " "+n.toString()+",\n"; + out += " "+n.toString()+",\n"; } else { - out += " "+n.toString()+": "+as.toStringVerbose()+",\n"; + out += " "+n.toString()+": "+as.toStringVerbose()+",\n"; } } @@ -144,7 +144,7 @@ public class OwnershipAnalysis { TaskDescriptor td = (TaskDescriptor) taskItr.next(); if( !tabularOutput ) { - bw.write("\n---------"+td+"--------\n"); + bw.write("\n---------"+td+"--------\n"); } HashSet allocSites = getFlaggedAllocationSitesReachableFromTask(td); @@ -159,38 +159,38 @@ public class OwnershipAnalysis { FlatMethod fm = state.getMethodFlat(td); for( int i = 0; i < fm.numParameters(); ++i ) { - // for the ith parameter check for aliases to all - // higher numbered parameters - for( int j = i + 1; j < fm.numParameters(); ++j ) { - common = createsPotentialAliases(td, i, j); - if( !common.isEmpty() ) { - foundSomeAlias = true; - if( !tabularOutput ) { - bw.write("Potential alias between parameters "+i+" and "+j+".\n"); - bw.write(prettyPrintNodeSet(common)+"\n"); - } else { - ++numAlias; - } - } - } - - // for the ith parameter, check for aliases against - // the set of allocation sites reachable from this - // task context - Iterator allocItr = allocSites.iterator(); - while( allocItr.hasNext() ) { - AllocationSite as = (AllocationSite) allocItr.next(); - common = createsPotentialAliases(td, i, as); - if( !common.isEmpty() ) { - foundSomeAlias = true; - if( !tabularOutput ) { - bw.write("Potential alias between parameter "+i+" and "+as.getFlatNew()+".\n"); - bw.write(prettyPrintNodeSet(common)+"\n"); - } else { - ++numAlias; - } - } - } + // for the ith parameter check for aliases to all + // higher numbered parameters + for( int j = i + 1; j < fm.numParameters(); ++j ) { + common = createsPotentialAliases(td, i, j); + if( !common.isEmpty() ) { + foundSomeAlias = true; + if( !tabularOutput ) { + bw.write("Potential alias between parameters "+i+" and "+j+".\n"); + bw.write(prettyPrintNodeSet(common)+"\n"); + } else { + ++numAlias; + } + } + } + + // for the ith parameter, check for aliases against + // the set of allocation sites reachable from this + // task context + Iterator allocItr = allocSites.iterator(); + while( allocItr.hasNext() ) { + AllocationSite as = (AllocationSite) allocItr.next(); + common = createsPotentialAliases(td, i, as); + if( !common.isEmpty() ) { + foundSomeAlias = true; + if( !tabularOutput ) { + bw.write("Potential alias between parameter "+i+" and "+as.getFlatNew()+".\n"); + bw.write(prettyPrintNodeSet(common)+"\n"); + } else { + ++numAlias; + } + } + } } // for each allocation site check for aliases with @@ -199,34 +199,34 @@ public class OwnershipAnalysis { HashSet outerChecked = new HashSet(); Iterator allocItr1 = allocSites.iterator(); while( allocItr1.hasNext() ) { - AllocationSite as1 = (AllocationSite) allocItr1.next(); - - Iterator allocItr2 = allocSites.iterator(); - while( allocItr2.hasNext() ) { - AllocationSite as2 = (AllocationSite) allocItr2.next(); - - if( !outerChecked.contains(as2) ) { - common = createsPotentialAliases(td, as1, as2); - - if( !common.isEmpty() ) { - foundSomeAlias = true; - if( !tabularOutput ) { - bw.write("Potential alias between "+as1.getFlatNew()+" and "+as2.getFlatNew()+".\n"); - bw.write(prettyPrintNodeSet(common)+"\n"); - } else { - ++numAlias; - } - } - } - } - - outerChecked.add(as1); + AllocationSite as1 = (AllocationSite) allocItr1.next(); + + Iterator allocItr2 = allocSites.iterator(); + while( allocItr2.hasNext() ) { + AllocationSite as2 = (AllocationSite) allocItr2.next(); + + if( !outerChecked.contains(as2) ) { + common = createsPotentialAliases(td, as1, as2); + + if( !common.isEmpty() ) { + foundSomeAlias = true; + if( !tabularOutput ) { + bw.write("Potential alias between "+as1.getFlatNew()+" and "+as2.getFlatNew()+".\n"); + bw.write(prettyPrintNodeSet(common)+"\n"); + } else { + ++numAlias; + } + } + } + } + + outerChecked.add(as1); } if( !foundSomeAlias ) { - if( !tabularOutput ) { - bw.write("No aliases between flagged objects in Task "+td+".\n"); - } + if( !tabularOutput ) { + bw.write("No aliases between flagged objects in Task "+td+".\n"); + } } } @@ -275,17 +275,17 @@ public class OwnershipAnalysis { Iterator allocItr2 = allocSites.iterator(); while( allocItr2.hasNext() ) { - AllocationSite as2 = (AllocationSite) allocItr2.next(); + AllocationSite as2 = (AllocationSite) allocItr2.next(); - if( !outerChecked.contains(as2) ) { - Set common = createsPotentialAliases(d, as1, as2); + if( !outerChecked.contains(as2) ) { + Set common = createsPotentialAliases(d, as1, as2); - if( !common.isEmpty() ) { - foundSomeAlias = true; - bw.write("Potential alias between "+as1.getDisjointId()+" and "+as2.getDisjointId()+".\n"); - bw.write(prettyPrintNodeSet(common)+"\n"); - } - } + if( !common.isEmpty() ) { + foundSomeAlias = true; + bw.write("Potential alias between "+as1.getDisjointId()+" and "+as2.getDisjointId()+".\n"); + bw.write(prettyPrintNodeSet(common)+"\n"); + } + } } outerChecked.add(as1); @@ -526,8 +526,8 @@ public class OwnershipAnalysis { // from those tasks Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator(); while( taskItr.hasNext() ) { - Descriptor d = (Descriptor) taskItr.next(); - scheduleAllCallees(d); + Descriptor d = (Descriptor) taskItr.next(); + scheduleAllCallees(d); } } else { @@ -548,10 +548,10 @@ public class OwnershipAnalysis { FlatMethod fm; if( d instanceof MethodDescriptor ) { - fm = state.getMethodFlat( (MethodDescriptor) d); + fm = state.getMethodFlat( (MethodDescriptor) d); } else { - assert d instanceof TaskDescriptor; - fm = state.getMethodFlat( (TaskDescriptor) d); + assert d instanceof TaskDescriptor; + fm = state.getMethodFlat( (TaskDescriptor) d); } MethodContext mc = new MethodContext(d); @@ -590,9 +590,9 @@ public class OwnershipAnalysis { if( aliasFile != null ) { if( state.TASK ) { - writeAllAliases(aliasFile, treport, justtime, state.OWNERSHIPALIASTAB, state.lines); + writeAllAliases(aliasFile, treport, justtime, state.OWNERSHIPALIASTAB, state.lines); } else { - writeAllAliasesJava(aliasFile, treport, justtime, state.OWNERSHIPALIASTAB, state.lines); + writeAllAliasesJava(aliasFile, treport, justtime, state.OWNERSHIPALIASTAB, state.lines); } } @@ -639,7 +639,7 @@ public class OwnershipAnalysis { Iterator itrmc = mcs.iterator(); while( itrmc.hasNext() ) { - allContexts.add(itrmc.next() ); + allContexts.add(itrmc.next() ); } } @@ -679,27 +679,27 @@ public class OwnershipAnalysis { Descriptor d = mc.getDescriptor(); FlatMethod fm; if( d instanceof MethodDescriptor ) { - fm = state.getMethodFlat( (MethodDescriptor) d); + fm = state.getMethodFlat( (MethodDescriptor) d); } else { - assert d instanceof TaskDescriptor; - fm = state.getMethodFlat( (TaskDescriptor) d); + assert d instanceof TaskDescriptor; + fm = state.getMethodFlat( (TaskDescriptor) d); } OwnershipGraph og = analyzeFlatMethod(mc, fm); OwnershipGraph ogPrev = mapMethodContextToCompleteOwnershipGraph.get(mc); if( !og.equals(ogPrev) ) { - setGraphForMethodContext(mc, og); - - Iterator depsItr = iteratorDependents(mc); - while( depsItr.hasNext() ) { - MethodContext mcNext = depsItr.next(); - - if( !methodContextsToVisitSet.contains(mcNext) ) { - methodContextsToVisitQ.add(new MethodContextQWrapper(mapDescriptorToPriority.get(mcNext.getDescriptor() ), - mcNext) ); - methodContextsToVisitSet.add(mcNext); - } - } + setGraphForMethodContext(mc, og); + + Iterator depsItr = iteratorDependents(mc); + while( depsItr.hasNext() ) { + MethodContext mcNext = depsItr.next(); + + if( !methodContextsToVisitSet.contains(mcNext) ) { + methodContextsToVisitQ.add(new MethodContextQWrapper(mapDescriptorToPriority.get(mcNext.getDescriptor() ), + mcNext) ); + methodContextsToVisitSet.add(mcNext); + } + } } } @@ -740,11 +740,11 @@ public class OwnershipAnalysis { // start by merging all node's parents' graphs for( int i = 0; i < fn.numPrev(); ++i ) { - FlatNode pn = fn.getPrev(i); - if( mapFlatNodeToOwnershipGraph.containsKey(pn) ) { - OwnershipGraph ogParent = mapFlatNodeToOwnershipGraph.get(pn); - og.merge(ogParent); - } + FlatNode pn = fn.getPrev(i); + if( mapFlatNodeToOwnershipGraph.containsKey(pn) ) { + OwnershipGraph ogParent = mapFlatNodeToOwnershipGraph.get(pn); + og.merge(ogParent); + } } // apply the analysis of the flat node to the @@ -761,7 +761,7 @@ public class OwnershipAnalysis { if( takeDebugSnapshots && mc.getDescriptor().getSymbol().equals(mcDescSymbolDebug) ) { - debugSnapshot(og,fn); + debugSnapshot(og,fn); } @@ -771,12 +771,12 @@ public class OwnershipAnalysis { // processing OwnershipGraph ogPrev = mapFlatNodeToOwnershipGraph.get(fn); if( !og.equals(ogPrev) ) { - mapFlatNodeToOwnershipGraph.put(fn, og); + mapFlatNodeToOwnershipGraph.put(fn, og); - for( int i = 0; i < fn.numNext(); i++ ) { - FlatNode nn = fn.getNext(i); - flatNodesToVisit.add(nn); - } + for( int i = 0; i < fn.numNext(); i++ ) { + FlatNode nn = fn.getNext(i); + flatNodesToVisit.add(nn); + } } } @@ -834,69 +834,69 @@ public class OwnershipAnalysis { OwnershipGraph ogInitParamAlloc = mapMethodContextToInitialParamAllocGraph.get(mc); if( ogInitParamAlloc == null ) { - // if the method context has aliased parameters, make sure - // there is a blob region for all those param to reference - Set aliasedParamIndices = mc.getAliasedParamIndices(); - - if( !aliasedParamIndices.isEmpty() ) { - og.makeAliasedParamHeapRegionNode(fm); - } - - // set up each parameter - for( int i = 0; i < fm.numParameters(); ++i ) { - TempDescriptor tdParam = fm.getParameter(i); - TypeDescriptor typeParam = tdParam.getType(); - Integer paramIndex = new Integer(i); - - if( typeParam.isImmutable() && !typeParam.isArray() ) { - // don't bother with this primitive parameter, it - // cannot affect reachability - continue; - } - - if( aliasedParamIndices.contains(paramIndex) ) { - // use the alias blob but give parameters their - // own primary obj region - og.assignTempEqualToAliasedParam(tdParam, - paramIndex, fm); - } else { - // this parameter is not aliased to others, give it - // a fresh primary obj and secondary object - og.assignTempEqualToParamAlloc(tdParam, - mc.getDescriptor() instanceof TaskDescriptor, - paramIndex, fm); - } - } - - // add additional edges for aliased regions if necessary - if( !aliasedParamIndices.isEmpty() ) { - og.addParam2ParamAliasEdges(fm, aliasedParamIndices); - } - - // clean up reachability on initial parameter shapes - og.globalSweep(); - - // this maps tokens to parameter indices and vice versa - // for when this method is a callee - og.prepareParamTokenMaps(fm); - - // cache the graph - OwnershipGraph ogResult = new OwnershipGraph(); - ogResult.merge(og); - mapMethodContextToInitialParamAllocGraph.put(mc, ogResult); + // if the method context has aliased parameters, make sure + // there is a blob region for all those param to reference + Set aliasedParamIndices = mc.getAliasedParamIndices(); + + if( !aliasedParamIndices.isEmpty() ) { + og.makeAliasedParamHeapRegionNode(fm); + } + + // set up each parameter + for( int i = 0; i < fm.numParameters(); ++i ) { + TempDescriptor tdParam = fm.getParameter(i); + TypeDescriptor typeParam = tdParam.getType(); + Integer paramIndex = new Integer(i); + + if( typeParam.isImmutable() && !typeParam.isArray() ) { + // don't bother with this primitive parameter, it + // cannot affect reachability + continue; + } + + if( aliasedParamIndices.contains(paramIndex) ) { + // use the alias blob but give parameters their + // own primary obj region + og.assignTempEqualToAliasedParam(tdParam, + paramIndex, fm); + } else { + // this parameter is not aliased to others, give it + // a fresh primary obj and secondary object + og.assignTempEqualToParamAlloc(tdParam, + mc.getDescriptor() instanceof TaskDescriptor, + paramIndex, fm); + } + } + + // add additional edges for aliased regions if necessary + if( !aliasedParamIndices.isEmpty() ) { + og.addParam2ParamAliasEdges(fm, aliasedParamIndices); + } + + // clean up reachability on initial parameter shapes + og.globalSweep(); + + // this maps tokens to parameter indices and vice versa + // for when this method is a callee + og.prepareParamTokenMaps(fm); + + // cache the graph + OwnershipGraph ogResult = new OwnershipGraph(); + ogResult.merge(og); + mapMethodContextToInitialParamAllocGraph.put(mc, ogResult); } else { - // or just leverage the cached copy - og.merge(ogInitParamAlloc); + // or just leverage the cached copy + og.merge(ogInitParamAlloc); } break; case FKind.FlatOpNode: FlatOpNode fon = (FlatOpNode) fn; if( fon.getOp().getOp() == Operation.ASSIGN ) { - lhs = fon.getDest(); - rhs = fon.getLeft(); - og.assignTempXEqualToTempY(lhs, rhs); + lhs = fon.getDest(); + rhs = fon.getLeft(); + og.assignTempXEqualToTempY(lhs, rhs); } break; @@ -917,7 +917,7 @@ public class OwnershipAnalysis { rhs = ffn.getSrc(); fld = ffn.getField(); if( !fld.getType().isImmutable() || fld.getType().isArray() ) { - og.assignTempXEqualToTempYFieldF(lhs, rhs, fld); + og.assignTempXEqualToTempYFieldF(lhs, rhs, fld); } meAnalysis.analyzeFlatFieldNode(mc, og, rhs, fld); @@ -930,7 +930,7 @@ public class OwnershipAnalysis { fld = fsfn.getField(); rhs = fsfn.getSrc(); if( !fld.getType().isImmutable() || fld.getType().isArray() ) { - og.assignTempXFieldFEqualToTempY(lhs, fld, rhs); + og.assignTempXFieldFEqualToTempY(lhs, fld, rhs); } meAnalysis.analyzeFlatSetFieldNode(mc, og, lhs, fld); @@ -944,13 +944,13 @@ public class OwnershipAnalysis { rhs = fen.getSrc(); if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) { - assert rhs.getType() != null; - assert rhs.getType().isArray(); + assert rhs.getType() != null; + assert rhs.getType().isArray(); - TypeDescriptor tdElement = rhs.getType().dereference(); - FieldDescriptor fdElement = getArrayField(tdElement); - og.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement); - meAnalysis.analyzeFlatElementNode(mc, og, lhs, fdElement); + TypeDescriptor tdElement = rhs.getType().dereference(); + FieldDescriptor fdElement = getArrayField(tdElement); + og.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement); + meAnalysis.analyzeFlatElementNode(mc, og, lhs, fdElement); } break; @@ -961,28 +961,28 @@ public class OwnershipAnalysis { lhs = fsen.getDst(); rhs = fsen.getSrc(); if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) { - TypeDescriptor tdElement = lhs.getType().dereference(); - FieldDescriptor fdElement = getArrayField(tdElement); - meAnalysis.analyzeFlatSetElementNode(mc, og, lhs, fdElement); + TypeDescriptor tdElement = lhs.getType().dereference(); + FieldDescriptor fdElement = getArrayField(tdElement); + meAnalysis.analyzeFlatSetElementNode(mc, og, lhs, fdElement); } if( arrayReferencees.doesNotCreateNewReaching(fsen) ) { - // skip this node if it cannot create new reachability paths - break; + // skip this node if it cannot create new reachability paths + break; } lhs = fsen.getDst(); rhs = fsen.getSrc(); if( !rhs.getType().isImmutable() || rhs.getType().isArray() ) { - assert lhs.getType() != null; - assert lhs.getType().isArray(); + assert lhs.getType() != null; + assert lhs.getType().isArray(); - TypeDescriptor tdElement = lhs.getType().dereference(); - FieldDescriptor fdElement = getArrayField(tdElement); + TypeDescriptor tdElement = lhs.getType().dereference(); + FieldDescriptor fdElement = getArrayField(tdElement); - og.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs); - meAnalysis.analyzeFlatSetElementNode(mc, og, lhs, fdElement); + og.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs); + meAnalysis.analyzeFlatSetElementNode(mc, og, lhs, fdElement); } break; @@ -991,23 +991,23 @@ public class OwnershipAnalysis { FlatNew fnn = (FlatNew) fn; lhs = fnn.getDst(); if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) { - AllocationSite as = getAllocationSiteFromFlatNewPRIVATE(fnn); - - if (mapMethodContextToLiveInAllocationSiteSet != null) { - HashSet alllocSet=mapMethodContextToLiveInAllocationSiteSet.get(mc); - if(alllocSet!=null) { - for (Iterator iterator = alllocSet.iterator(); iterator - .hasNext(); ) { - AllocationSite allocationSite = (AllocationSite) iterator - .next(); - if(allocationSite.flatNew.equals(as.flatNew)) { - as.setFlag(true); - } - } - } - } - - og.assignTempEqualToNewAlloc(lhs, as); + AllocationSite as = getAllocationSiteFromFlatNewPRIVATE(fnn); + + if (mapMethodContextToLiveInAllocationSiteSet != null) { + HashSet alllocSet=mapMethodContextToLiveInAllocationSiteSet.get(mc); + if(alllocSet!=null) { + for (Iterator iterator = alllocSet.iterator(); iterator + .hasNext(); ) { + AllocationSite allocationSite = (AllocationSite) iterator + .next(); + if(allocationSite.flatNew.equals(as.flatNew)) { + as.setFlag(true); + } + } + } + } + + og.assignTempEqualToNewAlloc(lhs, as); } break; @@ -1018,88 +1018,88 @@ public class OwnershipAnalysis { OwnershipGraph ogMergeOfAllPossibleCalleeResults = new OwnershipGraph(); if( md.isStatic() ) { - // a static method is simply always the same, makes life easy - ogMergeOfAllPossibleCalleeResults = og; + // a static method is simply always the same, makes life easy + ogMergeOfAllPossibleCalleeResults = og; - Set aliasedParamIndices = - ogMergeOfAllPossibleCalleeResults.calculateAliasedParamSet(fc, md.isStatic(), flatm); + Set aliasedParamIndices = + ogMergeOfAllPossibleCalleeResults.calculateAliasedParamSet(fc, md.isStatic(), flatm); - MethodContext mcNew = new MethodContext(md, aliasedParamIndices); - Set contexts = mapDescriptorToAllMethodContexts.get(md); - assert contexts != null; - contexts.add(mcNew); + MethodContext mcNew = new MethodContext(md, aliasedParamIndices); + Set contexts = mapDescriptorToAllMethodContexts.get(md); + assert contexts != null; + contexts.add(mcNew); - addDependent(mc, mcNew); + addDependent(mc, mcNew); - OwnershipGraph onlyPossibleCallee = mapMethodContextToCompleteOwnershipGraph.get(mcNew); + OwnershipGraph onlyPossibleCallee = mapMethodContextToCompleteOwnershipGraph.get(mcNew); - if( onlyPossibleCallee == null ) { - // if this method context has never been analyzed just schedule it for analysis - // and skip over this call site for now - if( !methodContextsToVisitSet.contains(mcNew) ) { - methodContextsToVisitQ.add(new MethodContextQWrapper(mapDescriptorToPriority.get(md), - mcNew) ); - methodContextsToVisitSet.add(mcNew); - } + if( onlyPossibleCallee == null ) { + // if this method context has never been analyzed just schedule it for analysis + // and skip over this call site for now + if( !methodContextsToVisitSet.contains(mcNew) ) { + methodContextsToVisitQ.add(new MethodContextQWrapper(mapDescriptorToPriority.get(md), + mcNew) ); + methodContextsToVisitSet.add(mcNew); + } - } else { - ogMergeOfAllPossibleCalleeResults.resolveMethodCall(fc, md.isStatic(), flatm, onlyPossibleCallee, mc, null); - } + } else { + ogMergeOfAllPossibleCalleeResults.resolveMethodCall(fc, md.isStatic(), flatm, onlyPossibleCallee, mc, null); + } - meAnalysis.createNewMapping(mcNew); - meAnalysis.analyzeFlatCall(ogMergeOfAllPossibleCalleeResults, mcNew, mc, fc); + meAnalysis.createNewMapping(mcNew); + meAnalysis.analyzeFlatCall(ogMergeOfAllPossibleCalleeResults, mcNew, mc, fc); } else { - // if the method descriptor is virtual, then there could be a - // set of possible methods that will actually be invoked, so - // find all of them and merge all of their results together - TypeDescriptor typeDesc = fc.getThis().getType(); - Set possibleCallees = callGraph.getMethods(md, typeDesc); + // if the method descriptor is virtual, then there could be a + // set of possible methods that will actually be invoked, so + // find all of them and merge all of their results together + TypeDescriptor typeDesc = fc.getThis().getType(); + Set possibleCallees = callGraph.getMethods(md, typeDesc); - Iterator i = possibleCallees.iterator(); - while( i.hasNext() ) { - MethodDescriptor possibleMd = (MethodDescriptor) i.next(); - FlatMethod pflatm = state.getMethodFlat(possibleMd); + Iterator i = possibleCallees.iterator(); + while( i.hasNext() ) { + MethodDescriptor possibleMd = (MethodDescriptor) i.next(); + FlatMethod pflatm = state.getMethodFlat(possibleMd); - // don't alter the working graph (og) until we compute a result for every - // possible callee, merge them all together, then set og to that - OwnershipGraph ogCopy = new OwnershipGraph(); - ogCopy.merge(og); + // don't alter the working graph (og) until we compute a result for every + // possible callee, merge them all together, then set og to that + OwnershipGraph ogCopy = new OwnershipGraph(); + ogCopy.merge(og); - Set aliasedParamIndices = - ogCopy.calculateAliasedParamSet(fc, possibleMd.isStatic(), pflatm); + Set aliasedParamIndices = + ogCopy.calculateAliasedParamSet(fc, possibleMd.isStatic(), pflatm); - MethodContext mcNew = new MethodContext(possibleMd, aliasedParamIndices); - Set contexts = mapDescriptorToAllMethodContexts.get(md); - assert contexts != null; - contexts.add(mcNew); + MethodContext mcNew = new MethodContext(possibleMd, aliasedParamIndices); + Set contexts = mapDescriptorToAllMethodContexts.get(md); + assert contexts != null; + contexts.add(mcNew); - meAnalysis.createNewMapping(mcNew); + meAnalysis.createNewMapping(mcNew); - addDependent(mc, mcNew); + addDependent(mc, mcNew); - OwnershipGraph ogPotentialCallee = mapMethodContextToCompleteOwnershipGraph.get(mcNew); + OwnershipGraph ogPotentialCallee = mapMethodContextToCompleteOwnershipGraph.get(mcNew); - if( ogPotentialCallee == null ) { - // if this method context has never been analyzed just schedule it for analysis - // and skip over this call site for now - if( !methodContextsToVisitSet.contains(mcNew) ) { - methodContextsToVisitQ.add(new MethodContextQWrapper(mapDescriptorToPriority.get(md), - mcNew) ); - methodContextsToVisitSet.add(mcNew); - } + if( ogPotentialCallee == null ) { + // if this method context has never been analyzed just schedule it for analysis + // and skip over this call site for now + if( !methodContextsToVisitSet.contains(mcNew) ) { + methodContextsToVisitQ.add(new MethodContextQWrapper(mapDescriptorToPriority.get(md), + mcNew) ); + methodContextsToVisitSet.add(mcNew); + } - } else { - ogCopy.resolveMethodCall(fc, possibleMd.isStatic(), pflatm, ogPotentialCallee, mc, null); - } + } else { + ogCopy.resolveMethodCall(fc, possibleMd.isStatic(), pflatm, ogPotentialCallee, mc, null); + } - ogMergeOfAllPossibleCalleeResults.merge(ogCopy); + ogMergeOfAllPossibleCalleeResults.merge(ogCopy); - meAnalysis.analyzeFlatCall(ogMergeOfAllPossibleCalleeResults, mcNew, mc, fc); - } + meAnalysis.analyzeFlatCall(ogMergeOfAllPossibleCalleeResults, mcNew, mc, fc); + } } @@ -1110,7 +1110,7 @@ public class OwnershipAnalysis { FlatReturnNode frn = (FlatReturnNode) fn; rhs = frn.getReturnTemp(); if( rhs != null && !rhs.getType().isImmutable() ) { - og.assignReturnEqualToTemp(rhs); + og.assignReturnEqualToTemp(rhs); } setRetNodes.add(frn); break; @@ -1120,7 +1120,7 @@ public class OwnershipAnalysis { if( methodEffects ) { Hashtable table=mapMethodContextToFlatNodeOwnershipGraph.get(mc); if(table==null) { - table=new Hashtable(); + table=new Hashtable(); } table.put(fn, og); mapMethodContextToFlatNodeOwnershipGraph.put(mc, table); @@ -1159,18 +1159,18 @@ public class OwnershipAnalysis { if( writeDOTs && writeAllDOTs ) { if( !mapMethodContextToNumUpdates.containsKey(mc) ) { - mapMethodContextToNumUpdates.put(mc, new Integer(0) ); + mapMethodContextToNumUpdates.put(mc, new Integer(0) ); } Integer n = mapMethodContextToNumUpdates.get(mc); try { - og.writeGraph(mc+"COMPLETE"+String.format("%05d", n), - true, // write labels (variables) - true, // selectively hide intermediate temp vars - true, // prune unreachable heap regions - false, // show back edges to confirm graph validity - false, // show parameter indices (unmaintained!) - true, // hide subset reachability states - true); // hide edge taints + og.writeGraph(mc+"COMPLETE"+String.format("%05d", n), + true, // write labels (variables) + true, // selectively hide intermediate temp vars + true, // prune unreachable heap regions + false, // show back edges to confirm graph validity + false, // show parameter indices (unmaintained!) + true, // hide subset reachability states + true); // hide edge taints } catch( IOException e ) { } mapMethodContextToNumUpdates.put(mc, n + 1); @@ -1206,14 +1206,14 @@ public class OwnershipAnalysis { OwnershipGraph og = (OwnershipGraph) me.getValue(); try { - og.writeGraph(mc+"COMPLETE", - true, // write labels (variables) - true, // selectively hide intermediate temp vars - true, // prune unreachable heap regions - false, // show back edges to confirm graph validity - false, // show parameter indices (unmaintained!) - true, // hide subset reachability states - true); // hide edge taints + og.writeGraph(mc+"COMPLETE", + true, // write labels (variables) + true, // selectively hide intermediate temp vars + true, // prune unreachable heap regions + false, // show back edges to confirm graph validity + false, // show parameter indices (unmaintained!) + true, // hide subset reachability states + true); // hide edge taints } catch( IOException e ) { } } @@ -1229,9 +1229,9 @@ public class OwnershipAnalysis { // the newest nodes are single objects for( int i = 0; i < allocationDepth; ++i ) { - Integer id = generateUniqueHeapRegionNodeID(); - as.setIthOldest(i, id); - mapHrnIdToAllocationSite.put(id, as); + Integer id = generateUniqueHeapRegionNodeID(); + as.setIthOldest(i, id); + mapHrnIdToAllocationSite.put(id, as); } // the oldest node is a summary node @@ -1278,17 +1278,17 @@ public class OwnershipAnalysis { FlatNode n = toVisit.iterator().next(); if( n instanceof FlatNew ) { - s.add(getAllocationSiteFromFlatNewPRIVATE( (FlatNew) n) ); + s.add(getAllocationSiteFromFlatNewPRIVATE( (FlatNew) n) ); } toVisit.remove(n); visited.add(n); for( int i = 0; i < n.numNext(); ++i ) { - FlatNode child = n.getNext(i); - if( !visited.contains(child) ) { - toVisit.add(child); - } + FlatNode child = n.getNext(i); + if( !visited.contains(child) ) { + toVisit.add(child); + } } } @@ -1312,24 +1312,24 @@ public class OwnershipAnalysis { HashSet asSet = getAllocationSiteSet(d); Iterator asItr = asSet.iterator(); while( asItr.hasNext() ) { - AllocationSite as = (AllocationSite) asItr.next(); - if( as.getDisjointId() != null ) { - out.add(as); - } + AllocationSite as = (AllocationSite) asItr.next(); + if( as.getDisjointId() != null ) { + out.add(as); + } } // enqueue callees of this method to be searched for // allocation sites also Set callees = callGraph.getCalleeSet(d); if( callees != null ) { - Iterator methItr = callees.iterator(); - while( methItr.hasNext() ) { - MethodDescriptor md = (MethodDescriptor) methItr.next(); - - if( !visited.contains(md) ) { - toVisit.add(md); - } - } + Iterator methItr = callees.iterator(); + while( methItr.hasNext() ) { + MethodDescriptor md = (MethodDescriptor) methItr.next(); + + if( !visited.contains(md) ) { + toVisit.add(md); + } + } } } @@ -1355,28 +1355,28 @@ public class OwnershipAnalysis { HashSet asSet = getAllocationSiteSet(d); Iterator asItr = asSet.iterator(); while( asItr.hasNext() ) { - AllocationSite as = (AllocationSite) asItr.next(); - TypeDescriptor typed = as.getType(); - if( typed != null ) { - ClassDescriptor cd = typed.getClassDesc(); - if( cd != null && cd.hasFlags() ) { - asSetTotal.add(as); - } - } + AllocationSite as = (AllocationSite) asItr.next(); + TypeDescriptor typed = as.getType(); + if( typed != null ) { + ClassDescriptor cd = typed.getClassDesc(); + if( cd != null && cd.hasFlags() ) { + asSetTotal.add(as); + } + } } // enqueue callees of this method to be searched for // allocation sites also Set callees = callGraph.getCalleeSet(d); if( callees != null ) { - Iterator methItr = callees.iterator(); - while( methItr.hasNext() ) { - MethodDescriptor md = (MethodDescriptor) methItr.next(); - - if( !visited.contains(md) ) { - toVisit.add(md); - } - } + Iterator methItr = callees.iterator(); + while( methItr.hasNext() ) { + MethodDescriptor md = (MethodDescriptor) methItr.next(); + + if( !visited.contains(md) ) { + toVisit.add(md); + } + } } } @@ -1394,7 +1394,7 @@ public class OwnershipAnalysis { MethodContext mc = itr.next(); if( !discovered.contains(mc) ) { - dfsVisit(set, mc, sorted, discovered); + dfsVisit(set, mc, sorted, discovered); } } @@ -1412,22 +1412,22 @@ public class OwnershipAnalysis { MethodDescriptor md = (MethodDescriptor) d; Iterator itr = callGraph.getCallerSet(md).iterator(); while( itr.hasNext() ) { - Descriptor dCaller = (Descriptor) itr.next(); - - // only consider the callers in the original set to analyze - Set callerContexts = mapDescriptorToAllMethodContexts.get(dCaller); - if( callerContexts == null ) - continue; - - // since the analysis hasn't started, there should be exactly one - // context if there are any at all - assert callerContexts.size() == 1; - MethodContext mcCaller = callerContexts.iterator().next(); - assert set.contains(mcCaller); - - if( !discovered.contains(mcCaller) ) { - dfsVisit(set, mcCaller, sorted, discovered); - } + Descriptor dCaller = (Descriptor) itr.next(); + + // only consider the callers in the original set to analyze + Set callerContexts = mapDescriptorToAllMethodContexts.get(dCaller); + if( callerContexts == null ) + continue; + + // since the analysis hasn't started, there should be exactly one + // context if there are any at all + assert callerContexts.size() == 1; + MethodContext mcCaller = callerContexts.iterator().next(); + assert set.contains(mcCaller); + + if( !discovered.contains(mcCaller) ) { + dfsVisit(set, mcCaller, sorted, discovered); + } } } @@ -1448,7 +1448,7 @@ public class OwnershipAnalysis { Integer i = mapNumContexts2NumDesc.get(s.size() ); if( i == null ) { - i = new Integer(0); + i = new Integer(0); } mapNumContexts2NumDesc.put(s.size(), i + 1); } @@ -1518,20 +1518,20 @@ public class OwnershipAnalysis { System.out.println(" @@@ capturing debug "+(debugCounter-iterStartCapture)+" @@@"); String graphName = String.format("snap%04d",debugCounter-iterStartCapture); if( fn != null ) { - graphName = graphName+fn; + graphName = graphName+fn; } try { - og.writeGraph(graphName, - true, // write labels (variables) - true, // selectively hide intermediate temp vars - true, // prune unreachable heap regions - false, // show back edges to confirm graph validity - false, // show parameter indices (unmaintained!) - true, // hide subset reachability states - true); // hide edge taints + og.writeGraph(graphName, + true, // write labels (variables) + true, // selectively hide intermediate temp vars + true, // prune unreachable heap regions + false, // show back edges to confirm graph validity + false, // show parameter indices (unmaintained!) + true, // hide subset reachability states + true); // hide edge taints } catch( Exception e ) { - System.out.println("Error writing debug capture."); - System.exit(0); + System.out.println("Error writing debug capture."); + System.exit(0); } } @@ -1563,8 +1563,8 @@ public class OwnershipAnalysis { for(int i=0; i itrHrnFhrn = hrnY.iteratorToReferencees(); while( itrHrnFhrn.hasNext() ) { - ReferenceEdge edgeHrn = itrHrnFhrn.next(); - HeapRegionNode hrnHrn = edgeHrn.getDst(); - ReachabilitySet betaHrn = edgeHrn.getBeta(); - - // prune edges that are not a matching field - if( edgeHrn.getType() != null && - !edgeHrn.getField().equals(f.getSymbol() ) - ) { - continue; - } - - // check for impossible edges - if( !isSuperiorType(x.getType(), edgeHrn.getType() ) ) { - impossibleEdges.add(edgeHrn); - continue; - } - - TypeDescriptor tdNewEdge = - mostSpecificType(edgeHrn.getType(), - hrnHrn.getType() - ); - - ReferenceEdge edgeNew = new ReferenceEdge(lnX, - hrnHrn, - tdNewEdge, - null, - false, - betaY.intersection(betaHrn) - ); - - int newTaintIdentifier=getTaintIdentifierFromHRN(hrnHrn); - edgeNew.setTaintIdentifier(newTaintIdentifier); - - addReferenceEdge(lnX, hrnHrn, edgeNew); + ReferenceEdge edgeHrn = itrHrnFhrn.next(); + HeapRegionNode hrnHrn = edgeHrn.getDst(); + ReachabilitySet betaHrn = edgeHrn.getBeta(); + + // prune edges that are not a matching field + if( edgeHrn.getType() != null && + !edgeHrn.getField().equals(f.getSymbol() ) + ) { + continue; + } + + // check for impossible edges + if( !isSuperiorType(x.getType(), edgeHrn.getType() ) ) { + impossibleEdges.add(edgeHrn); + continue; + } + + TypeDescriptor tdNewEdge = + mostSpecificType(edgeHrn.getType(), + hrnHrn.getType() + ); + + ReferenceEdge edgeNew = new ReferenceEdge(lnX, + hrnHrn, + tdNewEdge, + null, + false, + betaY.intersection(betaHrn) + ); + + int newTaintIdentifier=getTaintIdentifierFromHRN(hrnHrn); + edgeNew.setTaintIdentifier(newTaintIdentifier); + + addReferenceEdge(lnX, hrnHrn, edgeNew); } } @@ -485,7 +485,7 @@ public class OwnershipGraph { // you must global sweep to clean up broken reachability if( !impossibleEdges.isEmpty() ) { if( !DISABLE_GLOBAL_SWEEP ) { - globalSweep(); + globalSweep(); } } } @@ -521,10 +521,10 @@ public class OwnershipGraph { (hrnX.isSingleObject() && lnX.getNumReferencees() == 1) // case 2 ) ) { - if( !DISABLE_STRONG_UPDATES ) { - strongUpdate = true; - clearReferenceEdgesFrom(hrnX, f.getType(), f.getSymbol(), false); - } + if( !DISABLE_STRONG_UPDATES ) { + strongUpdate = true; + clearReferenceEdgesFrom(hrnX, f.getType(), f.getSymbol(), false); + } } } @@ -538,39 +538,39 @@ public class OwnershipGraph { Iterator itrYhrn = lnY.iteratorToReferencees(); while( itrYhrn.hasNext() ) { - ReferenceEdge edgeY = itrYhrn.next(); - HeapRegionNode hrnY = edgeY.getDst(); - ReachabilitySet O = edgeY.getBeta(); - - // check for impossible edges - if( !isSuperiorType(f.getType(), edgeY.getType() ) ) { - impossibleEdges.add(edgeY); - continue; - } - - // propagate tokens over nodes starting from hrnSrc, and it will - // take care of propagating back up edges from any touched nodes - ChangeTupleSet Cy = O.unionUpArityToChangeSet(R); - propagateTokensOverNodes(hrnY, Cy, nodesWithNewAlpha, edgesWithNewBeta); - - - // then propagate back just up the edges from hrn - ChangeTupleSet Cx = R.unionUpArityToChangeSet(O); - HashSet todoEdges = new HashSet(); - - Hashtable edgePlannedChanges = - new Hashtable(); - - Iterator referItr = hrnX.iteratorToReferencers(); - while( referItr.hasNext() ) { - ReferenceEdge edgeUpstream = referItr.next(); - todoEdges.add(edgeUpstream); - edgePlannedChanges.put(edgeUpstream, Cx); - } - - propagateTokensOverEdges(todoEdges, - edgePlannedChanges, - edgesWithNewBeta); + ReferenceEdge edgeY = itrYhrn.next(); + HeapRegionNode hrnY = edgeY.getDst(); + ReachabilitySet O = edgeY.getBeta(); + + // check for impossible edges + if( !isSuperiorType(f.getType(), edgeY.getType() ) ) { + impossibleEdges.add(edgeY); + continue; + } + + // propagate tokens over nodes starting from hrnSrc, and it will + // take care of propagating back up edges from any touched nodes + ChangeTupleSet Cy = O.unionUpArityToChangeSet(R); + propagateTokensOverNodes(hrnY, Cy, nodesWithNewAlpha, edgesWithNewBeta); + + + // then propagate back just up the edges from hrn + ChangeTupleSet Cx = R.unionUpArityToChangeSet(O); + HashSet todoEdges = new HashSet(); + + Hashtable edgePlannedChanges = + new Hashtable(); + + Iterator referItr = hrnX.iteratorToReferencers(); + while( referItr.hasNext() ) { + ReferenceEdge edgeUpstream = referItr.next(); + todoEdges.add(edgeUpstream); + edgePlannedChanges.put(edgeUpstream, Cx); + } + + propagateTokensOverEdges(todoEdges, + edgePlannedChanges, + edgesWithNewBeta); } } @@ -595,59 +595,59 @@ public class OwnershipGraph { Iterator itrYhrn = lnY.iteratorToReferencees(); while( itrYhrn.hasNext() ) { - ReferenceEdge edgeY = itrYhrn.next(); - HeapRegionNode hrnY = edgeY.getDst(); - - // skip impossible edges here, we already marked them - // when computing reachability propagations above - if( !isSuperiorType(f.getType(), edgeY.getType() ) ) { - continue; - } - - // prepare the new reference edge hrnX.f -> hrnY - TypeDescriptor tdNewEdge = - mostSpecificType(y.getType(), - edgeY.getType(), - hrnY.getType() - ); - - ReferenceEdge edgeNew = new ReferenceEdge(hrnX, - hrnY, - tdNewEdge, - f.getSymbol(), - false, - edgeY.getBeta().pruneBy(hrnX.getAlpha() ) - ); - - // look to see if an edge with same field exists - // and merge with it, otherwise just add the edge - ReferenceEdge edgeExisting = hrnX.getReferenceTo(hrnY, - tdNewEdge, - f.getSymbol() ); - - if( edgeExisting != null ) { - edgeExisting.setBeta( - edgeExisting.getBeta().union(edgeNew.getBeta() ) - ); - - if((!hrnX.isParameter() && hrnY.isParameter()) || ( hrnX.isParameter() && hrnY.isParameter())) { - int newTaintIdentifier=getTaintIdentifierFromHRN(hrnY); - edgeExisting.unionTaintIdentifier(newTaintIdentifier); - } - // a new edge here cannot be reflexive, so existing will - // always be also not reflexive anymore - edgeExisting.setIsInitialParam(false); - } else { - - if((!hrnX.isParameter() && hrnY.isParameter()) || ( hrnX.isParameter() && hrnY.isParameter())) { - int newTaintIdentifier=getTaintIdentifierFromHRN(hrnY); - edgeNew.setTaintIdentifier(newTaintIdentifier); - } - //currently, taint isn't propagated through the chain of refrences - //propagateTaintIdentifier(hrnX,newTaintIdentifier,new HashSet()); - - addReferenceEdge(hrnX, hrnY, edgeNew); - } + ReferenceEdge edgeY = itrYhrn.next(); + HeapRegionNode hrnY = edgeY.getDst(); + + // skip impossible edges here, we already marked them + // when computing reachability propagations above + if( !isSuperiorType(f.getType(), edgeY.getType() ) ) { + continue; + } + + // prepare the new reference edge hrnX.f -> hrnY + TypeDescriptor tdNewEdge = + mostSpecificType(y.getType(), + edgeY.getType(), + hrnY.getType() + ); + + ReferenceEdge edgeNew = new ReferenceEdge(hrnX, + hrnY, + tdNewEdge, + f.getSymbol(), + false, + edgeY.getBeta().pruneBy(hrnX.getAlpha() ) + ); + + // look to see if an edge with same field exists + // and merge with it, otherwise just add the edge + ReferenceEdge edgeExisting = hrnX.getReferenceTo(hrnY, + tdNewEdge, + f.getSymbol() ); + + if( edgeExisting != null ) { + edgeExisting.setBeta( + edgeExisting.getBeta().union(edgeNew.getBeta() ) + ); + + if((!hrnX.isParameter() && hrnY.isParameter()) || ( hrnX.isParameter() && hrnY.isParameter())) { + int newTaintIdentifier=getTaintIdentifierFromHRN(hrnY); + edgeExisting.unionTaintIdentifier(newTaintIdentifier); + } + // a new edge here cannot be reflexive, so existing will + // always be also not reflexive anymore + edgeExisting.setIsInitialParam(false); + } else { + + if((!hrnX.isParameter() && hrnY.isParameter()) || ( hrnX.isParameter() && hrnY.isParameter())) { + int newTaintIdentifier=getTaintIdentifierFromHRN(hrnY); + edgeNew.setTaintIdentifier(newTaintIdentifier); + } + //currently, taint isn't propagated through the chain of refrences + //propagateTaintIdentifier(hrnX,newTaintIdentifier,new HashSet()); + + addReferenceEdge(hrnX, hrnY, edgeNew); + } } } @@ -661,7 +661,7 @@ public class OwnershipGraph { // reachability with a global sweep if( strongUpdate || !impossibleEdges.isEmpty() ) { if( !DISABLE_GLOBAL_SWEEP ) { - globalSweep(); + globalSweep(); } } } @@ -694,20 +694,20 @@ public class OwnershipGraph { // affect reachability TypeDescriptor typeDeref = typeParam.dereference(); if( !typeDeref.isImmutable() || typeDeref.isArray() ) { - primary2secondaryFields.add( - OwnershipAnalysis.getArrayField(typeDeref) - ); - createSecondaryRegion = true; - - // also handle a special case where an array of objects - // can point back to the array, which is an object! - if( typeParam.toPrettyString().equals("Object[]") && - typeDeref.toPrettyString().equals("Object") ) { - - primary2primaryFields.add( - OwnershipAnalysis.getArrayField(typeDeref) - ); - } + primary2secondaryFields.add( + OwnershipAnalysis.getArrayField(typeDeref) + ); + createSecondaryRegion = true; + + // also handle a special case where an array of objects + // can point back to the array, which is an object! + if( typeParam.toPrettyString().equals("Object[]") && + typeDeref.toPrettyString().equals("Object") ) { + + primary2primaryFields.add( + OwnershipAnalysis.getArrayField(typeDeref) + ); + } } } @@ -716,24 +716,24 @@ public class OwnershipGraph { ClassDescriptor cd = typeParam.getClassDesc(); while( cd != null ) { - Iterator fieldItr = cd.getFields(); - while( fieldItr.hasNext() ) { + Iterator fieldItr = cd.getFields(); + while( fieldItr.hasNext() ) { - FieldDescriptor fd = (FieldDescriptor) fieldItr.next(); - TypeDescriptor typeField = fd.getType(); - assert typeField != null; + FieldDescriptor fd = (FieldDescriptor) fieldItr.next(); + TypeDescriptor typeField = fd.getType(); + assert typeField != null; - if( !typeField.isImmutable() || typeField.isArray() ) { - primary2secondaryFields.add(fd); - createSecondaryRegion = true; - } + if( !typeField.isImmutable() || typeField.isArray() ) { + primary2secondaryFields.add(fd); + createSecondaryRegion = true; + } - if( typeUtil.isSuperorType(typeField, typeParam) ) { - primary2primaryFields.add(fd); - } - } + if( typeUtil.isSuperorType(typeField, typeParam) ) { + primary2primaryFields.add(fd); + } + } - cd = cd.getSuperDesc(); + cd = cd.getSuperDesc(); } } @@ -1114,127 +1114,127 @@ public class OwnershipGraph { // there might be an element reference for array types if( typeI.isArray() ) { - // only bother with this if the dereferenced type can - // affect reachability - TypeDescriptor typeDeref = typeI.dereference(); + // only bother with this if the dereferenced type can + // affect reachability + TypeDescriptor typeDeref = typeI.dereference(); - ///////////////////////////////////////////////////////////// - // NOTE! For the KMeans benchmark a parameter of type float - // array, which has an immutable dereferenced type, is causing - // this assertion to fail. I'm commenting it out for now which - // is safe, because it allows aliasing where no aliasing can occur, - // so it can only get a worse-but-not-wrong answer. FIX! - ///////////////////////////////////////////////////////////// - // for this parameter to be aliased the following must be true - //assert !typeDeref.isImmutable() || typeDeref.isArray(); + ///////////////////////////////////////////////////////////// + // NOTE! For the KMeans benchmark a parameter of type float + // array, which has an immutable dereferenced type, is causing + // this assertion to fail. I'm commenting it out for now which + // is safe, because it allows aliasing where no aliasing can occur, + // so it can only get a worse-but-not-wrong answer. FIX! + ///////////////////////////////////////////////////////////// + // for this parameter to be aliased the following must be true + //assert !typeDeref.isImmutable() || typeDeref.isArray(); - primary2secondaryFields.add( - OwnershipAnalysis.getArrayField(typeDeref) - ); + primary2secondaryFields.add( + OwnershipAnalysis.getArrayField(typeDeref) + ); - // also handle a special case where an array of objects - // can point back to the array, which is an object! - if( typeI.toPrettyString().equals("Object[]") && - typeDeref.toPrettyString().equals("Object") ) { - primary2primaryFields.add( - OwnershipAnalysis.getArrayField(typeDeref) - ); - } + // also handle a special case where an array of objects + // can point back to the array, which is an object! + if( typeI.toPrettyString().equals("Object[]") && + typeDeref.toPrettyString().equals("Object") ) { + primary2primaryFields.add( + OwnershipAnalysis.getArrayField(typeDeref) + ); + } } // there might be member references for class types if( typeI.isClass() ) { - ClassDescriptor cd = typeI.getClassDesc(); - while( cd != null ) { + ClassDescriptor cd = typeI.getClassDesc(); + while( cd != null ) { - Iterator fieldItr = cd.getFields(); - while( fieldItr.hasNext() ) { + Iterator fieldItr = cd.getFields(); + while( fieldItr.hasNext() ) { - FieldDescriptor fd = (FieldDescriptor) fieldItr.next(); - TypeDescriptor typeField = fd.getType(); - assert typeField != null; + FieldDescriptor fd = (FieldDescriptor) fieldItr.next(); + TypeDescriptor typeField = fd.getType(); + assert typeField != null; - if( !typeField.isImmutable() || typeField.isArray() ) { - primary2secondaryFields.add(fd); - } + if( !typeField.isImmutable() || typeField.isArray() ) { + primary2secondaryFields.add(fd); + } - if( typeUtil.isSuperorType(typeField, typeI) ) { - primary2primaryFields.add(fd); - } - } + if( typeUtil.isSuperorType(typeField, typeI) ) { + primary2primaryFields.add(fd); + } + } - cd = cd.getSuperDesc(); - } + cd = cd.getSuperDesc(); + } } Iterator fieldItr = primary2primaryFields.iterator(); while( fieldItr.hasNext() ) { - FieldDescriptor fd = fieldItr.next(); - - ReferenceEdge edgePrimaryReflexive = - new ReferenceEdge(primaryI, // src - primaryI, // dst - fd.getType(), // type - fd.getSymbol(), // field - true, // special param initial - betaSoup); // reachability - addReferenceEdge(primaryI, primaryI, edgePrimaryReflexive); + FieldDescriptor fd = fieldItr.next(); + + ReferenceEdge edgePrimaryReflexive = + new ReferenceEdge(primaryI, // src + primaryI, // dst + fd.getType(), // type + fd.getSymbol(), // field + true, // special param initial + betaSoup); // reachability + addReferenceEdge(primaryI, primaryI, edgePrimaryReflexive); } fieldItr = primary2secondaryFields.iterator(); while( fieldItr.hasNext() ) { - FieldDescriptor fd = fieldItr.next(); - TypeDescriptor typeField = fd.getType(); - assert typeField != null; - - ReferenceEdge edgePrimary2Secondary = - new ReferenceEdge(primaryI, // src - hrnAliasBlob, // dst - fd.getType(), // type - fd.getSymbol(), // field - true, // special param initial - betaSoup); // reachability - addReferenceEdge(primaryI, hrnAliasBlob, edgePrimary2Secondary); - - // ask whether these fields might match any of the other aliased - // parameters and make those edges too - Iterator apItrJ = aliasedParamIndices.iterator(); - while( apItrJ.hasNext() ) { - Integer j = apItrJ.next(); - TempDescriptor tdParamJ = fm.getParameter(j); - TypeDescriptor typeJ = tdParamJ.getType(); - - if( !i.equals(j) && typeUtil.isSuperorType(typeField, typeJ) ) { - - Integer idPrimaryJ = paramIndex2idPrimary.get(j); - assert idPrimaryJ != null; - HeapRegionNode primaryJ = id2hrn.get(idPrimaryJ); - assert primaryJ != null; - - TokenTuple ttPrimaryJ = new TokenTuple(idPrimaryJ, - false, // multi-object - TokenTuple.ARITY_ONE).makeCanonical(); - - TokenTupleSet ttsJ = new TokenTupleSet(ttPrimaryJ).makeCanonical(); - TokenTupleSet ttsIJ = ttsI.union(ttsJ); - TokenTupleSet ttsAJ = ttsA.union(ttsJ); - TokenTupleSet ttsIAJ = ttsIA.union(ttsJ); - ReachabilitySet betaSoupWJ = ReachabilitySet.factory(ttsJ).union(ttsIJ).union(ttsAJ).union(ttsIAJ); - - ReferenceEdge edgePrimaryI2PrimaryJ = - new ReferenceEdge(primaryI, // src - primaryJ, // dst - fd.getType(), // type - fd.getSymbol(), // field - true, // special param initial - betaSoupWJ); // reachability - addReferenceEdge(primaryI, primaryJ, edgePrimaryI2PrimaryJ); - } - } + FieldDescriptor fd = fieldItr.next(); + TypeDescriptor typeField = fd.getType(); + assert typeField != null; + + ReferenceEdge edgePrimary2Secondary = + new ReferenceEdge(primaryI, // src + hrnAliasBlob, // dst + fd.getType(), // type + fd.getSymbol(), // field + true, // special param initial + betaSoup); // reachability + addReferenceEdge(primaryI, hrnAliasBlob, edgePrimary2Secondary); + + // ask whether these fields might match any of the other aliased + // parameters and make those edges too + Iterator apItrJ = aliasedParamIndices.iterator(); + while( apItrJ.hasNext() ) { + Integer j = apItrJ.next(); + TempDescriptor tdParamJ = fm.getParameter(j); + TypeDescriptor typeJ = tdParamJ.getType(); + + if( !i.equals(j) && typeUtil.isSuperorType(typeField, typeJ) ) { + + Integer idPrimaryJ = paramIndex2idPrimary.get(j); + assert idPrimaryJ != null; + HeapRegionNode primaryJ = id2hrn.get(idPrimaryJ); + assert primaryJ != null; + + TokenTuple ttPrimaryJ = new TokenTuple(idPrimaryJ, + false, // multi-object + TokenTuple.ARITY_ONE).makeCanonical(); + + TokenTupleSet ttsJ = new TokenTupleSet(ttPrimaryJ).makeCanonical(); + TokenTupleSet ttsIJ = ttsI.union(ttsJ); + TokenTupleSet ttsAJ = ttsA.union(ttsJ); + TokenTupleSet ttsIAJ = ttsIA.union(ttsJ); + ReachabilitySet betaSoupWJ = ReachabilitySet.factory(ttsJ).union(ttsIJ).union(ttsAJ).union(ttsIAJ); + + ReferenceEdge edgePrimaryI2PrimaryJ = + new ReferenceEdge(primaryI, // src + primaryJ, // dst + fd.getType(), // type + fd.getSymbol(), // field + true, // special param initial + betaSoupWJ); // reachability + addReferenceEdge(primaryI, primaryJ, edgePrimaryI2PrimaryJ); + } + } } @@ -1242,29 +1242,29 @@ public class OwnershipGraph { // possibly be the same primary object, add edges Iterator apItrJ = aliasedParamIndices.iterator(); while( apItrJ.hasNext() ) { - Integer j = apItrJ.next(); - TempDescriptor tdParamJ = fm.getParameter(j); - TypeDescriptor typeJ = tdParamJ.getType(); - LabelNode lnParamJ = getLabelNodeFromTemp(tdParamJ); - - if( !i.equals(j) && typeUtil.isSuperorType(typeI, typeJ) ) { - - Integer idPrimaryJ = paramIndex2idPrimary.get(j); - assert idPrimaryJ != null; - HeapRegionNode primaryJ = id2hrn.get(idPrimaryJ); - assert primaryJ != null; - - ReferenceEdge lnJ2PrimaryJ = lnParamJ.getReferenceTo(primaryJ, - tdParamJ.getType(), - null); - assert lnJ2PrimaryJ != null; - - ReferenceEdge lnI2PrimaryJ = lnJ2PrimaryJ.copy(); - lnI2PrimaryJ.setSrc(lnParamI); - lnI2PrimaryJ.setType(tdParamI.getType() ); - lnI2PrimaryJ.tainedBy(new Integer(j)); - addReferenceEdge(lnParamI, primaryJ, lnI2PrimaryJ); - } + Integer j = apItrJ.next(); + TempDescriptor tdParamJ = fm.getParameter(j); + TypeDescriptor typeJ = tdParamJ.getType(); + LabelNode lnParamJ = getLabelNodeFromTemp(tdParamJ); + + if( !i.equals(j) && typeUtil.isSuperorType(typeI, typeJ) ) { + + Integer idPrimaryJ = paramIndex2idPrimary.get(j); + assert idPrimaryJ != null; + HeapRegionNode primaryJ = id2hrn.get(idPrimaryJ); + assert primaryJ != null; + + ReferenceEdge lnJ2PrimaryJ = lnParamJ.getReferenceTo(primaryJ, + tdParamJ.getType(), + null); + assert lnJ2PrimaryJ != null; + + ReferenceEdge lnI2PrimaryJ = lnJ2PrimaryJ.copy(); + lnI2PrimaryJ.setSrc(lnParamI); + lnI2PrimaryJ.setType(tdParamI.getType() ); + lnI2PrimaryJ.tainedBy(new Integer(j)); + addReferenceEdge(lnParamI, primaryJ, lnI2PrimaryJ); + } } } } @@ -1288,42 +1288,42 @@ public class OwnershipGraph { // immutable objects have no primary regions if( paramIndex2idPrimary.containsKey(paramIndex) ) { - Integer idPrimary = paramIndex2idPrimary.get(paramIndex); + Integer idPrimary = paramIndex2idPrimary.get(paramIndex); - assert id2hrn.containsKey(idPrimary); - HeapRegionNode hrnPrimary = id2hrn.get(idPrimary); + assert id2hrn.containsKey(idPrimary); + HeapRegionNode hrnPrimary = id2hrn.get(idPrimary); - TokenTuple p_i = new TokenTuple(hrnPrimary.getID(), - false, // multiple-object? - TokenTuple.ARITY_ONE).makeCanonical(); - paramTokenPrimary2paramIndex.put(p_i, paramIndex); - paramIndex2paramTokenPrimary.put(paramIndex, p_i); + TokenTuple p_i = new TokenTuple(hrnPrimary.getID(), + false, // multiple-object? + TokenTuple.ARITY_ONE).makeCanonical(); + paramTokenPrimary2paramIndex.put(p_i, paramIndex); + paramIndex2paramTokenPrimary.put(paramIndex, p_i); } // any parameter object, by type, may have no secondary region if( paramIndex2idSecondary.containsKey(paramIndex) ) { - Integer idSecondary = paramIndex2idSecondary.get(paramIndex); - - assert id2hrn.containsKey(idSecondary); - HeapRegionNode hrnSecondary = id2hrn.get(idSecondary); - - TokenTuple s_i = new TokenTuple(hrnSecondary.getID(), - true, // multiple-object? - TokenTuple.ARITY_ONE).makeCanonical(); - paramTokenSecondary2paramIndex.put(s_i, paramIndex); - paramIndex2paramTokenSecondary.put(paramIndex, s_i); - - TokenTuple s_i_plus = new TokenTuple(hrnSecondary.getID(), - true, // multiple-object? - TokenTuple.ARITY_ONEORMORE).makeCanonical(); - paramTokenSecondaryPlus2paramIndex.put(s_i_plus, paramIndex); - paramIndex2paramTokenSecondaryPlus.put(paramIndex, s_i_plus); - - TokenTuple s_i_star = new TokenTuple(hrnSecondary.getID(), - true, // multiple-object? - TokenTuple.ARITY_ZEROORMORE).makeCanonical(); - paramTokenSecondaryStar2paramIndex.put(s_i_star, paramIndex); - paramIndex2paramTokenSecondaryStar.put(paramIndex, s_i_star); + Integer idSecondary = paramIndex2idSecondary.get(paramIndex); + + assert id2hrn.containsKey(idSecondary); + HeapRegionNode hrnSecondary = id2hrn.get(idSecondary); + + TokenTuple s_i = new TokenTuple(hrnSecondary.getID(), + true, // multiple-object? + TokenTuple.ARITY_ONE).makeCanonical(); + paramTokenSecondary2paramIndex.put(s_i, paramIndex); + paramIndex2paramTokenSecondary.put(paramIndex, s_i); + + TokenTuple s_i_plus = new TokenTuple(hrnSecondary.getID(), + true, // multiple-object? + TokenTuple.ARITY_ONEORMORE).makeCanonical(); + paramTokenSecondaryPlus2paramIndex.put(s_i_plus, paramIndex); + paramIndex2paramTokenSecondaryPlus.put(paramIndex, s_i_plus); + + TokenTuple s_i_star = new TokenTuple(hrnSecondary.getID(), + true, // multiple-object? + TokenTuple.ARITY_ZEROORMORE).makeCanonical(); + paramTokenSecondaryStar2paramIndex.put(s_i_star, paramIndex); + paramIndex2paramTokenSecondaryStar.put(paramIndex, s_i_star); } } } @@ -1448,7 +1448,7 @@ public class OwnershipGraph { Iterator itrEdges = ln.iteratorToReferencees(); while( itrEdges.hasNext() ) { - ageTokens(as, itrEdges.next() ); + ageTokens(as, itrEdges.next() ); } } @@ -1461,7 +1461,7 @@ public class OwnershipGraph { Iterator itrEdges = hrnToAge.iteratorToReferencees(); while( itrEdges.hasNext() ) { - ageTokens(as, itrEdges.next() ); + ageTokens(as, itrEdges.next() ); } } @@ -1499,11 +1499,11 @@ public class OwnershipGraph { boolean hasFlags = false; if( as.getType().isClass() ) { - hasFlags = as.getType().getClassDesc().hasFlags(); + hasFlags = as.getType().getClassDesc().hasFlags(); } if(as.getFlag()) { - hasFlags=as.getFlag(); + hasFlags=as.getFlag(); } hrnSummary = createNewHeapRegionNode(idSummary, // id or null to generate a new one @@ -1518,18 +1518,18 @@ public class OwnershipGraph { generateUniqueIdentifier(as,0,true)); for( int i = 0; i < as.getAllocationDepth(); ++i ) { - Integer idIth = as.getIthOldest(i); - assert !id2hrn.containsKey(idIth); - createNewHeapRegionNode(idIth, // id or null to generate a new one - true, // single object? - false, // summary? - hasFlags, // flagged? - false, // is a parameter? - as.getType(), // type - as, // allocation site - null, // reachability set - as.toStringForDOT() + "\\n" + i + " oldest", - generateUniqueIdentifier(as,i,false)); + Integer idIth = as.getIthOldest(i); + assert !id2hrn.containsKey(idIth); + createNewHeapRegionNode(idIth, // id or null to generate a new one + true, // single object? + false, // summary? + hasFlags, // flagged? + false, // is a parameter? + as.getType(), // type + as, // allocation site + null, // reachability set + as.toStringForDOT() + "\\n" + i + " oldest", + generateUniqueIdentifier(as,i,false)); } } @@ -1546,7 +1546,7 @@ public class OwnershipGraph { boolean hasFlags = false; if( as.getType().isClass() ) { - hasFlags = as.getType().getClassDesc().hasFlags(); + hasFlags = as.getType().getClassDesc().hasFlags(); } hrnShadowSummary = createNewHeapRegionNode(idShadowSummary, // id or null to generate a new one @@ -1561,18 +1561,18 @@ public class OwnershipGraph { ""); for( int i = 0; i < as.getAllocationDepth(); ++i ) { - Integer idShadowIth = as.getIthOldestShadow(i); - assert !id2hrn.containsKey(idShadowIth); - createNewHeapRegionNode(idShadowIth, // id or null to generate a new one - true, // single object? - false, // summary? - hasFlags, // flagged? - false, // is a parameter? - as.getType(), // type - as, // allocation site - null, // reachability set - as + "\\n" + as.getType() + "\\n" + i + " shadow", - ""); + Integer idShadowIth = as.getIthOldestShadow(i); + assert !id2hrn.containsKey(idShadowIth); + createNewHeapRegionNode(idShadowIth, // id or null to generate a new one + true, // single object? + false, // summary? + hasFlags, // flagged? + false, // is a parameter? + as.getType(), // type + as, // allocation site + null, // reachability set + as + "\\n" + as.getType() + "\\n" + i + " shadow", + ""); } } @@ -1596,11 +1596,11 @@ public class OwnershipGraph { edge.getField() ); if( edgeSummary == null ) { - // the merge is trivial, nothing to be done + // the merge is trivial, nothing to be done } else { - // otherwise an edge from the referencer to hrnSummary exists already - // and the edge referencer->hrn should be merged with it - edgeMerged.setBeta(edgeMerged.getBeta().union(edgeSummary.getBeta() ) ); + // otherwise an edge from the referencer to hrnSummary exists already + // and the edge referencer->hrn should be merged with it + edgeMerged.setBeta(edgeMerged.getBeta().union(edgeSummary.getBeta() ) ); } addReferenceEdge(hrnSummary, hrnReferencee, edgeMerged); @@ -1619,11 +1619,11 @@ public class OwnershipGraph { edge.getField() ); if( edgeSummary == null ) { - // the merge is trivial, nothing to be done + // the merge is trivial, nothing to be done } else { - // otherwise an edge from the referencer to alpha_S exists already - // and the edge referencer->alpha_K should be merged with it - edgeMerged.setBeta(edgeMerged.getBeta().union(edgeSummary.getBeta() ) ); + // otherwise an edge from the referencer to alpha_S exists already + // and the edge referencer->alpha_K should be merged with it + edgeMerged.setBeta(edgeMerged.getBeta().union(edgeSummary.getBeta() ) ); } addReferenceEdge(onReferencer, hrnSummary, edgeMerged); @@ -1702,44 +1702,44 @@ public class OwnershipGraph { Iterator referItr = n.iteratorToReferencers(); while( referItr.hasNext() ) { - ReferenceEdge edge = referItr.next(); - todoEdges.add(edge); + ReferenceEdge edge = referItr.next(); + todoEdges.add(edge); - if( !edgePlannedChanges.containsKey(edge) ) { - edgePlannedChanges.put(edge, new ChangeTupleSet().makeCanonical() ); - } + if( !edgePlannedChanges.containsKey(edge) ) { + edgePlannedChanges.put(edge, new ChangeTupleSet().makeCanonical() ); + } - edgePlannedChanges.put(edge, edgePlannedChanges.get(edge).union(C) ); + edgePlannedChanges.put(edge, edgePlannedChanges.get(edge).union(C) ); } Iterator refeeItr = n.iteratorToReferencees(); while( refeeItr.hasNext() ) { - ReferenceEdge edgeF = refeeItr.next(); - HeapRegionNode m = edgeF.getDst(); + ReferenceEdge edgeF = refeeItr.next(); + HeapRegionNode m = edgeF.getDst(); - ChangeTupleSet changesToPass = new ChangeTupleSet().makeCanonical(); + ChangeTupleSet changesToPass = new ChangeTupleSet().makeCanonical(); - Iterator itrCprime = C.iterator(); - while( itrCprime.hasNext() ) { - ChangeTuple c = itrCprime.next(); - if( edgeF.getBeta().contains(c.getSetToMatch() ) ) { - changesToPass = changesToPass.union(c); - } - } + Iterator itrCprime = C.iterator(); + while( itrCprime.hasNext() ) { + ChangeTuple c = itrCprime.next(); + if( edgeF.getBeta().contains(c.getSetToMatch() ) ) { + changesToPass = changesToPass.union(c); + } + } - if( !changesToPass.isEmpty() ) { - if( !nodePlannedChanges.containsKey(m) ) { - nodePlannedChanges.put(m, new ChangeTupleSet().makeCanonical() ); - } + if( !changesToPass.isEmpty() ) { + if( !nodePlannedChanges.containsKey(m) ) { + nodePlannedChanges.put(m, new ChangeTupleSet().makeCanonical() ); + } - ChangeTupleSet currentChanges = nodePlannedChanges.get(m); + ChangeTupleSet currentChanges = nodePlannedChanges.get(m); - if( !changesToPass.isSubset(currentChanges) ) { + if( !changesToPass.isSubset(currentChanges) ) { - nodePlannedChanges.put(m, currentChanges.union(changesToPass) ); - todoNodes.add(m); - } - } + nodePlannedChanges.put(m, currentChanges.union(changesToPass) ); + todoNodes.add(m); + } + } } todoNodes.remove(n); @@ -1779,7 +1779,7 @@ public class OwnershipGraph { todoEdges.remove(edgeE); if( !edgePlannedChanges.containsKey(edgeE) ) { - edgePlannedChanges.put(edgeE, new ChangeTupleSet().makeCanonical() ); + edgePlannedChanges.put(edgeE, new ChangeTupleSet().makeCanonical() ); } ChangeTupleSet C = edgePlannedChanges.get(edgeE); @@ -1788,32 +1788,32 @@ public class OwnershipGraph { Iterator itrC = C.iterator(); while( itrC.hasNext() ) { - ChangeTuple c = itrC.next(); - if( edgeE.getBeta().contains(c.getSetToMatch() ) ) { - changesToPass = changesToPass.union(c); - } + ChangeTuple c = itrC.next(); + if( edgeE.getBeta().contains(c.getSetToMatch() ) ) { + changesToPass = changesToPass.union(c); + } } OwnershipNode onSrc = edgeE.getSrc(); if( !changesToPass.isEmpty() && onSrc instanceof HeapRegionNode ) { - HeapRegionNode n = (HeapRegionNode) onSrc; + HeapRegionNode n = (HeapRegionNode) onSrc; - Iterator referItr = n.iteratorToReferencers(); - while( referItr.hasNext() ) { - ReferenceEdge edgeF = referItr.next(); + Iterator referItr = n.iteratorToReferencers(); + while( referItr.hasNext() ) { + ReferenceEdge edgeF = referItr.next(); - if( !edgePlannedChanges.containsKey(edgeF) ) { - edgePlannedChanges.put(edgeF, new ChangeTupleSet().makeCanonical() ); - } + if( !edgePlannedChanges.containsKey(edgeF) ) { + edgePlannedChanges.put(edgeF, new ChangeTupleSet().makeCanonical() ); + } - ChangeTupleSet currentChanges = edgePlannedChanges.get(edgeF); + ChangeTupleSet currentChanges = edgePlannedChanges.get(edgeF); - if( !changesToPass.isSubset(currentChanges) ) { - todoEdges.add(edgeF); - edgePlannedChanges.put(edgeF, currentChanges.union(changesToPass) ); - } - } + if( !changesToPass.isSubset(currentChanges) ) { + todoEdges.add(edgeF); + edgePlannedChanges.put(edgeF, currentChanges.union(changesToPass) ); + } + } } } @@ -1854,9 +1854,9 @@ public class OwnershipGraph { TypeDescriptor typeParam = tdParam.getType(); if( typeParam.isImmutable() && !typeParam.isArray() ) { - // don't bother with this primitive parameter, it - // cannot affect reachability - continue; + // don't bother with this primitive parameter, it + // cannot affect reachability + continue; } // now depending on whether the callee is static or not @@ -1880,24 +1880,24 @@ public class OwnershipGraph { // to find all reachable nodes, start with label referencees Iterator edgeArgItr = lnArg_i.iteratorToReferencees(); while( edgeArgItr.hasNext() ) { - ReferenceEdge edge = edgeArgItr.next(); - todoNodes.add(edge.getDst() ); + ReferenceEdge edge = edgeArgItr.next(); + todoNodes.add(edge.getDst() ); } // then follow links until all reachable nodes have been found while( !todoNodes.isEmpty() ) { - HeapRegionNode hrn = todoNodes.iterator().next(); - todoNodes.remove(hrn); - reachableNodes.add(hrn); - - Iterator edgeItr = hrn.iteratorToReferencees(); - while( edgeItr.hasNext() ) { - ReferenceEdge edge = edgeItr.next(); - - if( !reachableNodes.contains(edge.getDst() ) ) { - todoNodes.add(edge.getDst() ); - } - } + HeapRegionNode hrn = todoNodes.iterator().next(); + todoNodes.remove(hrn); + reachableNodes.add(hrn); + + Iterator edgeItr = hrn.iteratorToReferencees(); + while( edgeItr.hasNext() ) { + ReferenceEdge edge = edgeItr.next(); + + if( !reachableNodes.contains(edge.getDst() ) ) { + todoNodes.add(edge.getDst() ); + } + } } // save for later @@ -1909,21 +1909,21 @@ public class OwnershipGraph { // check for arguments that are aliased for( int i = 0; i < fm.numParameters(); ++i ) { for( int j = 0; j < i; ++j ) { - HashSet s1 = paramIndex2reachableCallerNodes.get(i); - HashSet s2 = paramIndex2reachableCallerNodes.get(j); + HashSet s1 = paramIndex2reachableCallerNodes.get(i); + HashSet s2 = paramIndex2reachableCallerNodes.get(j); - // some parameters are immutable or primitive, so skip em - if( s1 == null || s2 == null ) { - continue; - } + // some parameters are immutable or primitive, so skip em + if( s1 == null || s2 == null ) { + continue; + } - Set intersection = new HashSet(s1); - intersection.retainAll(s2); + Set intersection = new HashSet(s1); + intersection.retainAll(s2); - if( !intersection.isEmpty() ) { - aliasedIndices.add(new Integer(i) ); - aliasedIndices.add(new Integer(j) ); - } + if( !intersection.isEmpty() ) { + aliasedIndices.add(new Integer(i) ); + aliasedIndices.add(new Integer(j) ); + } } } @@ -1986,7 +1986,7 @@ public class OwnershipGraph { // skip this if there is no secondary token or the parameter // is part of the aliasing context if( s_i == null || mc.getAliasedParamIndices().contains(i) ) { - continue; + continue; } rsOut = rsOut.removeTokenAIfTokenB(p_i, s_i); @@ -2018,13 +2018,13 @@ public class OwnershipGraph { Iterator fieldItr = cd.getFields(); while( fieldItr.hasNext() ) { - FieldDescriptor fd = (FieldDescriptor) fieldItr.next(); - TypeDescriptor typeField = fd.getType(); - assert typeField != null; + FieldDescriptor fd = (FieldDescriptor) fieldItr.next(); + TypeDescriptor typeField = fd.getType(); + assert typeField != null; - if( ogCallee.hasFieldBeenUpdated(hrnPrimary, fd.getSymbol() ) ) { - clearReferenceEdgesFrom(hrnCaller, fd.getType(), fd.getSymbol(), false); - } + if( ogCallee.hasFieldBeenUpdated(hrnPrimary, fd.getSymbol() ) ) { + clearReferenceEdgesFrom(hrnCaller, fd.getType(), fd.getSymbol(), false); + } } cd = cd.getSuperDesc(); @@ -2037,7 +2037,7 @@ public class OwnershipGraph { while( itr.hasNext() ) { ReferenceEdge e = itr.next(); if( e.fieldEquals(field) && e.isInitialParam() ) { - return false; + return false; } } @@ -2062,23 +2062,23 @@ public class OwnershipGraph { ) { try { - writeGraph("debug1BeforeCall", - true, // write labels (variables) - true, // selectively hide intermediate temp vars - true, // prune unreachable heap regions - false, // show back edges to confirm graph validity - false, // show parameter indices (unmaintained!) - true, // hide subset reachability states - true); // hide edge taints - - ogCallee.writeGraph("debug0Callee", - true, // write labels (variables) - true, // selectively hide intermediate temp vars - true, // prune unreachable heap regions - false, // show back edges to confirm graph validity - false, // show parameter indices (unmaintained!) - true, // hide subset reachability states - true); // hide edge taints + writeGraph("debug1BeforeCall", + true, // write labels (variables) + true, // selectively hide intermediate temp vars + true, // prune unreachable heap regions + false, // show back edges to confirm graph validity + false, // show parameter indices (unmaintained!) + true, // hide subset reachability states + true); // hide edge taints + + ogCallee.writeGraph("debug0Callee", + true, // write labels (variables) + true, // selectively hide intermediate temp vars + true, // prune unreachable heap regions + false, // show back edges to confirm graph validity + false, // show parameter indices (unmaintained!) + true, // hide subset reachability states + true); // hide edge taints } catch( IOException e ) { } @@ -2122,8 +2122,8 @@ public class OwnershipGraph { Integer paramIndex = new Integer(i); if( !ogCallee.paramIndex2idPrimary.containsKey(paramIndex) ) { - // skip this immutable parameter - continue; + // skip this immutable parameter + continue; } // setup H (primary) @@ -2136,28 +2136,28 @@ public class OwnershipGraph { // setup J (primary->X) Iterator p2xItr = hrnPrimary.iteratorToReferencees(); while( p2xItr.hasNext() ) { - ReferenceEdge p2xEdge = p2xItr.next(); - - // we only care about initial parameter edges here - if( !p2xEdge.isInitialParam() ) { - continue; - } - - HeapRegionNode hrnDst = p2xEdge.getDst(); - - if( ogCallee.idPrimary2paramIndexSet.containsKey(hrnDst.getID() ) ) { - Iterator jItr = ogCallee.idPrimary2paramIndexSet.get(hrnDst.getID() ).iterator(); - while( jItr.hasNext() ) { - Integer j = jItr.next(); - paramIndex2rewriteJ_p2p.put(makeMapKey(i, j, p2xEdge.getField() ), - toShadowTokens(ogCallee, p2xEdge.getBeta() ) ); - } - - } else { - assert ogCallee.idSecondary2paramIndexSet.containsKey(hrnDst.getID() ); - paramIndex2rewriteJ_p2s.put(makeMapKey(i, p2xEdge.getField() ), - toShadowTokens(ogCallee, p2xEdge.getBeta() ) ); - } + ReferenceEdge p2xEdge = p2xItr.next(); + + // we only care about initial parameter edges here + if( !p2xEdge.isInitialParam() ) { + continue; + } + + HeapRegionNode hrnDst = p2xEdge.getDst(); + + if( ogCallee.idPrimary2paramIndexSet.containsKey(hrnDst.getID() ) ) { + Iterator jItr = ogCallee.idPrimary2paramIndexSet.get(hrnDst.getID() ).iterator(); + while( jItr.hasNext() ) { + Integer j = jItr.next(); + paramIndex2rewriteJ_p2p.put(makeMapKey(i, j, p2xEdge.getField() ), + toShadowTokens(ogCallee, p2xEdge.getBeta() ) ); + } + + } else { + assert ogCallee.idSecondary2paramIndexSet.containsKey(hrnDst.getID() ); + paramIndex2rewriteJ_p2s.put(makeMapKey(i, p2xEdge.getField() ), + toShadowTokens(ogCallee, p2xEdge.getBeta() ) ); + } } // setup K (primary) @@ -2175,18 +2175,18 @@ public class OwnershipGraph { ReachabilitySet K_p = new ReachabilitySet().makeCanonical(); ReachabilitySet K_p2 = new ReachabilitySet().makeCanonical(); if( s_i == null ) { - K_p = qBeta; + K_p = qBeta; } else { - // sort qBeta into K_p1 and K_p2 - Iterator ttsItr = qBeta.iterator(); - while( ttsItr.hasNext() ) { - TokenTupleSet tts = ttsItr.next(); - if( s_i != null && tts.containsBoth(p_i, s_i) ) { - K_p2 = K_p2.union(tts); - } else { - K_p = K_p.union(tts); - } - } + // sort qBeta into K_p1 and K_p2 + Iterator ttsItr = qBeta.iterator(); + while( ttsItr.hasNext() ) { + TokenTupleSet tts = ttsItr.next(); + if( s_i != null && tts.containsBoth(p_i, s_i) ) { + K_p2 = K_p2.union(tts); + } else { + K_p = K_p.union(tts); + } + } } paramIndex2rewriteK_p.put(paramIndex, K_p); paramIndex2rewriteK_p2.put(paramIndex, K_p2); @@ -2195,46 +2195,46 @@ public class OwnershipGraph { // if there is a secondary node, compute the rest of the rewrite rules if( ogCallee.paramIndex2idSecondary.containsKey(paramIndex) ) { - // setup H (secondary) - Integer idSecondary = ogCallee.paramIndex2idSecondary.get(paramIndex); - assert ogCallee.id2hrn.containsKey(idSecondary); - HeapRegionNode hrnSecondary = ogCallee.id2hrn.get(idSecondary); - assert hrnSecondary != null; - paramIndex2rewriteH_s.put(paramIndex, toShadowTokens(ogCallee, hrnSecondary.getAlpha() ) ); - - // setup J (secondary->X) - Iterator s2xItr = hrnSecondary.iteratorToReferencees(); - while( s2xItr.hasNext() ) { - ReferenceEdge s2xEdge = s2xItr.next(); - - if( !s2xEdge.isInitialParam() ) { - continue; - } - - HeapRegionNode hrnDst = s2xEdge.getDst(); - - if( ogCallee.idPrimary2paramIndexSet.containsKey(hrnDst.getID() ) ) { - Iterator jItr = ogCallee.idPrimary2paramIndexSet.get(hrnDst.getID() ).iterator(); - while( jItr.hasNext() ) { - Integer j = jItr.next(); - paramIndex2rewriteJ_s2p.put(i, toShadowTokens(ogCallee, s2xEdge.getBeta() ) ); - } - - } else { - assert ogCallee.idSecondary2paramIndexSet.containsKey(hrnDst.getID() ); - paramIndex2rewriteJ_s2s.put(i, toShadowTokens(ogCallee, s2xEdge.getBeta() ) ); - } - } - - // setup K (secondary) - TempDescriptor tdParamR = ogCallee.paramIndex2tdR.get(paramIndex); - assert tdParamR != null; - LabelNode lnParamR = ogCallee.td2ln.get(tdParamR); - assert lnParamR != null; - ReferenceEdge edgeSpecialR_i = lnParamR.getReferenceTo(hrnSecondary, null, null); - assert edgeSpecialR_i != null; - paramIndex2rewriteK_s.put(paramIndex, - toShadowTokens(ogCallee, edgeSpecialR_i.getBeta() ) ); + // setup H (secondary) + Integer idSecondary = ogCallee.paramIndex2idSecondary.get(paramIndex); + assert ogCallee.id2hrn.containsKey(idSecondary); + HeapRegionNode hrnSecondary = ogCallee.id2hrn.get(idSecondary); + assert hrnSecondary != null; + paramIndex2rewriteH_s.put(paramIndex, toShadowTokens(ogCallee, hrnSecondary.getAlpha() ) ); + + // setup J (secondary->X) + Iterator s2xItr = hrnSecondary.iteratorToReferencees(); + while( s2xItr.hasNext() ) { + ReferenceEdge s2xEdge = s2xItr.next(); + + if( !s2xEdge.isInitialParam() ) { + continue; + } + + HeapRegionNode hrnDst = s2xEdge.getDst(); + + if( ogCallee.idPrimary2paramIndexSet.containsKey(hrnDst.getID() ) ) { + Iterator jItr = ogCallee.idPrimary2paramIndexSet.get(hrnDst.getID() ).iterator(); + while( jItr.hasNext() ) { + Integer j = jItr.next(); + paramIndex2rewriteJ_s2p.put(i, toShadowTokens(ogCallee, s2xEdge.getBeta() ) ); + } + + } else { + assert ogCallee.idSecondary2paramIndexSet.containsKey(hrnDst.getID() ); + paramIndex2rewriteJ_s2s.put(i, toShadowTokens(ogCallee, s2xEdge.getBeta() ) ); + } + } + + // setup K (secondary) + TempDescriptor tdParamR = ogCallee.paramIndex2tdR.get(paramIndex); + assert tdParamR != null; + LabelNode lnParamR = ogCallee.td2ln.get(tdParamR); + assert lnParamR != null; + ReferenceEdge edgeSpecialR_i = lnParamR.getReferenceTo(hrnSecondary, null, null); + assert edgeSpecialR_i != null; + paramIndex2rewriteK_s.put(paramIndex, + toShadowTokens(ogCallee, edgeSpecialR_i.getBeta() ) ); } @@ -2250,19 +2250,19 @@ public class OwnershipGraph { // do a callee-effect strong update pre-pass here if( argTemp_i.getType().isClass() ) { - Iterator edgeItr = argLabel_i.iteratorToReferencees(); - while( edgeItr.hasNext() ) { - ReferenceEdge edge = edgeItr.next(); - HeapRegionNode hrn = edge.getDst(); - - if( (hrn.getNumReferencers() == 1) || // case 1 - (hrn.isSingleObject() && argLabel_i.getNumReferencees() == 1) // case 2 - ) { - if( !DISABLE_STRONG_UPDATES ) { - effectCalleeStrongUpdates(paramIndex, ogCallee, hrn); - } - } - } + Iterator edgeItr = argLabel_i.iteratorToReferencees(); + while( edgeItr.hasNext() ) { + ReferenceEdge edge = edgeItr.next(); + HeapRegionNode hrn = edge.getDst(); + + if( (hrn.getNumReferencers() == 1) || // case 1 + (hrn.isSingleObject() && argLabel_i.getNumReferencees() == 1) // case 2 + ) { + if( !DISABLE_STRONG_UPDATES ) { + effectCalleeStrongUpdates(paramIndex, ogCallee, hrn); + } + } + } } // then calculate the d and D rewrite rules @@ -2270,10 +2270,10 @@ public class OwnershipGraph { ReachabilitySet d_i_s = new ReachabilitySet().makeCanonical(); Iterator edgeItr = argLabel_i.iteratorToReferencees(); while( edgeItr.hasNext() ) { - ReferenceEdge edge = edgeItr.next(); + ReferenceEdge edge = edgeItr.next(); - d_i_p = d_i_p.union(edge.getBeta().intersection(edge.getDst().getAlpha() ) ); - d_i_s = d_i_s.union(edge.getBeta() ); + d_i_p = d_i_p.union(edge.getBeta().intersection(edge.getDst().getAlpha() ) ); + d_i_s = d_i_s.union(edge.getBeta() ); } paramIndex2rewrite_d_p.put(paramIndex, d_i_p); paramIndex2rewrite_d_s.put(paramIndex, d_i_s); @@ -2310,40 +2310,40 @@ public class OwnershipGraph { // find all reachable nodes starting with label referencees Iterator edgeArgItr = lnArg_i.iteratorToReferencees(); while( edgeArgItr.hasNext() ) { - ReferenceEdge edge = edgeArgItr.next(); - HeapRegionNode hrn = edge.getDst(); - - dr.add(hrn); - - if( lnArg_i.getNumReferencees() == 1 && hrn.isSingleObject() ) { - defParamObj.add(hrn); - } - - Iterator edgeHrnItr = hrn.iteratorToReferencees(); - while( edgeHrnItr.hasNext() ) { - ReferenceEdge edger = edgeHrnItr.next(); - todo.add(edger.getDst() ); - } - - // then follow links until all reachable nodes have been found - while( !todo.isEmpty() ) { - HeapRegionNode hrnr = todo.iterator().next(); - todo.remove(hrnr); - - r.add(hrnr); - - Iterator edgeItr = hrnr.iteratorToReferencees(); - while( edgeItr.hasNext() ) { - ReferenceEdge edger = edgeItr.next(); - if( !r.contains(edger.getDst() ) ) { - todo.add(edger.getDst() ); - } - } - } - - if( hrn.isSingleObject() ) { - r.remove(hrn); - } + ReferenceEdge edge = edgeArgItr.next(); + HeapRegionNode hrn = edge.getDst(); + + dr.add(hrn); + + if( lnArg_i.getNumReferencees() == 1 && hrn.isSingleObject() ) { + defParamObj.add(hrn); + } + + Iterator edgeHrnItr = hrn.iteratorToReferencees(); + while( edgeHrnItr.hasNext() ) { + ReferenceEdge edger = edgeHrnItr.next(); + todo.add(edger.getDst() ); + } + + // then follow links until all reachable nodes have been found + while( !todo.isEmpty() ) { + HeapRegionNode hrnr = todo.iterator().next(); + todo.remove(hrnr); + + r.add(hrnr); + + Iterator edgeItr = hrnr.iteratorToReferencees(); + while( edgeItr.hasNext() ) { + ReferenceEdge edger = edgeItr.next(); + if( !r.contains(edger.getDst() ) ) { + todo.add(edger.getDst() ); + } + } + } + + if( hrn.isSingleObject() ) { + r.remove(hrn); + } } pi2dr.put(index, dr); @@ -2359,29 +2359,29 @@ public class OwnershipGraph { // report primary parameter object mappings mapItr = pi2dr.entrySet().iterator(); while( mapItr.hasNext() ) { - Map.Entry me = (Map.Entry)mapItr.next(); - Integer paramIndex = (Integer) me.getKey(); - Set hrnAset = (Set)me.getValue(); - - Iterator hrnItr = hrnAset.iterator(); - while( hrnItr.hasNext() ) { - HeapRegionNode hrnA = hrnItr.next(); - pd.mapRegionToParamObject(hrnA, paramIndex); - } + Map.Entry me = (Map.Entry)mapItr.next(); + Integer paramIndex = (Integer) me.getKey(); + Set hrnAset = (Set)me.getValue(); + + Iterator hrnItr = hrnAset.iterator(); + while( hrnItr.hasNext() ) { + HeapRegionNode hrnA = hrnItr.next(); + pd.mapRegionToParamObject(hrnA, paramIndex); + } } // report parameter-reachable mappings mapItr = pi2r.entrySet().iterator(); while( mapItr.hasNext() ) { - Map.Entry me = (Map.Entry)mapItr.next(); - Integer paramIndex = (Integer) me.getKey(); - Set hrnRset = (Set)me.getValue(); - - Iterator hrnItr = hrnRset.iterator(); - while( hrnItr.hasNext() ) { - HeapRegionNode hrnR = hrnItr.next(); - pd.mapRegionToParamReachable(hrnR, paramIndex); - } + Map.Entry me = (Map.Entry)mapItr.next(); + Integer paramIndex = (Integer) me.getKey(); + Set hrnRset = (Set)me.getValue(); + + Iterator hrnItr = hrnRset.iterator(); + while( hrnItr.hasNext() ) { + HeapRegionNode hrnR = hrnItr.next(); + pd.mapRegionToParamReachable(hrnR, paramIndex); + } } // and we're done in this method for special param decomp mode @@ -2421,141 +2421,141 @@ public class OwnershipGraph { Set dr = pi2dr.get(index); Iterator hrnItr = dr.iterator(); while( hrnItr.hasNext() ) { - // this heap region is definitely an "a_i" or primary by virtue of being in dr - HeapRegionNode hrn = hrnItr.next(); - - tokens2states.clear(); - tokens2states.put(p_i, hrn.getAlpha() ); - - rewriteCallerReachability(index, - hrn, - null, - paramIndex2rewriteH_p.get(index), - tokens2states, - paramIndex2rewrite_d_p, - paramIndex2rewrite_d_s, - paramIndex2rewriteD, - ogCallee, - false, - null); - - nodesWithNewAlpha.add(hrn); - - // sort edges - Iterator edgeItr = hrn.iteratorToReferencers(); - while( edgeItr.hasNext() ) { - ReferenceEdge edge = edgeItr.next(); - OwnershipNode on = edge.getSrc(); - - boolean edge_classified = false; - - - if( on instanceof HeapRegionNode ) { - // hrn0 may be "a_j" and/or "r_j" or even neither - HeapRegionNode hrn0 = (HeapRegionNode) on; - - Iterator itr = pi2dr.entrySet().iterator(); - while( itr.hasNext() ) { - Map.Entry mo = (Map.Entry)itr.next(); - Integer pi = (Integer) mo.getKey(); - Set dr_i = (Set)mo.getValue(); - - if( dr_i.contains(hrn0) ) { - addEdgeIndexPair(edges_p2p, pi, edge, index); - edge_classified = true; - } - } - - itr = pi2r.entrySet().iterator(); - while( itr.hasNext() ) { - Map.Entry mo = (Map.Entry)itr.next(); - Integer pi = (Integer) mo.getKey(); - Set r_i = (Set)mo.getValue(); - - if( r_i.contains(hrn0) ) { - addEdgeIndexPair(edges_s2p, pi, edge, index); - edge_classified = true; - } - } - } - - // all of these edges are upstream of directly reachable objects - if( !edge_classified ) { - addEdgeIndexPair(edges_up_dr, index, edge, index); - } - } + // this heap region is definitely an "a_i" or primary by virtue of being in dr + HeapRegionNode hrn = hrnItr.next(); + + tokens2states.clear(); + tokens2states.put(p_i, hrn.getAlpha() ); + + rewriteCallerReachability(index, + hrn, + null, + paramIndex2rewriteH_p.get(index), + tokens2states, + paramIndex2rewrite_d_p, + paramIndex2rewrite_d_s, + paramIndex2rewriteD, + ogCallee, + false, + null); + + nodesWithNewAlpha.add(hrn); + + // sort edges + Iterator edgeItr = hrn.iteratorToReferencers(); + while( edgeItr.hasNext() ) { + ReferenceEdge edge = edgeItr.next(); + OwnershipNode on = edge.getSrc(); + + boolean edge_classified = false; + + + if( on instanceof HeapRegionNode ) { + // hrn0 may be "a_j" and/or "r_j" or even neither + HeapRegionNode hrn0 = (HeapRegionNode) on; + + Iterator itr = pi2dr.entrySet().iterator(); + while( itr.hasNext() ) { + Map.Entry mo = (Map.Entry)itr.next(); + Integer pi = (Integer) mo.getKey(); + Set dr_i = (Set)mo.getValue(); + + if( dr_i.contains(hrn0) ) { + addEdgeIndexPair(edges_p2p, pi, edge, index); + edge_classified = true; + } + } + + itr = pi2r.entrySet().iterator(); + while( itr.hasNext() ) { + Map.Entry mo = (Map.Entry)itr.next(); + Integer pi = (Integer) mo.getKey(); + Set r_i = (Set)mo.getValue(); + + if( r_i.contains(hrn0) ) { + addEdgeIndexPair(edges_s2p, pi, edge, index); + edge_classified = true; + } + } + } + + // all of these edges are upstream of directly reachable objects + if( !edge_classified ) { + addEdgeIndexPair(edges_up_dr, index, edge, index); + } + } } Set r = pi2r.get(index); hrnItr = r.iterator(); while( hrnItr.hasNext() ) { - // this heap region is definitely an "r_i" or secondary by virtue of being in r - HeapRegionNode hrn = hrnItr.next(); - - if( paramIndex2rewriteH_s.containsKey(index) ) { - - tokens2states.clear(); - tokens2states.put(p_i, new ReachabilitySet().makeCanonical() ); - tokens2states.put(s_i, hrn.getAlpha() ); - - rewriteCallerReachability(index, - hrn, - null, - paramIndex2rewriteH_s.get(index), - tokens2states, - paramIndex2rewrite_d_p, - paramIndex2rewrite_d_s, - paramIndex2rewriteD, - ogCallee, - false, - null); - - nodesWithNewAlpha.add(hrn); - } - - // sort edges - Iterator edgeItr = hrn.iteratorToReferencers(); - while( edgeItr.hasNext() ) { - ReferenceEdge edge = edgeItr.next(); - OwnershipNode on = edge.getSrc(); - - boolean edge_classified = false; - - if( on instanceof HeapRegionNode ) { - // hrn0 may be "a_j" and/or "r_j" or even neither - HeapRegionNode hrn0 = (HeapRegionNode) on; - - Iterator itr = pi2dr.entrySet().iterator(); - while( itr.hasNext() ) { - Map.Entry mo = (Map.Entry)itr.next(); - Integer pi = (Integer) mo.getKey(); - Set dr_i = (Set)mo.getValue(); - - if( dr_i.contains(hrn0) ) { - addEdgeIndexPair(edges_p2s, pi, edge, index); - edge_classified = true; - } - } - - itr = pi2r.entrySet().iterator(); - while( itr.hasNext() ) { - Map.Entry mo = (Map.Entry)itr.next(); - Integer pi = (Integer) mo.getKey(); - Set r_i = (Set)mo.getValue(); - - if( r_i.contains(hrn0) ) { - addEdgeIndexPair(edges_s2s, pi, edge, index); - edge_classified = true; - } - } - } - - // these edges are all upstream of some reachable node - if( !edge_classified ) { - addEdgeIndexPair(edges_up_r, index, edge, index); - } - } + // this heap region is definitely an "r_i" or secondary by virtue of being in r + HeapRegionNode hrn = hrnItr.next(); + + if( paramIndex2rewriteH_s.containsKey(index) ) { + + tokens2states.clear(); + tokens2states.put(p_i, new ReachabilitySet().makeCanonical() ); + tokens2states.put(s_i, hrn.getAlpha() ); + + rewriteCallerReachability(index, + hrn, + null, + paramIndex2rewriteH_s.get(index), + tokens2states, + paramIndex2rewrite_d_p, + paramIndex2rewrite_d_s, + paramIndex2rewriteD, + ogCallee, + false, + null); + + nodesWithNewAlpha.add(hrn); + } + + // sort edges + Iterator edgeItr = hrn.iteratorToReferencers(); + while( edgeItr.hasNext() ) { + ReferenceEdge edge = edgeItr.next(); + OwnershipNode on = edge.getSrc(); + + boolean edge_classified = false; + + if( on instanceof HeapRegionNode ) { + // hrn0 may be "a_j" and/or "r_j" or even neither + HeapRegionNode hrn0 = (HeapRegionNode) on; + + Iterator itr = pi2dr.entrySet().iterator(); + while( itr.hasNext() ) { + Map.Entry mo = (Map.Entry)itr.next(); + Integer pi = (Integer) mo.getKey(); + Set dr_i = (Set)mo.getValue(); + + if( dr_i.contains(hrn0) ) { + addEdgeIndexPair(edges_p2s, pi, edge, index); + edge_classified = true; + } + } + + itr = pi2r.entrySet().iterator(); + while( itr.hasNext() ) { + Map.Entry mo = (Map.Entry)itr.next(); + Integer pi = (Integer) mo.getKey(); + Set r_i = (Set)mo.getValue(); + + if( r_i.contains(hrn0) ) { + addEdgeIndexPair(edges_s2s, pi, edge, index); + edge_classified = true; + } + } + } + + // these edges are all upstream of some reachable node + if( !edge_classified ) { + addEdgeIndexPair(edges_up_r, index, edge, index); + } + } } } @@ -2571,135 +2571,135 @@ public class OwnershipGraph { // update reachable edges Iterator edgeItr = edges_p2p.get(index).iterator(); while( edgeItr.hasNext() ) { - Vector mo = (Vector) edgeItr.next(); - ReferenceEdge edge = (ReferenceEdge) mo.get(0); - Integer indexJ = (Integer) mo.get(1); - - if( !paramIndex2rewriteJ_p2p.containsKey(makeMapKey(index, - indexJ, - edge.getField() ) ) ) { - continue; - } - - TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ); - assert p_j != null; - - tokens2states.clear(); - tokens2states.put(p_j, edge.getBeta() ); - - rewriteCallerReachability(index, - null, - edge, - paramIndex2rewriteJ_p2p.get(makeMapKey(index, - indexJ, - edge.getField() ) ), - tokens2states, - paramIndex2rewrite_d_p, - paramIndex2rewrite_d_s, - paramIndex2rewriteD, - ogCallee, - false, - null); - - edgesWithNewBeta.add(edge); + Vector mo = (Vector) edgeItr.next(); + ReferenceEdge edge = (ReferenceEdge) mo.get(0); + Integer indexJ = (Integer) mo.get(1); + + if( !paramIndex2rewriteJ_p2p.containsKey(makeMapKey(index, + indexJ, + edge.getField() ) ) ) { + continue; + } + + TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ); + assert p_j != null; + + tokens2states.clear(); + tokens2states.put(p_j, edge.getBeta() ); + + rewriteCallerReachability(index, + null, + edge, + paramIndex2rewriteJ_p2p.get(makeMapKey(index, + indexJ, + edge.getField() ) ), + tokens2states, + paramIndex2rewrite_d_p, + paramIndex2rewrite_d_s, + paramIndex2rewriteD, + ogCallee, + false, + null); + + edgesWithNewBeta.add(edge); } edgeItr = edges_p2s.get(index).iterator(); while( edgeItr.hasNext() ) { - Vector mo = (Vector) edgeItr.next(); - ReferenceEdge edge = (ReferenceEdge) mo.get(0); - Integer indexJ = (Integer) mo.get(1); - - if( !paramIndex2rewriteJ_p2s.containsKey(makeMapKey(index, - edge.getField() ) ) ) { - continue; - } - - TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ); - assert s_j != null; - - tokens2states.clear(); - tokens2states.put(s_j, edge.getBeta() ); - - rewriteCallerReachability(index, - null, - edge, - paramIndex2rewriteJ_p2s.get(makeMapKey(index, - edge.getField() ) ), - tokens2states, - paramIndex2rewrite_d_p, - paramIndex2rewrite_d_s, - paramIndex2rewriteD, - ogCallee, - false, - null); - - edgesWithNewBeta.add(edge); + Vector mo = (Vector) edgeItr.next(); + ReferenceEdge edge = (ReferenceEdge) mo.get(0); + Integer indexJ = (Integer) mo.get(1); + + if( !paramIndex2rewriteJ_p2s.containsKey(makeMapKey(index, + edge.getField() ) ) ) { + continue; + } + + TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ); + assert s_j != null; + + tokens2states.clear(); + tokens2states.put(s_j, edge.getBeta() ); + + rewriteCallerReachability(index, + null, + edge, + paramIndex2rewriteJ_p2s.get(makeMapKey(index, + edge.getField() ) ), + tokens2states, + paramIndex2rewrite_d_p, + paramIndex2rewrite_d_s, + paramIndex2rewriteD, + ogCallee, + false, + null); + + edgesWithNewBeta.add(edge); } edgeItr = edges_s2p.get(index).iterator(); while( edgeItr.hasNext() ) { - Vector mo = (Vector) edgeItr.next(); - ReferenceEdge edge = (ReferenceEdge) mo.get(0); - Integer indexJ = (Integer) mo.get(1); - - if( !paramIndex2rewriteJ_s2p.containsKey(index) ) { - continue; - } - - TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ); - assert p_j != null; - - tokens2states.clear(); - tokens2states.put(p_j, edge.getBeta() ); - - rewriteCallerReachability(index, - null, - edge, - paramIndex2rewriteJ_s2p.get(index), - tokens2states, - paramIndex2rewrite_d_p, - paramIndex2rewrite_d_s, - paramIndex2rewriteD, - ogCallee, - false, - null); - - edgesWithNewBeta.add(edge); + Vector mo = (Vector) edgeItr.next(); + ReferenceEdge edge = (ReferenceEdge) mo.get(0); + Integer indexJ = (Integer) mo.get(1); + + if( !paramIndex2rewriteJ_s2p.containsKey(index) ) { + continue; + } + + TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ); + assert p_j != null; + + tokens2states.clear(); + tokens2states.put(p_j, edge.getBeta() ); + + rewriteCallerReachability(index, + null, + edge, + paramIndex2rewriteJ_s2p.get(index), + tokens2states, + paramIndex2rewrite_d_p, + paramIndex2rewrite_d_s, + paramIndex2rewriteD, + ogCallee, + false, + null); + + edgesWithNewBeta.add(edge); } edgeItr = edges_s2s.get(index).iterator(); while( edgeItr.hasNext() ) { - Vector mo = (Vector) edgeItr.next(); - ReferenceEdge edge = (ReferenceEdge) mo.get(0); - Integer indexJ = (Integer) mo.get(1); - - if( !paramIndex2rewriteJ_s2s.containsKey(index) ) { - continue; - } - - TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ); - assert s_j != null; - - tokens2states.clear(); - tokens2states.put(s_j, edge.getBeta() ); - - rewriteCallerReachability(index, - null, - edge, - paramIndex2rewriteJ_s2s.get(index), - tokens2states, - paramIndex2rewrite_d_p, - paramIndex2rewrite_d_s, - paramIndex2rewriteD, - ogCallee, - false, - null); - - edgesWithNewBeta.add(edge); + Vector mo = (Vector) edgeItr.next(); + ReferenceEdge edge = (ReferenceEdge) mo.get(0); + Integer indexJ = (Integer) mo.get(1); + + if( !paramIndex2rewriteJ_s2s.containsKey(index) ) { + continue; + } + + TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ); + assert s_j != null; + + tokens2states.clear(); + tokens2states.put(s_j, edge.getBeta() ); + + rewriteCallerReachability(index, + null, + edge, + paramIndex2rewriteJ_s2s.get(index), + tokens2states, + paramIndex2rewrite_d_p, + paramIndex2rewrite_d_s, + paramIndex2rewriteD, + ogCallee, + false, + null); + + edgesWithNewBeta.add(edge); } @@ -2712,50 +2712,50 @@ public class OwnershipGraph { edgeItr = edges_up_dr.get(index).iterator(); while( edgeItr.hasNext() ) { - Vector mo = (Vector) edgeItr.next(); - ReferenceEdge edge = (ReferenceEdge) mo.get(0); - Integer indexJ = (Integer) mo.get(1); - - edgesDirectlyUpstream.add(edge); - - TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ); - assert p_j != null; - - // start with K_p2 and p_j - tokens2states.clear(); - tokens2states.put(p_j, edge.getBeta() ); - - rewriteCallerReachability(index, - null, - edge, - paramIndex2rewriteK_p2.get(index), - tokens2states, - paramIndex2rewrite_d_p, - paramIndex2rewrite_d_s, - paramIndex2rewriteD, - ogCallee, - true, - edgeUpstreamPlannedChanges); - - // and add in s_j, if required, and do K_p - TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ); - if( s_j != null ) { - tokens2states.put(s_j, edge.getBeta() ); - } - - rewriteCallerReachability(index, - null, - edge, - paramIndex2rewriteK_p.get(index), - tokens2states, - paramIndex2rewrite_d_p, - paramIndex2rewrite_d_s, - paramIndex2rewriteD, - ogCallee, - true, - edgeUpstreamPlannedChanges); - - edgesWithNewBeta.add(edge); + Vector mo = (Vector) edgeItr.next(); + ReferenceEdge edge = (ReferenceEdge) mo.get(0); + Integer indexJ = (Integer) mo.get(1); + + edgesDirectlyUpstream.add(edge); + + TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ); + assert p_j != null; + + // start with K_p2 and p_j + tokens2states.clear(); + tokens2states.put(p_j, edge.getBeta() ); + + rewriteCallerReachability(index, + null, + edge, + paramIndex2rewriteK_p2.get(index), + tokens2states, + paramIndex2rewrite_d_p, + paramIndex2rewrite_d_s, + paramIndex2rewriteD, + ogCallee, + true, + edgeUpstreamPlannedChanges); + + // and add in s_j, if required, and do K_p + TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ); + if( s_j != null ) { + tokens2states.put(s_j, edge.getBeta() ); + } + + rewriteCallerReachability(index, + null, + edge, + paramIndex2rewriteK_p.get(index), + tokens2states, + paramIndex2rewrite_d_p, + paramIndex2rewrite_d_s, + paramIndex2rewriteD, + ogCallee, + true, + edgeUpstreamPlannedChanges); + + edgesWithNewBeta.add(edge); } propagateTokensOverEdges(edgesDirectlyUpstream, @@ -2772,39 +2772,39 @@ public class OwnershipGraph { edgeItr = edges_up_r.get(index).iterator(); while( edgeItr.hasNext() ) { - Vector mo = (Vector) edgeItr.next(); - ReferenceEdge edge = (ReferenceEdge) mo.get(0); - Integer indexJ = (Integer) mo.get(1); - - if( !paramIndex2rewriteK_s.containsKey(index) ) { - continue; - } - - edgesUpstream.add(edge); - - TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ); - assert p_j != null; - - TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ); - assert s_j != null; - - tokens2states.clear(); - tokens2states.put(p_j, rsWttsEmpty); - tokens2states.put(s_j, edge.getBeta() ); - - rewriteCallerReachability(index, - null, - edge, - paramIndex2rewriteK_s.get(index), - tokens2states, - paramIndex2rewrite_d_p, - paramIndex2rewrite_d_s, - paramIndex2rewriteD, - ogCallee, - true, - edgeUpstreamPlannedChanges); - - edgesWithNewBeta.add(edge); + Vector mo = (Vector) edgeItr.next(); + ReferenceEdge edge = (ReferenceEdge) mo.get(0); + Integer indexJ = (Integer) mo.get(1); + + if( !paramIndex2rewriteK_s.containsKey(index) ) { + continue; + } + + edgesUpstream.add(edge); + + TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ); + assert p_j != null; + + TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ); + assert s_j != null; + + tokens2states.clear(); + tokens2states.put(p_j, rsWttsEmpty); + tokens2states.put(s_j, edge.getBeta() ); + + rewriteCallerReachability(index, + null, + edge, + paramIndex2rewriteK_s.get(index), + tokens2states, + paramIndex2rewrite_d_p, + paramIndex2rewrite_d_s, + paramIndex2rewriteD, + ogCallee, + true, + edgeUpstreamPlannedChanges); + + edgesWithNewBeta.add(edge); } propagateTokensOverEdges(edgesUpstream, @@ -2871,33 +2871,33 @@ public class OwnershipGraph { for( int i = 0; i < allocSite.getAllocationDepth(); ++i ) { - Integer idIth = allocSite.getIthOldest(i); - assert id2hrn.containsKey(idIth); - HeapRegionNode hrnIth = id2hrn.get(idIth); - - Integer idShadowIth = -(allocSite.getIthOldest(i)); - assert id2hrn.containsKey(idShadowIth); - HeapRegionNode hrnIthShadow = id2hrn.get(idShadowIth); - assert hrnIthShadow.getNumReferencers() == 0; - assert hrnIthShadow.getNumReferencees() == 0; - - assert ogCallee.id2hrn.containsKey(idIth); - HeapRegionNode hrnIthCallee = ogCallee.id2hrn.get(idIth); - hrnIthShadow.setAlpha(toShadowTokens(ogCallee, hrnIthCallee.getAlpha() ) ); - - rewriteCallerReachability(bogusIndex, - hrnIthShadow, - null, - funcScriptR(hrnIthShadow.getAlpha(), ogCallee, mc), - tokens2statesEmpty, - paramIndex2rewrite_d_p, - paramIndex2rewrite_d_s, - paramIndex2rewriteD, - ogCallee, - false, - null); - - hrnIthShadow.applyAlphaNew(); + Integer idIth = allocSite.getIthOldest(i); + assert id2hrn.containsKey(idIth); + HeapRegionNode hrnIth = id2hrn.get(idIth); + + Integer idShadowIth = -(allocSite.getIthOldest(i)); + assert id2hrn.containsKey(idShadowIth); + HeapRegionNode hrnIthShadow = id2hrn.get(idShadowIth); + assert hrnIthShadow.getNumReferencers() == 0; + assert hrnIthShadow.getNumReferencees() == 0; + + assert ogCallee.id2hrn.containsKey(idIth); + HeapRegionNode hrnIthCallee = ogCallee.id2hrn.get(idIth); + hrnIthShadow.setAlpha(toShadowTokens(ogCallee, hrnIthCallee.getAlpha() ) ); + + rewriteCallerReachability(bogusIndex, + hrnIthShadow, + null, + funcScriptR(hrnIthShadow.getAlpha(), ogCallee, mc), + tokens2statesEmpty, + paramIndex2rewrite_d_p, + paramIndex2rewrite_d_s, + paramIndex2rewriteD, + ogCallee, + false, + null); + + hrnIthShadow.applyAlphaNew(); } } @@ -2915,150 +2915,150 @@ public class OwnershipGraph { Iterator heapRegionsItrCallee = hrnCallee.iteratorToReferencees(); while( heapRegionsItrCallee.hasNext() ) { - ReferenceEdge edgeCallee = heapRegionsItrCallee.next(); - HeapRegionNode hrnChildCallee = edgeCallee.getDst(); - Integer idChildCallee = hrnChildCallee.getID(); - - // only address this edge if it is not a special initial edge - if( !edgeCallee.isInitialParam() ) { - - // now we know that in the callee method's ownership graph - // there is a heap region->heap region reference edge given - // by heap region pointers: - // hrnCallee -> heapChildCallee - // - // or by the ownership-graph independent ID's: - // idCallee -> idChildCallee - - // make the edge with src and dst so beta info is - // calculated once, then copy it for each new edge in caller - - ReferenceEdge edgeNewInCallerTemplate = new ReferenceEdge(null, - null, - edgeCallee.getType(), - edgeCallee.getField(), - false, - funcScriptR(toShadowTokens(ogCallee, - edgeCallee.getBeta() - ), - ogCallee, - mc) - ); - - rewriteCallerReachability(bogusIndex, - null, - edgeNewInCallerTemplate, - edgeNewInCallerTemplate.getBeta(), - tokens2statesEmpty, - paramIndex2rewrite_d_p, - paramIndex2rewrite_d_s, - paramIndex2rewriteD, - ogCallee, - false, - null); - - edgeNewInCallerTemplate.applyBetaNew(); - - - // So now make a set of possible source heaps in the caller graph - // and a set of destination heaps in the caller graph, and make - // a reference edge in the caller for every possible (src,dst) pair - HashSet possibleCallerSrcs = - getHRNSetThatPossiblyMapToCalleeHRN(ogCallee, - (HeapRegionNode) edgeCallee.getSrc(), - pi2dr, - pi2r); - - HashSet possibleCallerDsts = - getHRNSetThatPossiblyMapToCalleeHRN(ogCallee, - edgeCallee.getDst(), - pi2dr, - pi2r); - - // make every possible pair of {srcSet} -> {dstSet} edges in the caller - Iterator srcItr = possibleCallerSrcs.iterator(); - while( srcItr.hasNext() ) { - HeapRegionNode src = (HeapRegionNode) srcItr.next(); - - if( !hasMatchingField(src, edgeCallee) ) { - // prune this source node possibility - continue; - } - - Iterator dstItr = possibleCallerDsts.iterator(); - while( dstItr.hasNext() ) { - HeapRegionNode dst = (HeapRegionNode) dstItr.next(); - - if( !hasMatchingType(edgeCallee, dst) ) { - // prune - continue; - } - - - /* - //// KEEP THIS HACK AROUND FOR EXPERIMENTING WITH EDGE REMOVAL - TypeDescriptor tdX = src.getType(); - TypeDescriptor tdY = dst.getType(); - if( tdX != null && tdY != null ) { - if( tdX.toPrettyString().equals( "Object[]" ) && - tdY.toPrettyString().equals( "D2" ) ) { - System.out.println( "Skipping an edge from Object[] -> D2 during call mapping" ); - continue; - } - if( tdX.toPrettyString().equals( "Object[]" ) && - tdY.toPrettyString().equals( "MessageList" ) ) { - System.out.println( "Skipping an edge from Object[] -> MessageList during call mapping" ); - continue; - } - } - */ - - - // otherwise the caller src and dst pair can match the edge, so make it - TypeDescriptor tdNewEdge = - mostSpecificType(edgeCallee.getType(), - hrnChildCallee.getType(), - dst.getType() - ); - - ReferenceEdge edgeNewInCaller = edgeNewInCallerTemplate.copy(); - edgeNewInCaller.setSrc(src); - edgeNewInCaller.setDst(dst); - edgeNewInCaller.setType(tdNewEdge); - - - // handle taint info if callee created this edge - // added by eom - Set pParamSet=idPrimary2paramIndexSet.get(dst.getID()); - Set sParamSet=idSecondary2paramIndexSet.get(dst.getID()); - HashSet paramSet=new HashSet(); - if(pParamSet!=null) { - paramSet.addAll(pParamSet); - } - if(sParamSet!=null) { - paramSet.addAll(sParamSet); - } - Iterator paramIter=paramSet.iterator(); - int newTaintIdentifier=0; - while(paramIter.hasNext()) { - Integer paramIdx=paramIter.next(); - edgeNewInCaller.tainedBy(paramIdx); - } - - ReferenceEdge edgeExisting = src.getReferenceTo(dst, - edgeNewInCaller.getType(), - edgeNewInCaller.getField() ); - if( edgeExisting == null ) { - // if this edge doesn't exist in the caller, create it - addReferenceEdge(src, dst, edgeNewInCaller); - - } else { - // if it already exists, merge with it - edgeExisting.setBeta(edgeExisting.getBeta().union(edgeNewInCaller.getBeta() ) ); - } - } - } - } + ReferenceEdge edgeCallee = heapRegionsItrCallee.next(); + HeapRegionNode hrnChildCallee = edgeCallee.getDst(); + Integer idChildCallee = hrnChildCallee.getID(); + + // only address this edge if it is not a special initial edge + if( !edgeCallee.isInitialParam() ) { + + // now we know that in the callee method's ownership graph + // there is a heap region->heap region reference edge given + // by heap region pointers: + // hrnCallee -> heapChildCallee + // + // or by the ownership-graph independent ID's: + // idCallee -> idChildCallee + + // make the edge with src and dst so beta info is + // calculated once, then copy it for each new edge in caller + + ReferenceEdge edgeNewInCallerTemplate = new ReferenceEdge(null, + null, + edgeCallee.getType(), + edgeCallee.getField(), + false, + funcScriptR(toShadowTokens(ogCallee, + edgeCallee.getBeta() + ), + ogCallee, + mc) + ); + + rewriteCallerReachability(bogusIndex, + null, + edgeNewInCallerTemplate, + edgeNewInCallerTemplate.getBeta(), + tokens2statesEmpty, + paramIndex2rewrite_d_p, + paramIndex2rewrite_d_s, + paramIndex2rewriteD, + ogCallee, + false, + null); + + edgeNewInCallerTemplate.applyBetaNew(); + + + // So now make a set of possible source heaps in the caller graph + // and a set of destination heaps in the caller graph, and make + // a reference edge in the caller for every possible (src,dst) pair + HashSet possibleCallerSrcs = + getHRNSetThatPossiblyMapToCalleeHRN(ogCallee, + (HeapRegionNode) edgeCallee.getSrc(), + pi2dr, + pi2r); + + HashSet possibleCallerDsts = + getHRNSetThatPossiblyMapToCalleeHRN(ogCallee, + edgeCallee.getDst(), + pi2dr, + pi2r); + + // make every possible pair of {srcSet} -> {dstSet} edges in the caller + Iterator srcItr = possibleCallerSrcs.iterator(); + while( srcItr.hasNext() ) { + HeapRegionNode src = (HeapRegionNode) srcItr.next(); + + if( !hasMatchingField(src, edgeCallee) ) { + // prune this source node possibility + continue; + } + + Iterator dstItr = possibleCallerDsts.iterator(); + while( dstItr.hasNext() ) { + HeapRegionNode dst = (HeapRegionNode) dstItr.next(); + + if( !hasMatchingType(edgeCallee, dst) ) { + // prune + continue; + } + + + /* + //// KEEP THIS HACK AROUND FOR EXPERIMENTING WITH EDGE REMOVAL + TypeDescriptor tdX = src.getType(); + TypeDescriptor tdY = dst.getType(); + if( tdX != null && tdY != null ) { + if( tdX.toPrettyString().equals( "Object[]" ) && + tdY.toPrettyString().equals( "D2" ) ) { + System.out.println( "Skipping an edge from Object[] -> D2 during call mapping" ); + continue; + } + if( tdX.toPrettyString().equals( "Object[]" ) && + tdY.toPrettyString().equals( "MessageList" ) ) { + System.out.println( "Skipping an edge from Object[] -> MessageList during call mapping" ); + continue; + } + } + */ + + + // otherwise the caller src and dst pair can match the edge, so make it + TypeDescriptor tdNewEdge = + mostSpecificType(edgeCallee.getType(), + hrnChildCallee.getType(), + dst.getType() + ); + + ReferenceEdge edgeNewInCaller = edgeNewInCallerTemplate.copy(); + edgeNewInCaller.setSrc(src); + edgeNewInCaller.setDst(dst); + edgeNewInCaller.setType(tdNewEdge); + + + // handle taint info if callee created this edge + // added by eom + Set pParamSet=idPrimary2paramIndexSet.get(dst.getID()); + Set sParamSet=idSecondary2paramIndexSet.get(dst.getID()); + HashSet paramSet=new HashSet(); + if(pParamSet!=null) { + paramSet.addAll(pParamSet); + } + if(sParamSet!=null) { + paramSet.addAll(sParamSet); + } + Iterator paramIter=paramSet.iterator(); + int newTaintIdentifier=0; + while(paramIter.hasNext()) { + Integer paramIdx=paramIter.next(); + edgeNewInCaller.tainedBy(paramIdx); + } + + ReferenceEdge edgeExisting = src.getReferenceTo(dst, + edgeNewInCaller.getType(), + edgeNewInCaller.getField() ); + if( edgeExisting == null ) { + // if this edge doesn't exist in the caller, create it + addReferenceEdge(src, dst, edgeNewInCaller); + + } else { + // if it already exists, merge with it + edgeExisting.setBeta(edgeExisting.getBeta().union(edgeNewInCaller.getBeta() ) ); + } + } + } + } } } @@ -3074,92 +3074,92 @@ public class OwnershipGraph { LabelNode lnReturnCallee = ogCallee.getLabelNodeFromTemp(tdReturn); Iterator edgeCalleeItr = lnReturnCallee.iteratorToReferencees(); while( edgeCalleeItr.hasNext() ) { - ReferenceEdge edgeCallee = edgeCalleeItr.next(); - HeapRegionNode hrnChildCallee = edgeCallee.getDst(); - - // some edge types are not possible return values when we can - // see what type variable we are assigning it to - if( !isSuperiorType(returnTemp.getType(), edgeCallee.getType() ) ) { - System.out.println("*** NOT EXPECTING TO SEE THIS: Throwing out "+edgeCallee+" for return temp "+returnTemp); - // prune - continue; - } - - ReferenceEdge edgeNewInCallerTemplate = new ReferenceEdge(null, - null, - edgeCallee.getType(), - edgeCallee.getField(), - false, - funcScriptR(toShadowTokens(ogCallee, - edgeCallee.getBeta() ), - ogCallee, - mc) - ); - rewriteCallerReachability(bogusIndex, - null, - edgeNewInCallerTemplate, - edgeNewInCallerTemplate.getBeta(), - tokens2statesEmpty, - paramIndex2rewrite_d_p, - paramIndex2rewrite_d_s, - paramIndex2rewriteD, - ogCallee, - false, - null); - - edgeNewInCallerTemplate.applyBetaNew(); - - - HashSet assignCallerRhs = - getHRNSetThatPossiblyMapToCalleeHRN(ogCallee, - edgeCallee.getDst(), - pi2dr, - pi2r); - - Iterator itrHrn = assignCallerRhs.iterator(); - while( itrHrn.hasNext() ) { - HeapRegionNode hrnCaller = itrHrn.next(); - - // don't make edge in caller if it is disallowed by types - if( !isSuperiorType(returnTemp.getType(), hrnCaller.getType() ) ) { - // prune - continue; - } - - if( !isSuperiorType(returnTemp.getType(), hrnChildCallee.getType() ) ) { - // prune - continue; - } - - if( !isSuperiorType(edgeCallee.getType(), hrnCaller.getType() ) ) { - // prune - continue; - } - - TypeDescriptor tdNewEdge = - mostSpecificType(edgeCallee.getType(), - hrnChildCallee.getType(), - hrnCaller.getType() - ); - - // otherwise caller node can match callee edge, so make it - ReferenceEdge edgeNewInCaller = edgeNewInCallerTemplate.copy(); - edgeNewInCaller.setSrc(lnLhsCaller); - edgeNewInCaller.setDst(hrnCaller); - edgeNewInCaller.setType(tdNewEdge); - - ReferenceEdge edgeExisting = lnLhsCaller.getReferenceTo(hrnCaller, - tdNewEdge, - edgeNewInCaller.getField() ); - if( edgeExisting == null ) { - - // if this edge doesn't exist in the caller, create it - addReferenceEdge(lnLhsCaller, hrnCaller, edgeNewInCaller); - } else { - // if it already exists, merge with it - edgeExisting.setBeta(edgeExisting.getBeta().union(edgeNewInCaller.getBeta() ) ); - } - } + ReferenceEdge edgeCallee = edgeCalleeItr.next(); + HeapRegionNode hrnChildCallee = edgeCallee.getDst(); + + // some edge types are not possible return values when we can + // see what type variable we are assigning it to + if( !isSuperiorType(returnTemp.getType(), edgeCallee.getType() ) ) { + System.out.println("*** NOT EXPECTING TO SEE THIS: Throwing out "+edgeCallee+" for return temp "+returnTemp); + // prune + continue; + } + + ReferenceEdge edgeNewInCallerTemplate = new ReferenceEdge(null, + null, + edgeCallee.getType(), + edgeCallee.getField(), + false, + funcScriptR(toShadowTokens(ogCallee, + edgeCallee.getBeta() ), + ogCallee, + mc) + ); + rewriteCallerReachability(bogusIndex, + null, + edgeNewInCallerTemplate, + edgeNewInCallerTemplate.getBeta(), + tokens2statesEmpty, + paramIndex2rewrite_d_p, + paramIndex2rewrite_d_s, + paramIndex2rewriteD, + ogCallee, + false, + null); + + edgeNewInCallerTemplate.applyBetaNew(); + + + HashSet assignCallerRhs = + getHRNSetThatPossiblyMapToCalleeHRN(ogCallee, + edgeCallee.getDst(), + pi2dr, + pi2r); + + Iterator itrHrn = assignCallerRhs.iterator(); + while( itrHrn.hasNext() ) { + HeapRegionNode hrnCaller = itrHrn.next(); + + // don't make edge in caller if it is disallowed by types + if( !isSuperiorType(returnTemp.getType(), hrnCaller.getType() ) ) { + // prune + continue; + } + + if( !isSuperiorType(returnTemp.getType(), hrnChildCallee.getType() ) ) { + // prune + continue; + } + + if( !isSuperiorType(edgeCallee.getType(), hrnCaller.getType() ) ) { + // prune + continue; + } + + TypeDescriptor tdNewEdge = + mostSpecificType(edgeCallee.getType(), + hrnChildCallee.getType(), + hrnCaller.getType() + ); + + // otherwise caller node can match callee edge, so make it + ReferenceEdge edgeNewInCaller = edgeNewInCallerTemplate.copy(); + edgeNewInCaller.setSrc(lnLhsCaller); + edgeNewInCaller.setDst(hrnCaller); + edgeNewInCaller.setType(tdNewEdge); + + ReferenceEdge edgeExisting = lnLhsCaller.getReferenceTo(hrnCaller, + tdNewEdge, + edgeNewInCaller.getField() ); + if( edgeExisting == null ) { + + // if this edge doesn't exist in the caller, create it + addReferenceEdge(lnLhsCaller, hrnCaller, edgeNewInCaller); + } else { + // if it already exists, merge with it + edgeExisting.setBeta(edgeExisting.getBeta().union(edgeNewInCaller.getBeta() ) ); + } + } } } @@ -3191,7 +3191,7 @@ public class OwnershipGraph { // first age each allocation site enough times to make room for the shadow nodes for( int i = 0; i < as.getAllocationDepth(); ++i ) { - age(as); + age(as); } // then merge the shadow summary into the normal summary @@ -3211,42 +3211,42 @@ public class OwnershipGraph { // then transplant shadow nodes onto the now clean normal nodes for( int i = 0; i < as.getAllocationDepth(); ++i ) { - Integer idIth = as.getIthOldest(i); - HeapRegionNode hrnIth = id2hrn.get(idIth); - Integer idIthShadow = as.getIthOldestShadow(i); - HeapRegionNode hrnIthShadow = id2hrn.get(idIthShadow); + Integer idIth = as.getIthOldest(i); + HeapRegionNode hrnIth = id2hrn.get(idIth); + Integer idIthShadow = as.getIthOldestShadow(i); + HeapRegionNode hrnIthShadow = id2hrn.get(idIthShadow); - transferOnto(hrnIthShadow, hrnIth); + transferOnto(hrnIthShadow, hrnIth); - // clear off shadow nodes after transfer - clearReferenceEdgesFrom(hrnIthShadow, null, null, true); - clearReferenceEdgesTo(hrnIthShadow, null, null, true); - hrnIthShadow.setAlpha(new ReachabilitySet().makeCanonical() ); + // clear off shadow nodes after transfer + clearReferenceEdgesFrom(hrnIthShadow, null, null, true); + clearReferenceEdgesTo(hrnIthShadow, null, null, true); + hrnIthShadow.setAlpha(new ReachabilitySet().makeCanonical() ); } // finally, globally change shadow tokens into normal tokens Iterator itrAllLabelNodes = td2ln.entrySet().iterator(); while( itrAllLabelNodes.hasNext() ) { - Map.Entry me = (Map.Entry)itrAllLabelNodes.next(); - LabelNode ln = (LabelNode) me.getValue(); + Map.Entry me = (Map.Entry)itrAllLabelNodes.next(); + LabelNode ln = (LabelNode) me.getValue(); - Iterator itrEdges = ln.iteratorToReferencees(); - while( itrEdges.hasNext() ) { - unshadowTokens(as, itrEdges.next() ); - } + Iterator itrEdges = ln.iteratorToReferencees(); + while( itrEdges.hasNext() ) { + unshadowTokens(as, itrEdges.next() ); + } } Iterator itrAllHRNodes = id2hrn.entrySet().iterator(); while( itrAllHRNodes.hasNext() ) { - Map.Entry me = (Map.Entry)itrAllHRNodes.next(); - HeapRegionNode hrnToAge = (HeapRegionNode) me.getValue(); + Map.Entry me = (Map.Entry)itrAllHRNodes.next(); + HeapRegionNode hrnToAge = (HeapRegionNode) me.getValue(); - unshadowTokens(as, hrnToAge); + unshadowTokens(as, hrnToAge); - Iterator itrEdges = hrnToAge.iteratorToReferencees(); - while( itrEdges.hasNext() ) { - unshadowTokens(as, itrEdges.next() ); - } + Iterator itrEdges = hrnToAge.iteratorToReferencees(); + while( itrEdges.hasNext() ) { + unshadowTokens(as, itrEdges.next() ); + } } } @@ -3283,20 +3283,20 @@ public class OwnershipGraph { ) { try { - writeGraph("debug9endResolveCall", - true, // write labels (variables) - true, // selectively hide intermediate temp vars - true, // prune unreachable heap regions - false, // show back edges to confirm graph validity - false, // show parameter indices (unmaintained!) - true, // hide subset reachability states - true); // hide edge taints + writeGraph("debug9endResolveCall", + true, // write labels (variables) + true, // selectively hide intermediate temp vars + true, // prune unreachable heap regions + false, // show back edges to confirm graph validity + false, // show parameter indices (unmaintained!) + true, // hide subset reachability states + true); // hide edge taints } catch( IOException e ) { } System.out.println(" "+mc+" done calling "+fm); ++x; if( x == debugCallMapCount ) { - System.exit(0); + System.exit(0); } } } @@ -3320,7 +3320,7 @@ public class OwnershipGraph { assert tdSrcDeref != null; if( !typeUtil.isSuperorType(tdSrcDeref, td) ) { - return false; + return false; } return edge.getField().equals(OwnershipAnalysis.arrayElementFieldName); @@ -3336,12 +3336,12 @@ public class OwnershipGraph { Iterator fieldItr = cd.getFields(); while( fieldItr.hasNext() ) { - FieldDescriptor fd = (FieldDescriptor) fieldItr.next(); + FieldDescriptor fd = (FieldDescriptor) fieldItr.next(); - if( fd.getType().equals(edge.getType() ) && - fd.getSymbol().equals(edge.getField() ) ) { - return true; - } + if( fd.getType().equals(edge.getType() ) && + fd.getSymbol().equals(edge.getField() ) ) { + return true; + } } cd = cd.getSuperDesc(); @@ -3442,92 +3442,92 @@ public class OwnershipGraph { Iterator ruleItr = rule.iterator(); while(ruleItr.hasNext()) { - TokenTuple ttCallee = ruleItr.next(); - - // compute the possibilities for rewriting this callee token - ReachabilitySet ttCalleeRewrites = null; - boolean callerSourceUsed = false; - - if( tokens2states.containsKey(ttCallee) ) { - callerSourceUsed = true; - ttCalleeRewrites = tokens2states.get(ttCallee); - assert ttCalleeRewrites != null; - - } else if( ogCallee.paramTokenPrimary2paramIndex.containsKey(ttCallee) ) { - // use little d_p - Integer paramIndex_j = ogCallee.paramTokenPrimary2paramIndex.get(ttCallee); - assert paramIndex_j != null; - ttCalleeRewrites = paramIndex2rewrite_d_p.get(paramIndex_j); - assert ttCalleeRewrites != null; - - } else if( ogCallee.paramTokenSecondary2paramIndex.containsKey(ttCallee) ) { - // use little d_s - Integer paramIndex_j = ogCallee.paramTokenSecondary2paramIndex.get(ttCallee); - assert paramIndex_j != null; - ttCalleeRewrites = paramIndex2rewrite_d_s.get(paramIndex_j); - assert ttCalleeRewrites != null; - - } else if( ogCallee.paramTokenSecondaryPlus2paramIndex.containsKey(ttCallee) ) { - // worse, use big D - Integer paramIndex_j = ogCallee.paramTokenSecondaryPlus2paramIndex.get(ttCallee); - assert paramIndex_j != null; - ttCalleeRewrites = paramIndex2rewriteD.get(paramIndex_j); - assert ttCalleeRewrites != null; - - } else if( ogCallee.paramTokenSecondaryStar2paramIndex.containsKey(ttCallee) ) { - // worse, use big D - Integer paramIndex_j = ogCallee.paramTokenSecondaryStar2paramIndex.get(ttCallee); - assert paramIndex_j != null; - ttCalleeRewrites = paramIndex2rewriteD.get(paramIndex_j); - assert ttCalleeRewrites != null; - - } else { - // otherwise there's no need for a rewrite, just pass this one on - TokenTupleSet ttsCaller = new TokenTupleSet(ttCallee).makeCanonical(); - ttCalleeRewrites = new ReachabilitySet(ttsCaller).makeCanonical(); - } - - // branch every version of the working rewritten rule with - // the possibilities for rewriting the current callee token - ReachabilitySet rewrittenRuleWithTTCallee = new ReachabilitySet().makeCanonical(); - - Iterator rewrittenRuleItr = rewrittenRule.iterator(); - while( rewrittenRuleItr.hasNext() ) { - TokenTupleSet ttsRewritten = rewrittenRuleItr.next(); - - Iterator ttCalleeRewritesItr = ttCalleeRewrites.iterator(); - while( ttCalleeRewritesItr.hasNext() ) { - TokenTupleSet ttsBranch = ttCalleeRewritesItr.next(); - - TokenTupleSet ttsRewrittenNext = ttsRewritten.unionUpArity(ttsBranch); - - if( makeChangeSet ) { - // in order to keep the list of source token tuple sets - // start with the sets used to make the partially rewritten - // rule up to this point - HashSet sourceSets = rewritten2source.get(ttsRewritten); - assert sourceSets != null; - - // make a shallow copy for possible modification - sourceSets = (HashSet)sourceSets.clone(); - - // if we used something from the caller to rewrite it, remember - if( callerSourceUsed ) { - sourceSets.add(ttsBranch); - } - - // set mapping for the further rewritten rule - rewritten2source.put(ttsRewrittenNext, sourceSets); - } - - rewrittenRuleWithTTCallee = - rewrittenRuleWithTTCallee.union(ttsRewrittenNext); - } - } - - // now the rewritten rule's possibilities have been extended by - // rewriting the current callee token, remember result - rewrittenRule = rewrittenRuleWithTTCallee; + TokenTuple ttCallee = ruleItr.next(); + + // compute the possibilities for rewriting this callee token + ReachabilitySet ttCalleeRewrites = null; + boolean callerSourceUsed = false; + + if( tokens2states.containsKey(ttCallee) ) { + callerSourceUsed = true; + ttCalleeRewrites = tokens2states.get(ttCallee); + assert ttCalleeRewrites != null; + + } else if( ogCallee.paramTokenPrimary2paramIndex.containsKey(ttCallee) ) { + // use little d_p + Integer paramIndex_j = ogCallee.paramTokenPrimary2paramIndex.get(ttCallee); + assert paramIndex_j != null; + ttCalleeRewrites = paramIndex2rewrite_d_p.get(paramIndex_j); + assert ttCalleeRewrites != null; + + } else if( ogCallee.paramTokenSecondary2paramIndex.containsKey(ttCallee) ) { + // use little d_s + Integer paramIndex_j = ogCallee.paramTokenSecondary2paramIndex.get(ttCallee); + assert paramIndex_j != null; + ttCalleeRewrites = paramIndex2rewrite_d_s.get(paramIndex_j); + assert ttCalleeRewrites != null; + + } else if( ogCallee.paramTokenSecondaryPlus2paramIndex.containsKey(ttCallee) ) { + // worse, use big D + Integer paramIndex_j = ogCallee.paramTokenSecondaryPlus2paramIndex.get(ttCallee); + assert paramIndex_j != null; + ttCalleeRewrites = paramIndex2rewriteD.get(paramIndex_j); + assert ttCalleeRewrites != null; + + } else if( ogCallee.paramTokenSecondaryStar2paramIndex.containsKey(ttCallee) ) { + // worse, use big D + Integer paramIndex_j = ogCallee.paramTokenSecondaryStar2paramIndex.get(ttCallee); + assert paramIndex_j != null; + ttCalleeRewrites = paramIndex2rewriteD.get(paramIndex_j); + assert ttCalleeRewrites != null; + + } else { + // otherwise there's no need for a rewrite, just pass this one on + TokenTupleSet ttsCaller = new TokenTupleSet(ttCallee).makeCanonical(); + ttCalleeRewrites = new ReachabilitySet(ttsCaller).makeCanonical(); + } + + // branch every version of the working rewritten rule with + // the possibilities for rewriting the current callee token + ReachabilitySet rewrittenRuleWithTTCallee = new ReachabilitySet().makeCanonical(); + + Iterator rewrittenRuleItr = rewrittenRule.iterator(); + while( rewrittenRuleItr.hasNext() ) { + TokenTupleSet ttsRewritten = rewrittenRuleItr.next(); + + Iterator ttCalleeRewritesItr = ttCalleeRewrites.iterator(); + while( ttCalleeRewritesItr.hasNext() ) { + TokenTupleSet ttsBranch = ttCalleeRewritesItr.next(); + + TokenTupleSet ttsRewrittenNext = ttsRewritten.unionUpArity(ttsBranch); + + if( makeChangeSet ) { + // in order to keep the list of source token tuple sets + // start with the sets used to make the partially rewritten + // rule up to this point + HashSet sourceSets = rewritten2source.get(ttsRewritten); + assert sourceSets != null; + + // make a shallow copy for possible modification + sourceSets = (HashSet)sourceSets.clone(); + + // if we used something from the caller to rewrite it, remember + if( callerSourceUsed ) { + sourceSets.add(ttsBranch); + } + + // set mapping for the further rewritten rule + rewritten2source.put(ttsRewrittenNext, sourceSets); + } + + rewrittenRuleWithTTCallee = + rewrittenRuleWithTTCallee.union(ttsRewrittenNext); + } + } + + // now the rewritten rule's possibilities have been extended by + // rewriting the current callee token, remember result + rewrittenRule = rewrittenRuleWithTTCallee; } // the rule has been entirely rewritten into the caller context @@ -3543,17 +3543,17 @@ public class OwnershipGraph { // caller sources mapped to it, use to create the change set Iterator callerReachabilityItr = callerReachabilityNew.iterator(); while( callerReachabilityItr.hasNext() ) { - TokenTupleSet ttsRewrittenFinal = callerReachabilityItr.next(); - HashSet sourceSets = rewritten2source.get(ttsRewrittenFinal); - assert sourceSets != null; + TokenTupleSet ttsRewrittenFinal = callerReachabilityItr.next(); + HashSet sourceSets = rewritten2source.get(ttsRewrittenFinal); + assert sourceSets != null; - Iterator sourceSetsItr = sourceSets.iterator(); - while( sourceSetsItr.hasNext() ) { - TokenTupleSet ttsSource = sourceSetsItr.next(); + Iterator sourceSetsItr = sourceSets.iterator(); + while( sourceSetsItr.hasNext() ) { + TokenTupleSet ttsSource = sourceSetsItr.next(); - callerChangeSet = - callerChangeSet.union(new ChangeTuple(ttsSource, ttsRewrittenFinal) ); - } + callerChangeSet = + callerChangeSet.union(new ChangeTuple(ttsSource, ttsRewrittenFinal) ); + } } assert edgePlannedChanges != null; @@ -3593,18 +3593,18 @@ public class OwnershipGraph { Integer idCaller; if( age == AllocationSite.AGE_summary ) { - idCaller = as.getSummaryShadow(); + idCaller = as.getSummaryShadow(); } else if( age == AllocationSite.AGE_oldest ) { - idCaller = as.getOldestShadow(); + idCaller = as.getOldestShadow(); } else { - assert age == AllocationSite.AGE_in_I; + assert age == AllocationSite.AGE_in_I; - Integer I = as.getAge(hrnCallee.getID() ); - assert I != null; + Integer I = as.getAge(hrnCallee.getID() ); + assert I != null; - idCaller = as.getIthOldestShadow(I); + idCaller = as.getIthOldestShadow(I); } assert id2hrn.containsKey(idCaller); @@ -3619,9 +3619,9 @@ public class OwnershipGraph { // so it maps to some regions directly reachable from the arg labels Iterator itrIndex = paramIndicesCallee_p.iterator(); while( itrIndex.hasNext() ) { - Integer paramIndexCallee = itrIndex.next(); - assert pi2dr.containsKey(paramIndexCallee); - possibleCallerHRNs.addAll(pi2dr.get(paramIndexCallee) ); + Integer paramIndexCallee = itrIndex.next(); + assert pi2dr.containsKey(paramIndexCallee); + possibleCallerHRNs.addAll(pi2dr.get(paramIndexCallee) ); } } @@ -3631,9 +3631,9 @@ public class OwnershipGraph { // some parameter, so it maps to regions reachable from the arg labels Iterator itrIndex = paramIndicesCallee_s.iterator(); while( itrIndex.hasNext() ) { - Integer paramIndexCallee = itrIndex.next(); - assert pi2r.containsKey(paramIndexCallee); - possibleCallerHRNs.addAll(pi2r.get(paramIndexCallee) ); + Integer paramIndexCallee = itrIndex.next(); + assert pi2r.containsKey(paramIndexCallee); + possibleCallerHRNs.addAll(pi2r.get(paramIndexCallee) ); } } @@ -3674,56 +3674,56 @@ public class OwnershipGraph { Iterator itrRers = hrn.iteratorToReferencers(); while( itrRers.hasNext() ) { - ReferenceEdge edge = itrRers.next(); - assert rsEmpty.equals(edge.getBetaNew() ); + ReferenceEdge edge = itrRers.next(); + assert rsEmpty.equals(edge.getBetaNew() ); } // calculate boldB for this flagged node if( hrn.isFlagged() || hrn.isParameter() ) { - Hashtable boldB_f = - new Hashtable(); - - Set workSetEdges = new HashSet(); - - // initial boldB_f constraints - Iterator itrRees = hrn.iteratorToReferencees(); - while( itrRees.hasNext() ) { - ReferenceEdge edge = itrRees.next(); - - assert !boldB.containsKey(edge); - boldB_f.put(edge, edge.getBeta() ); - - assert !workSetEdges.contains(edge); - workSetEdges.add(edge); - } + Hashtable boldB_f = + new Hashtable(); - // enforce the boldB_f constraint at edges until we reach a fixed point - while( !workSetEdges.isEmpty() ) { - ReferenceEdge edge = workSetEdges.iterator().next(); - workSetEdges.remove(edge); + Set workSetEdges = new HashSet(); - Iterator itrPrime = edge.getDst().iteratorToReferencees(); - while( itrPrime.hasNext() ) { - ReferenceEdge edgePrime = itrPrime.next(); + // initial boldB_f constraints + Iterator itrRees = hrn.iteratorToReferencees(); + while( itrRees.hasNext() ) { + ReferenceEdge edge = itrRees.next(); - ReachabilitySet prevResult = boldB_f.get(edgePrime); - ReachabilitySet intersection = boldB_f.get(edge).intersection(edgePrime.getBeta() ); + assert !boldB.containsKey(edge); + boldB_f.put(edge, edge.getBeta() ); - if( prevResult == null || - prevResult.union(intersection).size() > prevResult.size() ) { + assert !workSetEdges.contains(edge); + workSetEdges.add(edge); + } - if( prevResult == null ) { - boldB_f.put(edgePrime, edgePrime.getBeta().union(intersection) ); - } else { - boldB_f.put(edgePrime, prevResult.union(intersection) ); - } - workSetEdges.add(edgePrime); - } - } - } + // enforce the boldB_f constraint at edges until we reach a fixed point + while( !workSetEdges.isEmpty() ) { + ReferenceEdge edge = workSetEdges.iterator().next(); + workSetEdges.remove(edge); + + Iterator itrPrime = edge.getDst().iteratorToReferencees(); + while( itrPrime.hasNext() ) { + ReferenceEdge edgePrime = itrPrime.next(); + + ReachabilitySet prevResult = boldB_f.get(edgePrime); + ReachabilitySet intersection = boldB_f.get(edge).intersection(edgePrime.getBeta() ); + + if( prevResult == null || + prevResult.union(intersection).size() > prevResult.size() ) { + + if( prevResult == null ) { + boldB_f.put(edgePrime, edgePrime.getBeta().union(intersection) ); + } else { + boldB_f.put(edgePrime, prevResult.union(intersection) ); + } + workSetEdges.add(edgePrime); + } + } + } - boldB.put(token, boldB_f); + boldB.put(token, boldB_f); } } @@ -3753,85 +3753,85 @@ public class OwnershipGraph { // mark tokens for removal Iterator stateItr = hrn.getAlpha().iterator(); while( stateItr.hasNext() ) { - TokenTupleSet ttsOld = stateItr.next(); - - TokenTupleSet markedTokens = new TokenTupleSet().makeCanonical(); - - Iterator ttItr = ttsOld.iterator(); - while( ttItr.hasNext() ) { - TokenTuple ttOld = ttItr.next(); - - // never remove the identity token from a flagged region - // because it is trivially satisfied - if( hrn.isFlagged() || hrn.isParameter() ) { - if( ttOld == ttException ) { - continue; - } - } - - // does boldB_ttOld allow this token? - boolean foundState = false; - Iterator incidentEdgeItr = hrn.iteratorToReferencers(); - while( incidentEdgeItr.hasNext() ) { - ReferenceEdge incidentEdge = incidentEdgeItr.next(); - - // if it isn't allowed, mark for removal - Integer idOld = ttOld.getToken(); - assert id2hrn.containsKey(idOld); - Hashtable B = boldB.get(idOld); - ReachabilitySet boldB_ttOld_incident = B.get(incidentEdge); // B is NULL! - if( boldB_ttOld_incident != null && - boldB_ttOld_incident.contains(ttsOld) ) { - foundState = true; - } - } - - if( !foundState ) { - markedTokens = markedTokens.add(ttOld); - } - } - - // if there is nothing marked, just move on - if( markedTokens.isEmpty() ) { - hrn.setAlphaNew(hrn.getAlphaNew().union(ttsOld) ); - continue; - } - - // remove all marked tokens and establish a change set that should - // propagate backwards over edges from this node - TokenTupleSet ttsPruned = new TokenTupleSet().makeCanonical(); - ttItr = ttsOld.iterator(); - while( ttItr.hasNext() ) { - TokenTuple ttOld = ttItr.next(); - - if( !markedTokens.containsTuple(ttOld) ) { - ttsPruned = ttsPruned.union(ttOld); - } - } - assert !ttsOld.equals(ttsPruned); - - hrn.setAlphaNew(hrn.getAlphaNew().union(ttsPruned) ); - ChangeTuple ct = new ChangeTuple(ttsOld, ttsPruned).makeCanonical(); - cts = cts.union(ct); + TokenTupleSet ttsOld = stateItr.next(); + + TokenTupleSet markedTokens = new TokenTupleSet().makeCanonical(); + + Iterator ttItr = ttsOld.iterator(); + while( ttItr.hasNext() ) { + TokenTuple ttOld = ttItr.next(); + + // never remove the identity token from a flagged region + // because it is trivially satisfied + if( hrn.isFlagged() || hrn.isParameter() ) { + if( ttOld == ttException ) { + continue; + } + } + + // does boldB_ttOld allow this token? + boolean foundState = false; + Iterator incidentEdgeItr = hrn.iteratorToReferencers(); + while( incidentEdgeItr.hasNext() ) { + ReferenceEdge incidentEdge = incidentEdgeItr.next(); + + // if it isn't allowed, mark for removal + Integer idOld = ttOld.getToken(); + assert id2hrn.containsKey(idOld); + Hashtable B = boldB.get(idOld); + ReachabilitySet boldB_ttOld_incident = B.get(incidentEdge); // B is NULL! + if( boldB_ttOld_incident != null && + boldB_ttOld_incident.contains(ttsOld) ) { + foundState = true; + } + } + + if( !foundState ) { + markedTokens = markedTokens.add(ttOld); + } + } + + // if there is nothing marked, just move on + if( markedTokens.isEmpty() ) { + hrn.setAlphaNew(hrn.getAlphaNew().union(ttsOld) ); + continue; + } + + // remove all marked tokens and establish a change set that should + // propagate backwards over edges from this node + TokenTupleSet ttsPruned = new TokenTupleSet().makeCanonical(); + ttItr = ttsOld.iterator(); + while( ttItr.hasNext() ) { + TokenTuple ttOld = ttItr.next(); + + if( !markedTokens.containsTuple(ttOld) ) { + ttsPruned = ttsPruned.union(ttOld); + } + } + assert !ttsOld.equals(ttsPruned); + + hrn.setAlphaNew(hrn.getAlphaNew().union(ttsPruned) ); + ChangeTuple ct = new ChangeTuple(ttsOld, ttsPruned).makeCanonical(); + cts = cts.union(ct); } // throw change tuple set on all incident edges if( !cts.isEmpty() ) { - Iterator incidentEdgeItr = hrn.iteratorToReferencers(); - while( incidentEdgeItr.hasNext() ) { - ReferenceEdge incidentEdge = incidentEdgeItr.next(); - - edgesForPropagation.add(incidentEdge); - - if( edgePlannedChanges.get(incidentEdge) == null ) { - edgePlannedChanges.put(incidentEdge, cts); - } else { - edgePlannedChanges.put( - incidentEdge, - edgePlannedChanges.get(incidentEdge).union(cts) - ); - } - } + Iterator incidentEdgeItr = hrn.iteratorToReferencers(); + while( incidentEdgeItr.hasNext() ) { + ReferenceEdge incidentEdge = incidentEdgeItr.next(); + + edgesForPropagation.add(incidentEdge); + + if( edgePlannedChanges.get(incidentEdge) == null ) { + edgePlannedChanges.put(incidentEdge, cts); + } else { + edgePlannedChanges.put( + incidentEdge, + edgePlannedChanges.get(incidentEdge).union(cts) + ); + } + } } } @@ -3856,7 +3856,7 @@ public class OwnershipGraph { hrn.applyAlphaNew(); Iterator itrRes = hrn.iteratorToReferencers(); while( itrRes.hasNext() ) { - res.add(itrRes.next() ); + res.add(itrRes.next() ); } } @@ -3869,7 +3869,7 @@ public class OwnershipGraph { // commit results of last phase if( edgesUpdated.contains(edge) ) { - edge.applyBetaNew(); + edge.applyBetaNew(); } // compute intial condition of 2nd phase @@ -3884,23 +3884,23 @@ public class OwnershipGraph { OwnershipNode on = edgePrime.getSrc(); if( !(on instanceof HeapRegionNode) ) { - continue; + continue; } HeapRegionNode hrn = (HeapRegionNode) on; Iterator itrEdge = hrn.iteratorToReferencers(); while( itrEdge.hasNext() ) { - ReferenceEdge edge = itrEdge.next(); + ReferenceEdge edge = itrEdge.next(); - ReachabilitySet prevResult = edge.getBetaNew(); - assert prevResult != null; + ReachabilitySet prevResult = edge.getBetaNew(); + assert prevResult != null; - ReachabilitySet intersection = edge.getBeta().intersection(edgePrime.getBetaNew() ); + ReachabilitySet intersection = edge.getBeta().intersection(edgePrime.getBetaNew() ); - if( prevResult.union(intersection).size() > prevResult.size() ) { - edge.setBetaNew(prevResult.union(intersection) ); - edgeWorkSet.add(edge); - } + if( prevResult.union(intersection).size() > prevResult.size() ) { + edge.setBetaNew(prevResult.union(intersection) ); + edgeWorkSet.add(edge); + } } } @@ -3947,16 +3947,16 @@ public class OwnershipGraph { // if this graph doesn't have a node the // incoming graph has, allocate it if( !id2hrn.containsKey(idA) ) { - HeapRegionNode hrnB = hrnA.copy(); - id2hrn.put(idA, hrnB); - gid2hrn.put(hrnA.getGloballyUniqueIdentifier(), hrnB); + HeapRegionNode hrnB = hrnA.copy(); + id2hrn.put(idA, hrnB); + gid2hrn.put(hrnA.getGloballyUniqueIdentifier(), hrnB); } else { - // otherwise this is a node present in both graphs - // so make the new reachability set a union of the - // nodes' reachability sets - HeapRegionNode hrnB = id2hrn.get(idA); - hrnB.setAlpha(hrnB.getAlpha().union(hrnA.getAlpha() ) ); + // otherwise this is a node present in both graphs + // so make the new reachability set a union of the + // nodes' reachability sets + HeapRegionNode hrnB = id2hrn.get(idA); + hrnB.setAlpha(hrnB.getAlpha().union(hrnA.getAlpha() ) ); } } @@ -3986,57 +3986,57 @@ public class OwnershipGraph { Iterator heapRegionsItrA = hrnA.iteratorToReferencees(); while( heapRegionsItrA.hasNext() ) { - ReferenceEdge edgeA = heapRegionsItrA.next(); - HeapRegionNode hrnChildA = edgeA.getDst(); - Integer idChildA = hrnChildA.getID(); - - // at this point we know an edge in graph A exists - // idA -> idChildA, does this exist in B? - assert id2hrn.containsKey(idA); - HeapRegionNode hrnB = id2hrn.get(idA); - ReferenceEdge edgeToMerge = null; - - Iterator heapRegionsItrB = hrnB.iteratorToReferencees(); - while( heapRegionsItrB.hasNext() && - edgeToMerge == null ) { - - ReferenceEdge edgeB = heapRegionsItrB.next(); - HeapRegionNode hrnChildB = edgeB.getDst(); - Integer idChildB = hrnChildB.getID(); - - // don't use the ReferenceEdge.equals() here because - // we're talking about existence between graphs - if( idChildB.equals(idChildA) && - edgeB.typeAndFieldEquals(edgeA) ) { - - edgeToMerge = edgeB; - } - } - - // if the edge from A was not found in B, - // add it to B. - if( edgeToMerge == null ) { - assert id2hrn.containsKey(idChildA); - HeapRegionNode hrnChildB = id2hrn.get(idChildA); - edgeToMerge = edgeA.copy(); - edgeToMerge.setSrc(hrnB); - edgeToMerge.setDst(hrnChildB); - addReferenceEdge(hrnB, hrnChildB, edgeToMerge); - } - // otherwise, the edge already existed in both graphs - // so merge their reachability sets - else { - // just replace this beta set with the union - assert edgeToMerge != null; - edgeToMerge.setBeta( - edgeToMerge.getBeta().union(edgeA.getBeta() ) - ); - //TODO eom - edgeToMerge.unionTaintIdentifier(edgeA.getTaintIdentifier()); - if( !edgeA.isInitialParam() ) { - edgeToMerge.setIsInitialParam(false); - } - } + ReferenceEdge edgeA = heapRegionsItrA.next(); + HeapRegionNode hrnChildA = edgeA.getDst(); + Integer idChildA = hrnChildA.getID(); + + // at this point we know an edge in graph A exists + // idA -> idChildA, does this exist in B? + assert id2hrn.containsKey(idA); + HeapRegionNode hrnB = id2hrn.get(idA); + ReferenceEdge edgeToMerge = null; + + Iterator heapRegionsItrB = hrnB.iteratorToReferencees(); + while( heapRegionsItrB.hasNext() && + edgeToMerge == null ) { + + ReferenceEdge edgeB = heapRegionsItrB.next(); + HeapRegionNode hrnChildB = edgeB.getDst(); + Integer idChildB = hrnChildB.getID(); + + // don't use the ReferenceEdge.equals() here because + // we're talking about existence between graphs + if( idChildB.equals(idChildA) && + edgeB.typeAndFieldEquals(edgeA) ) { + + edgeToMerge = edgeB; + } + } + + // if the edge from A was not found in B, + // add it to B. + if( edgeToMerge == null ) { + assert id2hrn.containsKey(idChildA); + HeapRegionNode hrnChildB = id2hrn.get(idChildA); + edgeToMerge = edgeA.copy(); + edgeToMerge.setSrc(hrnB); + edgeToMerge.setDst(hrnChildB); + addReferenceEdge(hrnB, hrnChildB, edgeToMerge); + } + // otherwise, the edge already existed in both graphs + // so merge their reachability sets + else { + // just replace this beta set with the union + assert edgeToMerge != null; + edgeToMerge.setBeta( + edgeToMerge.getBeta().union(edgeA.getBeta() ) + ); + //TODO eom + edgeToMerge.unionTaintIdentifier(edgeA.getTaintIdentifier()); + if( !edgeA.isInitialParam() ) { + edgeToMerge.setIsInitialParam(false); + } + } } } @@ -4050,55 +4050,55 @@ public class OwnershipGraph { Iterator heapRegionsItrA = lnA.iteratorToReferencees(); while( heapRegionsItrA.hasNext() ) { - ReferenceEdge edgeA = heapRegionsItrA.next(); - HeapRegionNode hrnChildA = edgeA.getDst(); - Integer idChildA = hrnChildA.getID(); - - // at this point we know an edge in graph A exists - // tdA -> idChildA, does this exist in B? - assert td2ln.containsKey(tdA); - LabelNode lnB = td2ln.get(tdA); - ReferenceEdge edgeToMerge = null; - - Iterator heapRegionsItrB = lnB.iteratorToReferencees(); - while( heapRegionsItrB.hasNext() && - edgeToMerge == null ) { - - ReferenceEdge edgeB = heapRegionsItrB.next(); - HeapRegionNode hrnChildB = edgeB.getDst(); - Integer idChildB = hrnChildB.getID(); - - // don't use the ReferenceEdge.equals() here because - // we're talking about existence between graphs - if( idChildB.equals(idChildA) && - edgeB.typeAndFieldEquals(edgeA) ) { - - edgeToMerge = edgeB; - } - } - - // if the edge from A was not found in B, - // add it to B. - if( edgeToMerge == null ) { - assert id2hrn.containsKey(idChildA); - HeapRegionNode hrnChildB = id2hrn.get(idChildA); - edgeToMerge = edgeA.copy(); - edgeToMerge.setSrc(lnB); - edgeToMerge.setDst(hrnChildB); - addReferenceEdge(lnB, hrnChildB, edgeToMerge); - } - // otherwise, the edge already existed in both graphs - // so merge their reachability sets - else { - // just replace this beta set with the union - edgeToMerge.setBeta( - edgeToMerge.getBeta().union(edgeA.getBeta() ) - ); - edgeToMerge.unionTaintIdentifier(edgeA.getTaintIdentifier()); - if( !edgeA.isInitialParam() ) { - edgeToMerge.setIsInitialParam(false); - } - } + ReferenceEdge edgeA = heapRegionsItrA.next(); + HeapRegionNode hrnChildA = edgeA.getDst(); + Integer idChildA = hrnChildA.getID(); + + // at this point we know an edge in graph A exists + // tdA -> idChildA, does this exist in B? + assert td2ln.containsKey(tdA); + LabelNode lnB = td2ln.get(tdA); + ReferenceEdge edgeToMerge = null; + + Iterator heapRegionsItrB = lnB.iteratorToReferencees(); + while( heapRegionsItrB.hasNext() && + edgeToMerge == null ) { + + ReferenceEdge edgeB = heapRegionsItrB.next(); + HeapRegionNode hrnChildB = edgeB.getDst(); + Integer idChildB = hrnChildB.getID(); + + // don't use the ReferenceEdge.equals() here because + // we're talking about existence between graphs + if( idChildB.equals(idChildA) && + edgeB.typeAndFieldEquals(edgeA) ) { + + edgeToMerge = edgeB; + } + } + + // if the edge from A was not found in B, + // add it to B. + if( edgeToMerge == null ) { + assert id2hrn.containsKey(idChildA); + HeapRegionNode hrnChildB = id2hrn.get(idChildA); + edgeToMerge = edgeA.copy(); + edgeToMerge.setSrc(lnB); + edgeToMerge.setDst(hrnChildB); + addReferenceEdge(lnB, hrnChildB, edgeToMerge); + } + // otherwise, the edge already existed in both graphs + // so merge their reachability sets + else { + // just replace this beta set with the union + edgeToMerge.setBeta( + edgeToMerge.getBeta().union(edgeA.getBeta() ) + ); + edgeToMerge.unionTaintIdentifier(edgeA.getTaintIdentifier()); + if( !edgeA.isInitialParam() ) { + edgeToMerge.setIsInitialParam(false); + } + } } } } @@ -4249,12 +4249,12 @@ public class OwnershipGraph { HeapRegionNode hrnA = (HeapRegionNode) meA.getValue(); if( !ogB.id2hrn.containsKey(idA) ) { - return false; + return false; } HeapRegionNode hrnB = ogB.id2hrn.get(idA); if( !hrnA.equalsIncludingAlpha(hrnB) ) { - return false; + return false; } } @@ -4284,7 +4284,7 @@ public class OwnershipGraph { TempDescriptor tdA = (TempDescriptor) meA.getKey(); if( !ogB.td2ln.containsKey(tdA) ) { - return false; + return false; } } @@ -4316,7 +4316,7 @@ public class OwnershipGraph { assert ogB.id2hrn.containsKey(idA); if( !areallREfromAequaltoB(ogA, hrnA, ogB) ) { - return false; + return false; } // then check every edge in B for presence in A, starting @@ -4324,7 +4324,7 @@ public class OwnershipGraph { HeapRegionNode hrnB = ogB.id2hrn.get(idA); if( !areallREfromAequaltoB(ogB, hrnB, ogA) ) { - return false; + return false; } } @@ -4341,7 +4341,7 @@ public class OwnershipGraph { assert ogB.td2ln.containsKey(tdA); if( !areallREfromAequaltoB(ogA, lnA, ogB) ) { - return false; + return false; } // then check every edge in B for presence in A, starting @@ -4349,7 +4349,7 @@ public class OwnershipGraph { LabelNode lnB = ogB.td2ln.get(tdA); if( !areallREfromAequaltoB(ogB, lnB, ogA) ) { - return false; + return false; } } @@ -4375,32 +4375,32 @@ public class OwnershipGraph { OwnershipNode onB = null; if( onA instanceof HeapRegionNode ) { - HeapRegionNode hrnA = (HeapRegionNode) onA; - onB = ogB.id2hrn.get(hrnA.getID() ); + HeapRegionNode hrnA = (HeapRegionNode) onA; + onB = ogB.id2hrn.get(hrnA.getID() ); } else { - LabelNode lnA = (LabelNode) onA; - onB = ogB.td2ln.get(lnA.getTempDescriptor() ); + LabelNode lnA = (LabelNode) onA; + onB = ogB.td2ln.get(lnA.getTempDescriptor() ); } Iterator itrB = onB.iteratorToReferencees(); while( itrB.hasNext() ) { - ReferenceEdge edgeB = itrB.next(); - HeapRegionNode hrnChildB = edgeB.getDst(); - Integer idChildB = hrnChildB.getID(); - - if( idChildA.equals(idChildB) && - edgeA.typeAndFieldEquals(edgeB) ) { - - // there is an edge in the right place with the right field, - // but do they have the same attributes? - if( edgeA.getBeta().equals(edgeB.getBeta() ) ) { - edgeFound = true; - } - } + ReferenceEdge edgeB = itrB.next(); + HeapRegionNode hrnChildB = edgeB.getDst(); + Integer idChildB = hrnChildB.getID(); + + if( idChildA.equals(idChildB) && + edgeA.typeAndFieldEquals(edgeB) ) { + + // there is an edge in the right place with the right field, + // but do they have the same attributes? + if( edgeA.getBeta().equals(edgeB.getBeta() ) ) { + edgeFound = true; + } + } } if( !edgeFound ) { - return false; + return false; } } @@ -4537,7 +4537,7 @@ public class OwnershipGraph { if( aliasDetected ) { common = findCommonReachableNodes(hrn1, hrn2); if( !(DISABLE_STRONG_UPDATES || DISABLE_GLOBAL_SWEEP) ) { - assert !common.isEmpty(); + assert !common.isEmpty(); } } @@ -4641,7 +4641,7 @@ public class OwnershipGraph { common = hasPotentialAlias(hrnParamPri, hrnIthOldest); if( hrnParamSec != null ) { - common.addAll(hasPotentialAlias(hrnParamSec, hrnIthOldest) ); + common.addAll(hasPotentialAlias(hrnParamSec, hrnIthOldest) ); } } @@ -4686,17 +4686,17 @@ public class OwnershipGraph { // while we're at it, do an inner loop for alloc2 vs alloc1 nodes for( int j = 0; j < as1.getAllocationDepth(); ++j ) { - Integer idI1 = as1.getIthOldest(j); + Integer idI1 = as1.getIthOldest(j); - // if these are the same site, don't look for the same token, no alias. - // different tokens of the same site could alias together though - if( idI1.equals(idI2) ) { - continue; - } + // if these are the same site, don't look for the same token, no alias. + // different tokens of the same site could alias together though + if( idI1.equals(idI2) ) { + continue; + } - HeapRegionNode hrnI1 = id2hrn.get(idI1); + HeapRegionNode hrnI1 = id2hrn.get(idI1); - common.addAll(hasPotentialAlias(hrnI1, hrnI2) ); + common.addAll(hasPotentialAlias(hrnI1, hrnI2) ); } } @@ -4724,11 +4724,11 @@ public class OwnershipGraph { Iterator edgeItr = hrn.iteratorToReferencees(); while( edgeItr.hasNext() ) { - ReferenceEdge edge = edgeItr.next(); + ReferenceEdge edge = edgeItr.next(); - if( !reachableNodes1.contains(edge.getDst() ) ) { - todoNodes1.add(edge.getDst() ); - } + if( !reachableNodes1.contains(edge.getDst() ) ) { + todoNodes1.add(edge.getDst() ); + } } } @@ -4739,11 +4739,11 @@ public class OwnershipGraph { Iterator edgeItr = hrn.iteratorToReferencees(); while( edgeItr.hasNext() ) { - ReferenceEdge edge = edgeItr.next(); + ReferenceEdge edge = edgeItr.next(); - if( !reachableNodes2.contains(edge.getDst() ) ) { - todoNodes2.add(edge.getDst() ); - } + if( !reachableNodes2.contains(edge.getDst() ) ) { + todoNodes2.add(edge.getDst() ); + } } } @@ -4787,16 +4787,16 @@ public class OwnershipGraph { hrn.getDescription().startsWith("param") ) { - if( !visited.contains(hrn) ) { - traverseHeapRegionNodes(VISIT_HRN_WRITE_FULL, - hrn, - bw, - null, - visited, - writeReferencers, - hideSubsetReachability, - hideEdgeTaints); - } + if( !visited.contains(hrn) ) { + traverseHeapRegionNodes(VISIT_HRN_WRITE_FULL, + hrn, + bw, + null, + visited, + writeReferencers, + hideSubsetReachability, + hideEdgeTaints); + } } } @@ -4820,47 +4820,47 @@ public class OwnershipGraph { s = td2ln.entrySet(); i = s.iterator(); while( i.hasNext() ) { - Map.Entry me = (Map.Entry)i.next(); - LabelNode ln = (LabelNode) me.getValue(); - - if( labelSelect ) { - String labelStr = ln.getTempDescriptorString(); - if( labelStr.startsWith("___temp") || - labelStr.startsWith("___dst") || - labelStr.startsWith("___srctmp") || - labelStr.startsWith("___neverused") || - labelStr.contains(qString) || - labelStr.contains(rString) || - labelStr.contains(blobString) - ) { - continue; - } - } - - //bw.write(" "+ln.toString() + ";\n"); - - Iterator heapRegionsItr = ln.iteratorToReferencees(); - while( heapRegionsItr.hasNext() ) { - ReferenceEdge edge = heapRegionsItr.next(); - HeapRegionNode hrn = edge.getDst(); - - if( pruneGarbage && !visited.contains(hrn) ) { - traverseHeapRegionNodes(VISIT_HRN_WRITE_FULL, - hrn, - bw, - null, - visited, - writeReferencers, - hideSubsetReachability, - hideEdgeTaints); - } - - bw.write(" " + ln.toString() + - " -> " + hrn.toString() + - "[label=\"" + edge.toGraphEdgeString(hideSubsetReachability, - hideEdgeTaints) + - "\",decorate];\n"); - } + Map.Entry me = (Map.Entry)i.next(); + LabelNode ln = (LabelNode) me.getValue(); + + if( labelSelect ) { + String labelStr = ln.getTempDescriptorString(); + if( labelStr.startsWith("___temp") || + labelStr.startsWith("___dst") || + labelStr.startsWith("___srctmp") || + labelStr.startsWith("___neverused") || + labelStr.contains(qString) || + labelStr.contains(rString) || + labelStr.contains(blobString) + ) { + continue; + } + } + + //bw.write(" "+ln.toString() + ";\n"); + + Iterator heapRegionsItr = ln.iteratorToReferencees(); + while( heapRegionsItr.hasNext() ) { + ReferenceEdge edge = heapRegionsItr.next(); + HeapRegionNode hrn = edge.getDst(); + + if( pruneGarbage && !visited.contains(hrn) ) { + traverseHeapRegionNodes(VISIT_HRN_WRITE_FULL, + hrn, + bw, + null, + visited, + writeReferencers, + hideSubsetReachability, + hideEdgeTaints); + } + + bw.write(" " + ln.toString() + + " -> " + hrn.toString() + + "[label=\"" + edge.toGraphEdgeString(hideSubsetReachability, + hideEdgeTaints) + + "\",decorate];\n"); + } } } @@ -4890,13 +4890,13 @@ public class OwnershipGraph { String attributes = "["; if( hrn.isSingleObject() ) { - attributes += "shape=box"; + attributes += "shape=box"; } else { - attributes += "shape=Msquare"; + attributes += "shape=Msquare"; } if( hrn.isFlagged() ) { - attributes += ",style=filled,fillcolor=lightgrey"; + attributes += ",style=filled,fillcolor=lightgrey"; } attributes += ",label=\"ID" + @@ -4904,7 +4904,7 @@ public class OwnershipGraph { "\\n"; if( hrn.getType() != null ) { - attributes += hrn.getType().toPrettyString() + "\\n"; + attributes += hrn.getType().toPrettyString() + "\\n"; } attributes += hrn.getDescription() + @@ -4944,12 +4944,12 @@ public class OwnershipGraph { switch( mode ) { case VISIT_HRN_WRITE_FULL: - bw.write(" " + hrn.toString() + - " -> " + hrnChild.toString() + - "[label=\"" + edge.toGraphEdgeString(hideSubsetReachability, - hideEdgeTaints) + - "\",decorate];\n"); - break; + bw.write(" " + hrn.toString() + + " -> " + hrnChild.toString() + + "[label=\"" + edge.toGraphEdgeString(hideSubsetReachability, + hideEdgeTaints) + + "\",decorate];\n"); + break; } traverseHeapRegionNodes(mode, @@ -4986,12 +4986,12 @@ public class OwnershipGraph { edge.unionTaintIdentifier(newTaintIdentifier); if(edge.getSrc() instanceof HeapRegionNode) { - HeapRegionNode refHRN=(HeapRegionNode)edge.getSrc(); - //check whether it is reflexive edge - if(!refHRN.equals(hrn) && !visitedSet.contains(refHRN)) { - visitedSet.add(refHRN); - propagateTaintIdentifier((HeapRegionNode)edge.getSrc(),newTaintIdentifier,visitedSet); - } + HeapRegionNode refHRN=(HeapRegionNode)edge.getSrc(); + //check whether it is reflexive edge + if(!refHRN.equals(hrn) && !visitedSet.contains(refHRN)) { + visitedSet.add(refHRN); + propagateTaintIdentifier((HeapRegionNode)edge.getSrc(),newTaintIdentifier,visitedSet); + } } } @@ -5007,12 +5007,12 @@ public class OwnershipGraph { edge.minusTaintIdentifier(newTaintIdentifier); if(edge.getSrc() instanceof HeapRegionNode) { - HeapRegionNode refHRN=(HeapRegionNode)edge.getSrc(); - //check whether it is reflexive edge - if(!refHRN.equals(hrn) && !visitedSet.contains(refHRN)) { - visitedSet.add(refHRN); - depropagateTaintIdentifier((HeapRegionNode)edge.getSrc(),newTaintIdentifier,visitedSet); - } + HeapRegionNode refHRN=(HeapRegionNode)edge.getSrc(); + //check whether it is reflexive edge + if(!refHRN.equals(hrn) && !visitedSet.contains(refHRN)) { + visitedSet.add(refHRN); + depropagateTaintIdentifier((HeapRegionNode)edge.getSrc(),newTaintIdentifier,visitedSet); + } } } @@ -5114,7 +5114,7 @@ public class OwnershipGraph { while (elements.hasMoreElements()) { HeapRegionNode hrn = elements.nextElement(); if (hrn.getGloballyUniqueIdentifier().equals(id)) { - return hrn; + return hrn; } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/OwnershipNode.java b/Robust/src/Analysis/OwnershipAnalysis/OwnershipNode.java index 10b7d2ed..ccb584c4 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/OwnershipNode.java +++ b/Robust/src/Analysis/OwnershipAnalysis/OwnershipNode.java @@ -50,7 +50,7 @@ public abstract class OwnershipNode { if( edge.getDst().equals(hrn) && edge.typeEquals(type) && edge.fieldEquals(field) ) { - return edge; + return edge; } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/ParameterDecomposition.java b/Robust/src/Analysis/OwnershipAnalysis/ParameterDecomposition.java index db6843fe..e7c7a0d9 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/ParameterDecomposition.java +++ b/Robust/src/Analysis/OwnershipAnalysis/ParameterDecomposition.java @@ -120,7 +120,7 @@ public class ParameterDecomposition { if( as != null ) { Set asSet = pi2a_as.get(paramIndex); if( asSet == null ) { - asSet = new HashSet(); + asSet = new HashSet(); } asSet.add(as); pi2a_as.put(paramIndex, asSet); @@ -128,7 +128,7 @@ public class ParameterDecomposition { // and if there is an allocation site, grab type Set tdSet = pi2a_td.get(paramIndex); if( tdSet == null ) { - tdSet = new HashSet(); + tdSet = new HashSet(); } tdSet.add(as.getType() ); pi2a_td.put(paramIndex, tdSet); @@ -150,7 +150,7 @@ public class ParameterDecomposition { if( as != null ) { Set asSet = pi2r_as.get(paramIndex); if( asSet == null ) { - asSet = new HashSet(); + asSet = new HashSet(); } asSet.add(as); pi2r_as.put(paramIndex, asSet); @@ -158,7 +158,7 @@ public class ParameterDecomposition { // and if there is an allocation site, grab type Set tdSet = pi2r_td.get(paramIndex); if( tdSet == null ) { - tdSet = new HashSet(); + tdSet = new HashSet(); } tdSet.add(as.getType() ); pi2r_td.put(paramIndex, tdSet); diff --git a/Robust/src/Analysis/OwnershipAnalysis/ReachabilitySet.java b/Robust/src/Analysis/OwnershipAnalysis/ReachabilitySet.java index bfd39278..87116743 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/ReachabilitySet.java +++ b/Robust/src/Analysis/OwnershipAnalysis/ReachabilitySet.java @@ -71,7 +71,7 @@ public class ReachabilitySet extends Canonical { while( itr.hasNext() ) { TokenTupleSet ttsThis = (TokenTupleSet) itr.next(); if( ttsThis.containsWithZeroes(tts) ) { - return true; + return true; } } @@ -98,13 +98,13 @@ public class ReachabilitySet extends Canonical { while( itr.hasNext() ) { TokenTupleSet ttsThis = (TokenTupleSet) itr.next(); if( strict ) { - if( !tts.equals(ttsThis) && tts.isSubset(ttsThis) ) { - return true; - } + if( !tts.equals(ttsThis) && tts.isSubset(ttsThis) ) { + return true; + } } else { - if( tts.isSubset(ttsThis) ) { - return true; - } + if( tts.isSubset(ttsThis) ) { + return true; + } } } @@ -117,7 +117,7 @@ public class ReachabilitySet extends Canonical { while( itr.hasNext() ) { TokenTupleSet tts = (TokenTupleSet) itr.next(); if( tts.containsTuple(tt) ) { - return true; + return true; } } return false; @@ -128,7 +128,7 @@ public class ReachabilitySet extends Canonical { while( itr.hasNext() ) { TokenTupleSet tts = (TokenTupleSet) itr.next(); if( tts.containsTuple(tt1) && tts.containsTuple(tt2) ) { - return true; + return true; } } return false; @@ -190,10 +190,10 @@ public class ReachabilitySet extends Canonical { ReachabilitySet rsOut = new ReachabilitySet(); Iterator i = this.iterator(); while( i.hasNext() ) { - TokenTupleSet tts = (TokenTupleSet) i.next(); - if( rsIn.possibleReachabilities.contains(tts) ) { - rsOut.possibleReachabilities.add(tts); - } + TokenTupleSet tts = (TokenTupleSet) i.next(); + if( rsIn.possibleReachabilities.contains(tts) ) { + rsOut.possibleReachabilities.add(tts); + } } ro.c=rsOut=rsOut.makeCanonical(); interhash.put(ro,ro); @@ -225,9 +225,9 @@ public class ReachabilitySet extends Canonical { while( i.hasNext() ) { TokenTupleSet tts = (TokenTupleSet) i.next(); if( tts.containsTuple(ttB) ) { - rsOut.possibleReachabilities.add(tts.remove(ttA) ); + rsOut.possibleReachabilities.add(tts.remove(ttA) ); } else { - rsOut.possibleReachabilities.add(tts); + rsOut.possibleReachabilities.add(tts); } } @@ -248,16 +248,16 @@ public class ReachabilitySet extends Canonical { Iterator itrC = C.iterator(); while( itrC.hasNext() ) { - ChangeTuple c = itrC.next(); + ChangeTuple c = itrC.next(); - if( tts.equals(c.getSetToMatch() ) ) { - rsOut.possibleReachabilities.add(c.getSetToAdd() ); - changeFound = true; - } + if( tts.equals(c.getSetToMatch() ) ) { + rsOut.possibleReachabilities.add(c.getSetToAdd() ); + changeFound = true; + } } if( keepSourceState || !changeFound ) { - rsOut.possibleReachabilities.add(tts); + rsOut.possibleReachabilities.add(tts); } } @@ -276,35 +276,35 @@ public class ReachabilitySet extends Canonical { Iterator itrR = rsIn.iterator(); while( itrR.hasNext() ) { - TokenTupleSet r = (TokenTupleSet) itrR.next(); - - TokenTupleSet theUnion = new TokenTupleSet().makeCanonical(); - - Iterator itrRelement = r.iterator(); - while( itrRelement.hasNext() ) { - TokenTuple ttR = (TokenTuple) itrRelement.next(); - TokenTuple ttO = o.containsToken(ttR.getToken() ); - - if( ttO != null ) { - theUnion = theUnion.union((new TokenTupleSet(ttR.unionArity(ttO)).makeCanonical() ) ); - } else { - theUnion = theUnion.union((new TokenTupleSet(ttR)).makeCanonical() ); - } - } - - Iterator itrOelement = o.iterator(); - while( itrOelement.hasNext() ) { - TokenTuple ttO = (TokenTuple) itrOelement.next(); - TokenTuple ttR = theUnion.containsToken(ttO.getToken() ); - - if( ttR == null ) { - theUnion = theUnion.union(new TokenTupleSet(ttO).makeCanonical() ); - } - } - - if( !theUnion.isEmpty() ) { - ctsOut = ctsOut.union((new ChangeTupleSet(new ChangeTuple(o, theUnion) )).makeCanonical() ); - } + TokenTupleSet r = (TokenTupleSet) itrR.next(); + + TokenTupleSet theUnion = new TokenTupleSet().makeCanonical(); + + Iterator itrRelement = r.iterator(); + while( itrRelement.hasNext() ) { + TokenTuple ttR = (TokenTuple) itrRelement.next(); + TokenTuple ttO = o.containsToken(ttR.getToken() ); + + if( ttO != null ) { + theUnion = theUnion.union((new TokenTupleSet(ttR.unionArity(ttO)).makeCanonical() ) ); + } else { + theUnion = theUnion.union((new TokenTupleSet(ttR)).makeCanonical() ); + } + } + + Iterator itrOelement = o.iterator(); + while( itrOelement.hasNext() ) { + TokenTuple ttO = (TokenTuple) itrOelement.next(); + TokenTuple ttR = theUnion.containsToken(ttO.getToken() ); + + if( ttR == null ) { + theUnion = theUnion.union(new TokenTupleSet(ttO).makeCanonical() ); + } + } + + if( !theUnion.isEmpty() ) { + ctsOut = ctsOut.union((new ChangeTupleSet(new ChangeTuple(o, theUnion) )).makeCanonical() ); + } } } @@ -370,15 +370,15 @@ public class ReachabilitySet extends Canonical { Iterator itrA = rsIn.iterator(); while( itrA.hasNext() && !subsetExists ) { - TokenTupleSet ttsA = (TokenTupleSet) itrA.next(); + TokenTupleSet ttsA = (TokenTupleSet) itrA.next(); - if( ttsA.isSubset(ttsB) ) { - subsetExists = true; - } + if( ttsA.isSubset(ttsB) ) { + subsetExists = true; + } } if( subsetExists ) { - rsOut.possibleReachabilities.add(ttsB); + rsOut.possibleReachabilities.add(ttsB); } } @@ -398,8 +398,8 @@ public class ReachabilitySet extends Canonical { Iterator itrThis = this.iterator(); while( itrThis.hasNext() ) { - TokenTupleSet ttsUnit = itrThis.next(); - ttsImprecise = ttsImprecise.unionUpArity(ttsUnit.makeArityZeroOrMore() ); + TokenTupleSet ttsUnit = itrThis.next(); + ttsImprecise = ttsImprecise.unionUpArity(ttsUnit.makeArityZeroOrMore() ); } //rsOut = this.union( ttsImprecise ); @@ -425,26 +425,26 @@ public class ReachabilitySet extends Canonical { TokenTupleSet ttsCoordinate = new TokenTupleSet().makeCanonical(); Iterator ttsItr = this.iterator(); for( int i = 0; i < numDimensions; ++i ) { - assert ttsItr.hasNext(); - TokenTupleSet ttsUnit = ttsItr.next(); - for( int j = 0; j < digits[i]; ++j ) { - ttsCoordinate = ttsCoordinate.unionUpArity(ttsUnit); - } + assert ttsItr.hasNext(); + TokenTupleSet ttsUnit = ttsItr.next(); + for( int j = 0; j < digits[i]; ++j ) { + ttsCoordinate = ttsCoordinate.unionUpArity(ttsUnit); + } } rsOut = rsOut.add(ttsCoordinate.makeCanonical() ); // increment for( int i = 0; i < numDimensions+1; ++i ) { - digits[i]++; + digits[i]++; - if( digits[i] > maxArity ) { - // this axis reached its max, so roll it back to min and increment next higher digit - digits[i] = minArity; + if( digits[i] > maxArity ) { + // this axis reached its max, so roll it back to min and increment next higher digit + digits[i] = minArity; - } else { - // this axis did not reach its max so we just enumerated a new unique coordinate, stop - break; - } + } else { + // this axis did not reach its max so we just enumerated a new unique coordinate, stop + break; + } } } @@ -476,9 +476,9 @@ public class ReachabilitySet extends Canonical { oldHashSet = true; } else { if( oldHash != currentHash ) { - System.out.println("IF YOU SEE THIS A CANONICAL ReachabilitySet CHANGED"); - Integer x = null; - x.toString(); + System.out.println("IF YOU SEE THIS A CANONICAL ReachabilitySet CHANGED"); + Integer x = null; + x.toString(); } } @@ -496,12 +496,12 @@ public class ReachabilitySet extends Canonical { // skip this if there is a superset already if( hideSubsetReachability && containsStrictSuperSet(tts) ) { - continue; + continue; } s += tts; if( i.hasNext() ) { - s += "\\n"; + s += "\\n"; } } @@ -524,12 +524,12 @@ public class ReachabilitySet extends Canonical { // skip this if there is a superset already if( hideSubsetReachability && containsStrictSuperSet(tts) ) { - continue; + continue; } s += tts; if( i.hasNext() ) { - s += "\n"; + s += "\n"; } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/TokenTuple.java b/Robust/src/Analysis/OwnershipAnalysis/TokenTuple.java index 6820f530..00d9561a 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/TokenTuple.java +++ b/Robust/src/Analysis/OwnershipAnalysis/TokenTuple.java @@ -48,7 +48,7 @@ public class TokenTuple extends Canonical { arity=ARITY_ONE; } else { if (arity==ARITY_ONEORMORE) - arity=ARITY_ZEROORMORE; + arity=ARITY_ZEROORMORE; } } @@ -81,17 +81,17 @@ public class TokenTuple extends Canonical { // when two tokens are present (absence of a token is arity=zero and is // handled outside of this method) if( arity == ARITY_ZEROORMORE && tt.arity == ARITY_ZEROORMORE ) { - return new TokenTuple(token, true, ARITY_ZEROORMORE).makeCanonical(); + return new TokenTuple(token, true, ARITY_ZEROORMORE).makeCanonical(); } else { - return new TokenTuple(token, true, ARITY_ONEORMORE).makeCanonical(); + return new TokenTuple(token, true, ARITY_ONEORMORE).makeCanonical(); } } else { // a single object region's token can only have ZEROORMORE or ONE if( arity == ARITY_ZEROORMORE && tt.arity == ARITY_ZEROORMORE ) { - return new TokenTuple(token, false, ARITY_ZEROORMORE).makeCanonical(); + return new TokenTuple(token, false, ARITY_ZEROORMORE).makeCanonical(); } else { - return new TokenTuple(token, false, ARITY_ONE).makeCanonical(); + return new TokenTuple(token, false, ARITY_ONE).makeCanonical(); } } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/TokenTupleSet.java b/Robust/src/Analysis/OwnershipAnalysis/TokenTupleSet.java index 4b82b3e5..1a84635e 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/TokenTupleSet.java +++ b/Robust/src/Analysis/OwnershipAnalysis/TokenTupleSet.java @@ -65,7 +65,7 @@ public class TokenTupleSet extends Canonical { TokenTuple ttThis = this.containsToken(ttIn.getToken() ); if( ttThis == null ) { - return false; + return false; } } @@ -78,7 +78,7 @@ public class TokenTupleSet extends Canonical { if( ttIn == null && ttThis.getArity() != TokenTuple.ARITY_ZEROORMORE ) { - return false; + return false; } } @@ -125,9 +125,9 @@ public class TokenTupleSet extends Canonical { TokenTuple ttIn = ttsIn.containsToken(ttThis.getToken() ); if( ttIn != null ) { - ttsOut.tokenTuples.add(ttThis.unionArity(ttIn) ); + ttsOut.tokenTuples.add(ttThis.unionArity(ttIn) ); } else { - ttsOut.tokenTuples.add(ttThis); + ttsOut.tokenTuples.add(ttThis); } } @@ -137,7 +137,7 @@ public class TokenTupleSet extends Canonical { TokenTuple ttThis = ttsOut.containsToken(ttIn.getToken() ); if( ttThis == null ) { - ttsOut.tokenTuples.add(ttIn); + ttsOut.tokenTuples.add(ttIn); } } @@ -195,7 +195,7 @@ public class TokenTupleSet extends Canonical { while( itr.hasNext() ) { TokenTuple tt = (TokenTuple) itr.next(); if( token.equals(tt.getToken() ) ) { - return tt; + return tt; } } return null; @@ -220,29 +220,29 @@ public class TokenTupleSet extends Canonical { // tokens not associated with // the site should be left alone if( age == AllocationSite.AGE_notInThisSite ) { - ttsOut.tokenTuples.add(tt); + ttsOut.tokenTuples.add(tt); } else if( age == AllocationSite.AGE_summary ) { - // remember the summary tuple, but don't add it - // we may combine it with the oldest tuple - ttSummary = tt; + // remember the summary tuple, but don't add it + // we may combine it with the oldest tuple + ttSummary = tt; } else if( age == AllocationSite.AGE_oldest ) { - // found an oldest token, again just remember - // for later - ttOldest = tt; + // found an oldest token, again just remember + // for later + ttOldest = tt; } else { - assert age == AllocationSite.AGE_in_I; + assert age == AllocationSite.AGE_in_I; - Integer I = as.getAge(token); - assert I != null; + Integer I = as.getAge(token); + assert I != null; - // otherwise, we change this token to the - // next older token - Integer tokenToChangeTo = as.getIthOldest(I + 1); - TokenTuple ttAged = tt.changeTokenTo(tokenToChangeTo); - ttsOut.tokenTuples.add(ttAged); + // otherwise, we change this token to the + // next older token + Integer tokenToChangeTo = as.getIthOldest(I + 1); + TokenTuple ttAged = tt.changeTokenTo(tokenToChangeTo); + ttsOut.tokenTuples.add(ttAged); } } @@ -293,32 +293,32 @@ public class TokenTupleSet extends Canonical { int shadowAge = as.getShadowAgeCategory(token); if( shadowAge == AllocationSite.AGE_summary ) { - // remember the summary tuple, but don't add it - // we may combine it with the oldest tuple - ttSummary = tt; + // remember the summary tuple, but don't add it + // we may combine it with the oldest tuple + ttSummary = tt; } else if( shadowAge == AllocationSite.SHADOWAGE_notInThisSite ) { - ttsOut.tokenTuples.add(tt); + ttsOut.tokenTuples.add(tt); } else if( shadowAge == AllocationSite.SHADOWAGE_summary ) { - // found the shadow summary token, again just remember - // for later - ttShadowSummary = tt; + // found the shadow summary token, again just remember + // for later + ttShadowSummary = tt; } else if( shadowAge == AllocationSite.SHADOWAGE_oldest ) { - Integer tokenToChangeTo = as.getOldest(); - TokenTuple ttNormal = tt.changeTokenTo(tokenToChangeTo); - ttsOut.tokenTuples.add(ttNormal); + Integer tokenToChangeTo = as.getOldest(); + TokenTuple ttNormal = tt.changeTokenTo(tokenToChangeTo); + ttsOut.tokenTuples.add(ttNormal); } else { - assert shadowAge == AllocationSite.SHADOWAGE_in_I; + assert shadowAge == AllocationSite.SHADOWAGE_in_I; - Integer I = as.getShadowAge(token); - assert I != null; + Integer I = as.getShadowAge(token); + assert I != null; - Integer tokenToChangeTo = as.getIthOldest(-I); - TokenTuple ttNormal = tt.changeTokenTo(tokenToChangeTo); - ttsOut.tokenTuples.add(ttNormal); + Integer tokenToChangeTo = as.getIthOldest(-I); + TokenTuple ttNormal = tt.changeTokenTo(tokenToChangeTo); + ttsOut.tokenTuples.add(ttNormal); } } @@ -360,21 +360,21 @@ public class TokenTupleSet extends Canonical { // summary tokens and tokens not associated with // the site should be left alone if( age == AllocationSite.AGE_notInThisSite ) { - ttsOut = ttsOut.union(tt); + ttsOut = ttsOut.union(tt); } else if( age == AllocationSite.AGE_summary ) { - ttsOut = ttsOut.union(tt.changeTokenTo(as.getSummaryShadow() )); + ttsOut = ttsOut.union(tt.changeTokenTo(as.getSummaryShadow() )); } else if( age == AllocationSite.AGE_oldest ) { - ttsOut = ttsOut.union(tt.changeTokenTo(as.getOldestShadow() )); + ttsOut = ttsOut.union(tt.changeTokenTo(as.getOldestShadow() )); } else { - assert age == AllocationSite.AGE_in_I; + assert age == AllocationSite.AGE_in_I; - Integer I = as.getAge(token); - assert I != null; + Integer I = as.getAge(token); + assert I != null; - ttsOut = ttsOut.union(tt.changeTokenTo(as.getIthOldestShadow(I) )); + ttsOut = ttsOut.union(tt.changeTokenTo(as.getIthOldestShadow(I) )); } } @@ -398,20 +398,20 @@ public class TokenTupleSet extends Canonical { Iterator replaceItr = replacements.iterator(); while( replaceItr.hasNext() ) { - TokenTupleSet replacement = replaceItr.next(); - TokenTupleSet replaced = new TokenTupleSet(ttsMinusToken).makeCanonical(); - replaced = replaced.unionUpArity(replacement); - rsOut = rsOut.add(replaced); + TokenTupleSet replacement = replaceItr.next(); + TokenTupleSet replaced = new TokenTupleSet(ttsMinusToken).makeCanonical(); + replaced = replaced.unionUpArity(replacement); + rsOut = rsOut.add(replaced); - if( makeChangeSet ) { - assert forChangeSet != null; + if( makeChangeSet ) { + assert forChangeSet != null; - if( forChangeSet.get(this) == null ) { - forChangeSet.put(this, new HashSet() ); - } + if( forChangeSet.get(this) == null ) { + forChangeSet.put(this, new HashSet() ); + } - forChangeSet.get(this).add(replaced); - } + forChangeSet.get(this).add(replaced); + } } } diff --git a/Robust/src/Analysis/Pointer/AllocFactory.java b/Robust/src/Analysis/Pointer/AllocFactory.java index f285a005..04a46e47 100644 --- a/Robust/src/Analysis/Pointer/AllocFactory.java +++ b/Robust/src/Analysis/Pointer/AllocFactory.java @@ -54,8 +54,8 @@ public class AllocFactory { public boolean equals(Object o) { if (o instanceof AllocNode) { - AllocNode an=(AllocNode)o; - return (allocsite==an.allocsite)&&(summary==an.summary); + AllocNode an=(AllocNode)o; + return (allocsite==an.allocsite)&&(summary==an.summary); } return false; } @@ -66,9 +66,9 @@ public class AllocFactory { public String getID() { if (summary) - return "SUM"+allocsite; + return "SUM"+allocsite; else - return "SING"+allocsite; + return "SING"+allocsite; } } @@ -99,8 +99,8 @@ public class AllocFactory { public boolean equals(Object o) { if (o instanceof AllocSiteNode) { - AllocSiteNode an=(AllocSiteNode)o; - return (allocsite==an.allocsite); + AllocSiteNode an=(AllocSiteNode)o; + return (allocsite==an.allocsite); } return false; } diff --git a/Robust/src/Analysis/Pointer/BasicBlock.java b/Robust/src/Analysis/Pointer/BasicBlock.java index 0b769ec8..9d3df1b9 100644 --- a/Robust/src/Analysis/Pointer/BasicBlock.java +++ b/Robust/src/Analysis/Pointer/BasicBlock.java @@ -66,44 +66,44 @@ public class BasicBlock { BBlock block=map.get(fn); block.nodes.add(fn); if (fn.kind()==FKind.FlatExit) - exit=block; + exit=block; do { - if (pm.numNext(fn)!=1) { - for(int i=0; i1) { - //new basic block - if (!map.containsKey(fn)) { - BBlock newb=new BBlock(); - blockset.add(newb); - map.put(fn, newb); - toprocess.add(fn); - } - //link block in - if (!block.nextb.contains(map.get(fn))) { - block.nextb.add(map.get(fn)); - map.get(fn).prevb.add(block); - } - break; - } - block.nodes.add(fn); - if (fn.kind()==FKind.FlatExit) - exit=block; + if (pm.numNext(fn)!=1) { + for(int i=0; i1) { + //new basic block + if (!map.containsKey(fn)) { + BBlock newb=new BBlock(); + blockset.add(newb); + map.put(fn, newb); + toprocess.add(fn); + } + //link block in + if (!block.nextb.contains(map.get(fn))) { + block.nextb.add(map.get(fn)); + map.get(fn).prevb.add(block); + } + break; + } + block.nodes.add(fn); + if (fn.kind()==FKind.FlatExit) + exit=block; } while(true); } return new BasicBlock(map.get(fm), exit, blockset); diff --git a/Robust/src/Analysis/Pointer/Delta.java b/Robust/src/Analysis/Pointer/Delta.java index abcee7b1..efbbe9fc 100644 --- a/Robust/src/Analysis/Pointer/Delta.java +++ b/Robust/src/Analysis/Pointer/Delta.java @@ -20,19 +20,19 @@ public class Delta { for(Map.Entry> entry : heapedgeadd.entrySet()) { AllocNode node=entry.getKey(); if (node==null) - throw new Error("null node key"); + throw new Error("null node key"); for(Edge e : entry.getValue()) - if (e.src!=node) - throw new Error(e.src+" is not equal to "+node); + if (e.src!=node) + throw new Error(e.src+" is not equal to "+node); } for(Map.Entry> entry : varedgeadd.entrySet()) { TempDescriptor tmp=entry.getKey(); if (tmp==null) - throw new Error("null temp key"); + throw new Error("null temp key"); for(Edge e : entry.getValue()) - if (e.srcvar!=tmp) - throw new Error(e.srcvar+" is not equal to "+tmp); + if (e.srcvar!=tmp) + throw new Error(e.srcvar+" is not equal to "+tmp); } return this; } @@ -105,10 +105,10 @@ public class Delta { TempDescriptor newTmp=tmpMap.get(entry.getKey()); MySet edgeset=entry.getValue(); if (!edgeset.isEmpty()) { - newdelta.varedgeadd.put(newTmp, new MySet()); - for(Edge e : edgeset) { - newdelta.varedgeadd.get(newTmp).add(e.rewrite(origTmp, newTmp)); - } + newdelta.varedgeadd.put(newTmp, new MySet()); + for(Edge e : edgeset) { + newdelta.varedgeadd.get(newTmp).add(e.rewrite(origTmp, newTmp)); + } } } newdelta.varedgeremove=varedgeremove; @@ -143,15 +143,15 @@ public class Delta { for(Edge e : edges) { if (e.srcvar!=null) { - if (!newdelta.varedgeadd.containsKey(e.srcvar)) { - newdelta.varedgeadd.put(e.srcvar, new MySet()); - } - newdelta.varedgeadd.get(e.srcvar).add(e); + if (!newdelta.varedgeadd.containsKey(e.srcvar)) { + newdelta.varedgeadd.put(e.srcvar, new MySet()); + } + newdelta.varedgeadd.get(e.srcvar).add(e); } else { - if (!newdelta.heapedgeadd.containsKey(e.src)) { - newdelta.heapedgeadd.put(e.src, new MySet()); - } - newdelta.heapedgeadd.get(e.src).add(e.makeOld()); + if (!newdelta.heapedgeadd.containsKey(e.src)) { + newdelta.heapedgeadd.put(e.src, new MySet()); + } + newdelta.heapedgeadd.get(e.src).add(e.makeOld()); } } return newdelta; diff --git a/Robust/src/Analysis/Pointer/Edge.java b/Robust/src/Analysis/Pointer/Edge.java index 5d6c0587..fe84b5c6 100644 --- a/Robust/src/Analysis/Pointer/Edge.java +++ b/Robust/src/Analysis/Pointer/Edge.java @@ -127,9 +127,9 @@ public class Edge { if (o instanceof Edge) { Edge e=(Edge) o; if (srcvar!=null) { - return (srcvar==e.srcvar)&&(dst==e.dst); + return (srcvar==e.srcvar)&&(dst==e.dst); } else { - return (src==e.src)&&(dst==e.dst)&&(fd==e.fd); + return (src==e.src)&&(dst==e.dst)&&(fd==e.fd); } } return false; @@ -180,9 +180,9 @@ public class Edge { newe.statuspredicate=mergeStatus(statuspredicate, e.statuspredicate); if (e.taints!=null) { if (newe.taints==null) - newe.taints=e.taints; + newe.taints=e.taints; else - newe.taints=newe.taints.merge(e.taints); + newe.taints=newe.taints.merge(e.taints); } return newe; } @@ -212,11 +212,11 @@ public class Edge { int edgeindex=0; for(int count=0; count<4; count++) { if ((mask&statuspredicate)==mask) { - Edge e=new Edge(); - e.fd=fd; - e.src=factory.getAllocNode(src, (mask&3)==0); - e.dst=factory.getAllocNode(dst, (mask&5)==0); - earray[edgeindex++]=e; + Edge e=new Edge(); + e.fd=fd; + e.src=factory.getAllocNode(src, (mask&3)==0); + e.dst=factory.getAllocNode(dst, (mask&5)==0); + earray[edgeindex++]=e; } mask=mask<<1; } @@ -232,9 +232,9 @@ public class Edge { return true; if (ts1==null) { if (ts2.isEmpty()) - return true; + return true; else - return false; + return false; } //Neither is null //Do a set comparison @@ -274,8 +274,8 @@ public class Edge { public static void mergeEdgesInto(MySet orig, MySet merge) { for(Edge e : merge) { if (orig.contains(e)) { - Edge old=orig.get(e); - e=e.merge(old); + Edge old=orig.get(e); + e=e.merge(old); } orig.add(e); } diff --git a/Robust/src/Analysis/Pointer/Graph.java b/Robust/src/Analysis/Pointer/Graph.java index afb98c59..0d7e16af 100644 --- a/Robust/src/Analysis/Pointer/Graph.java +++ b/Robust/src/Analysis/Pointer/Graph.java @@ -43,18 +43,18 @@ public class Graph { for(Map.Entry> entry : nodeMap.entrySet()) { AllocNode node=entry.getKey(); if (node==null) - throw new Error("Null node key"); + throw new Error("Null node key"); for(Edge e : entry.getValue()) - if (e.src!=node) - throw new Error(); + if (e.src!=node) + throw new Error(); } for(Map.Entry> entry : varMap.entrySet()) { TempDescriptor tmp=entry.getKey(); if (tmp==null) - throw new Error("Null tmp key"); + throw new Error("Null tmp key"); for(Edge e : entry.getValue()) - if (e.srcvar!=tmp) - throw new Error(); + if (e.srcvar!=tmp) + throw new Error(); } } @@ -97,16 +97,16 @@ public class Graph { if (old.srcvar!=null) { MySet edges=varMap.get(old.srcvar); if (edges==null) - edges=parent.varMap.get(old.srcvar); + edges=parent.varMap.get(old.srcvar); if (edges==null) - return null; + return null; return edges.get(old); } else { MySet edges=nodeMap.get(old.src); if (edges==null) - edges=parent.nodeMap.get(old.src); + edges=parent.nodeMap.get(old.src); if (edges==null) - return null; + return null; return edges.get(old); } } @@ -147,13 +147,13 @@ public class Graph { for(Map.Entry> entry : varMap.entrySet()) { TempDescriptor tmp=entry.getKey(); if (childvarMap!=null&&childvarMap.containsKey(tmp)) - continue; + continue; output.println(tmp.getSymbol()+"[shape=rectangle];"); for(Edge e : entry.getValue()) { - if (e.srcvar!=tmp) - throw new Error(e.srcvar +" is not equal to "+tmp); - AllocNode n=e.dst; - output.println("\t"+tmp.getSymbol()+"->"+n.getID()+"[label=\""+e.taintString()+"\"];"); + if (e.srcvar!=tmp) + throw new Error(e.srcvar +" is not equal to "+tmp); + AllocNode n=e.dst; + output.println("\t"+tmp.getSymbol()+"->"+n.getID()+"[label=\""+e.taintString()+"\"];"); } } } @@ -163,16 +163,16 @@ public class Graph { for(Map.Entry> entry : nodeMap.entrySet()) { AllocNode node=entry.getKey(); if (childNodeMap!=null&&childNodeMap.containsKey(node)) - continue; + continue; for(Edge e : entry.getValue()) { - if (e.src!=node) - throw new Error(e.src+" is not equal to "+node); - AllocNode n=e.dst; - String src=node.getID(); - String dst=n.getID(); - String field=e.fd!=null?e.fd.getSymbol():"[]"; - String taint=e.taints!=null?":"+e.taintString():""; - output.println("\t"+src+"->"+dst+"[label=\""+field+" "+taint+"\"];"); + if (e.src!=node) + throw new Error(e.src+" is not equal to "+node); + AllocNode n=e.dst; + String src=node.getID(); + String dst=n.getID(); + String field=e.fd!=null?e.fd.getSymbol():"[]"; + String taint=e.taints!=null?":"+e.taintString():""; + output.println("\t"+src+"->"+dst+"[label=\""+field+" "+taint+"\"];"); } } } diff --git a/Robust/src/Analysis/Pointer/GraphManip.java b/Robust/src/Analysis/Pointer/GraphManip.java index 535ca035..349e24cb 100644 --- a/Robust/src/Analysis/Pointer/GraphManip.java +++ b/Robust/src/Analysis/Pointer/GraphManip.java @@ -27,7 +27,7 @@ public class GraphManip { MySet edgeset=new MySet(); for(AllocNode srcnode : srcSet) { for(AllocNode dstnode : dstSet) { - edgeset.add(new Edge(srcnode, fd, dstnode, Edge.NEW)); + edgeset.add(new Edge(srcnode, fd, dstnode, Edge.NEW)); } } return edgeset; @@ -37,7 +37,7 @@ public class GraphManip { MySet edgeset=new MySet(); for(Edge srcedge : srcSet) { for(Edge dstedge : dstSet) { - edgeset.add(dstedge.changeSrc(fd, srcedge.dst)); + edgeset.add(dstedge.changeSrc(fd, srcedge.dst)); } } return edgeset; @@ -47,7 +47,7 @@ public class GraphManip { MySet edgeset=new MySet(); for(AllocNode srcnode : srcSet) { for(Edge dstedge : dstSet) { - edgeset.add(dstedge.changeSrc(fd, srcnode)); + edgeset.add(dstedge.changeSrc(fd, srcnode)); } } return edgeset; @@ -60,13 +60,13 @@ public class GraphManip { MySet baseedges=delta.basevaredge.get(tmp); if (baseedges!=null) { for(Edge e : baseedges) { - if (removeedges==null||!removeedges.contains(e)) - edges.add(e); + if (removeedges==null||!removeedges.contains(e)) + edges.add(e); } } if (delta.varedgeadd.containsKey(tmp)) for(Edge e : delta.varedgeadd.get(tmp)) { - edges.add(e); + edges.add(e); } return edges; } @@ -77,11 +77,11 @@ public class GraphManip { for(Edge e : graph.getEdges(tmp)) { if (removeedges==null||!removeedges.contains(e)) - edges.add(e); + edges.add(e); } if (delta.varedgeadd.containsKey(tmp)) for(Edge e : delta.varedgeadd.get(tmp)) { - edges.add(e); + edges.add(e); } return edges; } @@ -91,14 +91,14 @@ public class GraphManip { for(Edge node : srcNodes) { MySet removeedges=delta.heapedgeremove.get(node.dst); for(Edge e : graph.getEdges(node.dst)) { - if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) - nodes.add(e); + if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) + nodes.add(e); } if (delta.heapedgeadd.containsKey(node.dst)) - for(Edge e : delta.heapedgeadd.get(node.dst)) { - if (e.fd==fd) - nodes.add(e); - } + for(Edge e : delta.heapedgeadd.get(node.dst)) { + if (e.fd==fd) + nodes.add(e); + } } return nodes; } @@ -108,14 +108,14 @@ public class GraphManip { for(AllocNode node : srcNodes) { MySet removeedges=delta.heapedgeremove.get(node); for(Edge e : graph.getEdges(node)) { - if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) - nodes.add(e); + if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) + nodes.add(e); } if (delta.heapedgeadd.containsKey(node)) - for(Edge e : delta.heapedgeadd.get(node)) { - if (e.fd==fd) - nodes.add(e); - } + for(Edge e : delta.heapedgeadd.get(node)) { + if (e.fd==fd) + nodes.add(e); + } } return nodes; } @@ -125,11 +125,11 @@ public class GraphManip { MySet removeedges=delta.heapedgeremove.get(node); for(Edge e : graph.getEdges(node)) { if ((removeedges==null||!removeedges.contains(e))) - nodes.add(e); + nodes.add(e); } if (delta.heapedgeadd.containsKey(node)) for(Edge e : delta.heapedgeadd.get(node)) { - nodes.add(e); + nodes.add(e); } return nodes; @@ -143,12 +143,12 @@ public class GraphManip { if (baseEdges!=null) for(Edge e : baseEdges) { - if (removeedges==null||!removeedges.contains(e)) - nodes.add(e.dst); + if (removeedges==null||!removeedges.contains(e)) + nodes.add(e.dst); } if (delta.varedgeadd.containsKey(tmp)) for(Edge e : delta.varedgeadd.get(tmp)) { - nodes.add(e.dst); + nodes.add(e.dst); } return nodes; } @@ -159,11 +159,11 @@ public class GraphManip { for(Edge e : graph.getEdges(tmp)) { if (removeedges==null||!removeedges.contains(e)) - nodes.add(e.dst); + nodes.add(e.dst); } if (delta.varedgeadd.containsKey(tmp)) for(Edge e : delta.varedgeadd.get(tmp)) { - nodes.add(e.dst); + nodes.add(e.dst); } return nodes; } @@ -174,15 +174,15 @@ public class GraphManip { MySet removeedges=delta.heapedgeremove.get(node); MySet baseEdges=delta.baseheapedge.get(node); if (baseEdges!=null) - for(Edge e : baseEdges) { - if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) - nodes.add(e.dst); - } + for(Edge e : baseEdges) { + if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) + nodes.add(e.dst); + } if (delta.heapedgeadd.containsKey(node)) - for(Edge e : delta.heapedgeadd.get(node)) { - if (e.fd==fd) - nodes.add(e.dst); - } + for(Edge e : delta.heapedgeadd.get(node)) { + if (e.fd==fd) + nodes.add(e.dst); + } } return nodes; } @@ -192,20 +192,20 @@ public class GraphManip { for(Map.Entry> entry : delta.baseheapedge.entrySet()) { AllocNode node=entry.getKey(); if (srcNodes.contains(node)) { - MySet edges=entry.getValue(); - MySet removeedges=delta.heapedgeremove.get(node); - for(Edge e : edges) { - if (removeedges==null||!removeedges.contains(e)) { - newedges.add(e); - } - } + MySet edges=entry.getValue(); + MySet removeedges=delta.heapedgeremove.get(node); + for(Edge e : edges) { + if (removeedges==null||!removeedges.contains(e)) { + newedges.add(e); + } + } } } for(Map.Entry> entry : delta.heapedgeadd.entrySet()) { AllocNode node=entry.getKey(); if (srcNodes.contains(node)) { - MySet edges=entry.getValue(); - newedges.addAll(edges); + MySet edges=entry.getValue(); + newedges.addAll(edges); } } return newedges; @@ -216,23 +216,23 @@ public class GraphManip { for(Map.Entry> entry : delta.baseheapedge.entrySet()) { AllocNode node=entry.getKey(); if (srcNodes.contains(node)) { - MySet edges=entry.getValue(); - MySet removeedges=delta.heapedgeremove.get(node); - for(Edge e : edges) { - if ((removeedges==null||!removeedges.contains(e))&&(e.fd==fd)) { - newedges.add(e); - } - } + MySet edges=entry.getValue(); + MySet removeedges=delta.heapedgeremove.get(node); + for(Edge e : edges) { + if ((removeedges==null||!removeedges.contains(e))&&(e.fd==fd)) { + newedges.add(e); + } + } } } for(Map.Entry> entry : delta.heapedgeadd.entrySet()) { AllocNode node=entry.getKey(); if (srcNodes.contains(node)) { - MySet edges=entry.getValue(); - for(Edge e : edges) { - if (e.fd==fd) - newedges.add(e); - } + MySet edges=entry.getValue(); + for(Edge e : edges) { + if (e.fd==fd) + newedges.add(e); + } } } return newedges; @@ -251,34 +251,34 @@ public class GraphManip { for(Edge edge : srcEdges) { TaintSet ts=edge.getTaints(); if (ts!=null) { - ts=ts.reTaint(fn); + ts=ts.reTaint(fn); } MySet removeedges=delta.heapedgeremove.get(edge.dst); for(Edge e : graph.getEdges(edge.dst)) { - if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) { - e=e.changeSrcVar(dst, ts); - if (!edgeset.contains(e)) - edgeset.add(e); - else { - Edge preve=edgeset.get(e); - e=e.merge(preve); - edgeset.add(e); - } - } + if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) { + e=e.changeSrcVar(dst, ts); + if (!edgeset.contains(e)) + edgeset.add(e); + else { + Edge preve=edgeset.get(e); + e=e.merge(preve); + edgeset.add(e); + } + } } if (delta.heapedgeadd.containsKey(edge.dst)) - for(Edge e : delta.heapedgeadd.get(edge.dst)) { - if (e.fd==fd) { - e=e.changeSrcVar(dst, ts); - if (!edgeset.contains(e)) - edgeset.add(e); - else { - Edge preve=edgeset.get(e); - e=e.merge(preve); - edgeset.add(e); - } - } - } + for(Edge e : delta.heapedgeadd.get(edge.dst)) { + if (e.fd==fd) { + e=e.changeSrcVar(dst, ts); + if (!edgeset.contains(e)) + edgeset.add(e); + else { + Edge preve=edgeset.get(e); + e=e.merge(preve); + edgeset.add(e); + } + } + } } return edgeset; } @@ -288,36 +288,36 @@ public class GraphManip { for(Edge edge : srcEdges) { TaintSet ts=edge.getTaints(); if (ts!=null) { - ts=ts.reTaint(fn); + ts=ts.reTaint(fn); } MySet removeedges=delta.heapedgeremove.get(edge.dst); if (delta.baseheapedge.containsKey(edge.dst)) { - for(Edge e : delta.baseheapedge.get(edge.dst)) { - if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) { - e=e.changeSrcVar(dst, ts); - if (!edgeset.contains(e)) - edgeset.add(e); - else { - Edge preve=edgeset.get(e); - e=e.merge(preve); - edgeset.add(e); - } - } - } + for(Edge e : delta.baseheapedge.get(edge.dst)) { + if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) { + e=e.changeSrcVar(dst, ts); + if (!edgeset.contains(e)) + edgeset.add(e); + else { + Edge preve=edgeset.get(e); + e=e.merge(preve); + edgeset.add(e); + } + } + } } if (delta.heapedgeadd.containsKey(edge.dst)) - for(Edge e : delta.heapedgeadd.get(edge.dst)) { - if (e.fd==fd) { - e=e.changeSrcVar(dst, ts); - if (!edgeset.contains(e)) - edgeset.add(e); - else { - Edge preve=edgeset.get(e); - e=e.merge(preve); - edgeset.add(e); - } - } - } + for(Edge e : delta.heapedgeadd.get(edge.dst)) { + if (e.fd==fd) { + e=e.changeSrcVar(dst, ts); + if (!edgeset.contains(e)) + edgeset.add(e); + else { + Edge preve=edgeset.get(e); + e=e.merge(preve); + edgeset.add(e); + } + } + } } return edgeset; } @@ -327,14 +327,14 @@ public class GraphManip { for(AllocNode node : srcNodes) { MySet removeedges=delta.heapedgeremove.get(node); for(Edge e : graph.getEdges(node)) { - if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) - nodes.add(e.dst); + if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) + nodes.add(e.dst); } if (delta.heapedgeadd.containsKey(node)) - for(Edge e : delta.heapedgeadd.get(node)) { - if (e.fd==fd) - nodes.add(e.dst); - } + for(Edge e : delta.heapedgeadd.get(node)) { + if (e.fd==fd) + nodes.add(e.dst); + } } return nodes; } diff --git a/Robust/src/Analysis/Pointer/Pointer.java b/Robust/src/Analysis/Pointer/Pointer.java index c5f0bcd7..d5454e64 100644 --- a/Robust/src/Analysis/Pointer/Pointer.java +++ b/Robust/src/Analysis/Pointer/Pointer.java @@ -78,16 +78,16 @@ public class Pointer implements HeapAnalysis { blockMap.put(fm, BasicBlock.getBBlock(fm)); Hashtable> livemap=Liveness.computeLiveTemps(fm); for(BBlock bblock : blockMap.get(fm).getBlocks()) { - FlatNode fn=bblock.nodes.get(0); - if (fn==fm) { - HashSet fmset=new HashSet(); - fmset.addAll((List)Arrays.asList(fm.writesTemps())); - bblivetemps.put(bblock, fmset); - } else { - Set livetemps=livemap.get(fn); - bblivetemps.put(bblock, livetemps); - livetemps.add(returntmp); - } + FlatNode fn=bblock.nodes.get(0); + if (fn==fm) { + HashSet fmset=new HashSet(); + fmset.addAll((List)Arrays.asList(fm.writesTemps())); + bblivetemps.put(bblock, fmset); + } else { + Set livetemps=livemap.get(fn); + bblivetemps.put(bblock, livetemps); + livetemps.add(returntmp); + } } } return blockMap.get(fm); @@ -126,20 +126,20 @@ nextdelta: int startindex=0; if (ppoint.getIndex()==-1) { - //Build base graph for entrance to this basic block - //System.out.println("Processing "+bblock.nodes.get(0).toString().replace(' ','_')); - //delta.print(); - delta=applyInitDelta(delta, bblock); - //System.out.println("Generating:"); - //delta.print(); + //Build base graph for entrance to this basic block + //System.out.println("Processing "+bblock.nodes.get(0).toString().replace(' ','_')); + //delta.print(); + delta=applyInitDelta(delta, bblock); + //System.out.println("Generating:"); + //delta.print(); } else { - //System.out.println("Processing Call "+bblock.nodes.get(ppoint.getIndex()).toString().replace(' ','_')); - //delta.print(); + //System.out.println("Processing Call "+bblock.nodes.get(ppoint.getIndex()).toString().replace(' ','_')); + //delta.print(); - startindex=ppoint.getIndex()+1; - delta=applyCallDelta(delta, bblock); - //System.out.println("Generating:"); - //delta.print(); + startindex=ppoint.getIndex()+1; + delta=applyCallDelta(delta, bblock); + //System.out.println("Generating:"); + //delta.print(); } Graph graph=bbgraphMap.get(bblock); Graph nodeGraph=null; @@ -147,49 +147,49 @@ nextdelta: int lasti=-1; //Compute delta at exit of each node for(int i=startindex; i=i; lasti--) { - FlatNode scurrNode=nodes.get(lasti); - if (isNEEDED(scurrNode)||isINACC(scurrNode)) { - break; - } - } - } - if (i==lasti) { - mustProcess.add(currNode); - graphMap.put(currNode, new Graph(graph)); - fallthru=false; - } - } - if (fallthru) { - if (i==0) { - //base graph works for us - graphMap.put(currNode, new Graph(graph)); - } else { - //just use previous graph - graphMap.put(currNode, graphMap.get(nodes.get(i-1))); - } - } - } - } - - nodeGraph=graphMap.get(currNode); - delta=processNode(bblock, i, currNode, delta, nodeGraph); - //System.out.println("Processing "+currNode+" and generating delta:"); - //delta.print(); + FlatNode currNode=nodes.get(i); + //System.out.println("Start Processing "+currNode); + boolean init=delta.getInit(); + if (!init&&delta.isEmpty()) + continue nextdelta; + + + if (!graphMap.containsKey(currNode)) { + if (isNEEDED(currNode)) { + graphMap.put(currNode, new Graph(graph)); + } else { + boolean fallthru=true; + if (isINACC(currNode)&&((lasti==-1)||(lasti==i))) { + if (lasti==-1) { + for(lasti=nodes.size()-1; lasti>=i; lasti--) { + FlatNode scurrNode=nodes.get(lasti); + if (isNEEDED(scurrNode)||isINACC(scurrNode)) { + break; + } + } + } + if (i==lasti) { + mustProcess.add(currNode); + graphMap.put(currNode, new Graph(graph)); + fallthru=false; + } + } + if (fallthru) { + if (i==0) { + //base graph works for us + graphMap.put(currNode, new Graph(graph)); + } else { + //just use previous graph + graphMap.put(currNode, graphMap.get(nodes.get(i-1))); + } + } + } + } + + nodeGraph=graphMap.get(currNode); + delta=processNode(bblock, i, currNode, delta, nodeGraph); + //System.out.println("Processing "+currNode+" and generating delta:"); + //delta.print(); } generateFinalDelta(bblock, delta, nodeGraph); } @@ -198,19 +198,19 @@ nextdelta: if (false) { int debugindex=0; for(Map.Entry e : bbgraphMap.entrySet()) { - Graph g=e.getValue(); - plotGraph(g,"BB"+e.getKey().nodes.get(0).toString().replace(' ','_')); - debugindex++; + Graph g=e.getValue(); + plotGraph(g,"BB"+e.getKey().nodes.get(0).toString().replace(' ','_')); + debugindex++; } for(FlatMethod fm : blockMap.keySet()) { - System.out.println(fm.printMethod()); + System.out.println(fm.printMethod()); } for(Map.Entry e : graphMap.entrySet()) { - FlatNode fn=e.getKey(); - Graph g=e.getValue(); - plotGraph(g,"FN"+fn.toString()+debugindex); - debugindex++; + FlatNode fn=e.getKey(); + Graph g=e.getValue(); + plotGraph(g,"FN"+fn.toString()+debugindex); + debugindex++; } } @@ -249,9 +249,9 @@ nextdelta: MySet edgeSet=new MySet(); /* Get target set */ if (graph.varMap.containsKey(tmp)) - edgeSet.addAll(graph.varMap.get(tmp)); + edgeSet.addAll(graph.varMap.get(tmp)); else - edgeSet.addAll(graph.parent.varMap.get(tmp)); + edgeSet.addAll(graph.parent.varMap.get(tmp)); newDelta.varedgeadd.put(tmp, edgeSet); } @@ -264,18 +264,18 @@ nextdelta: MySet edgeSet=new MySet(); /* Get edge set */ if (graph.nodeMap.containsKey(node)) - edgeSet.addAll(graph.nodeMap.get(node)); + edgeSet.addAll(graph.nodeMap.get(node)); else - edgeSet.addAll(graph.parent.nodeMap.get(node)); + edgeSet.addAll(graph.parent.nodeMap.get(node)); newDelta.heapedgeadd.put(node, edgeSet); /* Compute ages */ if (graph.oldNodes.containsKey(node)) { - if (graph.oldNodes.get(node).booleanValue()) - newDelta.addOldNodes.put(node, Boolean.TRUE); + if (graph.oldNodes.get(node).booleanValue()) + newDelta.addOldNodes.put(node, Boolean.TRUE); } else if (graph.parent.oldNodes.containsKey(node)) { - //parent graphs only contain true...no need to check - newDelta.addOldNodes.put(node, Boolean.TRUE); + //parent graphs only contain true...no need to check + newDelta.addOldNodes.put(node, Boolean.TRUE); } } @@ -296,16 +296,16 @@ nextdelta: tmpSet.addAll(delta.basevaredge.keySet()); tmpSet.addAll(delta.varedgeadd.keySet()); for(TempDescriptor tmp : tmpSet) { - /* Start with the new incoming edges */ - MySet newbaseedge=delta.basevaredge.get(tmp); - /* Remove the remove set */ - if (newbaseedge==null) - newbaseedge=new MySet(); - newbaseedge.removeAll(delta.varedgeremove.get(tmp)); - /* Add in the new set*/ - newbaseedge.addAll(delta.varedgeadd.get(tmp)); - /* Store the results */ - newDelta.varedgeadd.put(tmp, newbaseedge); + /* Start with the new incoming edges */ + MySet newbaseedge=delta.basevaredge.get(tmp); + /* Remove the remove set */ + if (newbaseedge==null) + newbaseedge=new MySet(); + newbaseedge.removeAll(delta.varedgeremove.get(tmp)); + /* Add in the new set*/ + newbaseedge.addAll(delta.varedgeadd.get(tmp)); + /* Store the results */ + newDelta.varedgeadd.put(tmp, newbaseedge); } delta.basevaredge.clear(); @@ -315,25 +315,25 @@ nextdelta: nodeSet.addAll(delta.heapedgeadd.keySet()); nodeSet.addAll(delta.heapedgeremove.keySet()); for(AllocNode node : nodeSet) { - /* Start with the new incoming edges */ - MySet newheapedge=new MySet(delta.baseheapedge.get(node)); - /* Remove the remove set */ - MySet removeset=delta.heapedgeremove.get(node); + /* Start with the new incoming edges */ + MySet newheapedge=new MySet(delta.baseheapedge.get(node)); + /* Remove the remove set */ + MySet removeset=delta.heapedgeremove.get(node); - if (removeset!=null) - newheapedge.removeAll(removeset); + if (removeset!=null) + newheapedge.removeAll(removeset); - /* Add in the add set */ - MySet settoadd=delta.heapedgeadd.get(node); - if (settoadd!=null) - newheapedge.addAll(settoadd); - newDelta.heapedgeadd.put(node, newheapedge); + /* Add in the add set */ + MySet settoadd=delta.heapedgeadd.get(node); + if (settoadd!=null) + newheapedge.addAll(settoadd); + newDelta.heapedgeadd.put(node, newheapedge); - /* Remove the newly created edges..no need to propagate a diff for those */ - if (removeset!=null) { - removeset.removeAll(delta.baseheapedge.get(node)); - newDelta.heapedgeremove.put(node, removeset); - } + /* Remove the newly created edges..no need to propagate a diff for those */ + if (removeset!=null) { + removeset.removeAll(delta.baseheapedge.get(node)); + newDelta.heapedgeremove.put(node, removeset); + } } /* Compute new ages */ @@ -345,15 +345,15 @@ nextdelta: oldNodes.addAll(delta.baseOldNodes.keySet()); oldNodes.addAll(delta.addOldNodes.keySet()); for(AllocNode node : oldNodes) { - if (delta.addOldNodes.containsKey(node)) { - if (delta.addOldNodes.get(node).booleanValue()) { - newDelta.addOldNodes.put(node, Boolean.TRUE); - } - } else { - if (delta.baseOldNodes.get(node).booleanValue()) { - newDelta.addOldNodes.put(node, Boolean.TRUE); - } - } + if (delta.addOldNodes.containsKey(node)) { + if (delta.addOldNodes.get(node).booleanValue()) { + newDelta.addOldNodes.put(node, Boolean.TRUE); + } + } else { + if (delta.baseOldNodes.get(node).booleanValue()) { + newDelta.addOldNodes.put(node, Boolean.TRUE); + } + } } } @@ -368,35 +368,35 @@ nextdelta: if (!newDelta.heapedgeadd.isEmpty()||!newDelta.heapedgeremove.isEmpty()||!newDelta.varedgeadd.isEmpty()||!newDelta.addNodeAges.isEmpty()||!newDelta.addOldNodes.isEmpty()) { /* We have a delta to propagate */ if (returnMap.containsKey(bblock)) { - //exit of call block - boolean first=true; - - for(PPoint caller : returnMap.get(bblock)) { - //System.out.println("Sending Return BBlock to "+caller.getBBlock().nodes.get(caller.getIndex()).toString().replace(' ','_')); - //newDelta.print(); - if (first) { - newDelta.setBlock(caller); - toprocess.add(newDelta); - first=false; - } else { - Delta d=newDelta.diffBlock(caller); - toprocess.add(d); - } - } + //exit of call block + boolean first=true; + + for(PPoint caller : returnMap.get(bblock)) { + //System.out.println("Sending Return BBlock to "+caller.getBBlock().nodes.get(caller.getIndex()).toString().replace(' ','_')); + //newDelta.print(); + if (first) { + newDelta.setBlock(caller); + toprocess.add(newDelta); + first=false; + } else { + Delta d=newDelta.diffBlock(caller); + toprocess.add(d); + } + } } else { - //normal block - Vector blockvector=bblock.next(); - for(int i=0; i blockvector=bblock.next(); + for(int i=0; i edges=GraphManip.getEdges(graph, delta, tmp); - for(Edge e : edges) { - Edge newe=e.addTaint(taint); - delta.addVarEdge(newe); - } + Taint taint=Taint.factory(sese, null, tmp, AllocFactory.dummySite, null, ReachGraph.predsEmpty); + MySet edges=GraphManip.getEdges(graph, delta, tmp); + for(Edge e : edges) { + Edge newe=e.addTaint(taint); + delta.addVarEdge(newe); + } } } else { removeDiffTaints(null, delta); for (TempDescriptor tmp : sese.getInVarSet()) { - Taint taint=Taint.factory(sese, null, tmp, AllocFactory.dummySite, null, ReachGraph.predsEmpty); - MySet edges=GraphManip.getDiffEdges(delta, tmp); - for(Edge e : edges) { - Edge newe=e.addTaint(taint); - delta.addVarEdge(newe); - } + Taint taint=Taint.factory(sese, null, tmp, AllocFactory.dummySite, null, ReachGraph.predsEmpty); + MySet edges=GraphManip.getDiffEdges(delta, tmp); + for(Edge e : edges) { + Edge newe=e.addTaint(taint); + delta.addVarEdge(newe); + } } } @@ -531,10 +531,10 @@ nextdelta: //Process delta edges processEdgeMap(sese, delta.varedgeadd, null, null, edgestoremove, edgestoadd); for(Edge e : edgestoremove) { - delta.removeVarEdge(e); + delta.removeVarEdge(e); } for(Edge e : edgestoadd) { - delta.addVarEdge(e); + delta.addVarEdge(e); } } @@ -548,10 +548,10 @@ nextdelta: //Process delta edges processEdgeMap(sese, delta.heapedgeadd, null, null, edgestoremove, edgestoadd); for(Edge e : edgestoremove) { - delta.removeHeapEdge(e); + delta.removeHeapEdge(e); } for(Edge e : edgestoadd) { - delta.addHeapEdge(e); + delta.addHeapEdge(e); } } } @@ -569,10 +569,10 @@ nextdelta: //Process delta edges processEdgeMap(sese, delta.varedgeadd, null, null, edgestoremove, edgestoadd); for(Edge e : edgestoremove) { - delta.removeVarEdge(e); + delta.removeVarEdge(e); } for(Edge e : edgestoadd) { - delta.addVarEdge(e); + delta.addVarEdge(e); } } @@ -588,10 +588,10 @@ nextdelta: //Process delta edges processEdgeMap(sese, delta.heapedgeadd, null, null, edgestoremove, edgestoadd); for(Edge e : edgestoremove) { - delta.removeHeapEdge(e); + delta.removeHeapEdge(e); } for(Edge e : edgestoadd) { - delta.addHeapEdge(e); + delta.addHeapEdge(e); } } } @@ -600,22 +600,22 @@ nextdelta: for(Map.Entry> entry:edgemap.entrySet()) { //If the parent map exists and overrides this entry, skip it if (childmap!=null&&childmap.containsKey(entry.getKey())) - continue; + continue; for(Edge e:entry.getValue()) { - //check whether this edge has been removed - if (removemap!=null&&removemap.containsKey(entry.getKey())&& - removemap.get(entry.getKey()).contains(e)) - continue; - //have real edge - TaintSet ts=e.getTaints(); - TaintSet newts=null; - //update non-null taint set - if (ts!=null) - newts=Canonical.removeInContextTaintsNP(ts, sese); - if (newts!=null&&newts!=ts) { - edgestoremove.add(e); - edgestoadd.add(e.changeTaintSet(newts)); - } + //check whether this edge has been removed + if (removemap!=null&&removemap.containsKey(entry.getKey())&& + removemap.get(entry.getKey()).contains(e)) + continue; + //have real edge + TaintSet ts=e.getTaints(); + TaintSet newts=null; + //update non-null taint set + if (ts!=null) + newts=Canonical.removeInContextTaintsNP(ts, sese); + if (newts!=null&&newts!=ts) { + edgestoremove.add(e); + edgestoadd.add(e.changeTaintSet(newts)); + } } } } @@ -630,18 +630,18 @@ nextdelta: newDelta.varedgeadd.put(tmpthis, (MySet)edges.clone()); edgeset.addAll(edges); for(Edge e:edges) { - AllocNode dstnode=e.dst; - if (!nodeset.contains(dstnode)&&(oldnodeset==null||!oldnodeset.contains(dstnode))) { - TypeDescriptor type=dstnode.getType(); - if (!type.isArray()) { - targetSet.add(type.getClassDesc()); - } else { - //arrays don't have code - targetSet.add(typeUtil.getClass(TypeUtil.ObjectClass)); - } - nodeset.add(dstnode); - tovisit.add(dstnode); - } + AllocNode dstnode=e.dst; + if (!nodeset.contains(dstnode)&&(oldnodeset==null||!oldnodeset.contains(dstnode))) { + TypeDescriptor type=dstnode.getType(); + if (!type.isArray()) { + targetSet.add(type.getClassDesc()); + } else { + //arrays don't have code + targetSet.add(typeUtil.getClass(TypeUtil.ObjectClass)); + } + nodeset.add(dstnode); + tovisit.add(dstnode); + } } } } @@ -656,10 +656,10 @@ nextdelta: newDelta.varedgeadd.put(tmp, (MySet)edges.clone()); edgeset.addAll(edges); for(Edge e:edges) { - if (!nodeset.contains(e.dst)) { - nodeset.add(e.dst); - tovisit.add(e.dst); - } + if (!nodeset.contains(e.dst)) { + nodeset.add(e.dst); + tovisit.add(e.dst); + } } } } @@ -671,14 +671,14 @@ nextdelta: AllocNode node=tovisit.pop(); MySet edges=GraphManip.getEdges(graph, delta, node); if (!edges.isEmpty()) { - newDelta.heapedgeadd.put(node, Edge.makeOld(edges)); - edgeset.addAll(edges); - for(Edge e : edges) { - if (!nodeset.contains(e.dst)&&(oldnodeset==null||!oldnodeset.contains(e.dst))) { - nodeset.add(e.dst); - tovisit.add(e.dst); - } - } + newDelta.heapedgeadd.put(node, Edge.makeOld(edges)); + edgeset.addAll(edges); + for(Edge e : edges) { + if (!nodeset.contains(e.dst)&&(oldnodeset==null||!oldnodeset.contains(e.dst))) { + nodeset.add(e.dst); + tovisit.add(e.dst); + } + } } } } @@ -692,11 +692,11 @@ nextdelta: } else { //Compute Edges for(Edge e : newDelta.varedgeadd.get(tmpthis)) { - AllocNode node=e.dst; - ClassDescriptor cd=node.getType().getClassDesc(); - //Figure out exact method called and add to set - MethodDescriptor calledmd=cd.getCalledMethod(md); - targets.add(calledmd); + AllocNode node=e.dst; + ClassDescriptor cd=node.getType().getClassDesc(); + //Figure out exact method called and add to set + MethodDescriptor calledmd=cd.getCalledMethod(md); + targets.add(calledmd); } } return targets; @@ -714,11 +714,11 @@ nextdelta: HashMap tmpMap=new HashMap(); int offset=0; if(tmpthis!=null) { - tmpMap.put(tmpthis, fm.getParameter(offset++)); + tmpMap.put(tmpthis, fm.getParameter(offset++)); } for(int i=0; i()); + callMap.put(fcall, new HashSet()); } Delta returnDelta=null; if (!callMap.get(fcall).contains(block.getStart())) { - callMap.get(fcall).add(block.getStart()); - newmethod=true; - - //Hook up return - if (!returnMap.containsKey(block.getExit())) { - returnMap.put(block.getExit(), new HashSet()); - } - returnMap.get(block.getExit()).add(new PPoint(callblock, callindex)); - - if (bbgraphMap.containsKey(block.getExit())) { - //Need to push existing results to current node - if (returnDelta==null) { - returnDelta=new Delta(null, false); - Vector exitblocknodes=block.getExit().nodes(); - FlatExit fexit=(FlatExit)exitblocknodes.get(exitblocknodes.size()-1); - buildInitDelta(graphMap.get(fexit), returnDelta); - if (!returnDelta.heapedgeadd.isEmpty()||!returnDelta.heapedgeremove.isEmpty()||!returnDelta.varedgeadd.isEmpty()) { - returnDelta.setBlock(new PPoint(callblock, callindex)); - toprocess.add(returnDelta); - } - } else { - if (!returnDelta.heapedgeadd.isEmpty()||!returnDelta.heapedgeremove.isEmpty()||!returnDelta.varedgeadd.isEmpty()) { - toprocess.add(returnDelta.diffBlock(new PPoint(callblock, callindex))); - } - } - } + callMap.get(fcall).add(block.getStart()); + newmethod=true; + + //Hook up return + if (!returnMap.containsKey(block.getExit())) { + returnMap.put(block.getExit(), new HashSet()); + } + returnMap.get(block.getExit()).add(new PPoint(callblock, callindex)); + + if (bbgraphMap.containsKey(block.getExit())) { + //Need to push existing results to current node + if (returnDelta==null) { + returnDelta=new Delta(null, false); + Vector exitblocknodes=block.getExit().nodes(); + FlatExit fexit=(FlatExit)exitblocknodes.get(exitblocknodes.size()-1); + buildInitDelta(graphMap.get(fexit), returnDelta); + if (!returnDelta.heapedgeadd.isEmpty()||!returnDelta.heapedgeremove.isEmpty()||!returnDelta.varedgeadd.isEmpty()) { + returnDelta.setBlock(new PPoint(callblock, callindex)); + toprocess.add(returnDelta); + } + } else { + if (!returnDelta.heapedgeadd.isEmpty()||!returnDelta.heapedgeremove.isEmpty()||!returnDelta.varedgeadd.isEmpty()) { + toprocess.add(returnDelta.diffBlock(new PPoint(callblock, callindex))); + } + } + } } if (oldedgeset==null) { - //First build of this graph - //Build and enqueue delta...safe to just use existing delta - Delta d=newDelta.changeParams(tmpMap, new PPoint(block.getStart())); - //System.out.println("AProcessing "+block.getStart().nodes.get(0).toString().replace(' ','_')); - //d.print(); - toprocess.add(d); + //First build of this graph + //Build and enqueue delta...safe to just use existing delta + Delta d=newDelta.changeParams(tmpMap, new PPoint(block.getStart())); + //System.out.println("AProcessing "+block.getStart().nodes.get(0).toString().replace(' ','_')); + //d.print(); + toprocess.add(d); } else if (newmethod) { - if (basedelta==null) { - basedelta=newDelta.buildBase(oldedgeset); - } - //Build and enqueue delta - Delta d=basedelta.changeParams(tmpMap, new PPoint(block.getStart())); - //System.out.println("BProcessing "+block.getStart().nodes.get(0).toString().replace(' ','_')); - //d.print(); - toprocess.add(d); + if (basedelta==null) { + basedelta=newDelta.buildBase(oldedgeset); + } + //Build and enqueue delta + Delta d=basedelta.changeParams(tmpMap, new PPoint(block.getStart())); + //System.out.println("BProcessing "+block.getStart().nodes.get(0).toString().replace(' ','_')); + //d.print(); + toprocess.add(d); } else { - //Build and enqueue delta - Delta d=newDelta.changeParams(tmpMap, new PPoint(block.getStart())); - //System.out.println("CProcessing "+block.getStart().nodes.get(0).toString().replace(' ','_')); - //d.print(); - toprocess.add(d); + //Build and enqueue delta + Delta d=newDelta.changeParams(tmpMap, new PPoint(block.getStart())); + //System.out.println("CProcessing "+block.getStart().nodes.get(0).toString().replace(' ','_')); + //d.print(); + toprocess.add(d); } } } @@ -804,8 +804,8 @@ nextdelta: edges.addAll(delta.heapedgeadd.get(extNode)); for(Edge e : edges) { - if (nodeset.contains(e.dst)) - externaledgeset.add(e); + if (nodeset.contains(e.dst)) + externaledgeset.add(e); } } @@ -825,8 +825,8 @@ nextdelta: edges.addAll(delta.varedgeadd.get(tmp)); for(Edge e : edges) { - if (nodeset.contains(e.dst)) - externaledgeset.add(e); + if (nodeset.contains(e.dst)) + externaledgeset.add(e); } } } @@ -838,7 +838,7 @@ nextdelta: //Want to remove the set of internal edges for(Edge e : edgeset) { if (e.src!=null&&!graph.callerEdges.contains(e)) { - delta.removeHeapEdge(e); + delta.removeHeapEdge(e); } } @@ -846,7 +846,7 @@ nextdelta: for(Edge e : externaledgeset) { //want to remove the set of internal edges if (!graph.callerEdges.contains(e)) - delta.removeEdge(e); + delta.removeEdge(e); } } @@ -908,20 +908,20 @@ nextdelta: TempDescriptor tmpthis=fcall.getThis(); //Fix up delta to get rid of unnecessary heap edge removals for(Map.Entry> entry : delta.heapedgeremove.entrySet()) { - for(Iterator eit=entry.getValue().iterator(); eit.hasNext(); ) { - Edge e=eit.next(); - if (graph.callerEdges.contains(e)) - eit.remove(); - } + for(Iterator eit=entry.getValue().iterator(); eit.hasNext(); ) { + Edge e=eit.next(); + if (graph.callerEdges.contains(e)) + eit.remove(); + } } //Fix up delta to get rid of unnecessary var edge removals for(Map.Entry> entry : delta.varedgeremove.entrySet()) { - for(Iterator eit=entry.getValue().iterator(); eit.hasNext(); ) { - Edge e=eit.next(); - if (graph.callerEdges.contains(e)) - eit.remove(); - } + for(Iterator eit=entry.getValue().iterator(); eit.hasNext(); ) { + Edge e=eit.next(); + if (graph.callerEdges.contains(e)) + eit.remove(); + } } //Handle the this temp @@ -933,16 +933,16 @@ nextdelta: MySet newedges=GraphManip.getDiffEdges(delta, oldnodeset); edgeset.addAll(newedges); for(Edge e : newedges) { - //Add new edges that start from old node to newDelta - AllocNode src=e.src; - if (!newDelta.heapedgeadd.containsKey(src)) { - newDelta.heapedgeadd.put(src, new MySet()); - } - newDelta.heapedgeadd.get(src).add(e.makeOld()); - if (!nodeset.contains(e.dst)&&!oldnodeset.contains(e.dst)) { - nodeset.add(e.dst); - tovisit.add(e.dst); - } + //Add new edges that start from old node to newDelta + AllocNode src=e.src; + if (!newDelta.heapedgeadd.containsKey(src)) { + newDelta.heapedgeadd.put(src, new MySet()); + } + newDelta.heapedgeadd.get(src).add(e.makeOld()); + if (!nodeset.contains(e.dst)&&!oldnodeset.contains(e.dst)) { + nodeset.add(e.dst); + tovisit.add(e.dst); + } } //Traverse all reachable nodes @@ -971,30 +971,30 @@ nextdelta: Set seseCallers=OoOJava?taskAnalysis.getTransitiveExecutingRBlocks(fcall):null; //Check if the new nodes allow us to insert a new edge for(AllocNode node : nodeset) { - if (graph.callNewEdges.containsKey(node)) { - for(Iterator eit=graph.callNewEdges.get(node).iterator(); eit.hasNext(); ) { - Edge e=eit.next(); - if ((graph.callNodeAges.contains(e.src)||graph.reachNode.contains(e.src))&& - (graph.callNodeAges.contains(e.dst)||graph.reachNode.contains(e.dst))) { - Edge edgetoadd=e.copy(); //we need our own copy to modify below - eit.remove(); - if (seseCallers!=null) - edgetoadd.taintModify(seseCallers); - mergeCallEdge(graph, delta, edgetoadd); - } - } - } + if (graph.callNewEdges.containsKey(node)) { + for(Iterator eit=graph.callNewEdges.get(node).iterator(); eit.hasNext(); ) { + Edge e=eit.next(); + if ((graph.callNodeAges.contains(e.src)||graph.reachNode.contains(e.src))&& + (graph.callNodeAges.contains(e.dst)||graph.reachNode.contains(e.dst))) { + Edge edgetoadd=e.copy(); //we need our own copy to modify below + eit.remove(); + if (seseCallers!=null) + edgetoadd.taintModify(seseCallers); + mergeCallEdge(graph, delta, edgetoadd); + } + } + } } for(Edge e : edgeset) { - //See if these edges would allow an old edge to be added - if (graph.callOldEdges.containsKey(e)) { - for(Edge adde : graph.callOldEdges.get(e)) { - Edge ecopy=adde.copy(); - ecopy.statuspredicate=e.statuspredicate; - mergeCallEdge(graph, delta, ecopy); - } - } + //See if these edges would allow an old edge to be added + if (graph.callOldEdges.containsKey(e)) { + for(Edge adde : graph.callOldEdges.get(e)) { + Edge ecopy=adde.copy(); + ecopy.statuspredicate=e.statuspredicate; + mergeCallEdge(graph, delta, ecopy); + } + } } //Add in new external edges @@ -1020,21 +1020,21 @@ nextdelta: MySet edgeset=entry.getValue(); for(Edge e : edgeset) { - Edge copy=e.copy(); - boolean rewrite=false; - if (copy.dst!=null&&graph.callNodeAges.contains(copy.dst)) { - copy.dst=allocFactory.getAllocNode(copy.dst, true); - rewrite=true; - } - if (rewrite) { - edgestoremove.add(e); - edgestoadd.add(copy); - } + Edge copy=e.copy(); + boolean rewrite=false; + if (copy.dst!=null&&graph.callNodeAges.contains(copy.dst)) { + copy.dst=allocFactory.getAllocNode(copy.dst, true); + rewrite=true; + } + if (rewrite) { + edgestoremove.add(e); + edgestoadd.add(copy); + } } } for(Edge e : edgestoremove) { if (!graph.callerEdges.contains(e)) - delta.removeVarEdge(e); + delta.removeVarEdge(e); } for(Edge e : edgestoadd) { delta.addVarEdge(e); @@ -1054,25 +1054,25 @@ nextdelta: MySet edgeset=entry.getValue(); for(Edge e : edgeset) { - Edge copy=e.copy(); - boolean rewrite=false; - if (copy.src!=null&&graph.callNodeAges.contains(copy.src)) { - copy.src=allocFactory.getAllocNode(copy.src, true); - rewrite=true; - } - if (copy.dst!=null&&graph.callNodeAges.contains(copy.dst)) { - copy.dst=allocFactory.getAllocNode(copy.dst, true); - rewrite=true; - } - if (rewrite) { - edgestoremove.add(e); - edgestoadd.add(copy); - } + Edge copy=e.copy(); + boolean rewrite=false; + if (copy.src!=null&&graph.callNodeAges.contains(copy.src)) { + copy.src=allocFactory.getAllocNode(copy.src, true); + rewrite=true; + } + if (copy.dst!=null&&graph.callNodeAges.contains(copy.dst)) { + copy.dst=allocFactory.getAllocNode(copy.dst, true); + rewrite=true; + } + if (rewrite) { + edgestoremove.add(e); + edgestoadd.add(copy); + } } } for(Edge e : edgestoremove) { if (!graph.callerEdges.contains(e)) - delta.removeHeapEdge(e); + delta.removeHeapEdge(e); } for(Edge e : edgestoadd) { delta.addHeapEdge(e); @@ -1086,22 +1086,22 @@ nextdelta: //First did we age the source Edge newedge=e.copy(); if (newedge.src!=null&&!e.src.isSummary()&&graph.callNodeAges.contains(e.src)) { - AllocNode summaryNode=allocFactory.getAllocNode(newedge.src, true); - newedge.src=summaryNode; + AllocNode summaryNode=allocFactory.getAllocNode(newedge.src, true); + newedge.src=summaryNode; } //Compute target if (graph.callNodeAges.contains(e.dst)&&!e.dst.isSummary()) { - if (graph.callOldNodes.contains(e.dst)) { - //Need two edges - Edge copy=newedge.copy(); - mergeEdge(graph, newDelta, copy); - } - //Now add summarized node - newedge.dst=allocFactory.getAllocNode(newedge.dst, true); - mergeCallEdge(graph, newDelta, newedge); + if (graph.callOldNodes.contains(e.dst)) { + //Need two edges + Edge copy=newedge.copy(); + mergeEdge(graph, newDelta, copy); + } + //Now add summarized node + newedge.dst=allocFactory.getAllocNode(newedge.dst, true); + mergeCallEdge(graph, newDelta, newedge); } else { - //Add edge to single node - mergeEdge(graph, newDelta, newedge); + //Add edge to single node + mergeEdge(graph, newDelta, newedge); } } } @@ -1123,84 +1123,84 @@ nextdelta: for(Iterator nodeit=delta.addNodeAges.iterator(); nodeit.hasNext(); ) { AllocNode node=nodeit.next(); if (!graph.callNodeAges.contains(node)) { - graph.callNodeAges.add(node); - newDelta.addNodeAges.add(node); + graph.callNodeAges.add(node); + newDelta.addNodeAges.add(node); } AllocNode summaryAdd=null; if (!graph.reachNode.contains(node)&&!node.isSummary()) { - /* Need to age node in existing graph*/ + /* Need to age node in existing graph*/ - AllocNode summaryNode=allocFactory.getAllocNode(node, true); + AllocNode summaryNode=allocFactory.getAllocNode(node, true); - if (!graph.callNodeAges.contains(summaryNode)) { - graph.callNodeAges.add(summaryNode); - newDelta.addNodeAges.add(summaryNode); - summaryAdd=summaryNode; - } - summarizeInGraph(graph, newDelta, node); + if (!graph.callNodeAges.contains(summaryNode)) { + graph.callNodeAges.add(summaryNode); + newDelta.addNodeAges.add(summaryNode); + summaryAdd=summaryNode; + } + summarizeInGraph(graph, newDelta, node); } do { - if (graph.callNewEdges.containsKey(node)) { - for(Iterator eit=graph.callNewEdges.get(node).iterator(); eit.hasNext(); ) { - Edge e=eit.next(); - if ((graph.callNodeAges.contains(e.src)||graph.reachNode.contains(e.src))&& - (graph.callNodeAges.contains(e.dst)||graph.reachNode.contains(e.dst))) { - Edge edgetoadd=e.copy(); //we need our own copy to modify below - eit.remove(); - if (seseCallers!=null) - edgetoadd.taintModify(seseCallers); - mergeCallEdge(graph, newDelta, edgetoadd); - } - } - } - //do the summary node if we added that also... - node=summaryAdd; - summaryAdd=null; + if (graph.callNewEdges.containsKey(node)) { + for(Iterator eit=graph.callNewEdges.get(node).iterator(); eit.hasNext(); ) { + Edge e=eit.next(); + if ((graph.callNodeAges.contains(e.src)||graph.reachNode.contains(e.src))&& + (graph.callNodeAges.contains(e.dst)||graph.reachNode.contains(e.dst))) { + Edge edgetoadd=e.copy(); //we need our own copy to modify below + eit.remove(); + if (seseCallers!=null) + edgetoadd.taintModify(seseCallers); + mergeCallEdge(graph, newDelta, edgetoadd); + } + } + } + //do the summary node if we added that also... + node=summaryAdd; + summaryAdd=null; } while(node!=null); } //Add heap edges in for(Map.Entry> entry : delta.heapedgeadd.entrySet()) { for(Edge e : entry.getValue()) { - boolean addedge=false; - Edge edgetoadd=null; - if (e.statuspredicate==Edge.NEW) { - if ((graph.callNodeAges.contains(e.src)||graph.reachNode.contains(e.src))&& - (graph.callNodeAges.contains(e.dst)||graph.reachNode.contains(e.dst))) { - edgetoadd=e.copy(); //we need our own copy to modify below - } else { - graph.addCallEdge(e); - } - } else { - Edge[] edgeArray=e.makeStatus(allocFactory); - - int statuspredicate=0; - for(int i=0; i()); - } - if (graph.callOldEdges.get(origEdgeKey).contains(e)) { - Edge olde=graph.callOldEdges.get(origEdgeKey).get(e); - graph.callOldEdges.get(origEdgeKey).add(olde.merge(e)); - } else { - graph.callOldEdges.get(origEdgeKey).add(e); - } - } - if (statuspredicate!=0) { - Edge newe=e.copy(); - newe.statuspredicate=statuspredicate; - edgetoadd=newe; - } - } - if (seseCallers!=null&&edgetoadd!=null) - edgetoadd.taintModify(seseCallers); - mergeCallEdge(graph, newDelta, edgetoadd); + boolean addedge=false; + Edge edgetoadd=null; + if (e.statuspredicate==Edge.NEW) { + if ((graph.callNodeAges.contains(e.src)||graph.reachNode.contains(e.src))&& + (graph.callNodeAges.contains(e.dst)||graph.reachNode.contains(e.dst))) { + edgetoadd=e.copy(); //we need our own copy to modify below + } else { + graph.addCallEdge(e); + } + } else { + Edge[] edgeArray=e.makeStatus(allocFactory); + + int statuspredicate=0; + for(int i=0; i()); + } + if (graph.callOldEdges.get(origEdgeKey).contains(e)) { + Edge olde=graph.callOldEdges.get(origEdgeKey).get(e); + graph.callOldEdges.get(origEdgeKey).add(olde.merge(e)); + } else { + graph.callOldEdges.get(origEdgeKey).add(e); + } + } + if (statuspredicate!=0) { + Edge newe=e.copy(); + newe.statuspredicate=statuspredicate; + edgetoadd=newe; + } + } + if (seseCallers!=null&&edgetoadd!=null) + edgetoadd.taintModify(seseCallers); + mergeCallEdge(graph, newDelta, edgetoadd); } } @@ -1210,16 +1210,16 @@ nextdelta: if (fcall.getReturnTemp()!=null) { MySet returnedge=delta.varedgeadd.get(returntmp); if (returnedge!=null) - for(Edge e : returnedge) { - //skip the edge if types don't allow it... - if (!typeUtil.isSuperorType(fcall.getReturnTemp().getType(), e.dst.getType())) - continue; - Edge newedge=e.copy(); - newedge.srcvar=fcall.getReturnTemp(); - if (seseCallers!=null) - newedge.taintModify(seseCallers); - mergeEdge(graph, newDelta, newedge); - } + for(Edge e : returnedge) { + //skip the edge if types don't allow it... + if (!typeUtil.isSuperorType(fcall.getReturnTemp().getType(), e.dst.getType())) + continue; + Edge newedge=e.copy(); + newedge.srcvar=fcall.getReturnTemp(); + if (seseCallers!=null) + newedge.taintModify(seseCallers); + mergeEdge(graph, newDelta, newedge); + } } applyDiffs(graph, newDelta); return newDelta; @@ -1230,8 +1230,8 @@ nextdelta: Edge match=graph.getMatch(edgetoadd); if (match==null||!match.subsumes(edgetoadd)) { - Edge mergededge=edgetoadd.merge(match); - newDelta.addEdge(mergededge); + Edge mergededge=edgetoadd.merge(match); + newDelta.addEdge(mergededge); } } } @@ -1245,9 +1245,9 @@ nextdelta: Edge match=graph.getMatch(edgetoadd); if (match==null||!match.subsumes(edgetoadd)) { - Edge mergededge=edgetoadd.merge(match); - newDelta.addEdge(mergededge); - graph.callerEdges.add(mergededge); + Edge mergededge=edgetoadd.merge(match); + newDelta.addEdge(mergededge); + graph.callerEdges.add(mergededge); } } } @@ -1271,13 +1271,13 @@ nextdelta: MySet backedges=graph.getBackEdges(singleNode); for(Edge e : backedges) { if (e.dst==singleNode) { - //Need to get original edge so that predicate will be correct - Edge match=graph.getMatch(e); - if (match!=null) { - Edge rewrite=match.rewrite(singleNode, summaryNode); - newDelta.removeEdge(match); - mergeCallEdge(graph, newDelta, rewrite); - } + //Need to get original edge so that predicate will be correct + Edge match=graph.getMatch(e); + if (match!=null) { + Edge rewrite=match.rewrite(singleNode, summaryNode); + newDelta.removeEdge(match); + mergeCallEdge(graph, newDelta, rewrite); + } } } } @@ -1291,21 +1291,21 @@ nextdelta: if (genbackwards&&graph.backMap==null) { graph.backMap=new HashMap>(); if (graph.parent.backMap==null) { - graph.parent.backMap=new HashMap>(); - for(Map.Entry> entry : graph.nodeMap.entrySet()) { - for(Edge e : entry.getValue()) { - if (!graph.parent.backMap.containsKey(e.dst)) - graph.parent.backMap.put(e.dst, new MySet()); - graph.parent.backMap.get(e.dst).add(e); - } - } - for(Map.Entry> entry : graph.varMap.entrySet()) { - for(Edge e : entry.getValue()) { - if (!graph.parent.backMap.containsKey(e.dst)) - graph.parent.backMap.put(e.dst, new MySet()); - graph.parent.backMap.get(e.dst).add(e); - } - } + graph.parent.backMap=new HashMap>(); + for(Map.Entry> entry : graph.nodeMap.entrySet()) { + for(Edge e : entry.getValue()) { + if (!graph.parent.backMap.containsKey(e.dst)) + graph.parent.backMap.put(e.dst, new MySet()); + graph.parent.backMap.get(e.dst).add(e); + } + } + for(Map.Entry> entry : graph.varMap.entrySet()) { + for(Edge e : entry.getValue()) { + if (!graph.parent.backMap.containsKey(e.dst)) + graph.parent.backMap.put(e.dst, new MySet()); + graph.parent.backMap.get(e.dst).add(e); + } + } } } @@ -1314,8 +1314,8 @@ nextdelta: AllocNode node=e.getKey(); MySet edges=e.getValue(); if (graph.nodeMap.containsKey(node)) { - MySet nodeEdges=graph.nodeMap.get(node); - nodeEdges.addAll(edges); + MySet nodeEdges=graph.nodeMap.get(node); + nodeEdges.addAll(edges); } } @@ -1324,15 +1324,15 @@ nextdelta: AllocNode node=e.getKey(); MySet edgestoremove=e.getValue(); if (graph.nodeMap.containsKey(node)) { - //Just apply diff to current map - graph.nodeMap.get(node).removeAll(edgestoremove); + //Just apply diff to current map + graph.nodeMap.get(node).removeAll(edgestoremove); } else { - //Generate diff from parent graph - MySet parentedges=graph.parent.nodeMap.get(node); - if (parentedges!=null) { - MySet newedgeset=Util.setSubtract(parentedges, edgestoremove); - graph.nodeMap.put(node, newedgeset); - } + //Generate diff from parent graph + MySet parentedges=graph.parent.nodeMap.get(node); + if (parentedges!=null) { + MySet newedgeset=Util.setSubtract(parentedges, edgestoremove); + graph.nodeMap.put(node, newedgeset); + } } } @@ -1342,19 +1342,19 @@ nextdelta: MySet edgestoadd=e.getValue(); //If we have not done a subtract, then if (!graph.nodeMap.containsKey(node)) { - //Copy the parent entry - if (graph.parent.nodeMap.containsKey(node)) - graph.nodeMap.put(node, (MySet)graph.parent.nodeMap.get(node).clone()); - else - graph.nodeMap.put(node, new MySet()); + //Copy the parent entry + if (graph.parent.nodeMap.containsKey(node)) + graph.nodeMap.put(node, (MySet)graph.parent.nodeMap.get(node).clone()); + else + graph.nodeMap.put(node, new MySet()); } Edge.mergeEdgesInto(graph.nodeMap.get(node),edgestoadd); if (genbackwards) { - for(Edge eadd : edgestoadd) { - if (!graph.backMap.containsKey(eadd.dst)) - graph.backMap.put(eadd.dst, new MySet()); - graph.backMap.get(eadd.dst).add(eadd); - } + for(Edge eadd : edgestoadd) { + if (!graph.backMap.containsKey(eadd.dst)) + graph.backMap.put(eadd.dst, new MySet()); + graph.backMap.get(eadd.dst).add(eadd); + } } } @@ -1364,13 +1364,13 @@ nextdelta: MySet edgestoremove=e.getValue(); if (graph.varMap.containsKey(tmp)) { - //Just apply diff to current map - graph.varMap.get(tmp).removeAll(edgestoremove); + //Just apply diff to current map + graph.varMap.get(tmp).removeAll(edgestoremove); } else if (graph.parent.varMap.containsKey(tmp)) { - //Generate diff from parent graph - MySet parentedges=graph.parent.varMap.get(tmp); - MySet newedgeset=Util.setSubtract(parentedges, edgestoremove); - graph.varMap.put(tmp, newedgeset); + //Generate diff from parent graph + MySet parentedges=graph.parent.varMap.get(tmp); + MySet newedgeset=Util.setSubtract(parentedges, edgestoremove); + graph.varMap.put(tmp, newedgeset); } } @@ -1379,18 +1379,18 @@ nextdelta: TempDescriptor tmp=e.getKey(); MySet edgestoadd=e.getValue(); if (graph.varMap.containsKey(tmp)) { - Edge.mergeEdgesInto(graph.varMap.get(tmp), edgestoadd); + Edge.mergeEdgesInto(graph.varMap.get(tmp), edgestoadd); } else if (graph.parent.varMap.containsKey(tmp)) { - graph.varMap.put(tmp, new MySet(graph.parent.varMap.get(tmp))); - Edge.mergeEdgesInto(graph.varMap.get(tmp), edgestoadd); + graph.varMap.put(tmp, new MySet(graph.parent.varMap.get(tmp))); + Edge.mergeEdgesInto(graph.varMap.get(tmp), edgestoadd); } else - graph.varMap.put(tmp, (MySet)edgestoadd.clone()); + graph.varMap.put(tmp, (MySet)edgestoadd.clone()); if (genbackwards) { - for(Edge eadd : edgestoadd) { - if (!graph.backMap.containsKey(eadd.dst)) - graph.backMap.put(eadd.dst, new MySet()); - graph.backMap.get(eadd.dst).add(eadd); - } + for(Edge eadd : edgestoadd) { + if (!graph.backMap.containsKey(eadd.dst)) + graph.backMap.put(eadd.dst, new MySet()); + graph.backMap.get(eadd.dst).add(eadd); + } } } @@ -1453,37 +1453,37 @@ nextdelta: MySet dstEdges=GraphManip.getEdges(graph, delta, dst); if (OoOJava&&!accessible.isAccessible(node, dst)) { - Taint dstStallTaint=Taint.factory(node, dst, AllocFactory.dummySite, null, ReachGraph.predsEmpty); - dstEdges=Edge.taintAll(dstEdges, dstStallTaint); - updateVarDelta(graph, delta, dst, dstEdges, null); + Taint dstStallTaint=Taint.factory(node, dst, AllocFactory.dummySite, null, ReachGraph.predsEmpty); + dstEdges=Edge.taintAll(dstEdges, dstStallTaint); + updateVarDelta(graph, delta, dst, dstEdges, null); } if (OoOJava) { - effectsAnalysis.analyzeFlatSetFieldNode(dstEdges, fd, node); + effectsAnalysis.analyzeFlatSetFieldNode(dstEdges, fd, node); } //Do nothing for non pointers if (!src.getType().isPtr()) { - if (mustProcess.contains(node)) { - applyDiffs(graph, delta); - } - return delta; + if (mustProcess.contains(node)) { + applyDiffs(graph, delta); + } + return delta; } MySet srcEdges=GraphManip.getEdges(graph, delta, src); if (OoOJava&&!accessible.isAccessible(node, src)) { - Taint srcStallTaint=Taint.factory(node, src, AllocFactory.dummySite, null, ReachGraph.predsEmpty); - srcEdges=Edge.taintAll(srcEdges, srcStallTaint); - updateVarDelta(graph, delta, src, srcEdges, null); + Taint srcStallTaint=Taint.factory(node, src, AllocFactory.dummySite, null, ReachGraph.predsEmpty); + srcEdges=Edge.taintAll(srcEdges, srcStallTaint); + updateVarDelta(graph, delta, src, srcEdges, null); } MySet edgesToAdd=GraphManip.genEdges(dstEdges, fd, srcEdges); MySet edgesToRemove=null; if (dstEdges.size()==1&&!dstEdges.iterator().next().dst.isSummary()&&fd!=null) { - /* Can do a strong update */ - edgesToRemove=GraphManip.getEdges(graph, delta, dstEdges, fd); - graph.strongUpdateSet=edgesToRemove; + /* Can do a strong update */ + edgesToRemove=GraphManip.getEdges(graph, delta, dstEdges, fd); + graph.strongUpdateSet=edgesToRemove; } else - graph.strongUpdateSet=new MySet(); + graph.strongUpdateSet=new MySet(); /* Update diff */ updateHeapDelta(graph, delta, edgesToAdd, edgesToRemove); @@ -1492,20 +1492,20 @@ nextdelta: MySet newDstEdges=GraphManip.getDiffEdges(delta, dst); if (OoOJava&&!accessible.isAccessible(node, dst)) { - Taint dstStallTaint=Taint.factory(node, dst, AllocFactory.dummySite, null, ReachGraph.predsEmpty); - newDstEdges=Edge.taintAll(newDstEdges, dstStallTaint); - updateVarDelta(graph, delta, dst, newDstEdges, null); + Taint dstStallTaint=Taint.factory(node, dst, AllocFactory.dummySite, null, ReachGraph.predsEmpty); + newDstEdges=Edge.taintAll(newDstEdges, dstStallTaint); + updateVarDelta(graph, delta, dst, newDstEdges, null); } if (OoOJava) { - effectsAnalysis.analyzeFlatSetFieldNode(newDstEdges, fd, node); + effectsAnalysis.analyzeFlatSetFieldNode(newDstEdges, fd, node); } if (!src.getType().isPtr()) { - if (mustProcess.contains(node)) { - applyDiffs(graph, delta); - } - return delta; + if (mustProcess.contains(node)) { + applyDiffs(graph, delta); + } + return delta; } /* Next look at new sources */ @@ -1516,34 +1516,34 @@ nextdelta: HashSet dstNodes=GraphManip.getNodes(graph, delta, dst); if (OoOJava&&!accessible.isAccessible(node, src)) { - Taint srcStallTaint=Taint.factory(node, src, AllocFactory.dummySite, null, ReachGraph.predsEmpty); - newSrcEdges=Edge.taintAll(newSrcEdges, srcStallTaint); - updateVarDelta(graph, delta, src, newSrcEdges, null); + Taint srcStallTaint=Taint.factory(node, src, AllocFactory.dummySite, null, ReachGraph.predsEmpty); + newSrcEdges=Edge.taintAll(newSrcEdges, srcStallTaint); + updateVarDelta(graph, delta, src, newSrcEdges, null); } MySet edgesToRemove=null; if (newDstEdges.size()!=0) { - if (dstNodes.size()>1&&!dstNodes.iterator().next().isSummary()&&fd!=null) { - /* Need to undo strong update */ - if (graph.strongUpdateSet!=null) { - edgesToAdd.addAll(graph.strongUpdateSet); - graph.strongUpdateSet=null; //Prevent future strong updates - } - } else if (dstNodes.size()==1&&newDstEdges.size()==1&&!newDstEdges.iterator().next().dst.isSummary()&&graph.strongUpdateSet!=null&&fd!=null) { - edgesToRemove=GraphManip.getEdges(graph, delta, dstNodes, fd); - graph.strongUpdateSet.addAll(edgesToRemove); - } - Edge.mergeEdgesInto(edgesToAdd, GraphManip.genEdges(newDstEdges, fd, srcEdges)); + if (dstNodes.size()>1&&!dstNodes.iterator().next().isSummary()&&fd!=null) { + /* Need to undo strong update */ + if (graph.strongUpdateSet!=null) { + edgesToAdd.addAll(graph.strongUpdateSet); + graph.strongUpdateSet=null; //Prevent future strong updates + } + } else if (dstNodes.size()==1&&newDstEdges.size()==1&&!newDstEdges.iterator().next().dst.isSummary()&&graph.strongUpdateSet!=null&&fd!=null) { + edgesToRemove=GraphManip.getEdges(graph, delta, dstNodes, fd); + graph.strongUpdateSet.addAll(edgesToRemove); + } + Edge.mergeEdgesInto(edgesToAdd, GraphManip.genEdges(newDstEdges, fd, srcEdges)); } //Kill new edges if (graph.strongUpdateSet!=null&&fd!=null) { - MySet otherEdgesToRemove=GraphManip.getDiffEdges(delta, dstNodes, fd); - if (edgesToRemove!=null) - edgesToRemove.addAll(otherEdgesToRemove); - else - edgesToRemove=otherEdgesToRemove; - graph.strongUpdateSet.addAll(otherEdgesToRemove); + MySet otherEdgesToRemove=GraphManip.getDiffEdges(delta, dstNodes, fd); + if (edgesToRemove!=null) + edgesToRemove.addAll(otherEdgesToRemove); + else + edgesToRemove=otherEdgesToRemove; + graph.strongUpdateSet.addAll(otherEdgesToRemove); } //Next look at new destinations @@ -1569,9 +1569,9 @@ nextdelta: src=frn.getReturnTemp(); dst=returntmp; if (src==null||!src.getType().isPtr()) { - //This is a NOP - applyDiffs(graph, delta); - return delta; + //This is a NOP + applyDiffs(graph, delta); + return delta; } } else { FlatCastNode fcn=(FlatCastNode) node; @@ -1626,17 +1626,17 @@ nextdelta: if (delta.getInit()) { MySet srcedges=GraphManip.getEdges(graph, delta, src); if (OoOJava) { - if (taint!=null) { - srcedges=Edge.taintAll(srcedges, taint); - updateVarDelta(graph, delta, src, srcedges, null); - } - effectsAnalysis.analyzeFlatFieldNode(srcedges, fd, node); + if (taint!=null) { + srcedges=Edge.taintAll(srcedges, taint); + updateVarDelta(graph, delta, src, srcedges, null); + } + effectsAnalysis.analyzeFlatFieldNode(srcedges, fd, node); } if (!dst.getType().isPtr()) { - if (mustProcess.contains(node)) { - applyDiffs(graph, delta); - } - return delta; + if (mustProcess.contains(node)) { + applyDiffs(graph, delta); + } + return delta; } MySet edgesToAdd=GraphManip.dereference(graph, delta, dst, srcedges, fd, node); @@ -1647,17 +1647,17 @@ nextdelta: } else { MySet newsrcedges=GraphManip.getDiffEdges(delta, src); if (OoOJava) { - if (taint!=null) { - newsrcedges=Edge.taintAll(newsrcedges, taint); - updateVarDelta(graph, delta, src, newsrcedges, null); - } - effectsAnalysis.analyzeFlatFieldNode(newsrcedges, fd, node); + if (taint!=null) { + newsrcedges=Edge.taintAll(newsrcedges, taint); + updateVarDelta(graph, delta, src, newsrcedges, null); + } + effectsAnalysis.analyzeFlatFieldNode(newsrcedges, fd, node); } if (!dst.getType().isPtr()) { - if (mustProcess.contains(node)) { - applyDiffs(graph, delta); - } - return delta; + if (mustProcess.contains(node)) { + applyDiffs(graph, delta); + } + return delta; } /* First compute new objects we read fields of */ MySet allsrcedges=GraphManip.getEdges(graph, delta, src); @@ -1686,28 +1686,28 @@ nextdelta: MySet existingEdges=graph.getEdges(tmp); if (edgestoRemove!=null) for(Edge e : edgestoRemove) { - //remove edge from delta - if (edgeAdd!=null) - edgeAdd.remove(e); - //if the edge is already in the graph, add an explicit remove to the delta - if (existingEdges.contains(e)) - delta.removeVarEdge(e); + //remove edge from delta + if (edgeAdd!=null) + edgeAdd.remove(e); + //if the edge is already in the graph, add an explicit remove to the delta + if (existingEdges.contains(e)) + delta.removeVarEdge(e); } for(Edge e : edgestoAdd) { //Remove the edge from the remove set if (edgeRemove!=null) - edgeRemove.remove(e); + edgeRemove.remove(e); //Explicitly add it to the add set unless it is already in the graph if (typeUtil.isSuperorType(tmp.getType(), e.dst.getType())) { - if (!existingEdges.contains(e)) { - delta.addVarEdge(e); - } else { - //See if the old edge subsumes the new one - Edge olde=existingEdges.get(e); - if (!olde.subsumes(e)) { - delta.addVarEdge(olde.merge(e)); - } - } + if (!existingEdges.contains(e)) { + delta.addVarEdge(e); + } else { + //See if the old edge subsumes the new one + Edge olde=existingEdges.get(e); + if (!olde.subsumes(e)) { + delta.addVarEdge(olde.merge(e)); + } + } } } } @@ -1715,35 +1715,35 @@ nextdelta: void updateHeapDelta(Graph graph, Delta delta, MySet edgestoAdd, MySet edgestoRemove) { if (edgestoRemove!=null) for(Edge e : edgestoRemove) { - AllocNode src=e.src; - MySet edgeAdd=delta.heapedgeadd.get(src); - MySet existingEdges=graph.getEdges(src); - //remove edge from delta - if (edgeAdd!=null) - edgeAdd.remove(e); - //if the edge is already in the graph, add an explicit remove to the delta - if (existingEdges.contains(e)) { - delta.removeHeapEdge(e); - } + AllocNode src=e.src; + MySet edgeAdd=delta.heapedgeadd.get(src); + MySet existingEdges=graph.getEdges(src); + //remove edge from delta + if (edgeAdd!=null) + edgeAdd.remove(e); + //if the edge is already in the graph, add an explicit remove to the delta + if (existingEdges.contains(e)) { + delta.removeHeapEdge(e); + } } if (edgestoAdd!=null) for(Edge e : edgestoAdd) { - AllocNode src=e.src; - MySet edgeRemove=delta.heapedgeremove.get(src); - MySet existingEdges=graph.getEdges(src); - //Remove the edge from the remove set - if (edgeRemove!=null) - edgeRemove.remove(e); - //Explicitly add it to the add set unless it is already in the graph - if (!existingEdges.contains(e)) { - delta.addHeapEdge(e); - } else { - //See if the old edge subsumes the new one - Edge olde=existingEdges.get(e); - if (!olde.subsumes(e)) { - delta.addHeapEdge(olde.merge(e)); - } - } + AllocNode src=e.src; + MySet edgeRemove=delta.heapedgeremove.get(src); + MySet existingEdges=graph.getEdges(src); + //Remove the edge from the remove set + if (edgeRemove!=null) + edgeRemove.remove(e); + //Explicitly add it to the add set unless it is already in the graph + if (!existingEdges.contains(e)) { + delta.addHeapEdge(e); + } else { + //See if the old edge subsumes the new one + Edge olde=existingEdges.get(e); + if (!olde.subsumes(e)) { + delta.addHeapEdge(olde.merge(e)); + } + } } } @@ -1773,48 +1773,48 @@ nextdelta: //Remove the old edges MySet oldedges=graph.getEdges(tmp); if (!oldedges.isEmpty()) - delta.varedgeremove.put(tmp, (MySet)oldedges); + delta.varedgeremove.put(tmp, (MySet)oldedges); //Note that we create a single node delta.addNodeAges.add(single); //Kill the old node if (delta.addOldNodes.containsKey(single)||delta.baseOldNodes.containsKey(single)) { - delta.addOldNodes.put(single, Boolean.FALSE); + delta.addOldNodes.put(single, Boolean.FALSE); } } else { /* 1. Fix up the variable edge additions */ for(Iterator>> entryIt=delta.varedgeadd.entrySet().iterator(); entryIt.hasNext(); ) { - Map.Entry> entry=entryIt.next(); + Map.Entry> entry=entryIt.next(); - if (entry.getKey()==tmp) { - /* Check if this is the tmp we overwrite */ - entryIt.remove(); - } else { - /* Otherwise, check if the target of the edge is changed... */ - summarizeSet(entry.getValue(), graph.varMap.get(entry.getKey()), single, summary); - } + if (entry.getKey()==tmp) { + /* Check if this is the tmp we overwrite */ + entryIt.remove(); + } else { + /* Otherwise, check if the target of the edge is changed... */ + summarizeSet(entry.getValue(), graph.varMap.get(entry.getKey()), single, summary); + } } /* 2. Fix up the base variable edges */ for(Iterator>> entryIt=delta.basevaredge.entrySet().iterator(); entryIt.hasNext(); ) { - Map.Entry> entry=entryIt.next(); - TempDescriptor entrytmp=entry.getKey(); - if (entrytmp==tmp) { - /* Check is this is the tmp we overwrite, if so add to remove set */ - Util.relationUpdate(delta.varedgeremove, tmp, null, entry.getValue()); - } else if (graph.varMap.containsKey(entrytmp)) { - /* Check if the target of the edge is changed */ - MySet newset=(MySet)entry.getValue().clone(); - MySet removeset=shrinkSet(newset, graph.varMap.get(entrytmp), single, summary); - Util.relationUpdate(delta.varedgeremove, entrytmp, newset, removeset); - Util.relationUpdate(delta.varedgeadd, entrytmp, null, newset); - } else { - /* Check if the target of the edge is changed */ - MySet newset=(MySet)entry.getValue().clone(); - MySet removeset=shrinkSet(newset, graph.parent.varMap.get(entrytmp), single, summary); - Util.relationUpdate(delta.varedgeremove, entrytmp, newset, removeset); - Util.relationUpdate(delta.varedgeadd, entrytmp, null, newset); - } + Map.Entry> entry=entryIt.next(); + TempDescriptor entrytmp=entry.getKey(); + if (entrytmp==tmp) { + /* Check is this is the tmp we overwrite, if so add to remove set */ + Util.relationUpdate(delta.varedgeremove, tmp, null, entry.getValue()); + } else if (graph.varMap.containsKey(entrytmp)) { + /* Check if the target of the edge is changed */ + MySet newset=(MySet)entry.getValue().clone(); + MySet removeset=shrinkSet(newset, graph.varMap.get(entrytmp), single, summary); + Util.relationUpdate(delta.varedgeremove, entrytmp, newset, removeset); + Util.relationUpdate(delta.varedgeadd, entrytmp, null, newset); + } else { + /* Check if the target of the edge is changed */ + MySet newset=(MySet)entry.getValue().clone(); + MySet removeset=shrinkSet(newset, graph.parent.varMap.get(entrytmp), single, summary); + Util.relationUpdate(delta.varedgeremove, entrytmp, newset, removeset); + Util.relationUpdate(delta.varedgeadd, entrytmp, null, newset); + } } @@ -1822,40 +1822,40 @@ nextdelta: HashMap> addheapedge=new HashMap>(); for(Iterator>> entryIt=delta.heapedgeadd.entrySet().iterator(); entryIt.hasNext(); ) { - Map.Entry> entry=entryIt.next(); - MySet edgeset=entry.getValue(); - AllocNode allocnode=entry.getKey(); - if (allocnode==single) { - entryIt.remove(); - summarizeSet(edgeset, graph.nodeMap.get(summary), single, summary); - addheapedge.put(summary, edgeset); - } else { - summarizeSet(edgeset, graph.nodeMap.get(allocnode), single, summary); - } + Map.Entry> entry=entryIt.next(); + MySet edgeset=entry.getValue(); + AllocNode allocnode=entry.getKey(); + if (allocnode==single) { + entryIt.remove(); + summarizeSet(edgeset, graph.nodeMap.get(summary), single, summary); + addheapedge.put(summary, edgeset); + } else { + summarizeSet(edgeset, graph.nodeMap.get(allocnode), single, summary); + } } /* Merge in diffs */ for(Map.Entry> entry : addheapedge.entrySet()) { - AllocNode allocnode=entry.getKey(); - Util.relationUpdate(delta.heapedgeadd, allocnode, null, entry.getValue()); + AllocNode allocnode=entry.getKey(); + Util.relationUpdate(delta.heapedgeadd, allocnode, null, entry.getValue()); } /* 4. Fix up the base heap edges */ for(Iterator>> entryIt=delta.baseheapedge.entrySet().iterator(); entryIt.hasNext(); ) { - Map.Entry> entry=entryIt.next(); - MySet edgeset=entry.getValue(); - AllocNode allocnode=entry.getKey(); - if (allocnode==single) { - entryIt.remove(); - } - AllocNode addnode=(allocnode==single)?summary:allocnode; + Map.Entry> entry=entryIt.next(); + MySet edgeset=entry.getValue(); + AllocNode allocnode=entry.getKey(); + if (allocnode==single) { + entryIt.remove(); + } + AllocNode addnode=(allocnode==single)?summary:allocnode; - MySet newset=(MySet)edgeset.clone(); - MySet removeset=shrinkSet(newset, graph.nodeMap.get(addnode), single, summary); - Util.relationUpdate(delta.heapedgeadd, addnode, null, newset); - Util.relationUpdate(delta.heapedgeremove, allocnode, null, removeset); + MySet newset=(MySet)edgeset.clone(); + MySet removeset=shrinkSet(newset, graph.nodeMap.get(addnode), single, summary); + Util.relationUpdate(delta.heapedgeadd, addnode, null, newset); + Util.relationUpdate(delta.heapedgeremove, allocnode, null, removeset); } /* Update Node Ages...If the base or addNodeAges set contains a @@ -1863,12 +1863,12 @@ nextdelta: * need to generate a single node as that has already been * done. */ if (delta.baseNodeAges.contains(single)||delta.addNodeAges.contains(single)) { - delta.addNodeAges.add(summary); + delta.addNodeAges.add(summary); } //Kill the old node if someone tries to add it if (delta.addOldNodes.containsKey(single)||delta.baseOldNodes.containsKey(single)) { - delta.addOldNodes.put(single, Boolean.FALSE); + delta.addOldNodes.put(single, Boolean.FALSE); } } @@ -1885,20 +1885,20 @@ nextdelta: for(Iterator edgeit=edgeset.iterator(); edgeit.hasNext(); ) { Edge e=edgeit.next(); if (e.dst==oldnode||e.src==oldnode) { - if (newSet==null) { - newSet=new MySet(); - } - edgeit.remove(); - e=e.copy(); - - if (e.dst==oldnode) { - e.dst=sumnode; - } - if (e.src==oldnode) { - e.src=sumnode; - } - if (oldedgeset==null||!oldedgeset.contains(e)) - newSet.add(e); + if (newSet==null) { + newSet=new MySet(); + } + edgeit.remove(); + e=e.copy(); + + if (e.dst==oldnode) { + e.dst=sumnode; + } + if (e.src==oldnode) { + e.src=sumnode; + } + if (oldedgeset==null||!oldedgeset.contains(e)) + newSet.add(e); } } if (newSet!=null) @@ -1915,19 +1915,19 @@ nextdelta: Edge e=edgeit.next(); edgeit.remove(); if (e.dst==oldnode||e.src==oldnode) { - if (newSet==null) { - newSet=new MySet(); - removeSet=new MySet(); - } + if (newSet==null) { + newSet=new MySet(); + removeSet=new MySet(); + } - removeSet.add(e); - e=e.copy(); - if (e.dst==oldnode) - e.dst=newnode; - if (e.src==oldnode) - e.src=newnode; - if (oldedgeset==null||!oldedgeset.contains(e)) - newSet.add(e); + removeSet.add(e); + e=e.copy(); + if (e.dst==oldnode) + e.dst=newnode; + if (e.src==oldnode) + e.src=newnode; + if (oldedgeset==null||!oldedgeset.contains(e)) + newSet.add(e); } } if (newSet!=null) @@ -1952,22 +1952,22 @@ nextdelta: //Add in heap edges and throw away original diff for(Map.Entry> entry : delta.heapedgeadd.entrySet()) { - graph.nodeMap.put(entry.getKey(), new MySet(entry.getValue())); + graph.nodeMap.put(entry.getKey(), new MySet(entry.getValue())); } //Add in var edges and throw away original diff Set livetemps=bblivetemps.get(block); for(Map.Entry> entry : delta.varedgeadd.entrySet()) { - if (livetemps.contains(entry.getKey())) - graph.varMap.put(entry.getKey(), new MySet(entry.getValue())); + if (livetemps.contains(entry.getKey())) + graph.varMap.put(entry.getKey(), new MySet(entry.getValue())); } //Record that this is initial set... graph.nodeAges.addAll(delta.addNodeAges); //Add old nodes for(Map.Entry oldentry : delta.addOldNodes.entrySet()) { - if (oldentry.getValue().booleanValue()) { - graph.oldNodes.put(oldentry.getKey(), Boolean.TRUE); - } + if (oldentry.getValue().booleanValue()) { + graph.oldNodes.put(oldentry.getKey(), Boolean.TRUE); + } } return newdelta; } else { @@ -1990,36 +1990,36 @@ nextdelta: MySet edges=heapedge.getValue(); if (graph.backMap!=null) { - for(Edge e : edges) { - if (!graph.backMap.containsKey(e.dst)) - graph.backMap.put(e.dst, new MySet()); - graph.backMap.get(e.dst).add(e); - } + for(Edge e : edges) { + if (!graph.backMap.containsKey(e.dst)) + graph.backMap.put(e.dst, new MySet()); + graph.backMap.get(e.dst).add(e); + } } if (!graph.nodeMap.containsKey(nsrc)) { - graph.nodeMap.put(nsrc, new MySet()); + graph.nodeMap.put(nsrc, new MySet()); } MySet dstedges=graph.nodeMap.get(nsrc); MySet diffedges=new MySet(); for(Edge e : edges) { - if (!dstedges.contains(e)) { - //We have a new edge - diffedges.add(e); - dstedges.add(e); - } else { - Edge origedge=dstedges.get(e); - if (!origedge.subsumes(e)) { - Edge mergededge=origedge.merge(e); - diffedges.add(mergededge); - dstedges.add(mergededge); - } - } + if (!dstedges.contains(e)) { + //We have a new edge + diffedges.add(e); + dstedges.add(e); + } else { + Edge origedge=dstedges.get(e); + if (!origedge.subsumes(e)) { + Edge mergededge=origedge.merge(e); + diffedges.add(mergededge); + dstedges.add(mergededge); + } + } } //Done with edge set... if (diffedges.size()>0) { - //completely new - newdelta.baseheapedge.put(nsrc, diffedges); + //completely new + newdelta.baseheapedge.put(nsrc, diffedges); } } } @@ -2034,39 +2034,39 @@ nextdelta: for(Map.Entry> varedge : delta.varedgeadd.entrySet()) { TempDescriptor tmpsrc=varedge.getKey(); if (livetemps.contains(tmpsrc)) { - MySet edges=varedge.getValue(); - if (graph.backMap!=null) { - for(Edge e : edges) { - if (!graph.backMap.containsKey(e.dst)) - graph.backMap.put(e.dst, new MySet()); - graph.backMap.get(e.dst).add(e); - } - } - - if (!graph.varMap.containsKey(tmpsrc)) { - graph.varMap.put(tmpsrc, new MySet()); - } - MySet dstedges=graph.varMap.get(tmpsrc); - MySet diffedges=new MySet(); - for(Edge e : edges) { - if (!dstedges.contains(e)) { - //We have a new edge - diffedges.add(e); - dstedges.add(e); - } else { - Edge origedge=dstedges.get(e); - if (!origedge.subsumes(e)) { - Edge mergededge=origedge.merge(e); - diffedges.add(mergededge); - dstedges.add(mergededge); - } - } - } - //Done with edge set... - if (diffedges.size()>0) { - //completely new - newdelta.basevaredge.put(tmpsrc,diffedges); - } + MySet edges=varedge.getValue(); + if (graph.backMap!=null) { + for(Edge e : edges) { + if (!graph.backMap.containsKey(e.dst)) + graph.backMap.put(e.dst, new MySet()); + graph.backMap.get(e.dst).add(e); + } + } + + if (!graph.varMap.containsKey(tmpsrc)) { + graph.varMap.put(tmpsrc, new MySet()); + } + MySet dstedges=graph.varMap.get(tmpsrc); + MySet diffedges=new MySet(); + for(Edge e : edges) { + if (!dstedges.contains(e)) { + //We have a new edge + diffedges.add(e); + dstedges.add(e); + } else { + Edge origedge=dstedges.get(e); + if (!origedge.subsumes(e)) { + Edge mergededge=origedge.merge(e); + diffedges.add(mergededge); + dstedges.add(mergededge); + } + } + } + //Done with edge set... + if (diffedges.size()>0) { + //completely new + newdelta.basevaredge.put(tmpsrc,diffedges); + } } } } @@ -2075,16 +2075,16 @@ nextdelta: //Merge in edges for(AllocNode node : delta.addNodeAges) { if (!graph.nodeAges.contains(node)) { - graph.nodeAges.add(node); - newDelta.baseNodeAges.add(node); + graph.nodeAges.add(node); + newDelta.baseNodeAges.add(node); } } for(Map.Entry oldentry : delta.addOldNodes.entrySet()) { AllocNode node=oldentry.getKey(); boolean ispresent=oldentry.getValue().booleanValue(); if (ispresent&&!graph.oldNodes.containsKey(node)) { - graph.oldNodes.put(node, Boolean.TRUE); - newDelta.baseOldNodes.put(node, Boolean.TRUE); + graph.oldNodes.put(node, Boolean.TRUE); + newDelta.baseOldNodes.put(node, Boolean.TRUE); } } } diff --git a/Robust/src/Analysis/Pointer/Util.java b/Robust/src/Analysis/Pointer/Util.java index 0fe00b93..cef2485e 100644 --- a/Robust/src/Analysis/Pointer/Util.java +++ b/Robust/src/Analysis/Pointer/Util.java @@ -8,7 +8,7 @@ public class Util { MySet newset=new MySet(); for(T e : orig) { if (!sub.contains(e)) - newset.add(e); + newset.add(e); } return newset; } @@ -16,11 +16,11 @@ public class Util { public static void relationUpdate(HashMap> map, K key, MySet toremove, MySet toadd) { if (map.containsKey(key)) { if (toremove!=null) - map.get(key).removeAll(toremove); + map.get(key).removeAll(toremove); map.get(key).addAll(toadd); } else { if (toadd!=null) - map.put(key, (MySet)toadd.clone()); + map.put(key, (MySet)toadd.clone()); } } diff --git a/Robust/src/Analysis/Prefetch/IndexDescriptor.java b/Robust/src/Analysis/Prefetch/IndexDescriptor.java index 2eaa795b..7a770f67 100644 --- a/Robust/src/Analysis/Prefetch/IndexDescriptor.java +++ b/Robust/src/Analysis/Prefetch/IndexDescriptor.java @@ -67,8 +67,8 @@ public class IndexDescriptor extends Descriptor { } else { ListIterator lit = getTempDesc().listIterator(); for(; lit.hasNext(); ) { - TempDescriptor td = (TempDescriptor) lit.next(); - label += td.toString()+"+"; + TempDescriptor td = (TempDescriptor) lit.next(); + label += td.toString()+"+"; } label +=offset.toString(); } diff --git a/Robust/src/Analysis/Prefetch/LoopExit.java b/Robust/src/Analysis/Prefetch/LoopExit.java index 7769b48f..06f8e955 100644 --- a/Robust/src/Analysis/Prefetch/LoopExit.java +++ b/Robust/src/Analysis/Prefetch/LoopExit.java @@ -42,19 +42,19 @@ public class LoopExit { FlatNode fn=nodeset.iterator().next(); nodeset.remove(fn); if (fn.kind()==FKind.FlatCondBranch&&((FlatCondBranch)fn).isLoopBranch()) { - FlatCondBranch fcb=(FlatCondBranch)fn; - loopbranchset.add(fcb); - //True edge - propagateset(nodeset, table, fcb, fcb.getNext(0), fcb); - //False edge - propagateset(nodeset, table, fcb, fcb.getNext(1), null); - loopbranchset.add(fcb); + FlatCondBranch fcb=(FlatCondBranch)fn; + loopbranchset.add(fcb); + //True edge + propagateset(nodeset, table, fcb, fcb.getNext(0), fcb); + //False edge + propagateset(nodeset, table, fcb, fcb.getNext(1), null); + loopbranchset.add(fcb); } else if (fn.kind()==FKind.FlatReturnNode) { - if (table.containsKey(fn)) - exitset.addAll(table.get(fn)); + if (table.containsKey(fn)) + exitset.addAll(table.get(fn)); } else { - for(int i=0; i toadd=new HashSet(); toadd.addAll(table.get(fn)); if (toadd.contains(fnnext)) //can't propagate back to node - toadd.remove(fnnext); + toadd.remove(fnnext); if(!table.get(fnnext).containsAll(toadd)) { - table.get(fnnext).addAll(toadd); - enqueuechange=true; + table.get(fnnext).addAll(toadd); + enqueuechange=true; } } if (fcb!=null&&!table.get(fnnext).contains(fcb)) { diff --git a/Robust/src/Analysis/Prefetch/PrefetchAnalysis.java b/Robust/src/Analysis/Prefetch/PrefetchAnalysis.java index 3ed1336a..e8f8090b 100644 --- a/Robust/src/Analysis/Prefetch/PrefetchAnalysis.java +++ b/Robust/src/Analysis/Prefetch/PrefetchAnalysis.java @@ -46,13 +46,13 @@ public class PrefetchAnalysis { for (Iterator methodit=locality.getMethods().iterator(); methodit.hasNext(); ) { MethodDescriptor md=(MethodDescriptor)methodit.next(); if (state.excprefetch.contains(md.getClassMethodName())) - continue; //Skip this method + continue; //Skip this method Hashtable> newprefetchset = new Hashtable>(); FlatMethod fm=state.getMethodFlat(md); doFlatNodeAnalysis(fm); doInsPrefetchAnalysis(fm, newprefetchset); if(newprefetchset.size() > 0) { - addFlatPrefetchNode(newprefetchset); + addFlatPrefetchNode(newprefetchset); } newprefetchset = null; } @@ -91,16 +91,16 @@ public class PrefetchAnalysis { } else { Hashtable child_prefetch_set_copy = new Hashtable(); if(curr.numNext() != 0) { - FlatNode child_node = curr.getNext(0); - if(prefetch_hash.containsKey(child_node)) { - child_prefetch_set_copy = (Hashtable)prefetch_hash.get(child_node).clone(); - } + FlatNode child_node = curr.getNext(0); + if(prefetch_hash.containsKey(child_node)) { + child_prefetch_set_copy = (Hashtable)prefetch_hash.get(child_node).clone(); + } } switch(curr.kind()) { case FKind.FlatCall: - processCall((FlatCall)curr,child_prefetch_set_copy); - break; + processCall((FlatCall)curr,child_prefetch_set_copy); + break; case FKind.FlatBackEdge: case FKind.FlatCheckNode: @@ -115,44 +115,44 @@ public class PrefetchAnalysis { case FKind.FlatCastNode: case FKind.FlatTagDeclaration: case FKind.FlatInstanceOfNode: - processDefaultCase(curr,child_prefetch_set_copy); - break; + processDefaultCase(curr,child_prefetch_set_copy); + break; case FKind.FlatMethod: - //TODO change it to take care of FlatMethod, Flatcalls - processFlatMethod(curr, child_prefetch_set_copy); - break; + //TODO change it to take care of FlatMethod, Flatcalls + processFlatMethod(curr, child_prefetch_set_copy); + break; case FKind.FlatFieldNode: - processFlatFieldNode(curr, child_prefetch_set_copy); - break; + processFlatFieldNode(curr, child_prefetch_set_copy); + break; case FKind.FlatElementNode: - processFlatElementNode(curr, child_prefetch_set_copy); - break; + processFlatElementNode(curr, child_prefetch_set_copy); + break; case FKind.FlatOpNode: - processFlatOpNode(curr, child_prefetch_set_copy); - break; + processFlatOpNode(curr, child_prefetch_set_copy); + break; case FKind.FlatLiteralNode: - processFlatLiteralNode(curr, child_prefetch_set_copy); - break; + processFlatLiteralNode(curr, child_prefetch_set_copy); + break; case FKind.FlatSetElementNode: - processFlatSetElementNode(curr, child_prefetch_set_copy); - break; + processFlatSetElementNode(curr, child_prefetch_set_copy); + break; case FKind.FlatSetFieldNode: - processFlatSetFieldNode(curr, child_prefetch_set_copy); - break; + processFlatSetFieldNode(curr, child_prefetch_set_copy); + break; case FKind.FlatOffsetNode: - processDefaultCase(curr,child_prefetch_set_copy); - break; + processDefaultCase(curr,child_prefetch_set_copy); + break; default: - throw new Error("No such Flatnode kind"); + throw new Error("No such Flatnode kind"); } } } @@ -169,18 +169,18 @@ public class PrefetchAnalysis { PrefetchPair pp = (PrefetchPair) e.nextElement(); double newprob = newPrefetchSet.get(pp).doubleValue(); if (!oldPrefetchSet.containsKey(pp)) - return true; + return true; double oldprob = oldPrefetchSet.get(pp).doubleValue(); if((newprob - oldprob) > PROB_DIFF) { - return true; + return true; } if (newprob >= PREFETCH_THRESHOLD_PROB && oldprob < PREFETCH_THRESHOLD_PROB) { - return true; + return true; } if (oldprob>newprob) { - System.out.println("ERROR:" + pp); - System.out.println(oldprob + " -> "+ newprob); + System.out.println("ERROR:" + pp); + System.out.println(oldprob + " -> "+ newprob); } } return false; @@ -199,7 +199,7 @@ public class PrefetchAnalysis { Hashtableoldset=prefetch_hash.get(curr); if (comparePrefetchSets(oldset, newset)) { for(int i=0; i newdesc = new ArrayList(); - newdesc.add(currffn.getField()); - newdesc.addAll(childpp.desc); - PrefetchPair newpp = new PrefetchPair(currffn.getSrc(), newdesc); - Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); - if (tocompare.containsKey(newpp)) { - Double oldprob=tocompare.get(newpp); - newprob=1.0-(1.0-oldprob)*(1.0-newprob); - } - tocompare.put(newpp, newprob); - pm.addPair(childpp, newpp); - } - //drop if not ptr + if (currffn.getField().getType().isPtr()) { + ArrayList newdesc = new ArrayList(); + newdesc.add(currffn.getField()); + newdesc.addAll(childpp.desc); + PrefetchPair newpp = new PrefetchPair(currffn.getSrc(), newdesc); + Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); + if (tocompare.containsKey(newpp)) { + Double oldprob=tocompare.get(newpp); + newprob=1.0-(1.0-oldprob)*(1.0-newprob); + } + tocompare.put(newpp, newprob); + pm.addPair(childpp, newpp); + } + //drop if not ptr } else if(childpp.base == currffn.getDst() && (childpp.getDesc() == null)) { - //covered by current prefetch - child_prefetch_set_copy.remove(childpp); + //covered by current prefetch + child_prefetch_set_copy.remove(childpp); } else if(childpp.containsTemp(currffn.getDst())) { - child_prefetch_set_copy.remove(childpp); + child_prefetch_set_copy.remove(childpp); } else { - Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); - if (tocompare.containsKey(childpp)) { - Double oldprob=tocompare.get(childpp); - newprob=1.0-(1.0-oldprob)*(1.0-newprob); - } - tocompare.put(childpp, newprob); - pm.addPair(childpp, childpp); + Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); + if (tocompare.containsKey(childpp)) { + Double oldprob=tocompare.get(childpp); + newprob=1.0-(1.0-oldprob)*(1.0-newprob); + } + tocompare.put(childpp, newprob); + pm.addPair(childpp, childpp); } } for(Iterator it=tocompare.keySet().iterator(); it.hasNext(); ) { PrefetchPair pp=it.next(); if (tocompare.get(pp) newdesc = new ArrayList(); - newdesc.add((Descriptor)idesc); - newdesc.addAll(childpp.desc); - PrefetchPair newpp = new PrefetchPair(currfen.getSrc(), newdesc); - Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); - tocompare.put(newpp, newprob); - pm.addPair(childpp, newpp); - child_prefetch_set_copy.remove(childpp); - /* Check for independence of prefetch pairs to compute new probability */ - if(child_prefetch_set_copy.containsKey(newpp)) { - newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue()))); - if(newprob < ANALYSIS_THRESHOLD_PROB) { - tocompare.remove(newpp); - } else { - tocompare.put(newpp, newprob); - pm.addPair(newpp, newpp); - } - child_prefetch_set_copy.remove(newpp); - } - } + if (currfen.getDst().getType().isPtr()) { + ArrayList newdesc = new ArrayList(); + newdesc.add((Descriptor)idesc); + newdesc.addAll(childpp.desc); + PrefetchPair newpp = new PrefetchPair(currfen.getSrc(), newdesc); + Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); + tocompare.put(newpp, newprob); + pm.addPair(childpp, newpp); + child_prefetch_set_copy.remove(childpp); + /* Check for independence of prefetch pairs to compute new probability */ + if(child_prefetch_set_copy.containsKey(newpp)) { + newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue()))); + if(newprob < ANALYSIS_THRESHOLD_PROB) { + tocompare.remove(newpp); + } else { + tocompare.put(newpp, newprob); + pm.addPair(newpp, newpp); + } + child_prefetch_set_copy.remove(newpp); + } + } } else if(childpp.base == currfen.getDst() && (childpp.getDesc() == null)) { - child_prefetch_set_copy.remove(childpp); + child_prefetch_set_copy.remove(childpp); } else if(childpp.containsTemp(currfen.getDst())) { - child_prefetch_set_copy.remove(childpp); + child_prefetch_set_copy.remove(childpp); } else { - continue; + continue; } } /* Check if curr prefetch set and the child prefetch set have same prefetch pairs @@ -335,12 +335,12 @@ public class PrefetchAnalysis { for(Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements(); ) { PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); for(Enumeration e = currcopy.keys(); e.hasMoreElements(); ) { - currpp = (PrefetchPair) e.nextElement(); - if(currpp.equals(childpp)) { - pm.addPair(childpp, currpp); - child_prefetch_set_copy.remove(childpp); - break; - } + currpp = (PrefetchPair) e.nextElement(); + if(currpp.equals(childpp)) { + pm.addPair(childpp, currpp); + child_prefetch_set_copy.remove(childpp); + break; + } } } @@ -376,38 +376,38 @@ public class PrefetchAnalysis { for (Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements(); ) { PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); if(childpp.base == currfsfn.getDst()) { - int size = childpp.desc.size(); - if(size >=2) { /*e.g. x.f = g (with child prefetches x.f.g, x.f[0].j) */ - if((childpp.getDescAt(0) instanceof FieldDescriptor) && (childpp.getDescAt(0) == currfsfn.getField())) { - ArrayList newdesc = new ArrayList(); - for(int i = 0; i<(childpp.desc.size()-1); i++) { - newdesc.add(i,childpp.desc.get(i+1)); - } - PrefetchPair newpp = new PrefetchPair(currfsfn.getSrc(), newdesc); - Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); - tocompare.put(newpp, newprob); - pm.addPair(childpp, newpp); - child_prefetch_set_copy.remove(childpp); - /* Check for independence of prefetch pairs in newly generated prefetch pair - * to compute new probability */ - if(child_prefetch_set_copy.containsKey(newpp)) { - newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue()))); - if(newprob < ANALYSIS_THRESHOLD_PROB) { - tocompare.remove(newpp); - } else { - tocompare.put(newpp, newprob); - pm.addPair(newpp, newpp); - } - child_prefetch_set_copy.remove(newpp); - } - } - } else if(size==1) { /* e.g x.f = g (with child prefetch x.f) */ - if((childpp.getDescAt(0) instanceof FieldDescriptor) && (childpp.getDescAt(0) == currfsfn.getField())) { - child_prefetch_set_copy.remove(childpp); - } - } else { - continue; - } + int size = childpp.desc.size(); + if(size >=2) { /*e.g. x.f = g (with child prefetches x.f.g, x.f[0].j) */ + if((childpp.getDescAt(0) instanceof FieldDescriptor) && (childpp.getDescAt(0) == currfsfn.getField())) { + ArrayList newdesc = new ArrayList(); + for(int i = 0; i<(childpp.desc.size()-1); i++) { + newdesc.add(i,childpp.desc.get(i+1)); + } + PrefetchPair newpp = new PrefetchPair(currfsfn.getSrc(), newdesc); + Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); + tocompare.put(newpp, newprob); + pm.addPair(childpp, newpp); + child_prefetch_set_copy.remove(childpp); + /* Check for independence of prefetch pairs in newly generated prefetch pair + * to compute new probability */ + if(child_prefetch_set_copy.containsKey(newpp)) { + newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue()))); + if(newprob < ANALYSIS_THRESHOLD_PROB) { + tocompare.remove(newpp); + } else { + tocompare.put(newpp, newprob); + pm.addPair(newpp, newpp); + } + child_prefetch_set_copy.remove(newpp); + } + } + } else if(size==1) { /* e.g x.f = g (with child prefetch x.f) */ + if((childpp.getDescAt(0) instanceof FieldDescriptor) && (childpp.getDescAt(0) == currfsfn.getField())) { + child_prefetch_set_copy.remove(childpp); + } + } else { + continue; + } } } @@ -436,39 +436,39 @@ public class PrefetchAnalysis { for (Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements(); ) { PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); if (childpp.base == currfsen.getDst()) { - int sizedesc = childpp.desc.size(); - if((childpp.getDescAt(0) instanceof IndexDescriptor)) { - int sizetempdesc = ((IndexDescriptor)(childpp.getDescAt(0))).tddesc.size(); - if(sizetempdesc == 1) { - if((((IndexDescriptor)childpp.getDescAt(0)).tddesc.get(0) == currfsen.getIndex()) && (sizedesc>=2)) { - /* For e.g. a[i] = g with child prefetch set a[i].r or a[i].r.f */ - ArrayList newdesc = new ArrayList(); - for(int i = 0; i<(childpp.desc.size()-1); i++) { - newdesc.add(i,childpp.desc.get(i+1)); - } - PrefetchPair newpp = new PrefetchPair(currfsen.getSrc(), newdesc); - Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); - tocompare.put(newpp, newprob); - pm.addPair(childpp, newpp); - child_prefetch_set_copy.remove(childpp); - /* Check for independence of prefetch pairs to compute new probability */ - if(child_prefetch_set_copy.containsKey(newpp)) { - newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue()))); - if(newprob < ANALYSIS_THRESHOLD_PROB) { - tocompare.remove(newpp); - } else { - tocompare.put(newpp, newprob); - pm.addPair(newpp, newpp); - } - child_prefetch_set_copy.remove(newpp); - } - } else if((((IndexDescriptor)childpp.getDescAt(0)).tddesc.get(0) == currfsen.getIndex()) && (sizedesc==1)) - /* For e.g. a[i] = g with child prefetch set a[i] */ - child_prefetch_set_copy.remove(childpp); - } else { - continue; - } - } + int sizedesc = childpp.desc.size(); + if((childpp.getDescAt(0) instanceof IndexDescriptor)) { + int sizetempdesc = ((IndexDescriptor)(childpp.getDescAt(0))).tddesc.size(); + if(sizetempdesc == 1) { + if((((IndexDescriptor)childpp.getDescAt(0)).tddesc.get(0) == currfsen.getIndex()) && (sizedesc>=2)) { + /* For e.g. a[i] = g with child prefetch set a[i].r or a[i].r.f */ + ArrayList newdesc = new ArrayList(); + for(int i = 0; i<(childpp.desc.size()-1); i++) { + newdesc.add(i,childpp.desc.get(i+1)); + } + PrefetchPair newpp = new PrefetchPair(currfsen.getSrc(), newdesc); + Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); + tocompare.put(newpp, newprob); + pm.addPair(childpp, newpp); + child_prefetch_set_copy.remove(childpp); + /* Check for independence of prefetch pairs to compute new probability */ + if(child_prefetch_set_copy.containsKey(newpp)) { + newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue()))); + if(newprob < ANALYSIS_THRESHOLD_PROB) { + tocompare.remove(newpp); + } else { + tocompare.put(newpp, newprob); + pm.addPair(newpp, newpp); + } + child_prefetch_set_copy.remove(newpp); + } + } else if((((IndexDescriptor)childpp.getDescAt(0)).tddesc.get(0) == currfsen.getIndex()) && (sizedesc==1)) + /* For e.g. a[i] = g with child prefetch set a[i] */ + child_prefetch_set_copy.remove(childpp); + } else { + continue; + } + } } } /* Merge child prefetch pairs */ @@ -494,85 +494,85 @@ public class PrefetchAnalysis { if(currfopn.getOp().getOp() == Operation.ASSIGN) { for (Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements(); ) { - PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); - PrefetchPair copyofchildpp = (PrefetchPair) childpp.clone(); - - /* For cases like x=y with child prefetch set x[i].z,x.g*/ - if(childpp.base == currfopn.getDest()) { - ArrayList newdesc = new ArrayList(); - newdesc.addAll(childpp.desc); - PrefetchPair newpp = new PrefetchPair(currfopn.getLeft(), newdesc); - Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); - tocompare.put(newpp, newprob); - pm.addPair(childpp, newpp); - child_prefetch_set_copy.remove(childpp); - /* Check for independence of prefetch pairs to compute new probability */ - if(child_prefetch_set_copy.containsKey(newpp)) { - newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue()))); - if(newprob < ANALYSIS_THRESHOLD_PROB) { - tocompare.remove(newpp); - } else { - tocompare.put(newpp, newprob); - pm.addPair(newpp, newpp); - } - child_prefetch_set_copy.remove(newpp); - } - /* For cases like x=y with child prefetch set r[x].p, r[p+x].q where x is a tempdescriptor*/ - } else if(copyofchildpp.containsTemp(currfopn.getDest())) { - PrefetchPair newpp=copyofchildpp.replaceTemp(currfopn.getDest(), new TempDescriptor[] {currfopn.getLeft()}); - Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); - tocompare.put(newpp, newprob); - pm.addPair(childpp, newpp); - child_prefetch_set_copy.remove(childpp); - /* Check for independence of prefetch pairs to compute new probability*/ - if(child_prefetch_set_copy.containsKey(newpp)) { - newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue()))); - if(newprob < ANALYSIS_THRESHOLD_PROB) { - tocompare.remove(newpp); - } else { - tocompare.put(newpp, newprob); - pm.addPair(newpp, newpp); - } - child_prefetch_set_copy.remove(newpp); - } - newpp = null; - } else { - continue; - } + PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); + PrefetchPair copyofchildpp = (PrefetchPair) childpp.clone(); + + /* For cases like x=y with child prefetch set x[i].z,x.g*/ + if(childpp.base == currfopn.getDest()) { + ArrayList newdesc = new ArrayList(); + newdesc.addAll(childpp.desc); + PrefetchPair newpp = new PrefetchPair(currfopn.getLeft(), newdesc); + Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); + tocompare.put(newpp, newprob); + pm.addPair(childpp, newpp); + child_prefetch_set_copy.remove(childpp); + /* Check for independence of prefetch pairs to compute new probability */ + if(child_prefetch_set_copy.containsKey(newpp)) { + newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue()))); + if(newprob < ANALYSIS_THRESHOLD_PROB) { + tocompare.remove(newpp); + } else { + tocompare.put(newpp, newprob); + pm.addPair(newpp, newpp); + } + child_prefetch_set_copy.remove(newpp); + } + /* For cases like x=y with child prefetch set r[x].p, r[p+x].q where x is a tempdescriptor*/ + } else if(copyofchildpp.containsTemp(currfopn.getDest())) { + PrefetchPair newpp=copyofchildpp.replaceTemp(currfopn.getDest(), new TempDescriptor[] {currfopn.getLeft()}); + Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); + tocompare.put(newpp, newprob); + pm.addPair(childpp, newpp); + child_prefetch_set_copy.remove(childpp); + /* Check for independence of prefetch pairs to compute new probability*/ + if(child_prefetch_set_copy.containsKey(newpp)) { + newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue()))); + if(newprob < ANALYSIS_THRESHOLD_PROB) { + tocompare.remove(newpp); + } else { + tocompare.put(newpp, newprob); + pm.addPair(newpp, newpp); + } + child_prefetch_set_copy.remove(newpp); + } + newpp = null; + } else { + continue; + } } //case i = i+z with child prefetch set a[i].x } else if(currfopn.getRight()!=null && (currfopn.getOp().getOp() == Operation.ADD)) { for (Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements(); ) { - PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); - PrefetchPair copyofchildpp = (PrefetchPair) childpp.clone(); - - if(copyofchildpp.containsTemp(currfopn.getDest())) { - PrefetchPair newpp=copyofchildpp.replaceTemp(currfopn.getDest(), new TempDescriptor[] {currfopn.getLeft(), currfopn.getRight()}); - Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); - tocompare.put(newpp, newprob); - pm.addPair(childpp, newpp); - child_prefetch_set_copy.remove(childpp); - /* Check for independence of prefetch pairs to compute new probability*/ - if(child_prefetch_set_copy.containsKey(newpp)) { - newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue()))); - if(newprob < ANALYSIS_THRESHOLD_PROB) { - tocompare.remove(newpp); - } else { - tocompare.put(newpp, newprob); - pm.addPair(newpp, newpp); - } - child_prefetch_set_copy.remove(newpp); - } - } else { - continue; - } + PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); + PrefetchPair copyofchildpp = (PrefetchPair) childpp.clone(); + + if(copyofchildpp.containsTemp(currfopn.getDest())) { + PrefetchPair newpp=copyofchildpp.replaceTemp(currfopn.getDest(), new TempDescriptor[] {currfopn.getLeft(), currfopn.getRight()}); + Double newprob = child_prefetch_set_copy.get(childpp).doubleValue(); + tocompare.put(newpp, newprob); + pm.addPair(childpp, newpp); + child_prefetch_set_copy.remove(childpp); + /* Check for independence of prefetch pairs to compute new probability*/ + if(child_prefetch_set_copy.containsKey(newpp)) { + newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue()))); + if(newprob < ANALYSIS_THRESHOLD_PROB) { + tocompare.remove(newpp); + } else { + tocompare.put(newpp, newprob); + pm.addPair(newpp, newpp); + } + child_prefetch_set_copy.remove(newpp); + } + } else { + continue; + } } } else if(currfopn.getRight()!=null && (currfopn.getOp().getOp() == Operation.SUB)) { for(Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements(); ) { - PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); - if(childpp.containsTemp(currfopn.getDest())) { - child_prefetch_set_copy.remove(childpp); - } + PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); + if(childpp.containsTemp(currfopn.getDest())) { + child_prefetch_set_copy.remove(childpp); + } } } else { //FIXME Is not taken care of for cases like x = -y followed by a[x].i @@ -600,42 +600,42 @@ public class PrefetchAnalysis { if(currfln.getType().isIntegerType()) { for (Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements(); ) { - PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); - PrefetchPair copyofchildpp = (PrefetchPair) childpp.clone(); - if(copyofchildpp.containsTemp(currfln.getDst())) { - ArrayList copychilddesc = (ArrayList)copyofchildpp.getDesc(); - int sizetempdesc = copychilddesc.size(); - for(ListIterator it = copychilddesc.listIterator(); it.hasNext(); ) { - Object o = it.next(); - if(o instanceof IndexDescriptor) { - ArrayList td = (ArrayList)((IndexDescriptor)o).tddesc; - int sizetddesc = td.size(); - if(td.contains(currfln.getDst())) { - int index = td.indexOf(currfln.getDst()); - td.remove(index); - ((IndexDescriptor)o).offset += (Integer)currfln.getValue(); - } - } - } - ArrayList newdesc = new ArrayList(); - newdesc.addAll(copychilddesc); - PrefetchPair newpp = new PrefetchPair(childpp.base, newdesc); - Double newprob = (child_prefetch_set_copy.get(childpp)).doubleValue(); - tocompare.put(newpp, newprob); - pm.addPair(childpp, newpp); - child_prefetch_set_copy.remove(childpp); - /* Check for independence of prefetch pairs to compute new probability */ - if(child_prefetch_set_copy.containsKey(newpp)) { - newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue()))); - if(newprob < ANALYSIS_THRESHOLD_PROB) { - tocompare.remove(newpp); - } else { - tocompare.put(newpp, newprob); - pm.addPair(newpp, newpp); - } - child_prefetch_set_copy.remove(newpp); - } - } + PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); + PrefetchPair copyofchildpp = (PrefetchPair) childpp.clone(); + if(copyofchildpp.containsTemp(currfln.getDst())) { + ArrayList copychilddesc = (ArrayList)copyofchildpp.getDesc(); + int sizetempdesc = copychilddesc.size(); + for(ListIterator it = copychilddesc.listIterator(); it.hasNext(); ) { + Object o = it.next(); + if(o instanceof IndexDescriptor) { + ArrayList td = (ArrayList)((IndexDescriptor)o).tddesc; + int sizetddesc = td.size(); + if(td.contains(currfln.getDst())) { + int index = td.indexOf(currfln.getDst()); + td.remove(index); + ((IndexDescriptor)o).offset += (Integer)currfln.getValue(); + } + } + } + ArrayList newdesc = new ArrayList(); + newdesc.addAll(copychilddesc); + PrefetchPair newpp = new PrefetchPair(childpp.base, newdesc); + Double newprob = (child_prefetch_set_copy.get(childpp)).doubleValue(); + tocompare.put(newpp, newprob); + pm.addPair(childpp, newpp); + child_prefetch_set_copy.remove(childpp); + /* Check for independence of prefetch pairs to compute new probability */ + if(child_prefetch_set_copy.containsKey(newpp)) { + newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue()))); + if(newprob < ANALYSIS_THRESHOLD_PROB) { + tocompare.remove(newpp); + } else { + tocompare.put(newpp, newprob); + pm.addPair(newpp, newpp); + } + child_prefetch_set_copy.remove(newpp); + } + } } } @@ -688,25 +688,25 @@ public class PrefetchAnalysis { PrefetchPair pp=ppit.next(); double trueprob=0,falseprob=0; if (truechild.containsKey(pp)) - trueprob=truechild.get(pp).doubleValue(); + trueprob=truechild.get(pp).doubleValue(); if (falsechild.containsKey(pp)) - falseprob=falsechild.get(pp).doubleValue(); + falseprob=falsechild.get(pp).doubleValue(); double newprob=trueprob*fcb.getTrueProb()+falseprob*fcb.getFalseProb(); if (loop.isLoopingBranch(md,fcb)&& newprob currhash = (Hashtable) prefetch_hash.get(fn); for(Enumeration pphash= currhash.keys(); pphash.hasMoreElements(); ) { - PrefetchPair pp = (PrefetchPair) pphash.nextElement(); - double v=currhash.get(pp).doubleValue(); - if (v>.2) - System.out.print(pp.toString() +"-"+v + ", "); + PrefetchPair pp = (PrefetchPair) pphash.nextElement(); + double v=currhash.get(pp).doubleValue(); + if (v>.2) + System.out.print(pp.toString() +"-"+v + ", "); } System.out.println(")"); } else { @@ -817,20 +817,20 @@ nexttemp: Set toremove=new HashSet(); for(Iterator it1=ppairs.iterator(); it1.hasNext(); ) { - PrefetchPair pp1=it1.next(); - if (toremove.contains(pp1)) - continue; - int l1=pp1.desc.size()+1; - for(Iterator it2=ppairs.iterator(); it2.hasNext(); ) { - PrefetchPair pp2=it2.next(); - int l2=pp2.desc.size()+1; - - if (l1l1&&isSubSet(pp2,pp1)) - toremove.add(pp2); - } + PrefetchPair pp1=it1.next(); + if (toremove.contains(pp1)) + continue; + int l1=pp1.desc.size()+1; + for(Iterator it2=ppairs.iterator(); it2.hasNext(); ) { + PrefetchPair pp2=it2.next(); + int l2=pp2.desc.size()+1; + + if (l1l1&&isSubSet(pp2,pp1)) + toremove.add(pp2); + } } ppairs.removeAll(toremove); @@ -845,21 +845,21 @@ nexttemp: } for (int j = 0; j < shrt.desc.size(); j++) { if(shrt.getDescAt(j) instanceof IndexDescriptor) { - IndexDescriptor shrtid = (IndexDescriptor) shrt.getDescAt(j); - if(lng.getDescAt(j) instanceof IndexDescriptor) { - IndexDescriptor lngid = (IndexDescriptor) lng.getDescAt(j); - if(shrtid.equals(lngid)) { - continue; - } else { - return false; - } - } else { - return false; - } + IndexDescriptor shrtid = (IndexDescriptor) shrt.getDescAt(j); + if(lng.getDescAt(j) instanceof IndexDescriptor) { + IndexDescriptor lngid = (IndexDescriptor) lng.getDescAt(j); + if(shrtid.equals(lngid)) { + continue; + } else { + return false; + } + } else { + return false; + } } else { - if ((Descriptor)shrt.getDescAt(j) != (Descriptor)lng.getDescAt(j)) { - return false; - } + if ((Descriptor)shrt.getDescAt(j) != (Descriptor)lng.getDescAt(j)) { + return false; + } } } return true; @@ -874,9 +874,9 @@ nexttemp: return true; } else { for(Iterator it = newPSet.iterator(); it.hasNext(); ) { - if(!oldPSet.contains((PrefetchPair)it.next())) { - return true; - } + if(!oldPSet.contains((PrefetchPair)it.next())) { + return true; + } } } return false; @@ -892,19 +892,19 @@ nexttemp: HashSet pset1 = new HashSet(); Hashtable prefetchset = prefetch_hash.get(fn); for(Enumeration e = prefetchset.keys(); e.hasMoreElements(); ) { - PrefetchPair pp = (PrefetchPair) e.nextElement(); - /* Apply initial rule */ - if(prefetchset.get(pp).doubleValue() >= PREFETCH_THRESHOLD_PROB) { - pset1.add(pp); - } + PrefetchPair pp = (PrefetchPair) e.nextElement(); + /* Apply initial rule */ + if(prefetchset.get(pp).doubleValue() >= PREFETCH_THRESHOLD_PROB) { + pset1.add(pp); + } } /* Enqueue child node if Pset1 has changed */ if (comparePSet1(pset1_hash.get(fn), pset1)) { - for(int j=0; j prefetchset = prefetch_hash.get(fn); Hashtable ppairmaphash = pmap_hash.get(fn); for(Enumeration epset = prefetchset.keys(); epset.hasMoreElements(); ) { - PrefetchPair pp = (PrefetchPair) epset.nextElement(); - boolean pprobIsGreater = (prefetchset.get(pp).doubleValue() >= PREFETCH_THRESHOLD_PROB); - boolean mapprobIsLess=false; - boolean mapIsPresent=true; - for(int i=0; i= PREFETCH_THRESHOLD_PROB); + boolean mapprobIsLess=false; + boolean mapIsPresent=true; + for(int i=0; i pset1 = new HashSet(); @@ -954,11 +954,11 @@ nexttemp: /* Enqueue child node if Pset1 has changed */ if (comparePSet1(pset1_hash.get(fn), pset1)) { - for(int i=0; i 0) { - fpn.insAllpp((HashSet)newprefetchset.get(fn)); - if(fn.kind() == FKind.FlatMethod) { - FlatNode nn = fn.getNext(0); - fn.setNext(0, fpn); - fpn.addNext(nn); - fpn.siteid = prefetchsiteid++; - } else { - /* Check if previous node of this FlatNode is a NEW node - * If yes, delete this flatnode and its prefetch set from hash table - * This eliminates prefetches for NULL ptrs*/ - while(fn.numPrev() > 0) { - FlatNode nn = fn.getPrev(0); - for(int j = 0; j 0) { + FlatNode nn = fn.getPrev(0); + for(int j = 0; j td = new ArrayList(); - for(int j = 0; j < ((IndexDescriptor)o).tddesc.size(); j++) { - td.add(((IndexDescriptor)o).getTempDescAt(j)); - } - IndexDescriptor idesc = new IndexDescriptor(); - idesc.tddesc = td; - idesc.offset = ((IndexDescriptor)o).offset; - newpp.desc.add(idesc); + ArrayList td = new ArrayList(); + for(int j = 0; j < ((IndexDescriptor)o).tddesc.size(); j++) { + td.add(((IndexDescriptor)o).getTempDescAt(j)); + } + IndexDescriptor idesc = new IndexDescriptor(); + idesc.tddesc = td; + idesc.offset = ((IndexDescriptor)o).offset; + newpp.desc.add(idesc); } } return newpp; @@ -106,10 +106,10 @@ public class PrefetchPair { for(ListIterator it = desc.listIterator(); it.hasNext(); ) { Object o = it.next(); if(o instanceof IndexDescriptor) { - ArrayList tdarray = (ArrayList)((IndexDescriptor)o).tddesc; - if(tdarray.contains(td)) { - return true; - } + ArrayList tdarray = (ArrayList)((IndexDescriptor)o).tddesc; + if(tdarray.contains(td)) { + return true; + } } } return false; @@ -123,14 +123,14 @@ public class PrefetchPair { for(ListIterator it = desc.listIterator(); it.hasNext(); ) { Object currdesc = it.next(); if(currdesc instanceof IndexDescriptor) { - ArrayList tdarray = (ArrayList)((IndexDescriptor)currdesc).tddesc; - if (tdarray.contains(td)) { - int index = tdarray.indexOf(td); - tdarray.set(index, newtd[0]); - for(int i=1; i tdarray = (ArrayList)((IndexDescriptor)currdesc).tddesc; + if (tdarray.contains(td)) { + int index = tdarray.indexOf(td); + tdarray.set(index, newtd[0]); + for(int i=1; i> map = definitelyWrittenResults.get(fn); - if (map != null) { - if (map.get(rhs).get(fn).booleanValue()) { - // throw new Error("variable " + rhs - // + - // " was not overwritten in-between the same read statement by the out-most loop."); - } - } + lhs = fon.getDest(); + rhs = fon.getLeft(); + // read(rhs) + Hashtable> map = definitelyWrittenResults.get(fn); + if (map != null) { + if (map.get(rhs).get(fn).booleanValue()) { + // throw new Error("variable " + rhs + // + + // " was not overwritten in-between the same read statement by the out-most loop."); + } + } } @@ -232,23 +232,23 @@ public class DefinitelyWrittenCheck { Hashtable> curr = new Hashtable>(); for (int i = 0; i < fn.numPrev(); i++) { - FlatNode nn = fn.getPrev(i); - Hashtable> dwIn = definitelyWrittenResults.get(nn); - if (dwIn != null) { - mergeResults(curr, dwIn); - } + FlatNode nn = fn.getPrev(i); + Hashtable> dwIn = definitelyWrittenResults.get(nn); + if (dwIn != null) { + mergeResults(curr, dwIn); + } } definitelyWritten_nodeActions(fn, curr, entrance); // if a new result, schedule forward nodes for analysis if (!curr.equals(prev)) { - definitelyWrittenResults.put(fn, curr); + definitelyWrittenResults.put(fn, curr); - for (int i = 0; i < fn.numNext(); i++) { - FlatNode nn = fn.getNext(i); - flatNodesToVisit.add(nn); - } + for (int i = 0; i < fn.numNext(); i++) { + FlatNode nn = fn.getNext(i); + flatNodesToVisit.add(nn); + } } } } @@ -263,22 +263,22 @@ public class DefinitelyWrittenCheck { Set pairKeySet = inPair.keySet(); for (Iterator iterator2 = pairKeySet.iterator(); iterator2.hasNext(); ) { - FlatNode pairKey = (FlatNode) iterator2.next(); - Boolean inFlag = inPair.get(pairKey); - - Hashtable currPair = curr.get(inKey); - if (currPair == null) { - currPair = new Hashtable(); - curr.put(inKey, currPair); - } - - Boolean currFlag = currPair.get(pairKey); - // by default, flag is set by false - if (currFlag == null) { - currFlag = Boolean.FALSE; - } - currFlag = Boolean.valueOf(inFlag.booleanValue() | currFlag.booleanValue()); - currPair.put(pairKey, currFlag); + FlatNode pairKey = (FlatNode) iterator2.next(); + Boolean inFlag = inPair.get(pairKey); + + Hashtable currPair = curr.get(inKey); + if (currPair == null) { + currPair = new Hashtable(); + curr.put(inKey, currPair); + } + + Boolean currFlag = currPair.get(pairKey); + // by default, flag is set by false + if (currFlag == null) { + currFlag = Boolean.FALSE; + } + currFlag = Boolean.valueOf(inFlag.booleanValue() | currFlag.booleanValue()); + currPair.put(pairKey, currFlag); } } @@ -292,15 +292,15 @@ public class DefinitelyWrittenCheck { Set keySet = curr.keySet(); for (Iterator iterator = keySet.iterator(); iterator.hasNext(); ) { - Descriptor key = (Descriptor) iterator.next(); - Hashtable pair = curr.get(key); - if (pair != null) { - Set pairKeySet = pair.keySet(); - for (Iterator iterator2 = pairKeySet.iterator(); iterator2.hasNext(); ) { - FlatNode pairKey = (FlatNode) iterator2.next(); - pair.put(pairKey, Boolean.TRUE); - } - } + Descriptor key = (Descriptor) iterator.next(); + Hashtable pair = curr.get(key); + if (pair != null) { + Set pairKeySet = pair.keySet(); + for (Iterator iterator2 = pairKeySet.iterator(); iterator2.hasNext(); ) { + FlatNode pairKey = (FlatNode) iterator2.next(); + pair.put(pairKey, Boolean.TRUE); + } + } } } else { @@ -312,41 +312,41 @@ public class DefinitelyWrittenCheck { case FKind.FlatOpNode: { - FlatOpNode fon = (FlatOpNode) fn; - lhs = fon.getDest(); - rhs = fon.getLeft(); - System.out.println("\nfon=" + fon); - - if (fon.getOp().getOp() == Operation.ASSIGN) { - - // read(rhs) - Hashtable gen = curr.get(rhs); - if (gen == null) { - gen = new Hashtable(); - curr.put(rhs, gen); - } - System.out.println("READ LOC=" + rhs.getType().getExtension()); - - Boolean currentStatus = gen.get(fn); - if (currentStatus == null) { - gen.put(fn, Boolean.FALSE); - } - } - // write(lhs) - curr.put(lhs, new Hashtable()); - System.out.println("WRITING LOC=" + lhs.getType().getExtension()); + FlatOpNode fon = (FlatOpNode) fn; + lhs = fon.getDest(); + rhs = fon.getLeft(); + System.out.println("\nfon=" + fon); + + if (fon.getOp().getOp() == Operation.ASSIGN) { + + // read(rhs) + Hashtable gen = curr.get(rhs); + if (gen == null) { + gen = new Hashtable(); + curr.put(rhs, gen); + } + System.out.println("READ LOC=" + rhs.getType().getExtension()); + + Boolean currentStatus = gen.get(fn); + if (currentStatus == null) { + gen.put(fn, Boolean.FALSE); + } + } + // write(lhs) + curr.put(lhs, new Hashtable()); + System.out.println("WRITING LOC=" + lhs.getType().getExtension()); } break; case FKind.FlatLiteralNode: { - FlatLiteralNode fln = (FlatLiteralNode) fn; - lhs = fln.getDst(); + FlatLiteralNode fln = (FlatLiteralNode) fn; + lhs = fln.getDst(); - // write(lhs) - curr.put(lhs, new Hashtable()); + // write(lhs) + curr.put(lhs, new Hashtable()); - System.out.println("WRITING LOC=" + lhs.getType().getExtension()); + System.out.println("WRITING LOC=" + lhs.getType().getExtension()); } break; @@ -354,24 +354,24 @@ public class DefinitelyWrittenCheck { case FKind.FlatFieldNode: case FKind.FlatElementNode: { - FlatFieldNode ffn = (FlatFieldNode) fn; - lhs = ffn.getSrc(); - fld = ffn.getField(); - - // read field - Hashtable gen = curr.get(fld); - if (gen == null) { - gen = new Hashtable(); - curr.put(fld, gen); - } - Boolean currentStatus = gen.get(fn); - if (currentStatus == null) { - gen.put(fn, Boolean.FALSE); - } - - System.out.println("\nffn=" + ffn); - System.out.println("READ LOCfld=" + fld.getType().getExtension()); - System.out.println("READ LOClhs=" + lhs.getType().getExtension()); + FlatFieldNode ffn = (FlatFieldNode) fn; + lhs = ffn.getSrc(); + fld = ffn.getField(); + + // read field + Hashtable gen = curr.get(fld); + if (gen == null) { + gen = new Hashtable(); + curr.put(fld, gen); + } + Boolean currentStatus = gen.get(fn); + if (currentStatus == null) { + gen.put(fn, Boolean.FALSE); + } + + System.out.println("\nffn=" + ffn); + System.out.println("READ LOCfld=" + fld.getType().getExtension()); + System.out.println("READ LOClhs=" + lhs.getType().getExtension()); } break; @@ -379,14 +379,14 @@ public class DefinitelyWrittenCheck { case FKind.FlatSetFieldNode: case FKind.FlatSetElementNode: { - FlatSetFieldNode fsfn = (FlatSetFieldNode) fn; - fld = fsfn.getField(); + FlatSetFieldNode fsfn = (FlatSetFieldNode) fn; + fld = fsfn.getField(); - // write(field) - curr.put(fld, new Hashtable()); + // write(field) + curr.put(fld, new Hashtable()); - System.out.println("\nfsfn=" + fsfn); - System.out.println("WRITELOC LOC=" + fld.getType().getExtension()); + System.out.println("\nfsfn=" + fsfn); + System.out.println("WRITELOC LOC=" + fld.getType().getExtension()); } break; diff --git a/Robust/src/Analysis/SSJava/DeltaLocation.java b/Robust/src/Analysis/SSJava/DeltaLocation.java index 9e5df0a0..29a4a416 100644 --- a/Robust/src/Analysis/SSJava/DeltaLocation.java +++ b/Robust/src/Analysis/SSJava/DeltaLocation.java @@ -80,11 +80,11 @@ public class DeltaLocation extends CompositeLocation { if (locTuple.size() != 0) { int tupleSize = locTuple.size(); for (int i = 0; i < tupleSize; i++) { - Location locElement = locTuple.at(i); - if (i != 0) { - rtr += ","; - } - rtr += locElement; + Location locElement = locTuple.at(i); + if (i != 0) { + rtr += ","; + } + rtr += locElement; } } else { rtr += "LOC_REF"; diff --git a/Robust/src/Analysis/SSJava/FlowDownCheck.java b/Robust/src/Analysis/SSJava/FlowDownCheck.java index 4613bede..5d0b3dc7 100644 --- a/Robust/src/Analysis/SSJava/FlowDownCheck.java +++ b/Robust/src/Analysis/SSJava/FlowDownCheck.java @@ -67,8 +67,8 @@ public class FlowDownCheck { Set locIdSet = lattice.getKeySet(); for (Iterator iterator2 = locIdSet.iterator(); iterator2.hasNext(); ) { - String locID = (String) iterator2.next(); - id2cd.put(locID, cd); + String locID = (String) iterator2.next(); + id2cd.put(locID, cd); } } @@ -91,13 +91,13 @@ public class FlowDownCheck { // } checkDeclarationInClass(cd); for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) { - MethodDescriptor md = (MethodDescriptor) method_it.next(); - try { - checkDeclarationInMethodBody(cd, md); - } catch (Error e) { - System.out.println("Error in " + md); - throw e; - } + MethodDescriptor md = (MethodDescriptor) method_it.next(); + try { + checkDeclarationInMethodBody(cd, md); + } catch (Error e) { + System.out.println("Error in " + md); + throw e; + } } } @@ -110,26 +110,26 @@ public class FlowDownCheck { Location loc = td2loc.get(td); if (loc.getType() == Location.DELTA) { - // if it contains delta reference pointing to another location element - CompositeLocation compLoc = (CompositeLocation) loc; + // if it contains delta reference pointing to another location element + CompositeLocation compLoc = (CompositeLocation) loc; - Location locElement = compLoc.getTuple().at(0); - assert(locElement instanceof DeltaLocation); + Location locElement = compLoc.getTuple().at(0); + assert(locElement instanceof DeltaLocation); - DeltaLocation delta = (DeltaLocation) locElement; - Descriptor refType = delta.getRefLocationId(); - if (refType != null) { - Location refLoc = td2loc.get(refType); + DeltaLocation delta = (DeltaLocation) locElement; + Descriptor refType = delta.getRefLocationId(); + if (refType != null) { + Location refLoc = td2loc.get(refType); - assert(refLoc instanceof CompositeLocation); - CompositeLocation refCompLoc = (CompositeLocation) refLoc; + assert(refLoc instanceof CompositeLocation); + CompositeLocation refCompLoc = (CompositeLocation) refLoc; - assert(refCompLoc.getTuple().at(0) instanceof DeltaLocation); - DeltaLocation refDelta = (DeltaLocation) refCompLoc.getTuple().at(0); + assert(refCompLoc.getTuple().at(0) instanceof DeltaLocation); + DeltaLocation refDelta = (DeltaLocation) refCompLoc.getTuple().at(0); - delta.addDeltaOperand(refDelta); - // compLoc.addLocation(refDelta); - } + delta.addDeltaOperand(refDelta); + // compLoc.addLocation(refDelta); + } } } @@ -147,13 +147,13 @@ public class FlowDownCheck { // } checkClass(cd); for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) { - MethodDescriptor md = (MethodDescriptor) method_it.next(); - try { - checkMethodBody(cd, md); - } catch (Error e) { - System.out.println("Error in " + md); - throw e; - } + MethodDescriptor md = (MethodDescriptor) method_it.next(); + try { + checkMethodBody(cd, md); + } catch (Error e) { + System.out.println("Error in " + md); + throw e; + } } } @@ -206,8 +206,8 @@ public class FlowDownCheck { ClassDescriptor cd = md.getClassDesc(); BlockNode bn = ln.getInitializer(); for (int i = 0; i < bn.size(); i++) { - BlockStatementNode bsn = bn.get(i); - checkDeclarationInBlockStatementNode(md, nametable, bsn); + BlockStatementNode bsn = bn.get(i); + checkDeclarationInBlockStatementNode(md, nametable, bsn); } } @@ -229,11 +229,11 @@ public class FlowDownCheck { CompositeLocation bLoc = checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn); if (lowestLoc == null) { - lowestLoc = bLoc; + lowestLoc = bLoc; } else { - if (CompositeLattice.isGreaterThan(lowestLoc, bLoc, md.getClassDesc())) { - lowestLoc = bLoc; - } + if (CompositeLattice.isGreaterThan(lowestLoc, bLoc, md.getClassDesc())) { + lowestLoc = bLoc; + } } } return lowestLoc; @@ -290,10 +290,10 @@ public class FlowDownCheck { CompositeLocation bodyLoc = checkLocationFromBlockNode(md, nametable, ln.getBody()); if (!CompositeLattice.isGreaterThan(condLoc, bodyLoc, cd)) { - // loop condition should be higher than loop body - throw new Error( - "The location of the while-condition statement is lower than the loop body at " - + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine()); + // loop condition should be higher than loop body + throw new Error( + "The location of the while-condition statement is lower than the loop body at " + + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine()); } return bodyLoc; @@ -319,14 +319,14 @@ public class FlowDownCheck { CompositeLocation blockLoc = checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody()); if (blockLoc == null) { - // when there is no statement in the loop body - return glbLocOfForLoopCond; + // when there is no statement in the loop body + return glbLocOfForLoopCond; } if (!CompositeLattice.isGreaterThan(glbLocOfForLoopCond, blockLoc, cd)) { - throw new Error( - "The location of the for-condition statement is lower than the for-loop body at " - + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine()); + throw new Error( + "The location of the for-condition statement is lower than the for-loop body at " + + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine()); } return blockLoc; } @@ -370,10 +370,10 @@ public class FlowDownCheck { glbInputSet.add(locFalseBlock); if (!CompositeLattice.isGreaterThan(condLoc, locFalseBlock, localCD)) { - // error - throw new Error( - "The location of the if-condition statement is lower than the conditional block at " - + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine()); + // error + throw new Error( + "The location of the if-condition statement is lower than the conditional block at " + + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine()); } } @@ -398,11 +398,11 @@ public class FlowDownCheck { addTypeLocation(dn.getExpression().getType(), expressionLoc); if (expressionLoc != null) { - // checking location order - if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc, localCD)) { - throw new Error("The value flow from " + expressionLoc + " to " + destLoc - + " does not respect location hierarchy on the assignment " + dn.printNode(0)); - } + // checking location order + if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc, localCD)) { + throw new Error("The value flow from " + expressionLoc + " to " + destLoc + + " does not respect location hierarchy on the assignment " + dn.printNode(0)); + } } return expressionLoc; @@ -540,41 +540,41 @@ public class FlowDownCheck { // callee's hierarchy for (int i = 0; i < min.numArgs(); i++) { - ExpressionNode en = min.getArg(i); - CompositeLocation callerArg1 = - checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(cd)); - - ClassDescriptor calleecd = min.getMethod().getClassDesc(); - VarDescriptor calleevd = (VarDescriptor) min.getMethod().getParameter(i); - Location calleeLoc1 = td2loc.get(calleevd); - - if (!callerArg1.getLocation(cd).isTop()) { - // here, check if ordering relations among caller's args respect - // ordering relations in-between callee's args - for (int currentIdx = 0; currentIdx < min.numArgs(); currentIdx++) { - if (currentIdx != i) { // skip itself - ExpressionNode argExp = min.getArg(currentIdx); - CompositeLocation callerArg2 = - checkLocationFromExpressionNode(md, nametable, argExp, new CompositeLocation(cd)); - - VarDescriptor calleevd2 = (VarDescriptor) min.getMethod().getParameter(currentIdx); - Location calleeLoc2 = td2loc.get(calleevd2); - boolean callerResult = CompositeLattice.isGreaterThan(callerArg1, callerArg2, cd); - boolean calleeResult = - CompositeLattice.isGreaterThan(calleeLoc1, calleeLoc2, calleecd); - - if (calleeResult && !callerResult) { - // in callee, calleeLoc1 is higher than calleeLoc2 - // then, caller should have same ordering relation in-bet - // callerLoc1 & callerLoc2 - - throw new Error("Caller doesn't respect ordering relations among method arguments:" - + cd.getSourceFileName() + ":" + min.getNumLine()); - } - - } - } - } + ExpressionNode en = min.getArg(i); + CompositeLocation callerArg1 = + checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(cd)); + + ClassDescriptor calleecd = min.getMethod().getClassDesc(); + VarDescriptor calleevd = (VarDescriptor) min.getMethod().getParameter(i); + Location calleeLoc1 = td2loc.get(calleevd); + + if (!callerArg1.getLocation(cd).isTop()) { + // here, check if ordering relations among caller's args respect + // ordering relations in-between callee's args + for (int currentIdx = 0; currentIdx < min.numArgs(); currentIdx++) { + if (currentIdx != i) { // skip itself + ExpressionNode argExp = min.getArg(currentIdx); + CompositeLocation callerArg2 = + checkLocationFromExpressionNode(md, nametable, argExp, new CompositeLocation(cd)); + + VarDescriptor calleevd2 = (VarDescriptor) min.getMethod().getParameter(currentIdx); + Location calleeLoc2 = td2loc.get(calleevd2); + boolean callerResult = CompositeLattice.isGreaterThan(callerArg1, callerArg2, cd); + boolean calleeResult = + CompositeLattice.isGreaterThan(calleeLoc1, calleeLoc2, calleecd); + + if (calleeResult && !callerResult) { + // in callee, calleeLoc1 is higher than calleeLoc2 + // then, caller should have same ordering relation in-bet + // callerLoc1 & callerLoc2 + + throw new Error("Caller doesn't respect ordering relations among method arguments:" + + cd.getSourceFileName() + ":" + min.getNumLine()); + } + + } + } + } } @@ -748,18 +748,18 @@ public class FlowDownCheck { Location localLoc = null; if (d instanceof VarDescriptor) { - VarDescriptor vd = (VarDescriptor) d; - localLoc = td2loc.get(vd); + VarDescriptor vd = (VarDescriptor) d; + localLoc = td2loc.get(vd); } else if (d instanceof FieldDescriptor) { - FieldDescriptor fd = (FieldDescriptor) d; - localLoc = td2loc.get(fd); + FieldDescriptor fd = (FieldDescriptor) d; + localLoc = td2loc.get(fd); } assert(localLoc != null); if (localLoc instanceof CompositeLocation) { - loc = (CompositeLocation) localLoc; + loc = (CompositeLocation) localLoc; } else { - loc.addLocation(localLoc); + loc.addLocation(localLoc); } } @@ -798,8 +798,8 @@ public class FlowDownCheck { srcLocation = checkLocationFromExpressionNode(md, nametable, an.getSrc(), srcLocation); if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, cd)) { - throw new Error("The value flow from " + srcLocation + " to " + destLocation - + " does not respect location hierarchy on the assignment " + an.printNode(0)); + throw new Error("The value flow from " + srcLocation + " to " + destLocation + + " does not respect location hierarchy on the assignment " + an.printNode(0)); } } else { destLocation = @@ -807,8 +807,8 @@ public class FlowDownCheck { if (!((Set)state.getCd2LocationPropertyMap().get(cd)).contains(destLocation .getLocation(cd).getLocIdentifier())) { - throw new Error("Location " + destLocation + " is not allowed to have spinning values at " - + cd.getSourceFileName() + ":" + an.getNumLine()); + throw new Error("Location " + destLocation + " is not allowed to have spinning values at " + + cd.getSourceFileName() + ":" + an.getNumLine()); } } @@ -846,8 +846,8 @@ public class FlowDownCheck { Lattice lattice = (Lattice)state.getCd2LocationOrder().get(cd); if (lattice == null || (!lattice.containsKey(locationID))) { - throw new Error("Location " + locationID - + " is not defined in the location hierarchy of class " + cd.getSymbol() + "."); + throw new Error("Location " + locationID + + " is not defined in the location hierarchy of class " + cd.getSymbol() + "."); } Location loc = new Location(cd, locationID); @@ -857,56 +857,56 @@ public class FlowDownCheck { } else if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) { if (ad.getMarker().equals(SSJavaAnalysis.DELTA)) { - CompositeLocation compLoc = new CompositeLocation(cd); - - if (ad.getData().length() == 0) { - throw new Error("Delta function of " + vd.getSymbol() + " does not have any locations: " - + cd.getSymbol() + "."); - } - - String deltaStr = ad.getData(); - if (deltaStr.startsWith("LOC(")) { - - if (!deltaStr.endsWith(")")) { - throw new Error("The declaration of the delta location is wrong at " - + cd.getSourceFileName() + ":" + n.getNumLine()); - } - String locationOperand = deltaStr.substring(4, deltaStr.length() - 1); - - nametable.get(locationOperand); - Descriptor d = (Descriptor) nametable.get(locationOperand); - - if (d instanceof VarDescriptor) { - VarDescriptor varDescriptor = (VarDescriptor) d; - DeltaLocation deltaLoc = new DeltaLocation(cd, varDescriptor); - // td2loc.put(vd.getType(), compLoc); - compLoc.addLocation(deltaLoc); - } else if (d instanceof FieldDescriptor) { - throw new Error("Applying delta operation to the field " + locationOperand - + " is not allowed at " + cd.getSourceFileName() + ":" + n.getNumLine()); - } - } else { - StringTokenizer token = new StringTokenizer(deltaStr, ","); - DeltaLocation deltaLoc = new DeltaLocation(cd); - - while (token.hasMoreTokens()) { - String deltaOperand = token.nextToken(); - ClassDescriptor deltaCD = id2cd.get(deltaOperand); - if (deltaCD == null) { - // delta operand is not defined in the location hierarchy - throw new Error("Delta operand '" + deltaOperand + "' of declaration node '" + vd - + "' is not defined by location hierarchies."); - } - - Location loc = new Location(deltaCD, deltaOperand); - deltaLoc.addDeltaOperand(loc); - } - compLoc.addLocation(deltaLoc); - - } - - td2loc.put(vd, compLoc); - addTypeLocation(vd.getType(), compLoc); + CompositeLocation compLoc = new CompositeLocation(cd); + + if (ad.getData().length() == 0) { + throw new Error("Delta function of " + vd.getSymbol() + " does not have any locations: " + + cd.getSymbol() + "."); + } + + String deltaStr = ad.getData(); + if (deltaStr.startsWith("LOC(")) { + + if (!deltaStr.endsWith(")")) { + throw new Error("The declaration of the delta location is wrong at " + + cd.getSourceFileName() + ":" + n.getNumLine()); + } + String locationOperand = deltaStr.substring(4, deltaStr.length() - 1); + + nametable.get(locationOperand); + Descriptor d = (Descriptor) nametable.get(locationOperand); + + if (d instanceof VarDescriptor) { + VarDescriptor varDescriptor = (VarDescriptor) d; + DeltaLocation deltaLoc = new DeltaLocation(cd, varDescriptor); + // td2loc.put(vd.getType(), compLoc); + compLoc.addLocation(deltaLoc); + } else if (d instanceof FieldDescriptor) { + throw new Error("Applying delta operation to the field " + locationOperand + + " is not allowed at " + cd.getSourceFileName() + ":" + n.getNumLine()); + } + } else { + StringTokenizer token = new StringTokenizer(deltaStr, ","); + DeltaLocation deltaLoc = new DeltaLocation(cd); + + while (token.hasMoreTokens()) { + String deltaOperand = token.nextToken(); + ClassDescriptor deltaCD = id2cd.get(deltaOperand); + if (deltaCD == null) { + // delta operand is not defined in the location hierarchy + throw new Error("Delta operand '" + deltaOperand + "' of declaration node '" + vd + + "' is not defined by location hierarchies."); + } + + Location loc = new Location(deltaCD, deltaOperand); + deltaLoc.addDeltaOperand(loc); + } + compLoc.addLocation(deltaLoc); + + } + + td2loc.put(vd, compLoc); + addTypeLocation(vd.getType(), compLoc); } } @@ -961,8 +961,8 @@ public class FlowDownCheck { Lattice lattice = (Lattice)state.getCd2LocationOrder().get(cd); if (lattice == null || (!lattice.containsKey(locationID))) { - throw new Error("Location " + locationID - + " is not defined in the location hierarchy of class " + cd.getSymbol() + "."); + throw new Error("Location " + locationID + + " is not defined in the location hierarchy of class " + cd.getSymbol() + "."); } Location localLoc = new Location(cd, locationID); @@ -972,30 +972,30 @@ public class FlowDownCheck { } else if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) { if (ad.getMarker().equals(SSJavaAnalysis.DELTA)) { - if (ad.getData().length() == 0) { - throw new Error("Delta function of " + fd.getSymbol() + " does not have any locations: " - + cd.getSymbol() + "."); - } - - CompositeLocation compLoc = new CompositeLocation(cd); - DeltaLocation deltaLoc = new DeltaLocation(cd); - - StringTokenizer token = new StringTokenizer(ad.getData(), ","); - while (token.hasMoreTokens()) { - String deltaOperand = token.nextToken(); - ClassDescriptor deltaCD = id2cd.get(deltaOperand); - if (deltaCD == null) { - // delta operand is not defined in the location hierarchy - throw new Error("Delta operand '" + deltaOperand + "' of field node '" + fd - + "' is not defined by location hierarchies."); - } - - Location loc = new Location(deltaCD, deltaOperand); - deltaLoc.addDeltaOperand(loc); - } - compLoc.addLocation(deltaLoc); - td2loc.put(fd, compLoc); - addTypeLocation(fd.getType(), compLoc); + if (ad.getData().length() == 0) { + throw new Error("Delta function of " + fd.getSymbol() + " does not have any locations: " + + cd.getSymbol() + "."); + } + + CompositeLocation compLoc = new CompositeLocation(cd); + DeltaLocation deltaLoc = new DeltaLocation(cd); + + StringTokenizer token = new StringTokenizer(ad.getData(), ","); + while (token.hasMoreTokens()) { + String deltaOperand = token.nextToken(); + ClassDescriptor deltaCD = id2cd.get(deltaOperand); + if (deltaCD == null) { + // delta operand is not defined in the location hierarchy + throw new Error("Delta operand '" + deltaOperand + "' of field node '" + fd + + "' is not defined by location hierarchies."); + } + + Location loc = new Location(deltaCD, deltaOperand); + deltaLoc.addDeltaOperand(loc); + } + compLoc.addLocation(deltaLoc); + td2loc.put(fd, compLoc); + addTypeLocation(fd.getType(), compLoc); } } @@ -1017,19 +1017,19 @@ public class FlowDownCheck { CompositeLocation compLoc2; if (loc1 instanceof CompositeLocation) { - compLoc1 = (CompositeLocation) loc1; + compLoc1 = (CompositeLocation) loc1; } else { - // create a bogus composite location for a single location - compLoc1 = new CompositeLocation(loc1.getClassDescriptor()); - compLoc1.addLocation(loc1); + // create a bogus composite location for a single location + compLoc1 = new CompositeLocation(loc1.getClassDescriptor()); + compLoc1.addLocation(loc1); } if (loc2 instanceof CompositeLocation) { - compLoc2 = (CompositeLocation) loc2; + compLoc2 = (CompositeLocation) loc2; } else { - // create a bogus composite location for a single location - compLoc2 = new CompositeLocation(loc2.getClassDescriptor()); - compLoc2.addLocation(loc2); + // create a bogus composite location for a single location + compLoc2 = new CompositeLocation(loc2.getClassDescriptor()); + compLoc2.addLocation(loc2); } // comparing two composite locations @@ -1038,24 +1038,24 @@ public class FlowDownCheck { int baseCompareResult = compareBaseLocationSet(compLoc1, compLoc2, priorityCD); if (baseCompareResult == ComparisonResult.EQUAL) { - if (compareDelta(compLoc1, compLoc2) == ComparisonResult.GREATER) { - return true; - } else { - return false; - } + if (compareDelta(compLoc1, compLoc2) == ComparisonResult.GREATER) { + return true; + } else { + return false; + } } else if (baseCompareResult == ComparisonResult.GREATER) { - return true; + return true; } else { - return false; + return false; } } private static int compareDelta(CompositeLocation compLoc1, CompositeLocation compLoc2) { if (compLoc1.getNumofDelta() < compLoc2.getNumofDelta()) { - return ComparisonResult.GREATER; + return ComparisonResult.GREATER; } else { - return ComparisonResult.LESS; + return ComparisonResult.LESS; } } @@ -1078,23 +1078,23 @@ public class FlowDownCheck { Lattice locationOrder = (Lattice)state.getCd2LocationOrder().get(cd); if (priorityLoc1.getLocIdentifier().equals(priorityLoc2.getLocIdentifier())) { - // have the same level of local hierarchy + // have the same level of local hierarchy - Set spinSet = (Set)state.getCd2LocationPropertyMap().get(cd); - if (spinSet != null && spinSet.contains(priorityLoc1.getLocIdentifier())) { - // this location can be spinning - return ComparisonResult.GREATER; - } + Set spinSet = (Set)state.getCd2LocationPropertyMap().get(cd); + if (spinSet != null && spinSet.contains(priorityLoc1.getLocIdentifier())) { + // this location can be spinning + return ComparisonResult.GREATER; + } } else if (locationOrder.isGreaterThan(priorityLoc1.getLocIdentifier(), priorityLoc2.getLocIdentifier())) { - // if priority loc of compLoc1 is higher than compLoc2 - // then, compLoc 1 is higher than compLoc2 - return ComparisonResult.GREATER; + // if priority loc of compLoc1 is higher than compLoc2 + // then, compLoc 1 is higher than compLoc2 + return ComparisonResult.GREATER; } else { - // if priority loc of compLoc1 is NOT higher than compLoc2 - // then, compLoc 1 is NOT higher than compLoc2 - return ComparisonResult.LESS; + // if priority loc of compLoc1 is NOT higher than compLoc2 + // then, compLoc 1 is NOT higher than compLoc2 + return ComparisonResult.LESS; } // compare base locations except priority by class descriptor @@ -1102,40 +1102,40 @@ public class FlowDownCheck { int numEqualLoc = 0; for (Iterator iterator = keySet1.iterator(); iterator.hasNext(); ) { - ClassDescriptor cd1 = (ClassDescriptor) iterator.next(); - - Location loc1 = cd2loc1.get(cd1); - Location loc2 = cd2loc2.get(cd1); - - if (priorityLoc1.equals(loc1)) { - continue; - } - - if (loc2 == null) { - // if comploc2 doesn't have corresponding location, - // then we determines that comploc1 is lower than comploc 2 - return ComparisonResult.LESS; - } - - System.out.println("lattice comparison:" + loc1.getLocIdentifier() + " ? " - + loc2.getLocIdentifier()); - locationOrder = (Lattice)state.getCd2LocationOrder().get(cd1); - if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) { - // have the same level of local hierarchy - numEqualLoc++; - } else if (!locationOrder.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) { - // if one element of composite location 1 is not higher than composite - // location 2 - // then, composite loc 1 is not higher than composite loc 2 - - System.out.println(compLoc1 + " < " + compLoc2); - return ComparisonResult.LESS; - } + ClassDescriptor cd1 = (ClassDescriptor) iterator.next(); + + Location loc1 = cd2loc1.get(cd1); + Location loc2 = cd2loc2.get(cd1); + + if (priorityLoc1.equals(loc1)) { + continue; + } + + if (loc2 == null) { + // if comploc2 doesn't have corresponding location, + // then we determines that comploc1 is lower than comploc 2 + return ComparisonResult.LESS; + } + + System.out.println("lattice comparison:" + loc1.getLocIdentifier() + " ? " + + loc2.getLocIdentifier()); + locationOrder = (Lattice)state.getCd2LocationOrder().get(cd1); + if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) { + // have the same level of local hierarchy + numEqualLoc++; + } else if (!locationOrder.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) { + // if one element of composite location 1 is not higher than composite + // location 2 + // then, composite loc 1 is not higher than composite loc 2 + + System.out.println(compLoc1 + " < " + compLoc2); + return ComparisonResult.LESS; + } } if (numEqualLoc == (compLoc1.getBaseLocationSize() - 1)) { - return ComparisonResult.EQUAL; + return ComparisonResult.EQUAL; } System.out.println(compLoc1 + " > " + compLoc2); @@ -1155,35 +1155,35 @@ public class FlowDownCheck { // creating mapping from class to set of locations for (Iterator iterator = inputSet.iterator(); iterator.hasNext(); ) { - CompositeLocation compLoc = (CompositeLocation) iterator.next(); + CompositeLocation compLoc = (CompositeLocation) iterator.next(); - int numOfDelta = compLoc.getNumofDelta(); - if (numOfDelta > maxDeltaFunction) { - maxDeltaFunction = numOfDelta; - } + int numOfDelta = compLoc.getNumofDelta(); + if (numOfDelta > maxDeltaFunction) { + maxDeltaFunction = numOfDelta; + } - Set baseLocationSet = compLoc.getBaseLocationSet(); - for (Iterator iterator2 = baseLocationSet.iterator(); iterator2.hasNext(); ) { - Location locElement = (Location) iterator2.next(); - ClassDescriptor locCD = locElement.getClassDescriptor(); + Set baseLocationSet = compLoc.getBaseLocationSet(); + for (Iterator iterator2 = baseLocationSet.iterator(); iterator2.hasNext(); ) { + Location locElement = (Location) iterator2.next(); + ClassDescriptor locCD = locElement.getClassDescriptor(); - Set locSet = cd2locSet.get(locCD); - if (locSet == null) { - locSet = new HashSet(); - } - locSet.add(locElement); + Set locSet = cd2locSet.get(locCD); + if (locSet == null) { + locSet = new HashSet(); + } + locSet.add(locElement); - cd2locSet.put(locCD, locSet); + cd2locSet.put(locCD, locSet); - } + } } Set locSetofClass = cd2locSet.get(priorityCD); Set locIdentifierSet = new HashSet(); for (Iterator locIterator = locSetofClass.iterator(); locIterator.hasNext(); ) { - Location locElement = locIterator.next(); - locIdentifierSet.add(locElement.getLocIdentifier()); + Location locElement = locIterator.next(); + locIdentifierSet.add(locElement.getLocIdentifier()); } Lattice locOrder = (Lattice)state.getCd2LocationOrder().get(priorityCD); @@ -1194,48 +1194,48 @@ public class FlowDownCheck { Set sameGLBLoc = new HashSet(); for (Iterator iterator = inputSet.iterator(); iterator.hasNext(); ) { - CompositeLocation inputComploc = iterator.next(); - Location locElement = inputComploc.getLocation(priorityCD); + CompositeLocation inputComploc = iterator.next(); + Location locElement = inputComploc.getLocation(priorityCD); - if (locElement.equals(priorityGLB)) { - sameGLBLoc.add(inputComploc); - } + if (locElement.equals(priorityGLB)) { + sameGLBLoc.add(inputComploc); + } } glbCompLoc.addLocation(priorityGLB); if (sameGLBLoc.size() > 0) { - // if more than one location shares the same priority GLB - // need to calculate the rest of GLB loc - - Set glbElementSet = new HashSet(); - - for (Iterator iterator = cd2locSet.keySet().iterator(); iterator.hasNext(); ) { - ClassDescriptor localCD = iterator.next(); - if (!localCD.equals(priorityCD)) { - Set localLocSet = cd2locSet.get(localCD); - Set LocalLocIdSet = new HashSet(); - - for (Iterator locIterator = localLocSet.iterator(); locIterator.hasNext(); ) { - Location locElement = locIterator.next(); - LocalLocIdSet.add(locElement.getLocIdentifier()); - } - - Lattice localOrder = (Lattice)state.getCd2LocationOrder().get(localCD); - Location localGLBLoc = new Location(localCD, localOrder.getGLB(LocalLocIdSet)); - glbCompLoc.addLocation(localGLBLoc); - } - } + // if more than one location shares the same priority GLB + // need to calculate the rest of GLB loc + + Set glbElementSet = new HashSet(); + + for (Iterator iterator = cd2locSet.keySet().iterator(); iterator.hasNext(); ) { + ClassDescriptor localCD = iterator.next(); + if (!localCD.equals(priorityCD)) { + Set localLocSet = cd2locSet.get(localCD); + Set LocalLocIdSet = new HashSet(); + + for (Iterator locIterator = localLocSet.iterator(); locIterator.hasNext(); ) { + Location locElement = locIterator.next(); + LocalLocIdSet.add(locElement.getLocIdentifier()); + } + + Lattice localOrder = (Lattice)state.getCd2LocationOrder().get(localCD); + Location localGLBLoc = new Location(localCD, localOrder.getGLB(LocalLocIdSet)); + glbCompLoc.addLocation(localGLBLoc); + } + } } else { - // if priority glb loc is lower than all of input loc - // assign top location to the rest of loc element + // if priority glb loc is lower than all of input loc + // assign top location to the rest of loc element - for (Iterator iterator = cd2locSet.keySet().iterator(); iterator.hasNext(); ) { - ClassDescriptor localCD = iterator.next(); - if (!localCD.equals(priorityCD)) { - Location localGLBLoc = Location.createTopLocation(localCD); - glbCompLoc.addLocation(localGLBLoc); - } + for (Iterator iterator = cd2locSet.keySet().iterator(); iterator.hasNext(); ) { + ClassDescriptor localCD = iterator.next(); + if (!localCD.equals(priorityCD)) { + Location localGLBLoc = Location.createTopLocation(localCD); + glbCompLoc.addLocation(localGLBLoc); + } - } + } } diff --git a/Robust/src/Analysis/SSJava/Location.java b/Robust/src/Analysis/SSJava/Location.java index decaee7c..0261f96a 100644 --- a/Robust/src/Analysis/SSJava/Location.java +++ b/Robust/src/Analysis/SSJava/Location.java @@ -49,13 +49,13 @@ public class Location implements TypeExtension { if (loc.getClassDescriptor().equals(getClassDescriptor())) { if (loc.getLocIdentifier() == null || getLocIdentifier() == null) { - if (loc.getType() == getType()) { - return true; - } + if (loc.getType() == getType()) { + return true; + } } else { - if (loc.getLocIdentifier().equals(getLocIdentifier())) { - return true; - } + if (loc.getLocIdentifier().equals(getLocIdentifier())) { + return true; + } } } diff --git a/Robust/src/Analysis/Scheduling/ClassNode.java b/Robust/src/Analysis/Scheduling/ClassNode.java index fa093e46..ed0ed898 100644 --- a/Robust/src/Analysis/Scheduling/ClassNode.java +++ b/Robust/src/Analysis/Scheduling/ClassNode.java @@ -126,7 +126,7 @@ public class ClassNode extends GraphNode implements Cloneable { (fs.isSorted() != sorted) || (fs.clone != this.clone) || (fs.transTime != this.transTime)) { - return false; + return false; } return (fs.getFlagStates().equals(flagStates)); } diff --git a/Robust/src/Analysis/Scheduling/CombinationUtil.java b/Robust/src/Analysis/Scheduling/CombinationUtil.java index 79d7969d..9af8d02e 100644 --- a/Robust/src/Analysis/Scheduling/CombinationUtil.java +++ b/Robust/src/Analysis/Scheduling/CombinationUtil.java @@ -57,86 +57,86 @@ public class CombinationUtil { public boolean nextGen() { boolean trial = false; if(this.rootNodes == null) { - int num2choose = this.rootNum; - this.rootNodes = new Vector>(); - this.rootNodes.add(new Vector()); - Vector toadd = this.sNodeVecs.elementAt(0); - for(int i = 0; i < toadd.size(); i++) { - // should be only one element: startup object - this.rootNodes.elementAt(0).add(toadd.elementAt(i)); - num2choose--; - } - int next = 1; - trial = trial(num2choose, next); - toadd = null; + int num2choose = this.rootNum; + this.rootNodes = new Vector>(); + this.rootNodes.add(new Vector()); + Vector toadd = this.sNodeVecs.elementAt(0); + for(int i = 0; i < toadd.size(); i++) { + // should be only one element: startup object + this.rootNodes.elementAt(0).add(toadd.elementAt(i)); + num2choose--; + } + int next = 1; + trial = trial(num2choose, next); + toadd = null; } else { - if(this.rootNodes.size() == 1) { - return false; - } - int next = this.rootNodes.lastElement().elementAt(0).getCid() + 1; - int num2choose = 0; - while(next == this.sNodeVecs.size()) { - // backtrack - num2choose = this.rootNodes.lastElement().size(); - this.rootNodes.removeElementAt(this.rootNodes.size() - 1); - if(this.rootNodes.size() == 1) { - // only startup object left, no more choices - return false; - } - next = this.rootNodes.lastElement().elementAt(0).getCid() + 1; - } - num2choose++; - // reduce one from the last one - this.rootNodes.lastElement().removeElementAt(this.rootNodes.lastElement().size() - 1); - if(this.rootNodes.lastElement().size() == 0) { - this.rootNodes.removeElementAt(this.rootNodes.size() - 1); - } - - trial = trial(num2choose, next); + if(this.rootNodes.size() == 1) { + return false; + } + int next = this.rootNodes.lastElement().elementAt(0).getCid() + 1; + int num2choose = 0; + while(next == this.sNodeVecs.size()) { + // backtrack + num2choose = this.rootNodes.lastElement().size(); + this.rootNodes.removeElementAt(this.rootNodes.size() - 1); + if(this.rootNodes.size() == 1) { + // only startup object left, no more choices + return false; + } + next = this.rootNodes.lastElement().elementAt(0).getCid() + 1; + } + num2choose++; + // reduce one from the last one + this.rootNodes.lastElement().removeElementAt(this.rootNodes.lastElement().size() - 1); + if(this.rootNodes.lastElement().size() == 0) { + this.rootNodes.removeElementAt(this.rootNodes.size() - 1); + } + + trial = trial(num2choose, next); } if(trial) { - // remaining nodes are all to be combined - this.node2Combine = new Vector>(); - int next = 1; - int index = 0; - for(int i = 1; i < this.rootNodes.size(); i++) { - int tmp = this.rootNodes.elementAt(i).elementAt(0).getCid(); - while(next < tmp) { - Vector toadd = this.sNodeVecs.elementAt(next); - if(toadd != null) { - this.node2Combine.add(new Vector()); - for(index = 0; index < toadd.size(); index++) { - this.node2Combine.lastElement().add(toadd.elementAt(index)); - } - toadd = null; - } else { - this.node2Combine.add(null); - } - next++; - } - Vector toadd = this.sNodeVecs.elementAt(tmp); - if(toadd.size() > this.rootNodes.elementAt(i).size()) { - this.node2Combine.add(new Vector()); - for(index = this.rootNodes.elementAt(i).size(); index < toadd.size(); index++) { - this.node2Combine.lastElement().add(toadd.elementAt(index)); - } - } - toadd = null; - next++; - } - while(next < this.sNodeVecs.size()) { - Vector toadd = this.sNodeVecs.elementAt(next); - if(toadd != null) { - this.node2Combine.add(new Vector()); - for(index = 0; index < toadd.size(); index++) { - this.node2Combine.lastElement().add(toadd.elementAt(index)); - } - toadd = null; - } else { - this.node2Combine.add(null); - } - next++; - } + // remaining nodes are all to be combined + this.node2Combine = new Vector>(); + int next = 1; + int index = 0; + for(int i = 1; i < this.rootNodes.size(); i++) { + int tmp = this.rootNodes.elementAt(i).elementAt(0).getCid(); + while(next < tmp) { + Vector toadd = this.sNodeVecs.elementAt(next); + if(toadd != null) { + this.node2Combine.add(new Vector()); + for(index = 0; index < toadd.size(); index++) { + this.node2Combine.lastElement().add(toadd.elementAt(index)); + } + toadd = null; + } else { + this.node2Combine.add(null); + } + next++; + } + Vector toadd = this.sNodeVecs.elementAt(tmp); + if(toadd.size() > this.rootNodes.elementAt(i).size()) { + this.node2Combine.add(new Vector()); + for(index = this.rootNodes.elementAt(i).size(); index < toadd.size(); index++) { + this.node2Combine.lastElement().add(toadd.elementAt(index)); + } + } + toadd = null; + next++; + } + while(next < this.sNodeVecs.size()) { + Vector toadd = this.sNodeVecs.elementAt(next); + if(toadd != null) { + this.node2Combine.add(new Vector()); + for(index = 0; index < toadd.size(); index++) { + this.node2Combine.lastElement().add(toadd.elementAt(index)); + } + toadd = null; + } else { + this.node2Combine.add(null); + } + next++; + } } return trial; } @@ -146,29 +146,29 @@ public class CombinationUtil { int index = 0; boolean first = true; while(num2choose > 0) { - if(first) { - if(next == this.sNodeVecs.size()) { - // no more nodes available to add - return false; - } - } - if(this.sNodeVecs.elementAt(next) != null) { - if(first) { - this.rootNodes.add(new Vector()); - first = false; - } - this.rootNodes.lastElement().add(this.sNodeVecs.elementAt(next).elementAt(index)); - num2choose--; - index++; - if(index == this.sNodeVecs.elementAt(next).size()) { - index = 0; - next++; - first = true; - } - } else { - next++; - first = true; - } + if(first) { + if(next == this.sNodeVecs.size()) { + // no more nodes available to add + return false; + } + } + if(this.sNodeVecs.elementAt(next) != null) { + if(first) { + this.rootNodes.add(new Vector()); + first = false; + } + this.rootNodes.lastElement().add(this.sNodeVecs.elementAt(next).elementAt(index)); + num2choose--; + index++; + if(index == this.sNodeVecs.elementAt(next).size()) { + index = 0; + next++; + first = true; + } + } else { + next++; + first = true; + } } return true; } @@ -212,27 +212,27 @@ public class CombinationUtil { this.rootNStates = new Vector>(); int rootnum = 0; for(int i = 0; i < this.rootNodes.size(); i++) { - this.rootNStates.add(new Vector()); - for(int j = 0; j < this.rootNodes.elementAt(i).size(); j++) { - this.rootNStates.elementAt(i).add(new int[this.node2Combine.size()]); - for(int k = 0; k < this.node2Combine.size(); k++) { - this.rootNStates.elementAt(i).elementAt(j)[k] = 0; - } - rootnum++; - } + this.rootNStates.add(new Vector()); + for(int j = 0; j < this.rootNodes.elementAt(i).size(); j++) { + this.rootNStates.elementAt(i).add(new int[this.node2Combine.size()]); + for(int k = 0; k < this.node2Combine.size(); k++) { + this.rootNStates.elementAt(i).elementAt(j)[k] = 0; + } + rootnum++; + } } this.combine = new Vector>(); int tomapnum = 0; for(int i = 0; i < this.node2Combine.size(); i++) { - if(this.node2Combine.elementAt(i) == null) { - this.combine.add(null); - } else { - this.combine.add(new Vector()); - for(int j = 0; j < this.node2Combine.elementAt(i).size(); j++) { - this.combine.elementAt(i).add(new Combine(this.node2Combine.elementAt(i).elementAt(j))); - tomapnum++; - } - } + if(this.node2Combine.elementAt(i) == null) { + this.combine.add(null); + } else { + this.combine.add(new Vector()); + for(int j = 0; j < this.node2Combine.elementAt(i).size(); j++) { + this.combine.elementAt(i).add(new Combine(this.node2Combine.elementAt(i).elementAt(j))); + tomapnum++; + } + } } this.lastchoices = null; this.first4choice = false; @@ -261,23 +261,23 @@ public class CombinationUtil { public boolean randomGenE() { this.rootLoads = new int[this.rootNodes.size()][]; for(int i = 0; i < this.rootNodes.size(); i++) { - this.rootLoads[i] = new int[this.rootNodes.elementAt(i).size()]; + this.rootLoads[i] = new int[this.rootNodes.elementAt(i).size()]; } int rootx = this.rootNodes.size(); for(int i = 0; i < this.node2Combine.size(); i++) { - for(int j = 0; j < this.node2Combine.elementAt(i).size(); j++) { - Combine tmp = this.combine.elementAt(i).elementAt(j); - do { - int x = Math.abs(rand.nextInt()) % rootx; - int y = Math.abs(rand.nextInt()) % this.rootNodes.elementAt(x).size(); - if(this.rootLoads[x][y] < this.limit) { - tmp.root = x; - tmp.index = y; - this.rootLoads[tmp.root][tmp.index]++; - break; - } - } while(true); - } + for(int j = 0; j < this.node2Combine.elementAt(i).size(); j++) { + Combine tmp = this.combine.elementAt(i).elementAt(j); + do { + int x = Math.abs(rand.nextInt()) % rootx; + int y = Math.abs(rand.nextInt()) % this.rootNodes.elementAt(x).size(); + if(this.rootLoads[x][y] < this.limit) { + tmp.root = x; + tmp.index = y; + this.rootLoads[tmp.root][tmp.index]++; + break; + } + } while(true); + } } return true; } @@ -285,11 +285,11 @@ public class CombinationUtil { public boolean randomGen() { int rootx = this.rootNodes.size(); for(int i = 0; i < this.node2Combine.size(); i++) { - for(int j = 0; j < this.node2Combine.elementAt(i).size(); j++) { - Combine tmp = this.combine.elementAt(i).elementAt(j); - tmp.root = Math.abs(rand.nextInt()) % rootx; - tmp.index = Math.abs(rand.nextInt()) % this.rootNodes.elementAt(tmp.root).size(); - } + for(int j = 0; j < this.node2Combine.elementAt(i).size(); j++) { + Combine tmp = this.combine.elementAt(i).elementAt(j); + tmp.root = Math.abs(rand.nextInt()) % rootx; + tmp.index = Math.abs(rand.nextInt()) % this.rootNodes.elementAt(tmp.root).size(); + } } return true; } @@ -297,48 +297,48 @@ public class CombinationUtil { public boolean nextGen() { boolean trial = false; if(this.lastchoices == null) { - // first time - this.lastchoices = new int[this.node2Combine.size()]; - for(int i = 0; i < this.lastchoices.length; i++) { - this.lastchoices[i] = 0; - } - this.first4choice = true; - trial = trial(); + // first time + this.lastchoices = new int[this.node2Combine.size()]; + for(int i = 0; i < this.lastchoices.length; i++) { + this.lastchoices[i] = 0; + } + this.first4choice = true; + trial = trial(); } else { - trial = trial(); - while(!trial) { - // no more available combination under this choice - // choose another choice - int next = this.node2Combine.size() - 1; - boolean iter = false; - do { - if(this.node2Combine.elementAt(next) != null) { - this.lastchoices[next]++; - if((this.lastchoices[next] == this.rootNodes.size() || - (this.rootNodes.elementAt(this.lastchoices[next]).elementAt(0).getCid() > - this.node2Combine.elementAt(next).elementAt(0).getCid()))) { - // break the rule that a node can only be combined to nodes with smaller colorid. - // or no more buckets - // backtrack - next--; - iter = true; - } else { - iter = false; - } - } else { - next--; - iter = true; - } - } while(iter && !(next < 0)); - if(next < 0) { - return false; - } - for(next += 1; next < this.node2Combine.size(); next++) { - this.lastchoices[next] = 0; - } - this.first4choice = true; - trial = trial(); - } + trial = trial(); + while(!trial) { + // no more available combination under this choice + // choose another choice + int next = this.node2Combine.size() - 1; + boolean iter = false; + do { + if(this.node2Combine.elementAt(next) != null) { + this.lastchoices[next]++; + if((this.lastchoices[next] == this.rootNodes.size() || + (this.rootNodes.elementAt(this.lastchoices[next]).elementAt(0).getCid() > + this.node2Combine.elementAt(next).elementAt(0).getCid()))) { + // break the rule that a node can only be combined to nodes with smaller colorid. + // or no more buckets + // backtrack + next--; + iter = true; + } else { + iter = false; + } + } else { + next--; + iter = true; + } + } while(iter && !(next < 0)); + if(next < 0) { + return false; + } + for(next += 1; next < this.node2Combine.size(); next++) { + this.lastchoices[next] = 0; + } + this.first4choice = true; + trial = trial(); + } } return trial; } @@ -346,15 +346,15 @@ public class CombinationUtil { private boolean trial() { boolean suc = false; if(this.first4choice) { - // first time for each choice - // put all the objects of one color into the first bucket indicated by the choice - int next = 0; - suc = firstexpand(next, this.first4choice); - this.first4choice = false; + // first time for each choice + // put all the objects of one color into the first bucket indicated by the choice + int next = 0; + suc = firstexpand(next, this.first4choice); + this.first4choice = false; } else { - int next = this.node2Combine.size() - 1; - int layer = 0; - suc = innertrial(next, layer); + int next = this.node2Combine.size() - 1; + int layer = 0; + suc = innertrial(next, layer); } return suc; } @@ -362,26 +362,26 @@ public class CombinationUtil { private boolean firstexpand(int next, boolean first) { for(int i = next; i < this.node2Combine.size(); i++) { - if(this.node2Combine.elementAt(i) != null) { - int choice = this.lastchoices[i]; - for(int j = 0; j < this.node2Combine.elementAt(i).size(); j++) { - Combine tmp = this.combine.elementAt(i).elementAt(j); - if(!first) { - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; - } - tmp.root = choice; - tmp.index = 0; - if(!first) { - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; - } - } - if(first) { - this.rootNStates.elementAt(choice).elementAt(0)[i] = this.node2Combine.elementAt(i).size(); - for(int j = 1; j < this.rootNodes.elementAt(choice).size(); j++) { - this.rootNStates.elementAt(choice).elementAt(j)[i] = 0; - } - } - } + if(this.node2Combine.elementAt(i) != null) { + int choice = this.lastchoices[i]; + for(int j = 0; j < this.node2Combine.elementAt(i).size(); j++) { + Combine tmp = this.combine.elementAt(i).elementAt(j); + if(!first) { + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; + } + tmp.root = choice; + tmp.index = 0; + if(!first) { + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; + } + } + if(first) { + this.rootNStates.elementAt(choice).elementAt(0)[i] = this.node2Combine.elementAt(i).size(); + for(int j = 1; j < this.rootNodes.elementAt(choice).size(); j++) { + this.rootNStates.elementAt(choice).elementAt(j)[i] = 0; + } + } + } } return true; } @@ -390,13 +390,13 @@ public class CombinationUtil { int layer) { if((this.combine.elementAt(next) == null) || (this.combine.elementAt(next).size() < 2)) { - // skip over empty buckets and bucket with only one obj ( make sure - // at least one obj is existing in the chosen bucket) - if(next - 1 < 0) { - return false; - } else { - return innertrial(next - 1, ++layer); - } + // skip over empty buckets and bucket with only one obj ( make sure + // at least one obj is existing in the chosen bucket) + if(next - 1 < 0) { + return false; + } else { + return innertrial(next - 1, ++layer); + } } Combine tmp = this.combine.elementAt(next).lastElement(); // try to move it backward @@ -404,141 +404,141 @@ public class CombinationUtil { int index = tmp.index; index++; if(index == this.rootNodes.elementAt(root).size()) { - // no more place in this color bucket - index = 0; - root++; + // no more place in this color bucket + index = 0; + root++; } else if(this.rootNStates.elementAt(root).elementAt(index - 1)[next] < this.rootNStates.elementAt(root).elementAt(index)[next] + 2) { - // break the law of non-increase order inside one color bucket - // try next bucket of another color - index = 0; - root++; + // break the law of non-increase order inside one color bucket + // try next bucket of another color + index = 0; + root++; } if(root == this.rootNodes.size()) { - // no more bucket - // backtrack - root = tmp.root; - index = tmp.index; - int t = this.combine.elementAt(next).size() - 2; - while(true) { - while(!(t < 0)) { - tmp = this.combine.elementAt(next).elementAt(t); - if ((tmp.root != root) || (tmp.index != index)) { - break; - } - t--; - } - if(t < 0) { - // try the bucket in node2combine before - if(next - 1 < 0) { - return false; - } else { - return innertrial(next - 1, ++layer); - } - } else if(tmp.root != root) { - if((tmp.root == this.lastchoices[next]) && - (this.rootNStates.elementAt(this.lastchoices[next]).elementAt(0)[next] == 1)) { - // only 1 obj left in the chosen bucket - // can not move this one - // try the bucket in node2combine before - if(next - 1 < 0) { - return false; - } else { - return innertrial(next - 1, ++layer); - } - } - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; - //tmp.root = root; - int newroot = tmp.root + 1; - tmp.root = newroot; - tmp.index = 0; - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; - // make all left things in this color bucket reset - for(t++; t < this.combine.elementAt(next).size(); t++) { - tmp = this.combine.elementAt(next).elementAt(t); - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; - tmp.root = newroot; - tmp.index = 0; - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; - } - if(layer != 0) { - return firstexpand(next+1, this.first4choice); - } - return true; - } else if(tmp.index != index) { - if(this.rootNStates.elementAt(root).elementAt(tmp.index)[next] == - this.rootNStates.elementAt(root).elementAt(index)[next]) { - // break the law of non-increase order inside one color bucket - // go on search forward - index = tmp.index; - } else if(this.rootNStates.elementAt(root).elementAt(tmp.index)[next] < - this.rootNStates.elementAt(root).elementAt(index)[next] + 2) { - // break the law of non-increase order inside one color bucket - // and now they only differ by 1 - // propagate this difference to see if it can fix - boolean suc = propagateOne(next, root, index, t, tmp); - if(suc) { - return suc; - } else { - // go on search forward - index = tmp.index; - } - } else { - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; - int tmproot = tmp.root; - int tmpindex = tmp.index; - tmp.root = root; - tmp.index = index; - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; - int desroot = tmp.root; - int desindex = tmp.index; - // make all left things in this color bucket reset - t++; - boolean first = true; - while(t < this.combine.elementAt(next).size()) { - int k = 0; - if(first) { - k = 1; - first = false; - } - for(; (k < this.rootNStates.elementAt(tmproot).elementAt(tmpindex)[next]) && (t < this.combine.elementAt(next).size()); t++) { - tmp = this.combine.elementAt(next).elementAt(t); - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; - tmp.root = desroot; - tmp.index = desindex; - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; - } - if(k == this.rootNStates.elementAt(tmproot).elementAt(tmpindex)[next]) { - desindex++; - } - } - if(layer != 0) { - return firstexpand(next+1, this.first4choice); - } - return true; - } - } - } + // no more bucket + // backtrack + root = tmp.root; + index = tmp.index; + int t = this.combine.elementAt(next).size() - 2; + while(true) { + while(!(t < 0)) { + tmp = this.combine.elementAt(next).elementAt(t); + if ((tmp.root != root) || (tmp.index != index)) { + break; + } + t--; + } + if(t < 0) { + // try the bucket in node2combine before + if(next - 1 < 0) { + return false; + } else { + return innertrial(next - 1, ++layer); + } + } else if(tmp.root != root) { + if((tmp.root == this.lastchoices[next]) && + (this.rootNStates.elementAt(this.lastchoices[next]).elementAt(0)[next] == 1)) { + // only 1 obj left in the chosen bucket + // can not move this one + // try the bucket in node2combine before + if(next - 1 < 0) { + return false; + } else { + return innertrial(next - 1, ++layer); + } + } + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; + //tmp.root = root; + int newroot = tmp.root + 1; + tmp.root = newroot; + tmp.index = 0; + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; + // make all left things in this color bucket reset + for(t++; t < this.combine.elementAt(next).size(); t++) { + tmp = this.combine.elementAt(next).elementAt(t); + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; + tmp.root = newroot; + tmp.index = 0; + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; + } + if(layer != 0) { + return firstexpand(next+1, this.first4choice); + } + return true; + } else if(tmp.index != index) { + if(this.rootNStates.elementAt(root).elementAt(tmp.index)[next] == + this.rootNStates.elementAt(root).elementAt(index)[next]) { + // break the law of non-increase order inside one color bucket + // go on search forward + index = tmp.index; + } else if(this.rootNStates.elementAt(root).elementAt(tmp.index)[next] < + this.rootNStates.elementAt(root).elementAt(index)[next] + 2) { + // break the law of non-increase order inside one color bucket + // and now they only differ by 1 + // propagate this difference to see if it can fix + boolean suc = propagateOne(next, root, index, t, tmp); + if(suc) { + return suc; + } else { + // go on search forward + index = tmp.index; + } + } else { + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; + int tmproot = tmp.root; + int tmpindex = tmp.index; + tmp.root = root; + tmp.index = index; + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; + int desroot = tmp.root; + int desindex = tmp.index; + // make all left things in this color bucket reset + t++; + boolean first = true; + while(t < this.combine.elementAt(next).size()) { + int k = 0; + if(first) { + k = 1; + first = false; + } + for(; (k < this.rootNStates.elementAt(tmproot).elementAt(tmpindex)[next]) && (t < this.combine.elementAt(next).size()); t++) { + tmp = this.combine.elementAt(next).elementAt(t); + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; + tmp.root = desroot; + tmp.index = desindex; + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; + } + if(k == this.rootNStates.elementAt(tmproot).elementAt(tmpindex)[next]) { + desindex++; + } + } + if(layer != 0) { + return firstexpand(next+1, this.first4choice); + } + return true; + } + } + } } else { - if((tmp.root != this.lastchoices[next]) || - (this.rootNStates.elementAt(this.lastchoices[next]).elementAt(0)[next] > 1)) { - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; - tmp.root = root; - tmp.index = index; - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; - if(layer != 0) { - return firstexpand(next+1, this.first4choice); - } - return true; - } else { - // only 1 obj with the color next exist on the chosen bucket this time, - // can not move it, try objs in forward color bucket - if(next - 1 < 0) { - return false; - } else { - return innertrial(next - 1, ++layer); - } - } + if((tmp.root != this.lastchoices[next]) || + (this.rootNStates.elementAt(this.lastchoices[next]).elementAt(0)[next] > 1)) { + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; + tmp.root = root; + tmp.index = index; + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; + if(layer != 0) { + return firstexpand(next+1, this.first4choice); + } + return true; + } else { + // only 1 obj with the color next exist on the chosen bucket this time, + // can not move it, try objs in forward color bucket + if(next - 1 < 0) { + return false; + } else { + return innertrial(next - 1, ++layer); + } + } } } @@ -560,76 +560,76 @@ public class CombinationUtil { Combine tmpt = null; if(this.rootNStates.elementAt(root).elementAt(index - 1)[next] < this.rootNStates.elementAt(root).elementAt(index)[next]) { - // need to continue propagate - while(t < this.combine.elementAt(next).size()) { - tmpt = this.combine.elementAt(next).elementAt(t); - if ((tmpt.root != root) || (tmpt.index != index)) { - break; - } - t++; - } - if(t == this.combine.elementAt(next).size()) { - // last element of this color bucket - if(index + 1 < this.rootNodes.elementAt(root).size()) { - // there is available place inside the same color bucket - Combine tmpbk = this.combine.elementAt(next).elementAt(t - 1); - boolean suc = propagateOne(next, root, index + 1, t - 1, tmpbk); - /*if(!suc) { - // fail, roll back - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; - tmp.root = rootbk; - tmp.index = indexbk; - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; - }*/ - return suc; - } else if(root+1 < this.rootNodes.size()) { // check if there are another bucket - // yes - this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]--; - tmpt.root = root + 1; - tmpt.index = 0; - this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]++; - return firstexpand(next+1, this.first4choice); - } else { - // no, roll back - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; - tmp.root = rootbk; - tmp.index = indexbk; - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; - return false; - } - } else if(tmpt.root != root) { - Combine tmpbk = this.combine.elementAt(next).elementAt(t - 1); - this.rootNStates.elementAt(tmpbk.root).elementAt(tmpbk.index)[next]--; - tmpbk.root = tmpt.root; - tmpbk.index = 0; - this.rootNStates.elementAt(tmpbk.root).elementAt(tmpbk.index)[next]++; - root = tmpt.root; - index = tmpt.index; - // make all left things in this color bucket reset - for(t += 1; t < this.combine.elementAt(next).size(); t++) { - tmpt = this.combine.elementAt(next).elementAt(t); - this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]--; - tmpt.root = root; - tmpt.index = 0; - this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]++; - } - return firstexpand(next+1, this.first4choice); - } else if(tmpt.index != index) { - Combine tmpbk = this.combine.elementAt(next).elementAt(t - 1); - boolean suc = propagateOne(next, root, tmpt.index, t - 1, tmpbk); - if(!suc) { - // fail, roll back - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; - tmp.root = rootbk; - tmp.index = indexbk; - this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; - } - return suc; - } - // won't reach here, only to avoid compiler's complain - return true; + // need to continue propagate + while(t < this.combine.elementAt(next).size()) { + tmpt = this.combine.elementAt(next).elementAt(t); + if ((tmpt.root != root) || (tmpt.index != index)) { + break; + } + t++; + } + if(t == this.combine.elementAt(next).size()) { + // last element of this color bucket + if(index + 1 < this.rootNodes.elementAt(root).size()) { + // there is available place inside the same color bucket + Combine tmpbk = this.combine.elementAt(next).elementAt(t - 1); + boolean suc = propagateOne(next, root, index + 1, t - 1, tmpbk); + /*if(!suc) { + // fail, roll back + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; + tmp.root = rootbk; + tmp.index = indexbk; + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; + }*/ + return suc; + } else if(root+1 < this.rootNodes.size()) { // check if there are another bucket + // yes + this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]--; + tmpt.root = root + 1; + tmpt.index = 0; + this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]++; + return firstexpand(next+1, this.first4choice); + } else { + // no, roll back + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; + tmp.root = rootbk; + tmp.index = indexbk; + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; + return false; + } + } else if(tmpt.root != root) { + Combine tmpbk = this.combine.elementAt(next).elementAt(t - 1); + this.rootNStates.elementAt(tmpbk.root).elementAt(tmpbk.index)[next]--; + tmpbk.root = tmpt.root; + tmpbk.index = 0; + this.rootNStates.elementAt(tmpbk.root).elementAt(tmpbk.index)[next]++; + root = tmpt.root; + index = tmpt.index; + // make all left things in this color bucket reset + for(t += 1; t < this.combine.elementAt(next).size(); t++) { + tmpt = this.combine.elementAt(next).elementAt(t); + this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]--; + tmpt.root = root; + tmpt.index = 0; + this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]++; + } + return firstexpand(next+1, this.first4choice); + } else if(tmpt.index != index) { + Combine tmpbk = this.combine.elementAt(next).elementAt(t - 1); + boolean suc = propagateOne(next, root, tmpt.index, t - 1, tmpbk); + if(!suc) { + // fail, roll back + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; + tmp.root = rootbk; + tmp.index = indexbk; + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; + } + return suc; + } + // won't reach here, only to avoid compiler's complain + return true; } else { - return true; + return true; } } } @@ -647,7 +647,7 @@ public class CombinationUtil { this.mapping = new Vector>(); for(int i = 0; i < this.rootNum; i++) { - this.mapping.add(null); + this.mapping.add(null); } this.rand = new Random(); } @@ -662,20 +662,20 @@ public class CombinationUtil { this.mapping = null; this.mapping = new Vector>(); for(int i = 0; i < this.rootNum; i++) { - this.mapping.add(null); + this.mapping.add(null); } // randomly choose a core for each node in sNodeVecs for(int i = 0; i < this.sNodeVecs.size(); i++) { - Vector sNodes = this.sNodeVecs.elementAt(i); - for(int j = 0; j < sNodes.size(); j++) { - ScheduleNode snode = sNodes.elementAt(j); - int core = Math.abs(rand.nextInt()) % this.rootNum; - if(this.mapping.elementAt(core) == null) { - this.mapping.setElementAt(new Vector(), core); - } - this.mapping.elementAt(core).add(snode); - } + Vector sNodes = this.sNodeVecs.elementAt(i); + for(int j = 0; j < sNodes.size(); j++) { + ScheduleNode snode = sNodes.elementAt(j); + int core = Math.abs(rand.nextInt()) % this.rootNum; + if(this.mapping.elementAt(core) == null) { + this.mapping.setElementAt(new Vector(), core); + } + this.mapping.elementAt(core).add(snode); + } } return true; } diff --git a/Robust/src/Analysis/Scheduling/CoreSimulator.java b/Robust/src/Analysis/Scheduling/CoreSimulator.java index d360fd9a..ce427382 100644 --- a/Robust/src/Analysis/Scheduling/CoreSimulator.java +++ b/Robust/src/Analysis/Scheduling/CoreSimulator.java @@ -143,49 +143,49 @@ public class CoreSimulator { if(this.rtask.currentRun.getExetype() == 0) { Vector> paraQueues = this.rtask.getParaQueues(); for(int i = 0; i < paraQueues.size(); i++) { - ObjectSimulator obj = paraQueues.elementAt(i).poll(); - obj.setHold(false); - boolean remove = false; - if((this.targetFState != null) - && (this.targetFState.containsKey(obj.getCurrentFS()))) { - if(transObjs == null) { - transObjs = new Vector(); - } - if(!transObjs.contains(obj)) { - transObjs.add(obj); - } - remove = true; - } - // check if this object becoming shared or not - Vector allycores = this.getAllyCores(obj.getCurrentFS()); - if(allycores != null) { - obj.setShared(true); - //for(int k = 0; k < allycores.size(); ++k) { - //Integer allyCore = allycores.elementAt(k); - if(transObjs == null) { - transObjs = new Vector(); - } - if(!transObjs.contains(obj)) { - transObjs.add(obj); - } - remove = false; - //} - allycores = null; - } - // check if need to transfer to other cores - Queue targetcores = this.getTargetCores(obj.getCurrentFS()); - if(targetcores != null) { - if(transObjs == null) { - transObjs = new Vector(); - } - if(!transObjs.contains(obj)) { - transObjs.add(obj); - } - remove = true; - } - for(int j = 0; j < this.tasks.size(); j++) { - this.tasks.elementAt(j).refreshPara(obj, remove); - } + ObjectSimulator obj = paraQueues.elementAt(i).poll(); + obj.setHold(false); + boolean remove = false; + if((this.targetFState != null) + && (this.targetFState.containsKey(obj.getCurrentFS()))) { + if(transObjs == null) { + transObjs = new Vector(); + } + if(!transObjs.contains(obj)) { + transObjs.add(obj); + } + remove = true; + } + // check if this object becoming shared or not + Vector allycores = this.getAllyCores(obj.getCurrentFS()); + if(allycores != null) { + obj.setShared(true); + //for(int k = 0; k < allycores.size(); ++k) { + //Integer allyCore = allycores.elementAt(k); + if(transObjs == null) { + transObjs = new Vector(); + } + if(!transObjs.contains(obj)) { + transObjs.add(obj); + } + remove = false; + //} + allycores = null; + } + // check if need to transfer to other cores + Queue targetcores = this.getTargetCores(obj.getCurrentFS()); + if(targetcores != null) { + if(transObjs == null) { + transObjs = new Vector(); + } + if(!transObjs.contains(obj)) { + transObjs.add(obj); + } + remove = true; + } + for(int j = 0; j < this.tasks.size(); j++) { + this.tasks.elementAt(j).refreshPara(obj, remove); + } } paraQueues = null; } diff --git a/Robust/src/Analysis/Scheduling/FIFORSchedule.java b/Robust/src/Analysis/Scheduling/FIFORSchedule.java index d8f4e672..e5eb1c59 100644 --- a/Robust/src/Analysis/Scheduling/FIFORSchedule.java +++ b/Robust/src/Analysis/Scheduling/FIFORSchedule.java @@ -28,18 +28,18 @@ public class FIFORSchedule extends RuntimeSchedule { int paraNum = next.getTd().numParameters(); Vector> pqueues = next.getParaQueues(); if((pqueues == null) || (pqueues.size() < paraNum)) { - continue; + continue; } int j = 0; for(; j < pqueues.size(); j++) { - Queue objs = pqueues.elementAt(j); - if((objs == null) || (objs.size() == 0)) { - break; - } + Queue objs = pqueues.elementAt(j); + if((objs == null) || (objs.size() == 0)) { + break; + } } if(j == pqueues.size()) { - pqueues = null; - return next; + pqueues = null; + return next; } pqueues = null; } diff --git a/Robust/src/Analysis/Scheduling/MCImplSynthesis.java b/Robust/src/Analysis/Scheduling/MCImplSynthesis.java index 6c3ff996..21c597af 100644 --- a/Robust/src/Analysis/Scheduling/MCImplSynthesis.java +++ b/Robust/src/Analysis/Scheduling/MCImplSynthesis.java @@ -102,9 +102,9 @@ public class MCImplSynthesis { PrintStream stdout = null; try { if(!state.BAMBOOCOMPILETIME) { - stdout = new PrintStream( - new FileOutputStream(this.state.outputdir + "SimulatorResult_" - + this.coreNum + ".out")); + stdout = new PrintStream( + new FileOutputStream(this.state.outputdir + "SimulatorResult_" + + this.coreNum + ".out")); } } catch (Exception e) { // Sigh. Couldn't open the file. @@ -135,7 +135,7 @@ public class MCImplSynthesis { while(it_tasks.hasNext()) { TaskDescriptor td = (TaskDescriptor)it_tasks.next(); if(td.numParameters() > 1) { - multiparamtds.addElement(td); + multiparamtds.addElement(td); } } it_tasks = null; @@ -169,35 +169,35 @@ public class MCImplSynthesis { // simulate the generated schedulings and try to optimize it do { if(!state.BAMBOOCOMPILETIME) { - System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); - System.out.print("Simulate and optimize round: #" + tryindex + ": \n"); + System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); + System.out.print("Simulate and optimize round: #" + tryindex + ": \n"); } gid += newscheduleGraphs.size(); if(scheduleGraphs != null) { - for(int i = 0; i < scheduleGraphs.size(); i++) { - Vector tmpgraph = scheduleGraphs.elementAt(i); - for(int j = 0; j < tmpgraph.size(); j++) { - ScheduleNode snode = tmpgraph.elementAt(j); - snode.getEdgeVector().clear(); - snode.getInedgeVector().clear(); - snode.getScheduleEdges().clear(); - snode.getClassNodes().clear(); - } - tmpgraph.clear(); - tmpgraph = null; - } - scheduleGraphs.clear(); + for(int i = 0; i < scheduleGraphs.size(); i++) { + Vector tmpgraph = scheduleGraphs.elementAt(i); + for(int j = 0; j < tmpgraph.size(); j++) { + ScheduleNode snode = tmpgraph.elementAt(j); + snode.getEdgeVector().clear(); + snode.getInedgeVector().clear(); + snode.getScheduleEdges().clear(); + snode.getClassNodes().clear(); + } + tmpgraph.clear(); + tmpgraph = null; + } + scheduleGraphs.clear(); } scheduleGraphs = newscheduleGraphs; schedulings.clear(); // get scheduling layouts from schedule graphs for(int i = 0; i < scheduleGraphs.size(); i++) { - Vector scheduleGraph = scheduleGraphs.elementAt(i); - Vector tmpscheduling = - generateScheduling(scheduleGraph, td2maincd); - schedulings.add(tmpscheduling); - scheduleGraph = null; - tmpscheduling = null; + Vector scheduleGraph = scheduleGraphs.elementAt(i); + Vector tmpscheduling = + generateScheduling(scheduleGraph, td2maincd); + schedulings.add(tmpscheduling); + scheduleGraph = null; + tmpscheduling = null; } selectedSchedulings.clear(); selectedSimExeGraphs.clear(); @@ -206,102 +206,102 @@ public class MCImplSynthesis { selectedSimExeGraphs); boolean remove = false; if(tmpexetime < bestexetime) { - remove = true; - bestexetime = tmpexetime; - if(scheduling != null) { - scheduling.clear(); - for(int j = 0; j < schedulinggraph.size(); j++) { - ScheduleNode snode = schedulinggraph.elementAt(j); - snode.getEdgeVector().clear(); - snode.getInedgeVector().clear(); - snode.getScheduleEdges().clear(); - snode.getClassNodes().clear(); - } - schedulinggraph.clear(); - selectedSimExeGraph_bk = null; - } - scheduling = schedulings.elementAt(selectedSchedulings.elementAt(0)); - schedulinggraph = scheduleGraphs.elementAt( - selectedSchedulings.elementAt(0)); - selectedSimExeGraph_bk = selectedSimExeGraphs.elementAt(0); - - if(!state.BAMBOOCOMPILETIME) { - System.out.print("end of: #" + tryindex + " (bestexetime: " - + bestexetime + ")\n"); - System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); - } - tryindex++; - threshold = this.scheduleThreshold; + remove = true; + bestexetime = tmpexetime; + if(scheduling != null) { + scheduling.clear(); + for(int j = 0; j < schedulinggraph.size(); j++) { + ScheduleNode snode = schedulinggraph.elementAt(j); + snode.getEdgeVector().clear(); + snode.getInedgeVector().clear(); + snode.getScheduleEdges().clear(); + snode.getClassNodes().clear(); + } + schedulinggraph.clear(); + selectedSimExeGraph_bk = null; + } + scheduling = schedulings.elementAt(selectedSchedulings.elementAt(0)); + schedulinggraph = scheduleGraphs.elementAt( + selectedSchedulings.elementAt(0)); + selectedSimExeGraph_bk = selectedSimExeGraphs.elementAt(0); + + if(!state.BAMBOOCOMPILETIME) { + System.out.print("end of: #" + tryindex + " (bestexetime: " + + bestexetime + ")\n"); + System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); + } + tryindex++; + threshold = this.scheduleThreshold; } else if(tmpexetime == bestexetime) { - if(!state.BAMBOOCOMPILETIME) { - System.out.print("end of: #" + tryindex + " (bestexetime: " - + bestexetime + ")\n"); - System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); - } - tryindex++; - threshold += 10; - if((threshold > 40) || - ((Math.abs(rand.nextInt()) % 100) < this.probThreshold + 10)) { - break; - } + if(!state.BAMBOOCOMPILETIME) { + System.out.print("end of: #" + tryindex + " (bestexetime: " + + bestexetime + ")\n"); + System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); + } + tryindex++; + threshold += 10; + if((threshold > 40) || + ((Math.abs(rand.nextInt()) % 100) < this.probThreshold + 10)) { + break; + } } else { - if(!state.BAMBOOCOMPILETIME) { - System.out.print("end of: #" + tryindex + " (bestexetime: " - + bestexetime + ")\n"); - System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); - } - tryindex++; - if(threshold == this.scheduleThreshold) { - if(scheduleGraphs != null) { - scheduleGraphs.clear(); - } - scheduleGraphs.addElement(schedulinggraph); - if(selectedSchedulings != null) { - selectedSchedulings.clear(); - } - selectedSchedulings.addElement(Integer.valueOf(0)); - if(selectedSimExeGraphs != null) { - selectedSimExeGraphs.clear(); - } - selectedSimExeGraphs.addElement(selectedSimExeGraph_bk); - } - threshold += 10; - if( (threshold > 40) || - ((Math.abs(rand.nextInt()) % 100) < this.probThreshold + 1)) { - break; - } - break; + if(!state.BAMBOOCOMPILETIME) { + System.out.print("end of: #" + tryindex + " (bestexetime: " + + bestexetime + ")\n"); + System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); + } + tryindex++; + if(threshold == this.scheduleThreshold) { + if(scheduleGraphs != null) { + scheduleGraphs.clear(); + } + scheduleGraphs.addElement(schedulinggraph); + if(selectedSchedulings != null) { + selectedSchedulings.clear(); + } + selectedSchedulings.addElement(Integer.valueOf(0)); + if(selectedSimExeGraphs != null) { + selectedSimExeGraphs.clear(); + } + selectedSimExeGraphs.addElement(selectedSimExeGraph_bk); + } + threshold += 10; + if( (threshold > 40) || + ((Math.abs(rand.nextInt()) % 100) < this.probThreshold + 1)) { + break; + } + break; } if(tooptimize) { - // try to optimize the best one scheduling - //do { - newscheduleGraphs = optimizeScheduling(scheduleGraphs, - selectedSchedulings, - selectedSimExeGraphs, - gid, - threshold); - /*if(newscheduleGraphs != null) { - if(this.generateThreshold < 30) { - this.generateThreshold = 30; - } - break; - } else { - threshold += 10; - if(this.generateThreshold > 0) { - this.generateThreshold -= 3; - } - if((Math.abs(rand.nextInt()) % 10000) < this.probThreshold + 1) { - break; - } - } - }while(true);*/ - if(remove) { - scheduleGraphs.removeElementAt(selectedSchedulings.elementAt(0)); - selectedSimExeGraphs.removeElementAt(0); - } + // try to optimize the best one scheduling + //do { + newscheduleGraphs = optimizeScheduling(scheduleGraphs, + selectedSchedulings, + selectedSimExeGraphs, + gid, + threshold); + /*if(newscheduleGraphs != null) { + if(this.generateThreshold < 30) { + this.generateThreshold = 30; + } + break; + } else { + threshold += 10; + if(this.generateThreshold > 0) { + this.generateThreshold -= 3; + } + if((Math.abs(rand.nextInt()) % 10000) < this.probThreshold + 1) { + break; + } + } + }while(true);*/ + if(remove) { + scheduleGraphs.removeElementAt(selectedSchedulings.elementAt(0)); + selectedSimExeGraphs.removeElementAt(0); + } } else { - break; + break; } } while(newscheduleGraphs != null); // TODO: could it possibly lead to endless loop? @@ -334,9 +334,9 @@ public class MCImplSynthesis { // Close the streams. try { if(!state.BAMBOOCOMPILETIME) { - stdout.close(); - stdout = null; - System.setOut(origOut); + stdout.close(); + stdout = null; + System.setOut(origOut); } } catch (Exception e) { origOut.println("Redirect: Unable to close files!"); @@ -392,10 +392,10 @@ public class MCImplSynthesis { Iterator it_tasks = this.state.getTaskSymbolTable().getDescriptorsIterator(); while(it_tasks.hasNext()) { - TaskDescriptor td = (TaskDescriptor)it_tasks.next(); - if(td.numParameters() > 1) { - multiparamtds.addElement(td); - } + TaskDescriptor td = (TaskDescriptor)it_tasks.next(); + if(td.numParameters() > 1) { + multiparamtds.addElement(td); + } } it_tasks = null; @@ -421,35 +421,35 @@ public class MCImplSynthesis { +".out"); FileOutputStream dotstream = null; try { - dotstream = new FileOutputStream(file,false); + dotstream = new FileOutputStream(file,false); } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); + e.printStackTrace(); + System.exit(-1); } PrintWriter output = new java.io.PrintWriter(dotstream, true); output.println("start time(1,000,000 cycles): " + totestscheduleGraphs.size()); for(int ii = 0; ii < totestscheduleGraphs.size(); ii++) { - Vector> newscheduleGraphs = - new Vector>(); - newscheduleGraphs.add(totestscheduleGraphs.elementAt(ii)); - // simulate the generated schedulings and try to optimize it - schedulings.clear(); - // get scheduling layouts from schedule graphs - for(int i = 0; i < newscheduleGraphs.size(); i++) { - Vector scheduleGraph = newscheduleGraphs.elementAt(i); - Vector tmpscheduling = - generateScheduling(scheduleGraph, td2maincd); - schedulings.add(tmpscheduling); - scheduleGraph = null; - tmpscheduling = null; - } - selectedSchedulings.clear(); - selectedSimExeGraphs.clear(); - long tmpexetime = this.scheduleSimulator.simulate(schedulings, - selectedSchedulings, - selectedSimExeGraphs); - output.println(((float)tmpexetime/100000000)); + Vector> newscheduleGraphs = + new Vector>(); + newscheduleGraphs.add(totestscheduleGraphs.elementAt(ii)); + // simulate the generated schedulings and try to optimize it + schedulings.clear(); + // get scheduling layouts from schedule graphs + for(int i = 0; i < newscheduleGraphs.size(); i++) { + Vector scheduleGraph = newscheduleGraphs.elementAt(i); + Vector tmpscheduling = + generateScheduling(scheduleGraph, td2maincd); + schedulings.add(tmpscheduling); + scheduleGraph = null; + tmpscheduling = null; + } + selectedSchedulings.clear(); + selectedSimExeGraphs.clear(); + long tmpexetime = this.scheduleSimulator.simulate(schedulings, + selectedSchedulings, + selectedSimExeGraphs); + output.println(((float)tmpexetime/100000000)); } } else { @@ -458,10 +458,10 @@ public class MCImplSynthesis { Iterator it_tasks = this.state.getTaskSymbolTable().getDescriptorsIterator(); while(it_tasks.hasNext()) { - TaskDescriptor td = (TaskDescriptor)it_tasks.next(); - if(td.numParameters() > 1) { - multiparamtds.addElement(td); - } + TaskDescriptor td = (TaskDescriptor)it_tasks.next(); + if(td.numParameters() > 1) { + multiparamtds.addElement(td); + } } it_tasks = null; @@ -494,11 +494,11 @@ public class MCImplSynthesis { + this.coreNum + ".out"); FileOutputStream dotstream2 = null; try { - dotstream = new FileOutputStream(file,false); - dotstream2 = new FileOutputStream(file2,false); + dotstream = new FileOutputStream(file,false); + dotstream2 = new FileOutputStream(file2,false); } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); + e.printStackTrace(); + System.exit(-1); } PrintWriter output = new java.io.PrintWriter(dotstream, true); PrintWriter output2 = new java.io.PrintWriter(dotstream2, true); @@ -507,159 +507,159 @@ public class MCImplSynthesis { output2.println("optimized time(100,000,000 cycles): " + totestscheduleGraphs.size()); for(int ii = startnum; ii < totestscheduleGraphs.size(); ii++) { - Vector> newscheduleGraphs = - new Vector>(); - newscheduleGraphs.add(totestscheduleGraphs.elementAt(ii)); - int tryindex = 1; - long bestexetime = Long.MAX_VALUE; - int gid = 1; - Vector scheduling = null; - Vector schedulinggraph = null; - boolean isfirst = true; - Random rand = new Random(); - int threshold = this.scheduleThreshold; - // simulate the generated schedulings and try to optimize it - System.out.print("=========================================================\n"); - System.out.print("# " + ii + ": \n"); - do { - System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); - System.out.print("Simulate and optimize round: #" + tryindex + ": \n"); - gid += newscheduleGraphs.size(); - if(scheduleGraphs != null) { - for(int i = 0; i < scheduleGraphs.size(); i++) { - Vector tmpgraph = scheduleGraphs.elementAt(i); - for(int j = 0; j < tmpgraph.size(); j++) { - ScheduleNode snode = tmpgraph.elementAt(j); - snode.getEdgeVector().clear(); - snode.getInedgeVector().clear(); - snode.getScheduleEdges().clear(); - snode.getClassNodes().clear(); - } - tmpgraph.clear(); - tmpgraph = null; - } - scheduleGraphs.clear(); - } - scheduleGraphs = newscheduleGraphs; - schedulings.clear(); - // get scheduling layouts from schedule graphs - for(int i = 0; i < scheduleGraphs.size(); i++) { - Vector scheduleGraph = scheduleGraphs.elementAt(i); - Vector tmpscheduling = - generateScheduling(scheduleGraph, td2maincd); - schedulings.add(tmpscheduling); - scheduleGraph = null; - tmpscheduling = null; - } - selectedSchedulings.clear(); - selectedSimExeGraphs.clear(); - long tmpexetime = this.scheduleSimulator.simulate(schedulings, - selectedSchedulings, - selectedSimExeGraphs); - if(isfirst) { - output.println(((float)tmpexetime/100000000)); - isfirst = false; - } - if(tmpexetime < bestexetime) { - bestexetime = tmpexetime; - if(scheduling != null) { - scheduling.clear(); - for(int j = 0; j < schedulinggraph.size(); j++) { - ScheduleNode snode = schedulinggraph.elementAt(j); - snode.getEdgeVector().clear(); - snode.getInedgeVector().clear(); - snode.getScheduleEdges().clear(); - snode.getClassNodes().clear(); - } - schedulinggraph.clear(); - selectedSimExeGraph_bk = null; - } - scheduling = schedulings.elementAt(selectedSchedulings.elementAt(0)); - schedulinggraph = scheduleGraphs.elementAt( - selectedSchedulings.elementAt(0)); - selectedSimExeGraph_bk = selectedSimExeGraphs.elementAt(0); - tryindex++; - threshold = this.scheduleThreshold; - System.out.print("end of: #" + tryindex + " (bestexetime: " - + bestexetime + ")\n"); - System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); - } else if(tmpexetime == bestexetime) { - System.out.print("end of: #" + tryindex + " (bestexetime: " - + bestexetime + ")\n"); - System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); - tryindex++; - threshold = this.scheduleThreshold; - if((Math.abs(rand.nextInt()) % 100) < this.probThreshold) { - break; - } - } else { - System.out.print("end of: #" + tryindex + " (bestexetime: " - + bestexetime + ")\n"); - System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); - tryindex++; - if(threshold == this.scheduleThreshold) { - if(scheduleGraphs != null) { - scheduleGraphs.clear(); - } - scheduleGraphs.addElement(schedulinggraph); - if(selectedSchedulings != null) { - selectedSchedulings.clear(); - } - selectedSchedulings.addElement(Integer.valueOf(0)); - if(selectedSimExeGraphs != null) { - selectedSimExeGraphs.clear(); - } - selectedSimExeGraphs.addElement(selectedSimExeGraph_bk); - } - threshold += 10; - if((Math.abs(rand.nextInt()) % 100) < this.probThreshold + 1) { - break; - } - //break; - } - - if(tooptimize) { - // try to optimize theschedulings best one scheduling - newscheduleGraphs = optimizeScheduling(scheduleGraphs, - selectedSchedulings, - selectedSimExeGraphs, - gid, - this.scheduleThreshold); - if(tmpexetime < bestexetime) { - scheduleGraphs.remove(selectedSchedulings.elementAt(0)); - } - } else { - break; - } - } while(newscheduleGraphs != null); // TODO: could it possibly lead to endless loop? - - scheduleGraphs.clear(); - scheduleGraphs = null; - scheduling = null; - schedulinggraph = null; - if(newscheduleGraphs != null) { - newscheduleGraphs.clear(); - } - newscheduleGraphs = null; - totestscheduleGraphs.elementAt(ii).clear(); - for(int i = 0; i < schedulings.size(); i++) { - schedulings.elementAt(i).clear(); - } - schedulings.clear(); - selectedSchedulings.clear(); - selectedSimExeGraphs.clear(); - - output2.println(((float)bestexetime/100000000)); - System.out.print("=========================================================\n"); + Vector> newscheduleGraphs = + new Vector>(); + newscheduleGraphs.add(totestscheduleGraphs.elementAt(ii)); + int tryindex = 1; + long bestexetime = Long.MAX_VALUE; + int gid = 1; + Vector scheduling = null; + Vector schedulinggraph = null; + boolean isfirst = true; + Random rand = new Random(); + int threshold = this.scheduleThreshold; + // simulate the generated schedulings and try to optimize it + System.out.print("=========================================================\n"); + System.out.print("# " + ii + ": \n"); + do { + System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); + System.out.print("Simulate and optimize round: #" + tryindex + ": \n"); + gid += newscheduleGraphs.size(); + if(scheduleGraphs != null) { + for(int i = 0; i < scheduleGraphs.size(); i++) { + Vector tmpgraph = scheduleGraphs.elementAt(i); + for(int j = 0; j < tmpgraph.size(); j++) { + ScheduleNode snode = tmpgraph.elementAt(j); + snode.getEdgeVector().clear(); + snode.getInedgeVector().clear(); + snode.getScheduleEdges().clear(); + snode.getClassNodes().clear(); + } + tmpgraph.clear(); + tmpgraph = null; + } + scheduleGraphs.clear(); + } + scheduleGraphs = newscheduleGraphs; + schedulings.clear(); + // get scheduling layouts from schedule graphs + for(int i = 0; i < scheduleGraphs.size(); i++) { + Vector scheduleGraph = scheduleGraphs.elementAt(i); + Vector tmpscheduling = + generateScheduling(scheduleGraph, td2maincd); + schedulings.add(tmpscheduling); + scheduleGraph = null; + tmpscheduling = null; + } + selectedSchedulings.clear(); + selectedSimExeGraphs.clear(); + long tmpexetime = this.scheduleSimulator.simulate(schedulings, + selectedSchedulings, + selectedSimExeGraphs); + if(isfirst) { + output.println(((float)tmpexetime/100000000)); + isfirst = false; + } + if(tmpexetime < bestexetime) { + bestexetime = tmpexetime; + if(scheduling != null) { + scheduling.clear(); + for(int j = 0; j < schedulinggraph.size(); j++) { + ScheduleNode snode = schedulinggraph.elementAt(j); + snode.getEdgeVector().clear(); + snode.getInedgeVector().clear(); + snode.getScheduleEdges().clear(); + snode.getClassNodes().clear(); + } + schedulinggraph.clear(); + selectedSimExeGraph_bk = null; + } + scheduling = schedulings.elementAt(selectedSchedulings.elementAt(0)); + schedulinggraph = scheduleGraphs.elementAt( + selectedSchedulings.elementAt(0)); + selectedSimExeGraph_bk = selectedSimExeGraphs.elementAt(0); + tryindex++; + threshold = this.scheduleThreshold; + System.out.print("end of: #" + tryindex + " (bestexetime: " + + bestexetime + ")\n"); + System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); + } else if(tmpexetime == bestexetime) { + System.out.print("end of: #" + tryindex + " (bestexetime: " + + bestexetime + ")\n"); + System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); + tryindex++; + threshold = this.scheduleThreshold; + if((Math.abs(rand.nextInt()) % 100) < this.probThreshold) { + break; + } + } else { + System.out.print("end of: #" + tryindex + " (bestexetime: " + + bestexetime + ")\n"); + System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n"); + tryindex++; + if(threshold == this.scheduleThreshold) { + if(scheduleGraphs != null) { + scheduleGraphs.clear(); + } + scheduleGraphs.addElement(schedulinggraph); + if(selectedSchedulings != null) { + selectedSchedulings.clear(); + } + selectedSchedulings.addElement(Integer.valueOf(0)); + if(selectedSimExeGraphs != null) { + selectedSimExeGraphs.clear(); + } + selectedSimExeGraphs.addElement(selectedSimExeGraph_bk); + } + threshold += 10; + if((Math.abs(rand.nextInt()) % 100) < this.probThreshold + 1) { + break; + } + //break; + } + + if(tooptimize) { + // try to optimize theschedulings best one scheduling + newscheduleGraphs = optimizeScheduling(scheduleGraphs, + selectedSchedulings, + selectedSimExeGraphs, + gid, + this.scheduleThreshold); + if(tmpexetime < bestexetime) { + scheduleGraphs.remove(selectedSchedulings.elementAt(0)); + } + } else { + break; + } + } while(newscheduleGraphs != null); // TODO: could it possibly lead to endless loop? + + scheduleGraphs.clear(); + scheduleGraphs = null; + scheduling = null; + schedulinggraph = null; + if(newscheduleGraphs != null) { + newscheduleGraphs.clear(); + } + newscheduleGraphs = null; + totestscheduleGraphs.elementAt(ii).clear(); + for(int i = 0; i < schedulings.size(); i++) { + schedulings.elementAt(i).clear(); + } + schedulings.clear(); + selectedSchedulings.clear(); + selectedSimExeGraphs.clear(); + + output2.println(((float)bestexetime/100000000)); + System.out.print("=========================================================\n"); } if(scheduleGraphs != null) { - scheduleGraphs.clear(); + scheduleGraphs.clear(); } scheduleGraphs = null; totestscheduleGraphs = null; for(int i = 0; i < schedulings.size(); i++) { - schedulings.elementAt(i).clear(); + schedulings.elementAt(i).clear(); } schedulings.clear(); schedulings = null; @@ -674,13 +674,13 @@ public class MCImplSynthesis { // Close the streams. try { - output.close(); - stdout.close(); - output = null; - stdout = null; - System.setOut(origOut); + output.close(); + stdout.close(); + output = null; + stdout = null; + System.setOut(origOut); } catch (Exception e) { - origOut.println("Redirect: Unable to close files!"); + origOut.println("Redirect: Unable to close files!"); } } @@ -709,7 +709,7 @@ public class MCImplSynthesis { Vector criticalPath = analyzeCriticalPath(startnode); // for Test if(this.state.PRINTCRITICALPATH) { - System.err.println("gid: " + lgid + " endpoint: " + startnode.getTimepoint()); + System.err.println("gid: " + lgid + " endpoint: " + startnode.getTimepoint()); } Vector> tmposchedulegraphs = optimizeCriticalPath(schedulegraph, @@ -717,18 +717,18 @@ public class MCImplSynthesis { lgid, left); if(tmposchedulegraphs != null) { - if(optimizeschedulegraphs == null) { - optimizeschedulegraphs = new Vector>(); - } - optimizeschedulegraphs.addAll(tmposchedulegraphs); - lgid += tmposchedulegraphs.size(); - left -= tmposchedulegraphs.size(); - if(left == 0) { - schedulegraph = null; - criticalPath = null; - tmposchedulegraphs = null; - break; - } + if(optimizeschedulegraphs == null) { + optimizeschedulegraphs = new Vector>(); + } + optimizeschedulegraphs.addAll(tmposchedulegraphs); + lgid += tmposchedulegraphs.size(); + left -= tmposchedulegraphs.size(); + if(left == 0) { + schedulegraph = null; + criticalPath = null; + tmposchedulegraphs = null; + break; + } } schedulegraph = null; criticalPath = null; @@ -761,16 +761,16 @@ public class MCImplSynthesis { Iterator it_iedges = (Iterator)snode.inedges(); while(it_iedges.hasNext()) { - SimExecutionEdge sedge = it_iedges.next(); - //if(sedge.getWeight() != 0) { - SimExecutionNode tsnode = (SimExecutionNode)(sedge.getSource()); - if(tsnode.getTimepoint() + sedge.getWeight() == snode.getTimepoint()) { - nsnode = tsnode; - criticalPath.insertElementAt(sedge, 0); - sum += sedge.getWeight(); - break; - } - //} + SimExecutionEdge sedge = it_iedges.next(); + //if(sedge.getWeight() != 0) { + SimExecutionNode tsnode = (SimExecutionNode)(sedge.getSource()); + if(tsnode.getTimepoint() + sedge.getWeight() == snode.getTimepoint()) { + nsnode = tsnode; + criticalPath.insertElementAt(sedge, 0); + sum += sedge.getWeight(); + break; + } + //} } it_iedges = null; snode = nsnode; @@ -784,33 +784,33 @@ public class MCImplSynthesis { SimExecutionEdge seedge = criticalPath.elementAt(i); Vector predicates = seedge.getPredicates(); if(predicates != null) { - // have predicates - long starttime = 0; - // check the latest finish time of all the predicates - for(int j = 0; j < predicates.size(); j++) { - SimExecutionEdge predicate = predicates.elementAt(j); - long tmptime = predicate.getBestStartPoint() + predicate.getWeight(); - if(tmptime > starttime) { - starttime = tmptime; - seedge.setLastpredicateEdge(predicate); - if(predicate.getTd() != null) { - seedge.setLastpredicateNode( - (SimExecutionNode)predicate.getTarget()); - } else { - // transfer edge - seedge.setLastpredicateNode( - (SimExecutionNode)predicate.getSource()); - } - } - } - seedge.setBestStartPoint(starttime); + // have predicates + long starttime = 0; + // check the latest finish time of all the predicates + for(int j = 0; j < predicates.size(); j++) { + SimExecutionEdge predicate = predicates.elementAt(j); + long tmptime = predicate.getBestStartPoint() + predicate.getWeight(); + if(tmptime > starttime) { + starttime = tmptime; + seedge.setLastpredicateEdge(predicate); + if(predicate.getTd() != null) { + seedge.setLastpredicateNode( + (SimExecutionNode)predicate.getTarget()); + } else { + // transfer edge + seedge.setLastpredicateNode( + (SimExecutionNode)predicate.getSource()); + } + } + } + seedge.setBestStartPoint(starttime); } else if(seedge.getSource().getInedgeVector().size() > 0) { - // should have only one in edge - long starttime = ((SimExecutionNode)seedge.getSource()).getTimepoint(); - seedge.setBestStartPoint(starttime); + // should have only one in edge + long starttime = ((SimExecutionNode)seedge.getSource()).getTimepoint(); + seedge.setBestStartPoint(starttime); } else { - // no predicates - seedge.setBestStartPoint(0); + // no predicates + seedge.setBestStartPoint(0); } predicates = null; } @@ -844,26 +844,26 @@ public class MCImplSynthesis { long starttime = seedge.getBestStartPoint(); if((starttime < ((SimExecutionNode)seedge.getSource()).getTimepoint()) && (seedge.getTd() != null)) { - // Note: must be a task related edge, can not be an object transfer edge - // no restrictions due to data dependencies - // have potential to be parallelled and start execution earlier - seedge.setFixedTime(false); - // consider to optimize it only when its predicates can NOT - // be optimized, otherwise first considering optimize its predicates - //SimExecutionEdge lastpredicateedge = seedge.getLastpredicateEdge(); - // TODO - //if(lastpredicateedge.isFixedTime()) { - int corenum = seedge.getCoreNum(); - if(!toselects.containsKey(starttime)) { - toselects.put(starttime, - new Hashtable>()); - } - if(!toselects.get(starttime).containsKey(corenum)) { - toselects.get(starttime).put(corenum, - new Vector()); - } - toselects.get(starttime).get(corenum).add(seedge); - //} + // Note: must be a task related edge, can not be an object transfer edge + // no restrictions due to data dependencies + // have potential to be parallelled and start execution earlier + seedge.setFixedTime(false); + // consider to optimize it only when its predicates can NOT + // be optimized, otherwise first considering optimize its predicates + //SimExecutionEdge lastpredicateedge = seedge.getLastpredicateEdge(); + // TODO + //if(lastpredicateedge.isFixedTime()) { + int corenum = seedge.getCoreNum(); + if(!toselects.containsKey(starttime)) { + toselects.put(starttime, + new Hashtable>()); + } + if(!toselects.get(starttime).containsKey(corenum)) { + toselects.get(starttime).put(corenum, + new Vector()); + } + toselects.get(starttime).get(corenum).add(seedge); + //} } } @@ -873,7 +873,7 @@ public class MCImplSynthesis { do { int length = keys.size(); if(length == 0) { - return optimizeschedulegraphs; + return optimizeschedulegraphs; } int tochoose = Math.abs(rand.nextInt()) % length; opcheckpoint = (keys.elementAt(tochoose)).longValue(); @@ -886,163 +886,163 @@ public class MCImplSynthesis { SimExecutionEdge lastpredicateedge = seedge.getLastpredicateEdge(); long timepoint = lastpredicatenode.getTimepoint(); if(lastpredicateedge.getTd() == null) { - // transfer edge - timepoint += lastpredicateedge.getWeight(); + // transfer edge + timepoint += lastpredicateedge.getWeight(); } // mapping to critical path for(int index = 0; index < criticalPath.size(); index++) { - SimExecutionEdge tmpseedge = criticalPath.elementAt(index); - SimExecutionNode tmpsenode = - (SimExecutionNode)tmpseedge.getTarget(); - if(tmpsenode.getTimepoint() > timepoint) { - // get the spare core info - sparecores = tmpsenode.getSpareCores(); - break; - } + SimExecutionEdge tmpseedge = criticalPath.elementAt(index); + SimExecutionNode tmpsenode = + (SimExecutionNode)tmpseedge.getTarget(); + if(tmpsenode.getTimepoint() > timepoint) { + // get the spare core info + sparecores = tmpsenode.getSpareCores(); + break; + } } if(tooptimize.size() > 0) { - Iterator it_cores = tooptimize.keySet().iterator(); - // check if it is possible to optimize these tasks - if((sparecores == null) || (sparecores.size() == 0)) { - // lack of spare cores - while(it_cores.hasNext()) { - int corenum = it_cores.next(); - Vector tmptasks = tooptimize.get(corenum); - // group the task instantiations according to whether it - // has backward data dependences or not - Vector candidatetasks = new Vector(); - for(int ii= 0; ii < tmptasks.size(); ii++) { - SimExecutionEdge tmpseedge = tmptasks.elementAt(ii); - SimExecutionNode target = (SimExecutionNode)tmpseedge.getTarget(); - Vector children = - (Vector)target.getEdgeVector(); - int jj = 0; - for(; jj < children.size(); jj++) { - SimExecutionEdge tmpedge = children.elementAt(jj); - if(tmpedge.getTd() != null) { - Vector predicates = - tmpedge.getPredicates(); - if((predicates != null) && - (predicates.contains(tmpseedge))) { - break; - } - predicates = null; - } else if(tmpedge.getWeight() != 0) { - // transfer edge - if(((SimExecutionNode)tmpedge.getTarget()).getTimepoint() - == tmpedge.getWeight() + target.getTimepoint()) { - break; - } - } - } - if(jj == children.size()) { - candidatetasks.add(tmpseedge); - } - } - if((candidatetasks.size() > 0) && - (candidatetasks.size() < tmptasks.size())) { - // there are less important tasks which have no backward - // data dependences at this timepoint, try to change - // original execution order - Hashtable> tooptimize2 = - new Hashtable>(); - tooptimize2.put(corenum, candidatetasks); - Vector> ops = - innerOptimizeCriticalPath(scheduleGraph, - tooptimize2, - null, - lgid, - left); - if(ops != null) { - if(optimizeschedulegraphs == null) { - optimizeschedulegraphs = new Vector>(); - } - optimizeschedulegraphs.addAll(ops); - lgid += ops.size(); - left -= ops.size(); - } - tooptimize2 = null; - ops = null; - } - tmptasks = null; - candidatetasks = null; - } - - if(left == 0) { - it_cores = null; - return optimizeschedulegraphs; - } - - // flush the dependences and earliest start time - if(!state.BAMBOOCOMPILETIME) { - it_cores = tooptimize.keySet().iterator(); - while(it_cores.hasNext()) { - int corenum = it_cores.next(); - Vector edgevec = - tooptimize.get(corenum); - for(int j = 0; j < edgevec.size(); j++) { - SimExecutionEdge edge = edgevec.elementAt(j); - lastpredicateedge = edge.getLastpredicateEdge(); - lastpredicatenode = edge.getLastpredicateNode(); - // if(edge.getCoreNum() != lastpredicate.getCoreNum()) // should never hit this - timepoint = lastpredicatenode.getTimepoint(); - if(lastpredicateedge.getTd() == null) { - // transfer edge - timepoint += lastpredicateedge.getWeight(); - } - // mapping to critical path - for(int index = 0; index < criticalPath.size(); index++) { - SimExecutionEdge tmpseedge = criticalPath.elementAt(index); - SimExecutionNode tmpsenode = - (SimExecutionNode)tmpseedge.getTarget(); - if(tmpsenode.getTimepoint() > timepoint) { - // update the predicate info - if(edge.getPredicates() != null) { - edge.getPredicates().remove(lastpredicateedge); - } - edge.addPredicate(criticalPath.elementAt(index)); - break; - } - } - } - edgevec = null; - } - it_cores = null; - computeBestStartPoint(criticalPath); - Vector> ops = optimizeCriticalPath(scheduleGraph, - criticalPath, - lgid, - left); - if(ops != null) { - if(optimizeschedulegraphs == null) { - optimizeschedulegraphs = new Vector>(); - } - optimizeschedulegraphs.addAll(ops); - lgid += ops.size(); - left -= ops.size(); - } - ops = null; - } - } else { - // there are spare cores, try to reorganize the tasks to the spare - // cores - Vector> ops = - innerOptimizeCriticalPath(scheduleGraph, - tooptimize, - sparecores, - lgid, - left); - if(ops != null) { - if(optimizeschedulegraphs == null) { - optimizeschedulegraphs = new Vector>(); - } - optimizeschedulegraphs.addAll(ops); - lgid += ops.size(); - left -= ops.size(); - } - ops = null; - } + Iterator it_cores = tooptimize.keySet().iterator(); + // check if it is possible to optimize these tasks + if((sparecores == null) || (sparecores.size() == 0)) { + // lack of spare cores + while(it_cores.hasNext()) { + int corenum = it_cores.next(); + Vector tmptasks = tooptimize.get(corenum); + // group the task instantiations according to whether it + // has backward data dependences or not + Vector candidatetasks = new Vector(); + for(int ii= 0; ii < tmptasks.size(); ii++) { + SimExecutionEdge tmpseedge = tmptasks.elementAt(ii); + SimExecutionNode target = (SimExecutionNode)tmpseedge.getTarget(); + Vector children = + (Vector)target.getEdgeVector(); + int jj = 0; + for(; jj < children.size(); jj++) { + SimExecutionEdge tmpedge = children.elementAt(jj); + if(tmpedge.getTd() != null) { + Vector predicates = + tmpedge.getPredicates(); + if((predicates != null) && + (predicates.contains(tmpseedge))) { + break; + } + predicates = null; + } else if(tmpedge.getWeight() != 0) { + // transfer edge + if(((SimExecutionNode)tmpedge.getTarget()).getTimepoint() + == tmpedge.getWeight() + target.getTimepoint()) { + break; + } + } + } + if(jj == children.size()) { + candidatetasks.add(tmpseedge); + } + } + if((candidatetasks.size() > 0) && + (candidatetasks.size() < tmptasks.size())) { + // there are less important tasks which have no backward + // data dependences at this timepoint, try to change + // original execution order + Hashtable> tooptimize2 = + new Hashtable>(); + tooptimize2.put(corenum, candidatetasks); + Vector> ops = + innerOptimizeCriticalPath(scheduleGraph, + tooptimize2, + null, + lgid, + left); + if(ops != null) { + if(optimizeschedulegraphs == null) { + optimizeschedulegraphs = new Vector>(); + } + optimizeschedulegraphs.addAll(ops); + lgid += ops.size(); + left -= ops.size(); + } + tooptimize2 = null; + ops = null; + } + tmptasks = null; + candidatetasks = null; + } + + if(left == 0) { + it_cores = null; + return optimizeschedulegraphs; + } + + // flush the dependences and earliest start time + if(!state.BAMBOOCOMPILETIME) { + it_cores = tooptimize.keySet().iterator(); + while(it_cores.hasNext()) { + int corenum = it_cores.next(); + Vector edgevec = + tooptimize.get(corenum); + for(int j = 0; j < edgevec.size(); j++) { + SimExecutionEdge edge = edgevec.elementAt(j); + lastpredicateedge = edge.getLastpredicateEdge(); + lastpredicatenode = edge.getLastpredicateNode(); + // if(edge.getCoreNum() != lastpredicate.getCoreNum()) // should never hit this + timepoint = lastpredicatenode.getTimepoint(); + if(lastpredicateedge.getTd() == null) { + // transfer edge + timepoint += lastpredicateedge.getWeight(); + } + // mapping to critical path + for(int index = 0; index < criticalPath.size(); index++) { + SimExecutionEdge tmpseedge = criticalPath.elementAt(index); + SimExecutionNode tmpsenode = + (SimExecutionNode)tmpseedge.getTarget(); + if(tmpsenode.getTimepoint() > timepoint) { + // update the predicate info + if(edge.getPredicates() != null) { + edge.getPredicates().remove(lastpredicateedge); + } + edge.addPredicate(criticalPath.elementAt(index)); + break; + } + } + } + edgevec = null; + } + it_cores = null; + computeBestStartPoint(criticalPath); + Vector> ops = optimizeCriticalPath(scheduleGraph, + criticalPath, + lgid, + left); + if(ops != null) { + if(optimizeschedulegraphs == null) { + optimizeschedulegraphs = new Vector>(); + } + optimizeschedulegraphs.addAll(ops); + lgid += ops.size(); + left -= ops.size(); + } + ops = null; + } + } else { + // there are spare cores, try to reorganize the tasks to the spare + // cores + Vector> ops = + innerOptimizeCriticalPath(scheduleGraph, + tooptimize, + sparecores, + lgid, + left); + if(ops != null) { + if(optimizeschedulegraphs == null) { + optimizeschedulegraphs = new Vector>(); + } + optimizeschedulegraphs.addAll(ops); + lgid += ops.size(); + left -= ops.size(); + } + ops = null; + } } sparecores = null; tooptimize.clear(); @@ -1077,7 +1077,7 @@ public class MCImplSynthesis { Vector roots = new Vector(); for(int i = 0; i < newscheduleGraph.size(); i++) { if((sparecores == null) || (sparecores.contains(i))) { - roots.add(newscheduleGraph.elementAt(i)); + roots.add(newscheduleGraph.elementAt(i)); } } @@ -1091,28 +1091,28 @@ public class MCImplSynthesis { Vector candidatetasks = tooptimize.get(corenum); for(int i = 0; i < candidatetasks.size(); i++) { - TaskDescriptor td = candidatetasks.elementAt(i).getTd(); - // TODO: currently do not consider multi-param tasks - if(td.numParameters() == 1) { - ClassDescriptor cd = td.getParamType(0).getClassDesc(); - ScheduleNode snode = newscheduleGraph.elementAt(corenum); // corresponding ScheduleNode - Iterator it_cnodes = snode.getClassNodesIterator(); - ClassNode tosplit = null; - while(it_cnodes.hasNext()) { - ClassNode cnode = it_cnodes.next(); - if(cnode.getClassDescriptor().equals(cd)) { - tosplit= cnode; - break; - } - } - it_cnodes = null; - - // split the node - ScheduleNode splitnode = snode.spliteClassNode(tosplit); - newscheduleGraph.add(splitnode); - tocombines.add(splitnode); - tosplit = null; - } + TaskDescriptor td = candidatetasks.elementAt(i).getTd(); + // TODO: currently do not consider multi-param tasks + if(td.numParameters() == 1) { + ClassDescriptor cd = td.getParamType(0).getClassDesc(); + ScheduleNode snode = newscheduleGraph.elementAt(corenum); // corresponding ScheduleNode + Iterator it_cnodes = snode.getClassNodesIterator(); + ClassNode tosplit = null; + while(it_cnodes.hasNext()) { + ClassNode cnode = it_cnodes.next(); + if(cnode.getClassDescriptor().equals(cd)) { + tosplit= cnode; + break; + } + } + it_cnodes = null; + + // split the node + ScheduleNode splitnode = snode.spliteClassNode(tosplit); + newscheduleGraph.add(splitnode); + tocombines.add(splitnode); + tosplit = null; + } } candidatetasks = null; } @@ -1148,33 +1148,33 @@ public class MCImplSynthesis { while ((left > 0) && (cGen.nextGen())) { //while ((left > 0) && (cGen.randomGenE())) { if(Math.abs(rand.nextInt()) % 100 > this.generateThreshold) { - Vector> combine = cGen.getCombine(); - Vector sNodes = - SchedulingUtil.generateScheduleGraph(this.state, - newscheduleGraph, - scheduleEdges, - rootNodes, - combine, - lgid++); - if(optimizeschedulegraphs == null) { - optimizeschedulegraphs = new Vector>(); - } - optimizeschedulegraphs.add(sNodes); - combine = null; - sNodes = null; - left--; + Vector> combine = cGen.getCombine(); + Vector sNodes = + SchedulingUtil.generateScheduleGraph(this.state, + newscheduleGraph, + scheduleEdges, + rootNodes, + combine, + lgid++); + if(optimizeschedulegraphs == null) { + optimizeschedulegraphs = new Vector>(); + } + optimizeschedulegraphs.add(sNodes); + combine = null; + sNodes = null; + left--; } } cGen.clear(); for(int i = 0; i < rootNodes.size(); i++) { if(rootNodes.elementAt(i) != null) { - rootNodes.elementAt(i).clear(); + rootNodes.elementAt(i).clear(); } } rootNodes = null; for(int i = 0; i < nodes2combine.size(); i++) { if(nodes2combine.elementAt(i) != null) { - nodes2combine.elementAt(i).clear(); + nodes2combine.elementAt(i).clear(); } } nodes2combine = null; @@ -1257,60 +1257,60 @@ public class MCImplSynthesis { Vector cNodes = sn.getClassNodes(); for(int k = 0; k < cNodes.size(); k++) { - ClassNode cNode = cNodes.elementAt(k); - ClassDescriptor cd = cNode.getClassDescriptor(); - Iterator it_flags = cNode.getFlags(); - while(it_flags.hasNext()) { - FlagState fs = (FlagState)it_flags.next(); - Iterator it_edges = fs.edges(); - while(it_edges.hasNext()) { - FEdge tmpfe = (FEdge)it_edges.next(); - TaskDescriptor td = (tmpfe).getTask(); - boolean contain = true; - if(td.numParameters() > 1) { - // td is a multi-param task, check if this core contains the - // main cd of it - ClassDescriptor cd1 = td2maincd.get(td); - if(td2maincd.get(td).equals(cd)) { - contain = true; - td2maincore.put(td, tmpSchedule.getCoreNum()); - } else { - contain = false; - if(!td2allycores.containsKey(td)) { - td2allycores.put(td, new Vector()); - } - Vector allycores = td2allycores.get(td); - if(!allycores.contains(tmpSchedule)) { - allycores.addElement(tmpSchedule); - } - allycores = null; - } - // If the FlagState can be fed to some multi-param tasks, - // need to record corresponding ally cores later. - tmpSchedule.addFState4TD(td, fs); - } - if(contain) { - tmpSchedule.addTask(td); - if(!td2cores.containsKey(td)) { - td2cores.put(td, new Vector()); - } - Vector tmpcores = td2cores.get(td); - if(!tmpcores.contains(tmpSchedule)) { - tmpcores.add(tmpSchedule); - } - tmpcores = null; - } - if(td.getParamType(0).getClassDesc().getSymbol().equals( - TypeUtil.StartupClass)) { - assert(!setstartupcore); - startupcore = j; - startup = tmpSchedule; - setstartupcore = true; - } - } - it_edges = null; - } - it_flags = null; + ClassNode cNode = cNodes.elementAt(k); + ClassDescriptor cd = cNode.getClassDescriptor(); + Iterator it_flags = cNode.getFlags(); + while(it_flags.hasNext()) { + FlagState fs = (FlagState)it_flags.next(); + Iterator it_edges = fs.edges(); + while(it_edges.hasNext()) { + FEdge tmpfe = (FEdge)it_edges.next(); + TaskDescriptor td = (tmpfe).getTask(); + boolean contain = true; + if(td.numParameters() > 1) { + // td is a multi-param task, check if this core contains the + // main cd of it + ClassDescriptor cd1 = td2maincd.get(td); + if(td2maincd.get(td).equals(cd)) { + contain = true; + td2maincore.put(td, tmpSchedule.getCoreNum()); + } else { + contain = false; + if(!td2allycores.containsKey(td)) { + td2allycores.put(td, new Vector()); + } + Vector allycores = td2allycores.get(td); + if(!allycores.contains(tmpSchedule)) { + allycores.addElement(tmpSchedule); + } + allycores = null; + } + // If the FlagState can be fed to some multi-param tasks, + // need to record corresponding ally cores later. + tmpSchedule.addFState4TD(td, fs); + } + if(contain) { + tmpSchedule.addTask(td); + if(!td2cores.containsKey(td)) { + td2cores.put(td, new Vector()); + } + Vector tmpcores = td2cores.get(td); + if(!tmpcores.contains(tmpSchedule)) { + tmpcores.add(tmpSchedule); + } + tmpcores = null; + } + if(td.getParamType(0).getClassDesc().getSymbol().equals( + TypeUtil.StartupClass)) { + assert(!setstartupcore); + startupcore = j; + startup = tmpSchedule; + setstartupcore = true; + } + } + it_edges = null; + } + it_flags = null; } cNodes = null; @@ -1318,138 +1318,138 @@ public class MCImplSynthesis { // target ScheduleNode into the queue inside sn Iterator it_edges = sn.edges(); while(it_edges.hasNext()) { - ScheduleEdge se = (ScheduleEdge)it_edges.next(); - ScheduleNode target = (ScheduleNode)se.getTarget(); - Integer targetcore = sn2coreNum.get(target); - switch(se.getType()) { - case ScheduleEdge.NEWEDGE: { - FlagState fs = se.getFstate(); - // Check if the new obj could be fed to some - // multi-parameter task, if so, add for ally cores - // checking - Iterator it = fs.edges(); - boolean canTriggerSTask = false; // Flag indicates if fs can trigger - // some single-param task - while(it.hasNext()) { - TaskDescriptor td = ((FEdge)it.next()).getTask(); - if(td.numParameters() > 1) { - tmpSchedule.addFState4TD(td, fs); // TODO - // add this core as a allycore of td - if(!td2allycores.containsKey(td)) { - td2allycores.put(td, new Vector()); - } - Vector allycores = td2allycores.get(td); - if(!allycores.contains(tmpSchedule)) { - allycores.addElement(tmpSchedule); - } - } else { - canTriggerSTask = true; - } - } - if(canTriggerSTask) { - // Only transfer the obj when it can trigger some single-parm task - // TODO: ensure that multi-param tasks have these objects - for(int k = 0; k < se.getNewRate(); k++) { - tmpSchedule.addTargetCore(fs, targetcore); - } - } - break; - } - - case ScheduleEdge.TRANSEDGE: { - // 'transmit' edge - tmpSchedule.addTargetCore(se.getFstate(), - targetcore, - se.getTargetFState()); - // check if missed some FlagState associated with some - // multi-parameter task, which has been cloned when - // splitting a ClassNode - FlagState fs = se.getSourceFState(); - FlagState tfs = se.getTargetFState(); - Iterator it = tfs.edges(); - while(it.hasNext()) { - TaskDescriptor td = ((FEdge)it.next()).getTask(); - if(td.numParameters() > 1) { - tmpSchedule.addFState4TD(td, fs); - // add this core as a allycore of td - if(!td2allycores.containsKey(td)) { - td2allycores.put(td, new Vector()); - } - Vector allycores = td2allycores.get(td); - if(!allycores.contains(tmpSchedule)) { - allycores.addElement(tmpSchedule); - } - } - } - break; - } - } + ScheduleEdge se = (ScheduleEdge)it_edges.next(); + ScheduleNode target = (ScheduleNode)se.getTarget(); + Integer targetcore = sn2coreNum.get(target); + switch(se.getType()) { + case ScheduleEdge.NEWEDGE: { + FlagState fs = se.getFstate(); + // Check if the new obj could be fed to some + // multi-parameter task, if so, add for ally cores + // checking + Iterator it = fs.edges(); + boolean canTriggerSTask = false; // Flag indicates if fs can trigger + // some single-param task + while(it.hasNext()) { + TaskDescriptor td = ((FEdge)it.next()).getTask(); + if(td.numParameters() > 1) { + tmpSchedule.addFState4TD(td, fs); // TODO + // add this core as a allycore of td + if(!td2allycores.containsKey(td)) { + td2allycores.put(td, new Vector()); + } + Vector allycores = td2allycores.get(td); + if(!allycores.contains(tmpSchedule)) { + allycores.addElement(tmpSchedule); + } + } else { + canTriggerSTask = true; + } + } + if(canTriggerSTask) { + // Only transfer the obj when it can trigger some single-parm task + // TODO: ensure that multi-param tasks have these objects + for(int k = 0; k < se.getNewRate(); k++) { + tmpSchedule.addTargetCore(fs, targetcore); + } + } + break; + } + + case ScheduleEdge.TRANSEDGE: { + // 'transmit' edge + tmpSchedule.addTargetCore(se.getFstate(), + targetcore, + se.getTargetFState()); + // check if missed some FlagState associated with some + // multi-parameter task, which has been cloned when + // splitting a ClassNode + FlagState fs = se.getSourceFState(); + FlagState tfs = se.getTargetFState(); + Iterator it = tfs.edges(); + while(it.hasNext()) { + TaskDescriptor td = ((FEdge)it.next()).getTask(); + if(td.numParameters() > 1) { + tmpSchedule.addFState4TD(td, fs); + // add this core as a allycore of td + if(!td2allycores.containsKey(td)) { + td2allycores.put(td, new Vector()); + } + Vector allycores = td2allycores.get(td); + if(!allycores.contains(tmpSchedule)) { + allycores.addElement(tmpSchedule); + } + } + } + break; + } + } } it_edges = sn.getScheduleEdgesIterator(); while(it_edges.hasNext()) { - ScheduleEdge se = (ScheduleEdge)it_edges.next(); - switch(se.getType()) { - case ScheduleEdge.NEWEDGE: { - // TODO, added 09/07/06 - FlagState fs = se.getFstate(); - // Check if the new obj could be fed to some - // multi-parameter task, if so, add for ally cores - // checking - Iterator it = fs.edges(); - boolean canTriggerSTask = false; // Flag indicates if fs can trigger - // some single-param task - while(it.hasNext()) { - TaskDescriptor td = ((FEdge)it.next()).getTask(); - if(td.numParameters() > 1) { - tmpSchedule.addFState4TD(td, fs); // TODO - // add this core as a allycore of td - if(!td2allycores.containsKey(td)) { - td2allycores.put(td, new Vector()); - } - Vector allycores = td2allycores.get(td); - if(!allycores.contains(tmpSchedule)) { - allycores.addElement(tmpSchedule); - } - } else { - canTriggerSTask = true; - } - } - if(canTriggerSTask) { - for(int k = 0; k < se.getNewRate(); k++) { - tmpSchedule.addTargetCore(se.getFstate(), j); - } - } - break; - } - - case ScheduleEdge.TRANSEDGE: { - // 'transmit' edge - tmpSchedule.addTargetCore(se.getFstate(), - j, - se.getTargetFState()); - // check if missed some FlagState associated with some - // multi-parameter task, which has been cloned when - // splitting a ClassNode - FlagState fs = se.getSourceFState(); - FlagState tfs = se.getTargetFState(); - Iterator it = tfs.edges(); - while(it.hasNext()) { - TaskDescriptor td = ((FEdge)it.next()).getTask(); - if(td.numParameters() > 1) { - tmpSchedule.addFState4TD(td, fs); - // add this core as a allycore of td - if(!td2allycores.containsKey(td)) { - td2allycores.put(td, new Vector()); - } - Vector allycores = td2allycores.get(td); - if(!allycores.contains(tmpSchedule)) { - allycores.addElement(tmpSchedule); - } - } - } - break; - } - } + ScheduleEdge se = (ScheduleEdge)it_edges.next(); + switch(se.getType()) { + case ScheduleEdge.NEWEDGE: { + // TODO, added 09/07/06 + FlagState fs = se.getFstate(); + // Check if the new obj could be fed to some + // multi-parameter task, if so, add for ally cores + // checking + Iterator it = fs.edges(); + boolean canTriggerSTask = false; // Flag indicates if fs can trigger + // some single-param task + while(it.hasNext()) { + TaskDescriptor td = ((FEdge)it.next()).getTask(); + if(td.numParameters() > 1) { + tmpSchedule.addFState4TD(td, fs); // TODO + // add this core as a allycore of td + if(!td2allycores.containsKey(td)) { + td2allycores.put(td, new Vector()); + } + Vector allycores = td2allycores.get(td); + if(!allycores.contains(tmpSchedule)) { + allycores.addElement(tmpSchedule); + } + } else { + canTriggerSTask = true; + } + } + if(canTriggerSTask) { + for(int k = 0; k < se.getNewRate(); k++) { + tmpSchedule.addTargetCore(se.getFstate(), j); + } + } + break; + } + + case ScheduleEdge.TRANSEDGE: { + // 'transmit' edge + tmpSchedule.addTargetCore(se.getFstate(), + j, + se.getTargetFState()); + // check if missed some FlagState associated with some + // multi-parameter task, which has been cloned when + // splitting a ClassNode + FlagState fs = se.getSourceFState(); + FlagState tfs = se.getTargetFState(); + Iterator it = tfs.edges(); + while(it.hasNext()) { + TaskDescriptor td = ((FEdge)it.next()).getTask(); + if(td.numParameters() > 1) { + tmpSchedule.addFState4TD(td, fs); + // add this core as a allycore of td + if(!td2allycores.containsKey(td)) { + td2allycores.put(td, new Vector()); + } + Vector allycores = td2allycores.get(td); + if(!allycores.contains(tmpSchedule)) { + allycores.addElement(tmpSchedule); + } + } + } + break; + } + } } it_edges = null; scheduling.add(tmpSchedule); @@ -1467,39 +1467,39 @@ public class MCImplSynthesis { Vector cores = td2cores.get(td); assert(cores.size() == 1); // should have only one core for(int k = 0; k < cores.size(); ++k) { - Schedule tmpSchedule = cores.elementAt(k); - - // Make sure all the parameter objs of a multi-parameter - // task would be send to right place after the task finished - for(int h = 0; h < fes.size(); ++h) { - FEdge tmpfe = fes.elementAt(h); - FlagState tmpfs = (FlagState)tmpfe.getTarget(); - Vector tmptds = new Vector(); - if((tmpSchedule.getTargetCoreTable() == null) - || (!tmpSchedule.getTargetCoreTable().containsKey(tmpfs))) { - // add up all possible cores' info - Iterator it_edges = tmpfs.edges(); - while(it_edges.hasNext()) { - TaskDescriptor tmptd = ((FEdge)it_edges.next()).getTask(); - if(!tmptds.contains(tmptd)) { - tmptds.add(tmptd); - // only multiparam task will be processed here!!! TODO - Vector tmpcores = td2cores.get(tmptd); - for(int m = 0; m < tmpcores.size(); ++m) { - Schedule target = tmpcores.elementAt(m); - int targetcore = target.getCoreNum(); - int num = target.getTaskNum(tmptd); - for(int n = 0; n < num; n++) { - tmpSchedule.addTargetCore(tmpfs, targetcore); - } - } - tmpcores = null; - } - } - it_edges = null; - } - tmptds = null; - } + Schedule tmpSchedule = cores.elementAt(k); + + // Make sure all the parameter objs of a multi-parameter + // task would be send to right place after the task finished + for(int h = 0; h < fes.size(); ++h) { + FEdge tmpfe = fes.elementAt(h); + FlagState tmpfs = (FlagState)tmpfe.getTarget(); + Vector tmptds = new Vector(); + if((tmpSchedule.getTargetCoreTable() == null) + || (!tmpSchedule.getTargetCoreTable().containsKey(tmpfs))) { + // add up all possible cores' info + Iterator it_edges = tmpfs.edges(); + while(it_edges.hasNext()) { + TaskDescriptor tmptd = ((FEdge)it_edges.next()).getTask(); + if(!tmptds.contains(tmptd)) { + tmptds.add(tmptd); + // only multiparam task will be processed here!!! TODO + Vector tmpcores = td2cores.get(tmptd); + for(int m = 0; m < tmpcores.size(); ++m) { + Schedule target = tmpcores.elementAt(m); + int targetcore = target.getCoreNum(); + int num = target.getTaskNum(tmptd); + for(int n = 0; n < num; n++) { + tmpSchedule.addTargetCore(tmpfs, targetcore); + } + } + tmpcores = null; + } + } + it_edges = null; + } + tmptds = null; + } } fes = null; cores = null; @@ -1511,13 +1511,13 @@ public class MCImplSynthesis { TaskDescriptor td = it_mptds.next(); Vector allycores = td2allycores.get(td); for(int i = 0; i < allycores.size(); i++) { - Schedule tSchedule = allycores.elementAt(i); - Vector tmpfss = tSchedule.getFStates4TD(td); - int targetcore = td2maincore.get(td).intValue(); - for(int h = 0; h < tmpfss.size(); ++h) { - tSchedule.addAllyCore(tmpfss.elementAt(h), targetcore); - } - tmpfss = null; + Schedule tSchedule = allycores.elementAt(i); + Vector tmpfss = tSchedule.getFStates4TD(td); + int targetcore = td2maincore.get(td).intValue(); + for(int h = 0; h < tmpfss.size(); ++h) { + tSchedule.addAllyCore(tmpfss.elementAt(h), targetcore); + } + tmpfss = null; } } it_mptds = null; diff --git a/Robust/src/Analysis/Scheduling/ObjectInfo.java b/Robust/src/Analysis/Scheduling/ObjectInfo.java index 7ffe09a6..ff08b1ca 100644 --- a/Robust/src/Analysis/Scheduling/ObjectInfo.java +++ b/Robust/src/Analysis/Scheduling/ObjectInfo.java @@ -19,7 +19,7 @@ public class ObjectInfo { if ((oi.obj != obj) || (oi.fs != fs) || (oi.version != version)) { - return false; + return false; } return true; } diff --git a/Robust/src/Analysis/Scheduling/ObjectSimulator.java b/Robust/src/Analysis/Scheduling/ObjectSimulator.java index 69421a4f..cdb9d339 100644 --- a/Robust/src/Analysis/Scheduling/ObjectSimulator.java +++ b/Robust/src/Analysis/Scheduling/ObjectSimulator.java @@ -40,12 +40,12 @@ public class ObjectSimulator { this.changed = true; currentFS = (FlagState)fedge.getTarget(); if(this.counter > 0) { - //System.err.println(this.counter); - this.counter--; + //System.err.println(this.counter); + this.counter--; } if((this.cd.getSymbol().equals("Cluster")) && (this.counter == 0)) { - // go to end state - this.currentFS = new FlagState(this.cd); + // go to end state + this.currentFS = new FlagState(this.cd); } } else { this.changed = false; diff --git a/Robust/src/Analysis/Scheduling/ScheduleAnalysis.java b/Robust/src/Analysis/Scheduling/ScheduleAnalysis.java index fbd883a3..f00eb546 100644 --- a/Robust/src/Analysis/Scheduling/ScheduleAnalysis.java +++ b/Robust/src/Analysis/Scheduling/ScheduleAnalysis.java @@ -91,7 +91,7 @@ public class ScheduleAnalysis { ScheduleNode startupNode = null; if((multiparamtds != null) || (multiparamtds.size() > 0)) { - this.td2maincd = new Hashtable(); + this.td2maincd = new Hashtable(); } // necessary preparation such as read profile info etc. @@ -125,80 +125,80 @@ public class ScheduleAnalysis { long tint = 0; Iterator it_classes = state.getClassSymbolTable().getDescriptorsIterator(); while(it_classes.hasNext()) { - ClassDescriptor cd = (ClassDescriptor) it_classes.next(); - if(cd.hasFlags()) { - Vector rootnodes = this.taskanalysis.getRootNodes(cd); - if(rootnodes!=null) { - Iterator it_rootnodes = rootnodes.iterator(); - while(it_rootnodes.hasNext()) { - FlagState root = (FlagState)it_rootnodes.next(); - Vector allocatingTasks = root.getAllocatingTasks(); - if(allocatingTasks != null) { - for(int k = 0; k < allocatingTasks.size(); k++) { - TaskDescriptor td = - (TaskDescriptor)allocatingTasks.elementAt(k); - Vector fev = this.taskanalysis.getFEdgesFromTD(td); - int numEdges = fev.size(); - for(int j = 0; j < numEdges; j++) { - FEdge pfe = fev.elementAt(j); - TaskInfo taskinfo = taskinfos.get(td.getSymbol()); - tint = taskinfo.m_exetime[pfe.getTaskExitIndex()]; - pfe.setExeTime(tint); - double idouble = - taskinfo.m_probability[pfe.getTaskExitIndex()]; - pfe.setProbability(idouble); - int newRate = 0; - int tindex = pfe.getTaskExitIndex(); - if((taskinfo.m_newobjinfo.elementAt(tindex) != null) - && (taskinfo.m_newobjinfo.elementAt(tindex).containsKey( - cd.getSymbol()))) { - newRate = taskinfo.m_newobjinfo.elementAt(tindex).get( - cd.getSymbol()); - } - pfe.addNewObjInfo(cd, newRate, idouble); - if(taskinfo.m_byObj != -1) { - ((FlagState)pfe.getSource()).setByObj(taskinfo.m_byObj); - } - // TODO for test - /*System.err.println("task " + td.getSymbol() + " exit# " + - pfe.getTaskExitIndex() + " exetime: " + pfe.getExeTime() - + " prob: " + pfe.getProbability() + "% newobj: " - + pfe.getNewObjInfoHashtable().size());*/ - } - fev = null; - } - } - } - it_rootnodes = null; - } - Iterator it_flags = this.taskanalysis.getFlagStates(cd).iterator(); - while(it_flags.hasNext()) { - FlagState fs = (FlagState)it_flags.next(); - Iterator it_edges = fs.edges(); - while(it_edges.hasNext()) { - FEdge edge = (FEdge)it_edges.next(); - TaskInfo taskinfo = taskinfos.get(edge.getTask().getSymbol()); - double idouble = 0.0; - if(edge.getTaskExitIndex() >= taskinfo.m_exetime.length) { - tint = 0; - } else { - tint = taskinfo.m_exetime[edge.getTaskExitIndex()]; - idouble = taskinfo.m_probability[edge.getTaskExitIndex()]; - } - edge.setExeTime(tint); - edge.setProbability(idouble); - if(taskinfo.m_byObj != -1) { - ((FlagState)edge.getSource()).setByObj(taskinfo.m_byObj); - } - // TODO for test - /*System.err.println("task " + edge.getTask().getSymbol() + " exit# " + - edge.getTaskExitIndex() + " exetime: " + edge.getExeTime() - + " prob: " + edge.getProbability());*/ - } - it_edges = null; - } - it_flags = null; - } + ClassDescriptor cd = (ClassDescriptor) it_classes.next(); + if(cd.hasFlags()) { + Vector rootnodes = this.taskanalysis.getRootNodes(cd); + if(rootnodes!=null) { + Iterator it_rootnodes = rootnodes.iterator(); + while(it_rootnodes.hasNext()) { + FlagState root = (FlagState)it_rootnodes.next(); + Vector allocatingTasks = root.getAllocatingTasks(); + if(allocatingTasks != null) { + for(int k = 0; k < allocatingTasks.size(); k++) { + TaskDescriptor td = + (TaskDescriptor)allocatingTasks.elementAt(k); + Vector fev = this.taskanalysis.getFEdgesFromTD(td); + int numEdges = fev.size(); + for(int j = 0; j < numEdges; j++) { + FEdge pfe = fev.elementAt(j); + TaskInfo taskinfo = taskinfos.get(td.getSymbol()); + tint = taskinfo.m_exetime[pfe.getTaskExitIndex()]; + pfe.setExeTime(tint); + double idouble = + taskinfo.m_probability[pfe.getTaskExitIndex()]; + pfe.setProbability(idouble); + int newRate = 0; + int tindex = pfe.getTaskExitIndex(); + if((taskinfo.m_newobjinfo.elementAt(tindex) != null) + && (taskinfo.m_newobjinfo.elementAt(tindex).containsKey( + cd.getSymbol()))) { + newRate = taskinfo.m_newobjinfo.elementAt(tindex).get( + cd.getSymbol()); + } + pfe.addNewObjInfo(cd, newRate, idouble); + if(taskinfo.m_byObj != -1) { + ((FlagState)pfe.getSource()).setByObj(taskinfo.m_byObj); + } + // TODO for test + /*System.err.println("task " + td.getSymbol() + " exit# " + + pfe.getTaskExitIndex() + " exetime: " + pfe.getExeTime() + + " prob: " + pfe.getProbability() + "% newobj: " + + pfe.getNewObjInfoHashtable().size());*/ + } + fev = null; + } + } + } + it_rootnodes = null; + } + Iterator it_flags = this.taskanalysis.getFlagStates(cd).iterator(); + while(it_flags.hasNext()) { + FlagState fs = (FlagState)it_flags.next(); + Iterator it_edges = fs.edges(); + while(it_edges.hasNext()) { + FEdge edge = (FEdge)it_edges.next(); + TaskInfo taskinfo = taskinfos.get(edge.getTask().getSymbol()); + double idouble = 0.0; + if(edge.getTaskExitIndex() >= taskinfo.m_exetime.length) { + tint = 0; + } else { + tint = taskinfo.m_exetime[edge.getTaskExitIndex()]; + idouble = taskinfo.m_probability[edge.getTaskExitIndex()]; + } + edge.setExeTime(tint); + edge.setProbability(idouble); + if(taskinfo.m_byObj != -1) { + ((FlagState)edge.getSource()).setByObj(taskinfo.m_byObj); + } + // TODO for test + /*System.err.println("task " + edge.getTask().getSymbol() + " exit# " + + edge.getTaskExitIndex() + " exetime: " + edge.getExeTime() + + " prob: " + edge.getProbability());*/ + } + it_edges = null; + } + it_flags = null; + } } taskinfos = null; it_classes = null; @@ -213,30 +213,30 @@ public class ScheduleAnalysis { while(it_classes.hasNext()) { ClassDescriptor cd=(ClassDescriptor) it_classes.next(); if(cd.hasFlags()) { - Set fss = this.taskanalysis.getFlagStates(cd); - SCC scc=GraphNode.DFS.computeSCC(fss); - if (scc.hasCycles()) { - for(int i=0; i fss = this.taskanalysis.getFlagStates(cd); + SCC scc=GraphNode.DFS.computeSCC(fss); + if (scc.hasCycles()) { + for(int i=0; i(), i); - numofnobjs = Integer.parseInt(tmpinfo.substring(0, tmpinindex)); - tmpinfo = tmpinfo.substring(tmpinindex + 1); - while(tmpinfo.startsWith(" ")) { - tmpinfo = tmpinfo.substring(1); - } - for(int j = 0; j < numofnobjs; j++) { - tmpinindex = tmpinfo.indexOf(','); - String nobjtype = tmpinfo.substring(0, tmpinindex); - tmpinfo = tmpinfo.substring(tmpinindex + 1); - while(tmpinfo.startsWith(" ")) { - tmpinfo = tmpinfo.substring(1); - } - int objnum = 0; - if(j < numofnobjs - 1) { - tmpinindex = tmpinfo.indexOf(','); - objnum = Integer.parseInt(tmpinfo.substring(0, tmpinindex)); - tmpinfo = tmpinfo.substring(tmpinindex + 1); - while(tmpinfo.startsWith(" ")) { - tmpinfo = tmpinfo.substring(1); - } - } else { - objnum = Integer.parseInt(tmpinfo); - } - tinfo.m_newobjinfo.elementAt(i).put(nobjtype, objnum); - } - } - } - taskinfos.put(inname, tinfo); - inindex = profiledata.indexOf('\n'); + String inline = profiledata.substring(0, inindex); + profiledata = profiledata.substring(inindex + 1); + //System.printString(inline + "\n"); + int tmpinindex = inline.indexOf(','); + if(tmpinindex == -1) { + break; + } + String inname = inline.substring(0, tmpinindex); + String inint = inline.substring(tmpinindex + 1); + while(inint.startsWith(" ")) { + inint = inint.substring(1); + } + tmpinindex = inint.indexOf(','); + if(tmpinindex == -1) { + break; + } + int numofexits = Integer.parseInt(inint.substring(0, tmpinindex)); + TaskInfo tinfo = new TaskInfo(numofexits); + inint = inint.substring(tmpinindex + 1); + while(inint.startsWith(" ")) { + inint = inint.substring(1); + } + tmpinindex = inint.indexOf(';'); + int byObj = Integer.parseInt(inint.substring(0, tmpinindex)); + if(byObj != -1) { + tinfo.m_byObj = byObj; + } + inint = inint.substring(tmpinindex + 1); + while(inint.startsWith(" ")) { + inint = inint.substring(1); + } + for(int i = 0; i < numofexits; i++) { + String tmpinfo = null; + if(i < numofexits - 1) { + tmpinindex = inint.indexOf(';'); + tmpinfo = inint.substring(0, tmpinindex); + inint = inint.substring(tmpinindex + 1); + while(inint.startsWith(" ")) { + inint = inint.substring(1); + } + } else { + tmpinfo = inint; + } + + tmpinindex = tmpinfo.indexOf(','); + tinfo.m_exetime[i] = Long.parseLong(tmpinfo.substring(0, tmpinindex)); + tmpinfo = tmpinfo.substring(tmpinindex + 1); + while(tmpinfo.startsWith(" ")) { + tmpinfo = tmpinfo.substring(1); + } + tmpinindex = tmpinfo.indexOf(','); + tinfo.m_probability[i] = Double.parseDouble( + tmpinfo.substring(0,tmpinindex)); + tmpinfo = tmpinfo.substring(tmpinindex + 1); + while(tmpinfo.startsWith(" ")) { + tmpinfo = tmpinfo.substring(1); + } + tmpinindex = tmpinfo.indexOf(','); + int numofnobjs = 0; + if(tmpinindex == -1) { + numofnobjs = Integer.parseInt(tmpinfo); + if(numofnobjs != 0) { + System.err.println("Error profile data format!"); + System.exit(-1); + } + } else { + tinfo.m_newobjinfo.setElementAt(new Hashtable(), i); + numofnobjs = Integer.parseInt(tmpinfo.substring(0, tmpinindex)); + tmpinfo = tmpinfo.substring(tmpinindex + 1); + while(tmpinfo.startsWith(" ")) { + tmpinfo = tmpinfo.substring(1); + } + for(int j = 0; j < numofnobjs; j++) { + tmpinindex = tmpinfo.indexOf(','); + String nobjtype = tmpinfo.substring(0, tmpinindex); + tmpinfo = tmpinfo.substring(tmpinindex + 1); + while(tmpinfo.startsWith(" ")) { + tmpinfo = tmpinfo.substring(1); + } + int objnum = 0; + if(j < numofnobjs - 1) { + tmpinindex = tmpinfo.indexOf(','); + objnum = Integer.parseInt(tmpinfo.substring(0, tmpinindex)); + tmpinfo = tmpinfo.substring(tmpinindex + 1); + while(tmpinfo.startsWith(" ")) { + tmpinfo = tmpinfo.substring(1); + } + } else { + objnum = Integer.parseInt(tmpinfo); + } + tinfo.m_newobjinfo.elementAt(i).put(nobjtype, objnum); + } + } + } + taskinfos.put(inname, tinfo); + inindex = profiledata.indexOf('\n'); } inStream.close(); inStream = null; @@ -376,116 +376,116 @@ public class ScheduleAnalysis { for(; it_classes.hasNext(); ) { ClassDescriptor cd=(ClassDescriptor) it_classes.next(); if(cd.hasFlags()) { - Vector rootnodes=this.taskanalysis.getRootNodes(cd); - if(rootnodes!=null) { - Iterator it_rootnodes=rootnodes.iterator(); - for(; it_rootnodes.hasNext(); ) { - FlagState root=(FlagState)it_rootnodes.next(); - Vector allocatingTasks = root.getAllocatingTasks(); - if(allocatingTasks != null) { - for(int k = 0; k < allocatingTasks.size(); k++) { - TaskDescriptor td = (TaskDescriptor)allocatingTasks.elementAt(k); - Vector fev = - (Vector) this.taskanalysis.getFEdgesFromTD(td); - int numEdges = fev.size(); - int total = 100; - for(int j = 0; j < numEdges; j++) { - FEdge pfe = fev.elementAt(j); - if(numEdges - j == 1) { - pfe.setProbability(total); - } else { - if((total != 0) && (total != 1)) { - do { - tint = r.nextInt()%total; - } while(tint <= 0); - } - pfe.setProbability(tint); - total -= tint; - } - //do { - // tint = r.nextInt()%10; - // } while(tint <= 0); - //int newRate = tint; - //int newRate = (j+1)%2+1; - int newRate = 1; - String cdname = cd.getSymbol(); - if((cdname.equals("SeriesRunner")) || - (cdname.equals("MDRunner")) || - (cdname.equals("Stage")) || - (cdname.equals("AppDemoRunner")) || - (cdname.equals("FilterBankAtom")) || - (cdname.equals("Grid")) || - (cdname.equals("Fractal")) || - (cdname.equals("KMeans")) || - (cdname.equals("ZTransform")) || - (cdname.equals("TestRunner")) || - (cdname.equals("TestRunner2")) || - (cdname.equals("LinkList")) || - (cdname.equals("BHRunner"))) { - newRate = this.coreNum; - } else if(cdname.equals("SentenceParser")) { - newRate = 4; - } else if(cdname.equals("BlurPiece")) { - newRate = 4; - } else if(cdname.equals("ImageX")) { - newRate = 2 * 2; - } else if(cdname.equals("ImageY")) { - newRate = 1 * 4; - } - //do { - // tint = r.nextInt()%100; - // } while(tint <= 0); - // int probability = tint; - int probability = 100; - pfe.addNewObjInfo(cd, newRate, probability); - } - fev = null; - } - } - } - it_rootnodes = null; - } - - Iterator it_flags = this.taskanalysis.getFlagStates(cd).iterator(); - while(it_flags.hasNext()) { - FlagState fs = (FlagState)it_flags.next(); - Iterator it_edges = fs.edges(); - int total = 100; - while(it_edges.hasNext()) { - //do { - // tint = r.nextInt()%10; - // } while(tint <= 0); - tint = 3; - FEdge edge = (FEdge)it_edges.next(); - edge.setExeTime(tint); - if((fs.getClassDescriptor().getSymbol().equals("MD")) - && (edge.getTask().getSymbol().equals("t6"))) { - if(edge.isbackedge()) { - if(edge.getTarget().equals(edge.getSource())) { - edge.setProbability(93.75); - } else { - edge.setProbability(3.125); - } - } else { - edge.setProbability(3.125); - } - continue; - } - if(!it_edges.hasNext()) { - edge.setProbability(total); - } else { - if((total != 0) && (total != 1)) { - do { - tint = r.nextInt()%total; - } while(tint <= 0); - } - edge.setProbability(tint); - total -= tint; - } - } - it_edges = null; - } - it_flags = null; + Vector rootnodes=this.taskanalysis.getRootNodes(cd); + if(rootnodes!=null) { + Iterator it_rootnodes=rootnodes.iterator(); + for(; it_rootnodes.hasNext(); ) { + FlagState root=(FlagState)it_rootnodes.next(); + Vector allocatingTasks = root.getAllocatingTasks(); + if(allocatingTasks != null) { + for(int k = 0; k < allocatingTasks.size(); k++) { + TaskDescriptor td = (TaskDescriptor)allocatingTasks.elementAt(k); + Vector fev = + (Vector) this.taskanalysis.getFEdgesFromTD(td); + int numEdges = fev.size(); + int total = 100; + for(int j = 0; j < numEdges; j++) { + FEdge pfe = fev.elementAt(j); + if(numEdges - j == 1) { + pfe.setProbability(total); + } else { + if((total != 0) && (total != 1)) { + do { + tint = r.nextInt()%total; + } while(tint <= 0); + } + pfe.setProbability(tint); + total -= tint; + } + //do { + // tint = r.nextInt()%10; + // } while(tint <= 0); + //int newRate = tint; + //int newRate = (j+1)%2+1; + int newRate = 1; + String cdname = cd.getSymbol(); + if((cdname.equals("SeriesRunner")) || + (cdname.equals("MDRunner")) || + (cdname.equals("Stage")) || + (cdname.equals("AppDemoRunner")) || + (cdname.equals("FilterBankAtom")) || + (cdname.equals("Grid")) || + (cdname.equals("Fractal")) || + (cdname.equals("KMeans")) || + (cdname.equals("ZTransform")) || + (cdname.equals("TestRunner")) || + (cdname.equals("TestRunner2")) || + (cdname.equals("LinkList")) || + (cdname.equals("BHRunner"))) { + newRate = this.coreNum; + } else if(cdname.equals("SentenceParser")) { + newRate = 4; + } else if(cdname.equals("BlurPiece")) { + newRate = 4; + } else if(cdname.equals("ImageX")) { + newRate = 2 * 2; + } else if(cdname.equals("ImageY")) { + newRate = 1 * 4; + } + //do { + // tint = r.nextInt()%100; + // } while(tint <= 0); + // int probability = tint; + int probability = 100; + pfe.addNewObjInfo(cd, newRate, probability); + } + fev = null; + } + } + } + it_rootnodes = null; + } + + Iterator it_flags = this.taskanalysis.getFlagStates(cd).iterator(); + while(it_flags.hasNext()) { + FlagState fs = (FlagState)it_flags.next(); + Iterator it_edges = fs.edges(); + int total = 100; + while(it_edges.hasNext()) { + //do { + // tint = r.nextInt()%10; + // } while(tint <= 0); + tint = 3; + FEdge edge = (FEdge)it_edges.next(); + edge.setExeTime(tint); + if((fs.getClassDescriptor().getSymbol().equals("MD")) + && (edge.getTask().getSymbol().equals("t6"))) { + if(edge.isbackedge()) { + if(edge.getTarget().equals(edge.getSource())) { + edge.setProbability(93.75); + } else { + edge.setProbability(3.125); + } + } else { + edge.setProbability(3.125); + } + continue; + } + if(!it_edges.hasNext()) { + edge.setProbability(total); + } else { + if((total != 0) && (total != 1)) { + do { + tint = r.nextInt()%total; + } while(tint <= 0); + } + edge.setProbability(tint); + total -= tint; + } + } + it_edges = null; + } + it_flags = null; } } it_classes = null; @@ -508,12 +508,12 @@ public class ScheduleAnalysis { Vector rootnodes = taskanalysis.getRootNodes(cd); if(((rootnodes != null) && (rootnodes.size() > 0)) || (cd.getSymbol().equals(TypeUtil.StartupClass))) { - ClassNode cNode = new ClassNode(cd, sFStates); - cNode.setSorted(true); - classNodes.add(cNode); - cd2ClassNode.put(cd, cNode); - cdToCNodes.put(cd, cNode); - cNode.calExeTime(); + ClassNode cNode = new ClassNode(cd, sFStates); + cNode.setSorted(true); + classNodes.add(cNode); + cd2ClassNode.put(cd, cNode); + cdToCNodes.put(cd, cNode); + cNode.calExeTime(); } rootnodes = null; fStates = null; @@ -528,14 +528,14 @@ public class ScheduleAnalysis { ClassNode cn = classNodes.elementAt(i); ScheduleNode sn = new ScheduleNode(cn, 0); if(cn.getClassDescriptor().getSymbol().equals(TypeUtil.StartupClass)) { - startupNode = sn; + startupNode = sn; } cn.setScheduleNode(sn); scheduleNodes.add(sn); try { - sn.calExeTime(); + sn.calExeTime(); } catch (Exception e) { - e.printStackTrace(); + e.printStackTrace(); } } @@ -545,56 +545,56 @@ public class ScheduleAnalysis { ClassDescriptor cd = cNode.getClassDescriptor(); Vector rootnodes = taskanalysis.getRootNodes(cd); if(rootnodes != null) { - for(int h = 0; h < rootnodes.size(); h++) { - FlagState root=(FlagState)rootnodes.elementAt(h); - Vector allocatingTasks = root.getAllocatingTasks(); - if(allocatingTasks != null) { - for(int k = 0; k < allocatingTasks.size(); k++) { - TaskDescriptor td = (TaskDescriptor)allocatingTasks.elementAt(k); - Vector fev = - (Vector)taskanalysis.getFEdgesFromTD(td); - int numEdges = fev.size(); - ScheduleNode sNode = cNode.getScheduleNode(); - for(int j = 0; j < numEdges; j++) { - FEdge pfe = fev.elementAt(j); - FEdge.NewObjInfo noi = pfe.getNewObjInfo(cd); - if ((noi == null) || (noi.getNewRate() == 0) - || (noi.getProbability() == 0)) { - // fake creating edge, do not need to create corresponding - // 'new' edge - continue; - } - if(noi.getRoot() == null) { - // set root FlagState - noi.setRoot(root); - } - FlagState pfs = (FlagState)pfe.getTarget(); - ClassDescriptor pcd = pfs.getClassDescriptor(); - ClassNode pcNode = cdToCNodes.get(pcd); - - ScheduleEdge sEdge = new ScheduleEdge(sNode, - "new", - root, - ScheduleEdge.NEWEDGE, - 0); - sEdge.setFEdge(pfe); - sEdge.setSourceCNode(pcNode); - sEdge.setTargetCNode(cNode); - sEdge.setTargetFState(root); - sEdge.setNewRate(noi.getNewRate()); - sEdge.setProbability(noi.getProbability()); - pcNode.getScheduleNode().addEdge(sEdge); - scheduleEdges.add(sEdge); - if((j !=0 ) || (k != 0) || (h != 0)) { - toBreakDown.add(sEdge); - } - } - fev = null; - } - allocatingTasks = null; - } - } - rootnodes = null; + for(int h = 0; h < rootnodes.size(); h++) { + FlagState root=(FlagState)rootnodes.elementAt(h); + Vector allocatingTasks = root.getAllocatingTasks(); + if(allocatingTasks != null) { + for(int k = 0; k < allocatingTasks.size(); k++) { + TaskDescriptor td = (TaskDescriptor)allocatingTasks.elementAt(k); + Vector fev = + (Vector)taskanalysis.getFEdgesFromTD(td); + int numEdges = fev.size(); + ScheduleNode sNode = cNode.getScheduleNode(); + for(int j = 0; j < numEdges; j++) { + FEdge pfe = fev.elementAt(j); + FEdge.NewObjInfo noi = pfe.getNewObjInfo(cd); + if ((noi == null) || (noi.getNewRate() == 0) + || (noi.getProbability() == 0)) { + // fake creating edge, do not need to create corresponding + // 'new' edge + continue; + } + if(noi.getRoot() == null) { + // set root FlagState + noi.setRoot(root); + } + FlagState pfs = (FlagState)pfe.getTarget(); + ClassDescriptor pcd = pfs.getClassDescriptor(); + ClassNode pcNode = cdToCNodes.get(pcd); + + ScheduleEdge sEdge = new ScheduleEdge(sNode, + "new", + root, + ScheduleEdge.NEWEDGE, + 0); + sEdge.setFEdge(pfe); + sEdge.setSourceCNode(pcNode); + sEdge.setTargetCNode(cNode); + sEdge.setTargetFState(root); + sEdge.setNewRate(noi.getNewRate()); + sEdge.setProbability(noi.getProbability()); + pcNode.getScheduleNode().addEdge(sEdge); + scheduleEdges.add(sEdge); + if((j !=0 ) || (k != 0) || (h != 0)) { + toBreakDown.add(sEdge); + } + } + fev = null; + } + allocatingTasks = null; + } + } + rootnodes = null; } } cdToCNodes = null; @@ -620,7 +620,7 @@ public class ScheduleAnalysis { // Break down the 'cycle's try { for(i = 0; i < toBreakDown.size(); i++ ) { - cloneSNodeList(toBreakDown.elementAt(i), false); + cloneSNodeList(toBreakDown.elementAt(i), false); } } catch (Exception e) { e.printStackTrace(); @@ -631,8 +631,8 @@ public class ScheduleAnalysis { for(i = 0; i < scheduleEdges.size(); i++) { ScheduleEdge se = (ScheduleEdge)scheduleEdges.elementAt(i); if((0 == se.getNewRate()) || (0 == se.getProbability())) { - scheduleEdges.removeElement(se); - scheduleNodes.removeElement(se.getTarget()); + scheduleEdges.removeElement(se); + scheduleNodes.removeElement(se.getTarget()); } } @@ -654,13 +654,13 @@ public class ScheduleAnalysis { while(!toVisit.isEmpty()) { ScheduleNode sn = toVisit.poll(); if(sn.getCid() == -1) { - // not visited before - sn.setCid(ScheduleNode.colorID++); - Iterator it_edge = sn.edges(); - while(it_edge.hasNext()) { - toVisit.add((ScheduleNode)((ScheduleEdge)it_edge.next()).getTarget()); - } - it_edge = null; + // not visited before + sn.setCid(ScheduleNode.colorID++); + Iterator it_edge = sn.edges(); + while(it_edge.hasNext()) { + toVisit.add((ScheduleNode)((ScheduleEdge)it_edge.next()).getTarget()); + } + it_edge = null; } } toVisit = null; @@ -678,11 +678,11 @@ public class ScheduleAnalysis { long temptime = tempse.getListExeTime(); // find out the ScheduleEdge with least exeTime for(int k = 1; k < ses.size(); k++) { - long ttemp = ses.elementAt(k).getListExeTime(); - if(ttemp < temptime) { - tempse = ses.elementAt(k); - temptime = ttemp; - } // if(ttemp < temptime) + long ttemp = ses.elementAt(k).getListExeTime(); + if(ttemp < temptime) { + tempse = ses.elementAt(k); + temptime = ttemp; + } // if(ttemp < temptime) } // for(int k = 1; k < ses.size(); k++) // handle the tempse handleScheduleEdge(tempse, true); @@ -709,112 +709,112 @@ public class ScheduleAnalysis { for(i = scheduleEdges.size(); i > 0; i--) { ScheduleEdge se = (ScheduleEdge)scheduleEdges.elementAt(i-1); if(ScheduleEdge.NEWEDGE == se.getType()) { - if(preSNode == null) { - preSNode = (ScheduleNode)se.getSource(); - } - - boolean split = false; - FEdge fe = se.getFEdge(); - if(fe.getSource() == fe.getTarget()) { - // the associated start fe is a back edge - try { - // check the number of newly created objs - int repeat = (int)Math.ceil(se.getNewRate()*se.getProbability()/100); - int rate = 0; - /*if(repeat > 1) { - // more than one new objs, expand the new edge - for(int j = 1; j< repeat; j++ ) { - cloneSNodeList(se, true); - } // for(int j = 1; j< repeat; j++ ) - se.setNewRate(1); - se.setProbability(100); - } // if(repeat > 1)*/ - try { - // match the rates of obj creation and new obj consumption - rate = (int)Math.ceil( - se.getListExeTime()/calInExeTime(se.getSourceFState())); - } catch (Exception e) { - e.printStackTrace(); - } // try-catch {} - repeat = (rate > repeat)?rate:repeat; - // expand the new edge - for(int j = 1; j< repeat; j++ ) { - cloneSNodeList(se, true); - } // for(int j = 1; j< repeat; j++ ) - se.setNewRate(1); - se.setProbability(100); - /*for(int j = rate - 1; j > 0; j--) { - for(int k = repeat; k > 0; k--) { - cloneSNodeList(se, true); - } // for(int k = repeat; k > 0; k--) - } // for(int j = rate - 1; j > 0; j--)*/ - } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); - } // try-catch{} - } else { // if(fe.getSource() == fe.getTarget()) - // the associated start fe is not a back edge - // Note: if preSNode is not the same as se's source ScheduleNode - // handle any ScheduleEdges previously put into fe2ses whose source - // ScheduleNode is preSNode - boolean same = (preSNode == se.getSource()); - if(!same) { - // check the topology sort, only process those after se.getSource() - if(preSNode.getFinishingTime() < se.getSource().getFinishingTime()) { - if(sn2fes.containsKey(preSNode)) { - Vector fes = sn2fes.remove(preSNode); - for(int j = 0; j < fes.size(); j++) { - FEdge tempfe = fes.elementAt(j); - Vector ses = fe2ses.get(tempfe); - boolean isflag = !(preSNode.edges().hasNext()); - this.handleDescenSEs(ses, isflag); - ses = null; - fe2ses.remove(tempfe); - } // for(int j = 0; j < fes.size(); j++) - fes = null; - } - } - preSNode = (ScheduleNode)se.getSource(); - } // if(!same) - - if(fe.getTarget().edges().hasNext()) { - // not associated with the last task, check if to split the snode - if((!(se.getTransTime() < this.transThreshold)) - && (se.getSourceCNode().getTransTime() < se.getTransTime())) { - // it's better to transfer the other obj with preSnode - split = true; - splitSNode(se, true); - } - } // if(!fe.getTarget().edges().hasNext()) - - if(!split) { - // delay the expanding and merging until we find all such 'new' - // edges associated with a last task inside this ClassNode - if(fe2ses.get(fe) == null) { - fe2ses.put(fe, new Vector()); - } - if(sn2fes.get((ScheduleNode)se.getSource()) == null) { - sn2fes.put((ScheduleNode)se.getSource(), new Vector()); - } - if(!fe2ses.get(fe).contains(se)) { - fe2ses.get(fe).add(se); - } - if(!sn2fes.get((ScheduleNode)se.getSource()).contains(fe)) { - sn2fes.get((ScheduleNode)se.getSource()).add(fe); - } - } // if(!split) - } // if(fe.getSource() == fe.getTarget()) + if(preSNode == null) { + preSNode = (ScheduleNode)se.getSource(); + } + + boolean split = false; + FEdge fe = se.getFEdge(); + if(fe.getSource() == fe.getTarget()) { + // the associated start fe is a back edge + try { + // check the number of newly created objs + int repeat = (int)Math.ceil(se.getNewRate()*se.getProbability()/100); + int rate = 0; + /*if(repeat > 1) { + // more than one new objs, expand the new edge + for(int j = 1; j< repeat; j++ ) { + cloneSNodeList(se, true); + } // for(int j = 1; j< repeat; j++ ) + se.setNewRate(1); + se.setProbability(100); + } // if(repeat > 1)*/ + try { + // match the rates of obj creation and new obj consumption + rate = (int)Math.ceil( + se.getListExeTime()/calInExeTime(se.getSourceFState())); + } catch (Exception e) { + e.printStackTrace(); + } // try-catch {} + repeat = (rate > repeat)?rate:repeat; + // expand the new edge + for(int j = 1; j< repeat; j++ ) { + cloneSNodeList(se, true); + } // for(int j = 1; j< repeat; j++ ) + se.setNewRate(1); + se.setProbability(100); + /*for(int j = rate - 1; j > 0; j--) { + for(int k = repeat; k > 0; k--) { + cloneSNodeList(se, true); + } // for(int k = repeat; k > 0; k--) + } // for(int j = rate - 1; j > 0; j--)*/ + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } // try-catch{} + } else { // if(fe.getSource() == fe.getTarget()) + // the associated start fe is not a back edge + // Note: if preSNode is not the same as se's source ScheduleNode + // handle any ScheduleEdges previously put into fe2ses whose source + // ScheduleNode is preSNode + boolean same = (preSNode == se.getSource()); + if(!same) { + // check the topology sort, only process those after se.getSource() + if(preSNode.getFinishingTime() < se.getSource().getFinishingTime()) { + if(sn2fes.containsKey(preSNode)) { + Vector fes = sn2fes.remove(preSNode); + for(int j = 0; j < fes.size(); j++) { + FEdge tempfe = fes.elementAt(j); + Vector ses = fe2ses.get(tempfe); + boolean isflag = !(preSNode.edges().hasNext()); + this.handleDescenSEs(ses, isflag); + ses = null; + fe2ses.remove(tempfe); + } // for(int j = 0; j < fes.size(); j++) + fes = null; + } + } + preSNode = (ScheduleNode)se.getSource(); + } // if(!same) + + if(fe.getTarget().edges().hasNext()) { + // not associated with the last task, check if to split the snode + if((!(se.getTransTime() < this.transThreshold)) + && (se.getSourceCNode().getTransTime() < se.getTransTime())) { + // it's better to transfer the other obj with preSnode + split = true; + splitSNode(se, true); + } + } // if(!fe.getTarget().edges().hasNext()) + + if(!split) { + // delay the expanding and merging until we find all such 'new' + // edges associated with a last task inside this ClassNode + if(fe2ses.get(fe) == null) { + fe2ses.put(fe, new Vector()); + } + if(sn2fes.get((ScheduleNode)se.getSource()) == null) { + sn2fes.put((ScheduleNode)se.getSource(), new Vector()); + } + if(!fe2ses.get(fe).contains(se)) { + fe2ses.get(fe).add(se); + } + if(!sn2fes.get((ScheduleNode)se.getSource()).contains(fe)) { + sn2fes.get((ScheduleNode)se.getSource()).add(fe); + } + } // if(!split) + } // if(fe.getSource() == fe.getTarget()) } // if(ScheduleEdge.NEWEDGE == se.getType()) } // for(i = scheduleEdges.size(); i > 0; i--) if(!fe2ses.isEmpty()) { Set keys = fe2ses.keySet(); Iterator it_keys = keys.iterator(); while(it_keys.hasNext()) { - FEdge tempfe = (FEdge)it_keys.next(); - Vector ses = fe2ses.get(tempfe); - boolean isflag = !(tempfe.getTarget().edges().hasNext()); - this.handleDescenSEs(ses, isflag); - ses = null; + FEdge tempfe = (FEdge)it_keys.next(); + Vector ses = fe2ses.get(tempfe); + boolean isflag = !(tempfe.getTarget().edges().hasNext()); + this.handleDescenSEs(ses, isflag); + ses = null; } keys = null; it_keys = null; @@ -836,58 +836,58 @@ public class ScheduleAnalysis { int rate = 0; int repeat = (int)Math.ceil(se.getNewRate() * se.getProbability() / 100); if(merge) { - try { - if(se.getListExeTime() == 0) { - rate = repeat; - } else { - rate = (int)Math.ceil( - (se.getTransTime()-calInExeTime(se.getSourceFState())) - /se.getListExeTime()); - } - if(rate < 0 ) { - rate = 0; - } - } catch (Exception e) { - e.printStackTrace(); - } - if(0 == rate) { - // clone the whole ScheduleNode lists starting with se's target - for(int j = 1; j < repeat; j++ ) { - cloneSNodeList(se, true); - } - se.setNewRate(1); - se.setProbability(100); - } else { - repeat -= rate; - if(repeat > 0) { - // clone the whole ScheduleNode lists starting with se's target - for(int j = 0; j < repeat; j++ ) { - cloneSNodeList(se, true); - } - se.setNewRate(rate); - se.setProbability(100); - } - } - // merge the original ScheduleNode to the source ScheduleNode - ((ScheduleNode)se.getSource()).mergeSEdge(se); - scheduleNodes.remove(se.getTarget()); - scheduleEdges.remove(se); - // As se has been changed into an internal edge inside a ScheduleNode, - // change the source and target of se from original ScheduleNodes - // into ClassNodes. - if(se.getType() == ScheduleEdge.NEWEDGE) { - se.setTarget(se.getTargetCNode()); - //se.setSource(se.getSourceCNode()); - //se.getTargetCNode().addEdge(se); - se.getSourceCNode().addEdge(se); - } + try { + if(se.getListExeTime() == 0) { + rate = repeat; + } else { + rate = (int)Math.ceil( + (se.getTransTime()-calInExeTime(se.getSourceFState())) + /se.getListExeTime()); + } + if(rate < 0 ) { + rate = 0; + } + } catch (Exception e) { + e.printStackTrace(); + } + if(0 == rate) { + // clone the whole ScheduleNode lists starting with se's target + for(int j = 1; j < repeat; j++ ) { + cloneSNodeList(se, true); + } + se.setNewRate(1); + se.setProbability(100); + } else { + repeat -= rate; + if(repeat > 0) { + // clone the whole ScheduleNode lists starting with se's target + for(int j = 0; j < repeat; j++ ) { + cloneSNodeList(se, true); + } + se.setNewRate(rate); + se.setProbability(100); + } + } + // merge the original ScheduleNode to the source ScheduleNode + ((ScheduleNode)se.getSource()).mergeSEdge(se); + scheduleNodes.remove(se.getTarget()); + scheduleEdges.remove(se); + // As se has been changed into an internal edge inside a ScheduleNode, + // change the source and target of se from original ScheduleNodes + // into ClassNodes. + if(se.getType() == ScheduleEdge.NEWEDGE) { + se.setTarget(se.getTargetCNode()); + //se.setSource(se.getSourceCNode()); + //se.getTargetCNode().addEdge(se); + se.getSourceCNode().addEdge(se); + } } else { - // clone the whole ScheduleNode lists starting with se's target - for(int j = 1; j < repeat; j++ ) { - cloneSNodeList(se, true); - } - se.setNewRate(1); - se.setProbability(100); + // clone the whole ScheduleNode lists starting with se's target + for(int j = 1; j < repeat; j++ ) { + cloneSNodeList(se, true); + } + se.setNewRate(1); + se.setProbability(100); } } catch (Exception e) { e.printStackTrace(); @@ -909,34 +909,34 @@ public class ScheduleAnalysis { if(copyIE) { Vector inedges = sEdge.getTarget().getInedgeVector(); for(i = 0; i < inedges.size(); i++) { - ScheduleEdge tse = (ScheduleEdge)inedges.elementAt(i); - ScheduleEdge se; - switch(tse.getType()) { - case ScheduleEdge.NEWEDGE: { - se = new ScheduleEdge(csNode,"new",tse.getFstate(),tse.getType(),0); - se.setProbability(100); - se.setNewRate(1); - break; - } - - case ScheduleEdge.TRANSEDGE: { - se = new ScheduleEdge(csNode,"transmit",tse.getFstate(),tse.getType(),0); - se.setProbability(tse.getProbability()); - se.setNewRate(tse.getNewRate()); - break; - } - - default: { - throw new Exception("Error: not valid ScheduleEdge here"); - } - } - se.setSourceCNode(tse.getSourceCNode()); - se.setTargetCNode(cn2cn.get(tse.getTargetCNode())); - se.setFEdge(tse.getFEdge()); - se.setTargetFState(tse.getTargetFState()); - se.setIsclone(true); - tse.getSource().addEdge(se); - scheduleEdges.add(se); + ScheduleEdge tse = (ScheduleEdge)inedges.elementAt(i); + ScheduleEdge se; + switch(tse.getType()) { + case ScheduleEdge.NEWEDGE: { + se = new ScheduleEdge(csNode,"new",tse.getFstate(),tse.getType(),0); + se.setProbability(100); + se.setNewRate(1); + break; + } + + case ScheduleEdge.TRANSEDGE: { + se = new ScheduleEdge(csNode,"transmit",tse.getFstate(),tse.getType(),0); + se.setProbability(tse.getProbability()); + se.setNewRate(tse.getNewRate()); + break; + } + + default: { + throw new Exception("Error: not valid ScheduleEdge here"); + } + } + se.setSourceCNode(tse.getSourceCNode()); + se.setTargetCNode(cn2cn.get(tse.getTargetCNode())); + se.setFEdge(tse.getFEdge()); + se.setTargetFState(tse.getTargetFState()); + se.setIsclone(true); + tse.getSource().addEdge(se); + scheduleEdges.add(se); } inedges = null; } else { @@ -967,40 +967,40 @@ public class ScheduleAnalysis { // Clone all the external ScheduleEdges and the following ScheduleNodes Vector edges = osNode.getEdgeVector(); for(i = 0; i < edges.size(); i++) { - ScheduleEdge tse = (ScheduleEdge)edges.elementAt(i); - ScheduleNode tSNode = - (ScheduleNode)((ScheduleNode)tse.getTarget()).clone(tocn2cn, 0); - scheduleNodes.add(tSNode); - clone.add(tSNode); - toClone.add((ScheduleNode)tse.getTarget()); - origins.addElement((ScheduleNode)tse.getTarget()); - sn2sn.put((ScheduleNode)tse.getTarget(), tSNode); - qcn2cn.add(tocn2cn); - ScheduleEdge se = null; - switch(tse.getType()) { - case ScheduleEdge.NEWEDGE: { - se = new ScheduleEdge(tSNode,"new",tse.getFstate(),tse.getType(),0); - break; - } - - case ScheduleEdge.TRANSEDGE: { - se = new ScheduleEdge(tSNode,"transmit",tse.getFstate(),tse.getType(),0); - break; - } - - default: { - throw new Exception("Error: not valid ScheduleEdge here"); - } - } - se.setSourceCNode(cn2cn.get(tse.getSourceCNode())); - se.setTargetCNode(tocn2cn.get(tse.getTargetCNode())); - se.setFEdge(tse.getFEdge()); - se.setTargetFState(tse.getTargetFState()); - se.setProbability(tse.getProbability()); - se.setNewRate(tse.getNewRate()); - se.setIsclone(true); - csNode.addEdge(se); - scheduleEdges.add(se); + ScheduleEdge tse = (ScheduleEdge)edges.elementAt(i); + ScheduleNode tSNode = + (ScheduleNode)((ScheduleNode)tse.getTarget()).clone(tocn2cn, 0); + scheduleNodes.add(tSNode); + clone.add(tSNode); + toClone.add((ScheduleNode)tse.getTarget()); + origins.addElement((ScheduleNode)tse.getTarget()); + sn2sn.put((ScheduleNode)tse.getTarget(), tSNode); + qcn2cn.add(tocn2cn); + ScheduleEdge se = null; + switch(tse.getType()) { + case ScheduleEdge.NEWEDGE: { + se = new ScheduleEdge(tSNode,"new",tse.getFstate(),tse.getType(),0); + break; + } + + case ScheduleEdge.TRANSEDGE: { + se = new ScheduleEdge(tSNode,"transmit",tse.getFstate(),tse.getType(),0); + break; + } + + default: { + throw new Exception("Error: not valid ScheduleEdge here"); + } + } + se.setSourceCNode(cn2cn.get(tse.getSourceCNode())); + se.setTargetCNode(tocn2cn.get(tse.getTargetCNode())); + se.setFEdge(tse.getFEdge()); + se.setTargetFState(tse.getTargetFState()); + se.setProbability(tse.getProbability()); + se.setNewRate(tse.getNewRate()); + se.setIsclone(true); + csNode.addEdge(se); + scheduleEdges.add(se); } tocn2cn = null; edges = null; @@ -1025,14 +1025,14 @@ public class ScheduleAnalysis { // Now that there are associate ScheduleEdges, there may be // multiple inedges of a ClassNode if(inedges.size() > 1) { - throw new Exception("Error: ClassNode's inedges more than one!"); + throw new Exception("Error: ClassNode's inedges more than one!"); } if(inedges.size() > 0) { - ScheduleEdge sEdge = (ScheduleEdge)inedges.elementAt(0); - cNode = (ClassNode)sEdge.getSource(); - exeTime += cNode.getFlagStates().elementAt(0).getExeTime(); + ScheduleEdge sEdge = (ScheduleEdge)inedges.elementAt(0); + cNode = (ClassNode)sEdge.getSource(); + exeTime += cNode.getFlagStates().elementAt(0).getExeTime(); } else { - break; + break; } inedges = null; } @@ -1061,12 +1061,12 @@ public class ScheduleAnalysis { FlagState tfs = toiterate.poll(); Iterator it_edges = tfs.edges(); while(it_edges.hasNext()) { - FlagState temp = (FlagState)((FEdge)it_edges.next()).getTarget(); - if(!fStates.contains(temp)) { - fStates.add(temp); - toiterate.add(temp); - sfss.removeElement(temp); - } + FlagState temp = (FlagState)((FEdge)it_edges.next()).getTarget(); + if(!fStates.contains(temp)) { + fStates.add(temp); + toiterate.add(temp); + sfss.removeElement(temp); + } } it_edges = null; } @@ -1094,13 +1094,13 @@ public class ScheduleAnalysis { long ttime = tfs.getExeTime(); Iterator it_inedges = tfs.inedges(); while(it_inedges.hasNext()) { - FEdge fEdge = (FEdge)it_inedges.next(); - FlagState temp = (FlagState)fEdge.getSource(); - long time = fEdge.getExeTime() + ttime; - if(temp.getExeTime() > time) { - temp.setExeTime(time); - toiterate.add(temp); - } + FEdge fEdge = (FEdge)it_inedges.next(); + FlagState temp = (FlagState)fEdge.getSource(); + long time = fEdge.getExeTime() + ttime; + if(temp.getExeTime() > time) { + temp.setExeTime(time); + toiterate.add(temp); + } } it_inedges = null; } @@ -1128,23 +1128,23 @@ public class ScheduleAnalysis { rCNodes.addElement(sCNode); if(it_isEdges != null) { while(it_isEdges.hasNext()) { - ScheduleEdge tse = (ScheduleEdge)it_isEdges.next(); - if(rCNodes.contains(tse.getSourceCNode())) { - if(sCNode.equals(tse.getSourceCNode())) { - if (!(tse.getSourceFState().equals(fs)) - && (sFStates.contains(tse.getSourceFState()))) { - tse.setSource(cNode); - tse.setSourceCNode(cNode); - } else { - continue; - } - } - sNode.getScheduleEdges().addElement(tse); - sNode.getClassNodes().addElement(tse.getTargetCNode()); - rCNodes.addElement(tse.getTargetCNode()); - oldSNode.getClassNodes().removeElement(tse.getTargetCNode()); - toremove.addElement(tse); - } + ScheduleEdge tse = (ScheduleEdge)it_isEdges.next(); + if(rCNodes.contains(tse.getSourceCNode())) { + if(sCNode.equals(tse.getSourceCNode())) { + if (!(tse.getSourceFState().equals(fs)) + && (sFStates.contains(tse.getSourceFState()))) { + tse.setSource(cNode); + tse.setSourceCNode(cNode); + } else { + continue; + } + } + sNode.getScheduleEdges().addElement(tse); + sNode.getClassNodes().addElement(tse.getTargetCNode()); + rCNodes.addElement(tse.getTargetCNode()); + oldSNode.getClassNodes().removeElement(tse.getTargetCNode()); + toremove.addElement(tse); + } } } it_isEdges = null; @@ -1156,13 +1156,13 @@ public class ScheduleAnalysis { ScheduleEdge tse = (ScheduleEdge)it_sEdges.next(); if(!(tse.equals(se)) && !(tse.equals(sEdge)) && (tse.getSourceCNode().equals(sCNode))) { - if(!(tse.getSourceFState().equals(fs)) - && (sFStates.contains(tse.getSourceFState()))) { - tse.setSource(sNode); - tse.setSourceCNode(cNode); - sNode.getEdgeVector().addElement(tse); - toremove.add(tse); - } + if(!(tse.getSourceFState().equals(fs)) + && (sFStates.contains(tse.getSourceFState()))) { + tse.setSource(sNode); + tse.setSourceCNode(cNode); + sNode.getEdgeVector().addElement(tse); + toremove.add(tse); + } } } it_sEdges = null; @@ -1173,23 +1173,23 @@ public class ScheduleAnalysis { try { if(!copy) { - //merge se into its source ScheduleNode - sNode.setCid(((ScheduleNode)se.getSource()).getCid()); - ((ScheduleNode)se.getSource()).mergeSEdge(se); - scheduleNodes.remove(se.getTarget()); - scheduleEdges.removeElement(se); - // As se has been changed into an internal edge inside a ScheduleNode, - // change the source and target of se from original ScheduleNodes - // into ClassNodes. - if(se.getType() == ScheduleEdge.NEWEDGE) { - se.setTarget(se.getTargetCNode()); - //se.setSource(se.getSourceCNode()); - //se.getTargetCNode().addEdge(se); - se.getSourceCNode().addEdge(se); - } + //merge se into its source ScheduleNode + sNode.setCid(((ScheduleNode)se.getSource()).getCid()); + ((ScheduleNode)se.getSource()).mergeSEdge(se); + scheduleNodes.remove(se.getTarget()); + scheduleEdges.removeElement(se); + // As se has been changed into an internal edge inside a ScheduleNode, + // change the source and target of se from original ScheduleNodes + // into ClassNodes. + if(se.getType() == ScheduleEdge.NEWEDGE) { + se.setTarget(se.getTargetCNode()); + //se.setSource(se.getSourceCNode()); + //se.getTargetCNode().addEdge(se); + se.getSourceCNode().addEdge(se); + } } else { - sNode.setCid(ScheduleNode.colorID++); - handleScheduleEdge(se, true); + sNode.setCid(ScheduleNode.colorID++); + handleScheduleEdge(se, true); } } catch (Exception e) { e.printStackTrace(); @@ -1220,8 +1220,8 @@ public class ScheduleAnalysis { this.scheduleGraphs.addElement(this.scheduleNodes); int gid = 1; if(this.state.PRINTSCHEDULING) { - String path = this.state.outputdir + "scheduling_" + gid + ".dot"; - SchedulingUtil.printScheduleGraph(path, this.scheduleNodes); + String path = this.state.outputdir + "scheduling_" + gid + ".dot"; + SchedulingUtil.printScheduleGraph(path, this.scheduleNodes); } return false; } else { @@ -1235,108 +1235,108 @@ public class ScheduleAnalysis { boolean isBig = Math.pow(this.coreNum, reduceNum) > 1000; Random rand = new Random(); if(isBig && state.BAMBOOCOMPILETIME) { - CombinationUtil.RootsGenerator rGen = - CombinationUtil.allocateRootsGenerator(sNodeVecs, - this.coreNum); - while((gid <= this.scheduleThreshold) && (rGen.nextGen())) { - // first get the chosen rootNodes - Vector> rootNodes = rGen.getRootNodes(); - Vector> nodes2combine = rGen.getNode2Combine(); - - CombinationUtil.CombineGenerator cGen = - CombinationUtil.allocateCombineGenerator(rootNodes, - nodes2combine); - while((gid <= this.scheduleThreshold) && (cGen.randomGenE())) { - boolean implement = true; - /*if(isBig) { - implement = Math.abs(rand.nextInt()) % 100 > generateThreshold; - }*/ - if(implement) { - Vector> combine = cGen.getCombine(); - Vector sNodes = - SchedulingUtil.generateScheduleGraph(this.state, - this.scheduleNodes, - this.scheduleEdges, - rootNodes, - combine, - gid++); - this.scheduleGraphs.add(sNodes); - sNodes = null; - combine = null; - } else if(Math.abs(rand.nextInt()) % 100 > skipThreshold) { - break; - } - } - cGen.clear(); - rootNodes = null; - nodes2combine = null; - } - rGen.clear(); - sNodeVecs = null; + CombinationUtil.RootsGenerator rGen = + CombinationUtil.allocateRootsGenerator(sNodeVecs, + this.coreNum); + while((gid <= this.scheduleThreshold) && (rGen.nextGen())) { + // first get the chosen rootNodes + Vector> rootNodes = rGen.getRootNodes(); + Vector> nodes2combine = rGen.getNode2Combine(); + + CombinationUtil.CombineGenerator cGen = + CombinationUtil.allocateCombineGenerator(rootNodes, + nodes2combine); + while((gid <= this.scheduleThreshold) && (cGen.randomGenE())) { + boolean implement = true; + /*if(isBig) { + implement = Math.abs(rand.nextInt()) % 100 > generateThreshold; + }*/ + if(implement) { + Vector> combine = cGen.getCombine(); + Vector sNodes = + SchedulingUtil.generateScheduleGraph(this.state, + this.scheduleNodes, + this.scheduleEdges, + rootNodes, + combine, + gid++); + this.scheduleGraphs.add(sNodes); + sNodes = null; + combine = null; + } else if(Math.abs(rand.nextInt()) % 100 > skipThreshold) { + break; + } + } + cGen.clear(); + rootNodes = null; + nodes2combine = null; + } + rGen.clear(); + sNodeVecs = null; } else if (false) { - CombinationUtil.RandomGenerator rGen = - CombinationUtil.allocateRandomGenerator(sNodeVecs, - this.coreNum); - // random genenration - while((gid <= this.scheduleThreshold) && (rGen.nextGen())) { - Vector> mapping = rGen.getMapping(); - boolean implement = true; - if(isBig) { - implement = Math.abs(rand.nextInt()) % 100 > generateThreshold; - } - if(implement) { - Vector sNodes = - SchedulingUtil.generateScheduleGraph(this.state, - this.scheduleNodes, - this.scheduleEdges, - mapping, - gid++); - this.scheduleGraphs.add(sNodes); - sNodes = null; - } - mapping = null; - } - rGen.clear(); - sNodeVecs = null; + CombinationUtil.RandomGenerator rGen = + CombinationUtil.allocateRandomGenerator(sNodeVecs, + this.coreNum); + // random genenration + while((gid <= this.scheduleThreshold) && (rGen.nextGen())) { + Vector> mapping = rGen.getMapping(); + boolean implement = true; + if(isBig) { + implement = Math.abs(rand.nextInt()) % 100 > generateThreshold; + } + if(implement) { + Vector sNodes = + SchedulingUtil.generateScheduleGraph(this.state, + this.scheduleNodes, + this.scheduleEdges, + mapping, + gid++); + this.scheduleGraphs.add(sNodes); + sNodes = null; + } + mapping = null; + } + rGen.clear(); + sNodeVecs = null; } else { - CombinationUtil.RootsGenerator rGen = - CombinationUtil.allocateRootsGenerator(sNodeVecs, - this.coreNum); - while((!isBig || (gid <= this.scheduleThreshold)) && (rGen.nextGen())) { - // first get the chosen rootNodes - Vector> rootNodes = rGen.getRootNodes(); - Vector> nodes2combine = rGen.getNode2Combine(); - - CombinationUtil.CombineGenerator cGen = - CombinationUtil.allocateCombineGenerator(rootNodes, - nodes2combine); - while((!isBig || (gid <= this.scheduleThreshold)) && (cGen.nextGen())) { - boolean implement = true; - if(isBig) { - implement = Math.abs(rand.nextInt()) % 100 > generateThreshold; - } - if(implement) { - Vector> combine = cGen.getCombine(); - Vector sNodes = - SchedulingUtil.generateScheduleGraph(this.state, - this.scheduleNodes, - this.scheduleEdges, - rootNodes, - combine, - gid++); - this.scheduleGraphs.add(sNodes); - sNodes = null; - combine = null; - } else if(Math.abs(rand.nextInt()) % 100 > skipThreshold) { - break; - } - } - cGen.clear(); - rootNodes = null; - nodes2combine = null; - } - rGen.clear(); - sNodeVecs = null; + CombinationUtil.RootsGenerator rGen = + CombinationUtil.allocateRootsGenerator(sNodeVecs, + this.coreNum); + while((!isBig || (gid <= this.scheduleThreshold)) && (rGen.nextGen())) { + // first get the chosen rootNodes + Vector> rootNodes = rGen.getRootNodes(); + Vector> nodes2combine = rGen.getNode2Combine(); + + CombinationUtil.CombineGenerator cGen = + CombinationUtil.allocateCombineGenerator(rootNodes, + nodes2combine); + while((!isBig || (gid <= this.scheduleThreshold)) && (cGen.nextGen())) { + boolean implement = true; + if(isBig) { + implement = Math.abs(rand.nextInt()) % 100 > generateThreshold; + } + if(implement) { + Vector> combine = cGen.getCombine(); + Vector sNodes = + SchedulingUtil.generateScheduleGraph(this.state, + this.scheduleNodes, + this.scheduleEdges, + rootNodes, + combine, + gid++); + this.scheduleGraphs.add(sNodes); + sNodes = null; + combine = null; + } else if(Math.abs(rand.nextInt()) % 100 > skipThreshold) { + break; + } + } + cGen.clear(); + rootNodes = null; + nodes2combine = null; + } + rGen.clear(); + sNodeVecs = null; } return isBig; } @@ -1355,7 +1355,7 @@ public class ScheduleAnalysis { this.m_probability = new double[this.m_numofexits]; this.m_newobjinfo = new Vector>(); for(int i = 0; i < this.m_numofexits; i++) { - this.m_newobjinfo.add(null); + this.m_newobjinfo.add(null); } this.m_byObj = -1; } diff --git a/Robust/src/Analysis/Scheduling/ScheduleEdge.java b/Robust/src/Analysis/Scheduling/ScheduleEdge.java index 2d4a5cfc..b33bf9fc 100644 --- a/Robust/src/Analysis/Scheduling/ScheduleEdge.java +++ b/Robust/src/Analysis/Scheduling/ScheduleEdge.java @@ -141,9 +141,9 @@ public class ScheduleEdge extends Edge { if (o instanceof ScheduleEdge) { ScheduleEdge e=(ScheduleEdge)o; if(e.gid == this.gid) { - if(e.uid != this.uid) { - return false; - } + if(e.uid != this.uid) { + return false; + } } if ((e.label.equals(label))&& (e.target.equals(target))&& @@ -156,17 +156,17 @@ public class ScheduleEdge extends Edge { (e.type == type) && (e.transTime == transTime) && (e.listExeTime == listExeTime)) - if(e.targetFState != null) { - if(!e.targetFState.equals(targetFState)) { - return false; - } - } else if(this.targetFState != null) { - return false; - } + if(e.targetFState != null) { + if(!e.targetFState.equals(targetFState)) { + return false; + } + } else if(this.targetFState != null) { + return false; + } if(e.fedge != null) { - return e.fedge.equals(fedge); + return e.fedge.equals(fedge); } else if(this.fedge == null) { - return true; + return true; } } return false; @@ -208,13 +208,13 @@ public class ScheduleEdge extends Edge { Iterator it_edges = this.getTarget().edges(); long temp = 0; if(it_edges.hasNext()) { - temp = ((ScheduleEdge)it_edges.next()).getListExeTime(); + temp = ((ScheduleEdge)it_edges.next()).getListExeTime(); } while(it_edges.hasNext()) { - long tetime = ((ScheduleEdge)it_edges.next()).getListExeTime(); - if(temp < tetime) { - temp = tetime; - } + long tetime = ((ScheduleEdge)it_edges.next()).getListExeTime(); + if(temp < tetime) { + temp = tetime; + } } listExeTime += temp; } diff --git a/Robust/src/Analysis/Scheduling/ScheduleNode.java b/Robust/src/Analysis/Scheduling/ScheduleNode.java index 11365f16..a756e722 100644 --- a/Robust/src/Analysis/Scheduling/ScheduleNode.java +++ b/Robust/src/Analysis/Scheduling/ScheduleNode.java @@ -122,12 +122,12 @@ public class ScheduleNode extends GraphNode implements Cloneable { // insert tomerge in accent order int j = mergedcids.size() - 1; for(; j > 0; j--) { - int tmp = mergedcids.elementAt(j-1); - if(tmp > tomerge) { - mergedcids.setElementAt(tmp, j); - } else { - break; - } + int tmp = mergedcids.elementAt(j-1); + if(tmp > tomerge) { + mergedcids.setElementAt(tmp, j); + } else { + break; + } } mergedcids.setElementAt(tomerge, j); } @@ -140,9 +140,9 @@ public class ScheduleNode extends GraphNode implements Cloneable { public long getExeTime() { if(this.executionTime == -1) { try { - calExeTime(); + calExeTime(); } catch (Exception e) { - e.printStackTrace(); + e.printStackTrace(); } } return this.executionTime; @@ -166,22 +166,22 @@ public class ScheduleNode extends GraphNode implements Cloneable { if (o instanceof ScheduleNode) { ScheduleNode fs=(ScheduleNode)o; if(fs.gid == this.gid) { - if(fs.uid != this.uid) { - return false; - } - if(fs.cid != this.cid) { - return false; - } + if(fs.uid != this.uid) { + return false; + } + if(fs.cid != this.cid) { + return false; + } } if ((fs.executionTime != this.executionTime)) { - return false; + return false; } if(fs.classNodes != null) { - if(!fs.classNodes.equals(classNodes)) { - return false; - } + if(!fs.classNodes.equals(classNodes)) { + return false; + } } else if(classNodes != null) { - return false; + return false; } return true; } @@ -235,25 +235,25 @@ public class ScheduleNode extends GraphNode implements Cloneable { ScheduleEdge se = null; switch(temp.getType()) { case ScheduleEdge.NEWEDGE: { - se = new ScheduleEdge(o, - "new", - temp.getFstate(), - ScheduleEdge.NEWEDGE, - gid); - se.setProbability(temp.getProbability()); - se.setNewRate(temp.getNewRate()); - break; + se = new ScheduleEdge(o, + "new", + temp.getFstate(), + ScheduleEdge.NEWEDGE, + gid); + se.setProbability(temp.getProbability()); + se.setNewRate(temp.getNewRate()); + break; } case ScheduleEdge.TRANSEDGE: { - se = new ScheduleEdge(o, - "transmit", - temp.getFstate(), - ScheduleEdge.TRANSEDGE, - gid); - se.setProbability(temp.getProbability()); - se.setNewRate(temp.getNewRate()); - break; + se = new ScheduleEdge(o, + "transmit", + temp.getFstate(), + ScheduleEdge.TRANSEDGE, + gid); + se.setProbability(temp.getProbability()); + se.setNewRate(temp.getNewRate()); + break; } } se.setSourceCNode(cn2cn.get(temp.getSourceCNode())); @@ -291,10 +291,10 @@ public class ScheduleNode extends GraphNode implements Cloneable { scheduleEdges = targetSEdges; } else { if(targetCNodes.size() != 0) { - classNodes.addAll(targetCNodes); + classNodes.addAll(targetCNodes); } if(targetSEdges.size() != 0) { - scheduleEdges.addAll(targetSEdges); + scheduleEdges.addAll(targetSEdges); } } targetCNodes = null; @@ -321,40 +321,40 @@ public class ScheduleNode extends GraphNode implements Cloneable { Queue toiterate = new LinkedList(); toiterate.add(sfs); while(!toiterate.isEmpty()) { - FlagState tmpfs = toiterate.poll(); - long ttime = tmpfs.getExeTime(); - Iterator it_inedges = tmpfs.inedges(); - while(it_inedges.hasNext()) { - FEdge fEdge = (FEdge)it_inedges.next(); - FlagState temp = (FlagState)fEdge.getSource(); - long time = fEdge.getExeTime() + ttime; - if(temp.getExeTime() > time) { - temp.setExeTime(time); - toiterate.add(temp); - } - } - it_inedges = null; + FlagState tmpfs = toiterate.poll(); + long ttime = tmpfs.getExeTime(); + Iterator it_inedges = tmpfs.inedges(); + while(it_inedges.hasNext()) { + FEdge fEdge = (FEdge)it_inedges.next(); + FlagState temp = (FlagState)fEdge.getSource(); + long time = fEdge.getExeTime() + ttime; + if(temp.getExeTime() > time) { + temp.setExeTime(time); + toiterate.add(temp); + } + } + it_inedges = null; } toiterate = null; // redirct internal ScheduleEdge from tcn to scn for(int i = 0; i < targetSEdges.size(); ++i) { - ScheduleEdge tmpse = targetSEdges.elementAt(i); - if(tmpse.getSourceCNode().equals(tcn)) { - tmpse.setSourceCNode(scn); - } + ScheduleEdge tmpse = targetSEdges.elementAt(i); + if(tmpse.getSourceCNode().equals(tcn)) { + tmpse.setSourceCNode(scn); + } } // redirect external ScheduleEdges to this ScheduleNode // and scn if it is originally from tcn Iterator it_edges = sn.edges(); while(it_edges.hasNext()) { - ScheduleEdge tse = (ScheduleEdge)it_edges.next(); - tse.setSource(this); - if(tse.getSourceCNode().equals(tcn)) { - tse.setSourceCNode(scn); - } - this.edges.addElement(tse); + ScheduleEdge tse = (ScheduleEdge)it_edges.next(); + tse.setSource(this); + if(tse.getSourceCNode().equals(tcn)) { + tse.setSourceCNode(scn); + } + this.edges.addElement(tse); } it_edges = null; @@ -363,10 +363,10 @@ public class ScheduleNode extends GraphNode implements Cloneable { // As all tasks inside one ScheduleNode are executed sequentially, // simply add the execution time of all the ClassNodes inside one ScheduleNode. if(this.executionTime == -1) { - throw new Exception("Error: ScheduleNode without initiate execution time when analysising."); + throw new Exception("Error: ScheduleNode without initiate execution time when analysising."); } if(this.executionTime < sn.getExeTime()) { - this.executionTime = sn.getExeTime(); + this.executionTime = sn.getExeTime(); } } else if(ScheduleEdge.NEWEDGE == se.getType()) { targetSEdges = null; @@ -377,16 +377,16 @@ public class ScheduleNode extends GraphNode implements Cloneable { this.removeEdge(se); Iterator it_edges = sn.edges(); while(it_edges.hasNext()) { - ScheduleEdge tse = (ScheduleEdge)it_edges.next(); - tse.setSource(this); - this.edges.addElement(tse); + ScheduleEdge tse = (ScheduleEdge)it_edges.next(); + tse.setSource(this); + this.edges.addElement(tse); } it_edges = null; // As all tasks inside one ScheduleNode are executed sequentially, // simply add the execution time of all the ClassNodes inside one ScheduleNode. if(this.executionTime == -1) { - this.executionTime = 0; + this.executionTime = 0; } this.executionTime += ((ScheduleNode)se.getTarget()).getExeTime(); } @@ -405,10 +405,10 @@ public class ScheduleNode extends GraphNode implements Cloneable { scheduleEdges = targetSEdges; } else { if(targetCNodes.size() != 0) { - classNodes.addAll(targetCNodes); + classNodes.addAll(targetCNodes); } if(targetSEdges.size() != 0) { - scheduleEdges.addAll(targetSEdges); + scheduleEdges.addAll(targetSEdges); } } targetCNodes = null; @@ -457,11 +457,11 @@ public class ScheduleNode extends GraphNode implements Cloneable { Vector toremove = new Vector(); if(it_innersEdges != null) { while(it_innersEdges.hasNext()) { - ScheduleEdge tse = (ScheduleEdge)it_innersEdges.next(); - if((cd.equals(tse.getSourceCNode())) || (cd.equals(tse.getTargetCNode()))) { - // related edge - toremove.addElement(tse); - } + ScheduleEdge tse = (ScheduleEdge)it_innersEdges.next(); + if((cd.equals(tse.getSourceCNode())) || (cd.equals(tse.getTargetCNode()))) { + // related edge + toremove.addElement(tse); + } } } it_innersEdges = null; @@ -469,13 +469,13 @@ public class ScheduleNode extends GraphNode implements Cloneable { for(int i = 0; i < toremove.size(); i++) { ScheduleEdge tse = toremove.elementAt(i); if(cd.equals(tse.getSourceCNode())) { - // outedge - tse.setTarget(this); - sNode.addEdge(tse); + // outedge + tse.setTarget(this); + sNode.addEdge(tse); } else if(cd.equals(tse.getTargetCNode())) { - // inedge - tse.setTarget(sNode); - this.addEdge(tse); + // inedge + tse.setTarget(sNode); + this.addEdge(tse); } } toremove.clear(); @@ -485,11 +485,11 @@ public class ScheduleNode extends GraphNode implements Cloneable { while(it_exsEdges.hasNext()) { ScheduleEdge tse = (ScheduleEdge)it_exsEdges.next(); if(tse.getSourceCNode().equals(cd)) { - toremove.add(tse); - //this.removeEdge(tse); - //sNode.addEdge(tse); - tse.setSource(sNode); - sNode.edges.addElement(tse); + toremove.add(tse); + //this.removeEdge(tse); + //sNode.addEdge(tse); + tse.setSource(sNode); + sNode.edges.addElement(tse); } } this.edges.removeAll(toremove); @@ -501,9 +501,9 @@ public class ScheduleNode extends GraphNode implements Cloneable { while(it_insEdges.hasNext()) { ScheduleEdge tse = (ScheduleEdge)it_insEdges.next(); if(tse.getTargetCNode().equals(cd)) { - toremove.add(tse); - tse.setTarget(sNode); - sNode.inedges.addElement(tse); + toremove.add(tse); + tse.setTarget(sNode); + sNode.inedges.addElement(tse); } } it_insEdges = null; diff --git a/Robust/src/Analysis/Scheduling/ScheduleSimulator.java b/Robust/src/Analysis/Scheduling/ScheduleSimulator.java index 034a5612..e32248c0 100644 --- a/Robust/src/Analysis/Scheduling/ScheduleSimulator.java +++ b/Robust/src/Analysis/Scheduling/ScheduleSimulator.java @@ -76,17 +76,17 @@ public class ScheduleSimulator { Iterator it_fStates = this.taskanalysis.getFlagStates(cd).iterator(); while(it_fStates.hasNext()) { - FlagState fs = it_fStates.next(); - if(!this.fstates.contains(fs)) { - this.fstates.addElement(fs); - } - Iterator it_fe = (Iterator)fs.edges(); - while(it_fe.hasNext()) { - FEdge next = it_fe.next(); - if(!this.fedges.contains(next)) { - this.fedges.addElement(next); - } - } + FlagState fs = it_fStates.next(); + if(!this.fstates.contains(fs)) { + this.fstates.addElement(fs); + } + Iterator it_fe = (Iterator)fs.edges(); + while(it_fe.hasNext()) { + FEdge next = it_fe.next(); + if(!this.fedges.contains(next)) { + this.fedges.addElement(next); + } + } } } } @@ -131,23 +131,23 @@ public class ScheduleSimulator { Vector scheduling = (Vector)it_scheduling.next(); if(!state.BAMBOOCOMPILETIME) { - System.out.println("Scheduling index:" + scheduling.elementAt(0).getGid()); + System.out.println("Scheduling index:" + scheduling.elementAt(0).getGid()); } this.setScheduling(scheduling); Vector simexegraph = new Vector(); Vector checkpoints = new Vector(); long tmpTime = process(checkpoints, simexegraph); if(tmpTime < processTime) { - selectedScheduling.clear(); - selectedScheduling.add(index); - selectedSimExeGraphs.clear(); - selectedSimExeGraphs.add(simexegraph.elementAt(0)); - processTime = tmpTime; + selectedScheduling.clear(); + selectedScheduling.add(index); + selectedSimExeGraphs.clear(); + selectedSimExeGraphs.add(simexegraph.elementAt(0)); + processTime = tmpTime; } else if(tmpTime == processTime) { - if(!selectedScheduling.contains(index)) { - selectedScheduling.add(index); - selectedSimExeGraphs.add(simexegraph.elementAt(0)); - } + if(!selectedScheduling.contains(index)) { + selectedScheduling.add(index); + selectedSimExeGraphs.add(simexegraph.elementAt(0)); + } } scheduling = null; checkpoints.clear(); @@ -161,8 +161,8 @@ public class ScheduleSimulator { if(!state.BAMBOOCOMPILETIME) { System.out.print("Selected schedulings with least exectution time " + processTime + ": \n\t"); for(int i = 0; i < selectedScheduling.size(); i++) { - int gid = schedulings.elementAt(selectedScheduling.elementAt(i)).elementAt(0).getGid(); - System.out.print(gid + ", "); + int gid = schedulings.elementAt(selectedScheduling.elementAt(i)).elementAt(0).getGid(); + System.out.print(gid + ", "); } System.out.println(); } @@ -205,14 +205,14 @@ public class ScheduleSimulator { } if(this.cores != null) { for(int i = 0; i < this.coreNum; i++) { - CoreSimulator core = this.cores.elementAt(i); - core.reset(); - core.setRSchedule(FIFORSchedule.getFIFORSchedule()); + CoreSimulator core = this.cores.elementAt(i); + core.reset(); + core.setRSchedule(FIFORSchedule.getFIFORSchedule()); } } else { this.cores = new Vector(this.coreNum); for(int i = 0; i < this.coreNum; i++) { - this.cores.add(new CoreSimulator(FIFORSchedule.getFIFORSchedule(), i)); + this.cores.add(new CoreSimulator(FIFORSchedule.getFIFORSchedule(), i)); } } @@ -284,7 +284,7 @@ public class ScheduleSimulator { CoreSimulator cs = this.cores.elementAt(i); TaskSimulator task = cs.process(); if(task != null) { - this.tasks.add(task); + this.tasks.add(task); } lastseNodes[i] = null; } @@ -300,12 +300,12 @@ public class ScheduleSimulator { task); cp.addAction(action); if(!(task instanceof TransTaskSimulator)) { - cp.removeSpareCore(coreid); - SimExecutionNode seNode = new SimExecutionNode(coreid, this.processTime); - seNode.setSpareCores(cp.getSpareCores()); - senode2action.put(seNode, action); - action2exetime.put(action, (long)-1); - lastseNodes[coreid] = seNode; + cp.removeSpareCore(coreid); + SimExecutionNode seNode = new SimExecutionNode(coreid, this.processTime); + seNode.setSpareCores(cp.getSpareCores()); + senode2action.put(seNode, action); + action2exetime.put(action, (long)-1); + lastseNodes[coreid] = seNode; } } checkpoints.add(cp); @@ -313,7 +313,7 @@ public class ScheduleSimulator { while(true) { // if no more tasks on each core, simulation finish if(this.tasks.size() == 0) { - break; + break; } // for each task in todo queue, decide the execution path of this time @@ -321,16 +321,16 @@ public class ScheduleSimulator { long finishTime = Long.MAX_VALUE; Vector finishTasks = new Vector(); for(i = 0; i < this.tasks.size(); i++) { - TaskSimulator task = this.tasks.elementAt(i); - task.process(); - long tempTime = task.getCurrentRun().getFinishTime(); - if(tempTime < finishTime) { - finishTime = tempTime; - finishTasks.clear(); - finishTasks.add(task); - } else if (tempTime == finishTime) { - finishTasks.add(task); - } + TaskSimulator task = this.tasks.elementAt(i); + task.process(); + long tempTime = task.getCurrentRun().getFinishTime(); + if(tempTime < finishTime) { + finishTime = tempTime; + finishTasks.clear(); + finishTasks.add(task); + } else if (tempTime == finishTime) { + finishTasks.add(task); + } } // advance to next finish point @@ -338,74 +338,74 @@ public class ScheduleSimulator { cp = new CheckPoint(this.processTime, this.coreNum); for(i = 0; i < this.tasks.size(); i++) { - TaskSimulator task = this.tasks.elementAt(i); - if(!finishTasks.contains(task)) { - task.getCs().updateTask(finishTime); - if(!(task instanceof TransTaskSimulator)) { - cp.removeSpareCore(task.getCs().getCoreNum()); - } - } + TaskSimulator task = this.tasks.elementAt(i); + if(!finishTasks.contains(task)) { + task.getCs().updateTask(finishTime); + if(!(task instanceof TransTaskSimulator)) { + cp.removeSpareCore(task.getCs().getCoreNum()); + } + } } Action action = null; for(i = 0; i < finishTasks.size(); i++) { - TaskSimulator task = finishTasks.elementAt(i); - this.tasks.removeElement(task); - if(task instanceof TransTaskSimulator) { - // handle TransTaskSimulator task's completion - finishTransTaskSimulator(task, - cp, - senode2action, - lastseNodes, - action2exetime, - tttask2senode, - obj2transtime); - } else { - CoreSimulator cs = task.getCs(); - Vector tttasks = new Vector(); - - Vector transObjs = null; - if(task.getCurrentRun().getExetype() == 0) { - // normal execution of a task - transObjs = finishTaskNormal(task, - cp, - tttasks, - senode2action, - lastseNodes, - action2exetime); - } else if (task.getCurrentRun().getExetype() == 1) { - // task abort - finishTaskAbnormal(cs, - cp, - senode2action, - lastseNodes, - action2exetime, - Action.TASKABORT); - } else if (task.getCurrentRun().getExetype() == 2) { - // task remove - finishTaskAbnormal(cs, - cp, - senode2action, - lastseNodes, - action2exetime, - Action.TASKREMOVE); - } - - // Choose a new task for this core - generateNewTask(cs, - cp, - transObjs, - tttasks, - senode2action, - lastseNodes, - action2exetime, - tttask2senode, - obj2transtime, - obj2lastseedge); - tttasks.clear(); - tttasks = null; - transObjs = null; - } // end of if(task instanceof TransTaskSimulator) else + TaskSimulator task = finishTasks.elementAt(i); + this.tasks.removeElement(task); + if(task instanceof TransTaskSimulator) { + // handle TransTaskSimulator task's completion + finishTransTaskSimulator(task, + cp, + senode2action, + lastseNodes, + action2exetime, + tttask2senode, + obj2transtime); + } else { + CoreSimulator cs = task.getCs(); + Vector tttasks = new Vector(); + + Vector transObjs = null; + if(task.getCurrentRun().getExetype() == 0) { + // normal execution of a task + transObjs = finishTaskNormal(task, + cp, + tttasks, + senode2action, + lastseNodes, + action2exetime); + } else if (task.getCurrentRun().getExetype() == 1) { + // task abort + finishTaskAbnormal(cs, + cp, + senode2action, + lastseNodes, + action2exetime, + Action.TASKABORT); + } else if (task.getCurrentRun().getExetype() == 2) { + // task remove + finishTaskAbnormal(cs, + cp, + senode2action, + lastseNodes, + action2exetime, + Action.TASKREMOVE); + } + + // Choose a new task for this core + generateNewTask(cs, + cp, + transObjs, + tttasks, + senode2action, + lastseNodes, + action2exetime, + tttask2senode, + obj2transtime, + obj2lastseedge); + tttasks.clear(); + tttasks = null; + transObjs = null; + } // end of if(task instanceof TransTaskSimulator) else } checkpoints.add(cp); finishTasks = null; @@ -418,48 +418,48 @@ public class ScheduleSimulator { SimExecutionNode lastsenode = lastseNodes[j]; // create edges between previous senode on this core to this node if(lastsenode != null) { - Action tmpaction = senode2action.get(lastsenode); - long weight = tmpaction != null?action2exetime.get(tmpaction):0; // TODO ???? - SimExecutionEdge seEdge = new SimExecutionEdge(seNode, - lastsenode.getCoreNum(), - tmpaction != null?tmpaction.getTd():null, - weight, - tmpaction != null?tmpaction.getTaskParams():null); - lastsenode.addEdge(seEdge); - - // setup data dependencies for the task - Vector taskparams = seEdge.getTaskparams(); - if(taskparams != null) { - for(int k = 0; k < taskparams.size(); k++) { - Integer tparam = taskparams.elementAt(k); - SimExecutionEdge lastedge = obj2lastseedge.get(tparam); - if(lastedge != null) { - if(lastedge.getCoreNum() != seEdge.getCoreNum()) { - // the obj is transferred from another core - // create an seEdge for this transfer - long transweight = obj2transtime.get(tparam); - SimExecutionEdge transseEdge = new SimExecutionEdge((SimExecutionNode)seEdge.getSource(), - lastedge.getCoreNum(), - null, // TODO: not sure if this is enough - transweight, - null); - if(((SimExecutionNode)seEdge.getSource()).getTimepoint() < - ((SimExecutionNode)lastedge.getTarget()).getTimepoint()) { - System.err.println("ScheduleSimulator:393"); - System.exit(-1); - } - lastedge.getTarget().addEdge(transseEdge); - transseEdge.addPredicate(lastedge); - seEdge.addPredicate(transseEdge); - } else { - seEdge.addPredicate(lastedge); - } - } - // update the last edge associated to the parameter obj - obj2lastseedge.put(tparam, seEdge); - } - } - taskparams = null; + Action tmpaction = senode2action.get(lastsenode); + long weight = tmpaction != null?action2exetime.get(tmpaction):0; // TODO ???? + SimExecutionEdge seEdge = new SimExecutionEdge(seNode, + lastsenode.getCoreNum(), + tmpaction != null?tmpaction.getTd():null, + weight, + tmpaction != null?tmpaction.getTaskParams():null); + lastsenode.addEdge(seEdge); + + // setup data dependencies for the task + Vector taskparams = seEdge.getTaskparams(); + if(taskparams != null) { + for(int k = 0; k < taskparams.size(); k++) { + Integer tparam = taskparams.elementAt(k); + SimExecutionEdge lastedge = obj2lastseedge.get(tparam); + if(lastedge != null) { + if(lastedge.getCoreNum() != seEdge.getCoreNum()) { + // the obj is transferred from another core + // create an seEdge for this transfer + long transweight = obj2transtime.get(tparam); + SimExecutionEdge transseEdge = new SimExecutionEdge((SimExecutionNode)seEdge.getSource(), + lastedge.getCoreNum(), + null, // TODO: not sure if this is enough + transweight, + null); + if(((SimExecutionNode)seEdge.getSource()).getTimepoint() < + ((SimExecutionNode)lastedge.getTarget()).getTimepoint()) { + System.err.println("ScheduleSimulator:393"); + System.exit(-1); + } + lastedge.getTarget().addEdge(transseEdge); + transseEdge.addPredicate(lastedge); + seEdge.addPredicate(transseEdge); + } else { + seEdge.addPredicate(lastedge); + } + } + // update the last edge associated to the parameter obj + obj2lastseedge.put(tparam, seEdge); + } + } + taskparams = null; } lastseNodes[j] = null; } @@ -488,7 +488,7 @@ public class ScheduleSimulator { System.out.println("\tTotal execution time is: " + this.processTime); System.out.println("\tUtility of cores: "); for(int j = 0; j < this.cores.size(); j++) { - System.out.println("\t\tcore" + j + ": " + getUtility(j) + "%"); + System.out.println("\t\tcore" + j + ": " + getUtility(j) + "%"); } } @@ -524,42 +524,42 @@ public class ScheduleSimulator { if(this.cores.elementAt(targetCoreNum).getRtask() == null) { TaskSimulator newTask = this.cores.elementAt(targetCoreNum).process(); if(newTask != null) { - this.tasks.add(newTask); - // add a TASKSTART action into this checkpoint - action = new Action(targetCoreNum, - Action.TASKSTART, - newTask); - cp.addAction(action); - if(!(newTask instanceof TransTaskSimulator)) { - cp.removeSpareCore(targetCoreNum); - SimExecutionNode seNode = new SimExecutionNode(targetCoreNum, this.processTime); - seNode.setSpareCores(cp.getSpareCores()); - senode2action.put(seNode, action); - action2exetime.put(action, (long)-1); - - SimExecutionNode lastsenode = lastseNodes[targetCoreNum]; - // create edges between previous senode on this core to this node - if(lastsenode != null) { - Action tmpaction = senode2action.get(lastsenode); - SimExecutionEdge seEdge = null; - if(tmpaction == null) { - seEdge = new SimExecutionEdge(seNode, - lastsenode.getCoreNum(), - null, - 0, - null); - } else { - long weight = action2exetime.get(tmpaction); - seEdge = new SimExecutionEdge(seNode, - lastsenode.getCoreNum(), - tmpaction.getTd(), - weight, - tmpaction.getTaskParams()); - } - lastsenode.addEdge(seEdge); - } - lastseNodes[targetCoreNum] = seNode; - } + this.tasks.add(newTask); + // add a TASKSTART action into this checkpoint + action = new Action(targetCoreNum, + Action.TASKSTART, + newTask); + cp.addAction(action); + if(!(newTask instanceof TransTaskSimulator)) { + cp.removeSpareCore(targetCoreNum); + SimExecutionNode seNode = new SimExecutionNode(targetCoreNum, this.processTime); + seNode.setSpareCores(cp.getSpareCores()); + senode2action.put(seNode, action); + action2exetime.put(action, (long)-1); + + SimExecutionNode lastsenode = lastseNodes[targetCoreNum]; + // create edges between previous senode on this core to this node + if(lastsenode != null) { + Action tmpaction = senode2action.get(lastsenode); + SimExecutionEdge seEdge = null; + if(tmpaction == null) { + seEdge = new SimExecutionEdge(seNode, + lastsenode.getCoreNum(), + null, + 0, + null); + } else { + long weight = action2exetime.get(tmpaction); + seEdge = new SimExecutionEdge(seNode, + lastsenode.getCoreNum(), + tmpaction.getTd(), + weight, + tmpaction.getTaskParams()); + } + lastsenode.addEdge(seEdge); + } + lastseNodes[targetCoreNum] = seNode; + } } } } @@ -599,56 +599,56 @@ public class ScheduleSimulator { // get the infomation of how to send new objects Vector nobjs = task.getCurrentRun().getNewObjs(); for(int j = 0; j < nobjs.size(); j++) { - ObjectSimulator nobj = nobjs.elementAt(j); - totransObjs.add(nobj); - - action.addNewObj(nobj.getCd(), Integer.valueOf(1)); - // send the new object to target core according to pre-decide scheduling - Queue cores = cs.getTargetCores(nobj.getCurrentFS()); - if(cores == null) { - // this obj will reside on this core - cs.addObject(nobj); - } else { - Integer targetCore = cores.poll(); - if(targetCore == corenum) { - // this obj will reside on this core - cs.addObject(nobj); - } else { - if(!transObjQueues.containsKey(targetCore)) { - transObjQueues.put(targetCore, new LinkedList()); - } - Queue tmpqueue = transObjQueues.get(targetCore); - tmpqueue.add(new ObjectInfo(nobj)); - tmpqueue = null; - } - // enqueue this core again - cores.add(targetCore); - } - cores = null; - // check if this object becoming shared or not - Vector allycores = cs.getAllyCores(nobj.getCurrentFS()); - if(allycores != null) { - nobj.setShared(true); - // TODO, temporarily send to at most 2 cores - int numtosend = allycores.size() > 2?2:allycores.size(); - for(int k = 0; k < numtosend; ++k) { - Integer allyCore = allycores.elementAt(k); - if(allyCore == corenum) { - cs.addObject(nobj); - } else { - if(!transObjQueues.containsKey(allyCore)) { - transObjQueues.put(allyCore, new LinkedList()); - } - Queue tmpqueue = transObjQueues.get(allyCore); - ObjectInfo nobjinfo = new ObjectInfo(nobj); - if(!tmpqueue.contains(nobjinfo)) { - tmpqueue.add(nobjinfo); - } - tmpqueue = null; - } - } - allycores = null; - } + ObjectSimulator nobj = nobjs.elementAt(j); + totransObjs.add(nobj); + + action.addNewObj(nobj.getCd(), Integer.valueOf(1)); + // send the new object to target core according to pre-decide scheduling + Queue cores = cs.getTargetCores(nobj.getCurrentFS()); + if(cores == null) { + // this obj will reside on this core + cs.addObject(nobj); + } else { + Integer targetCore = cores.poll(); + if(targetCore == corenum) { + // this obj will reside on this core + cs.addObject(nobj); + } else { + if(!transObjQueues.containsKey(targetCore)) { + transObjQueues.put(targetCore, new LinkedList()); + } + Queue tmpqueue = transObjQueues.get(targetCore); + tmpqueue.add(new ObjectInfo(nobj)); + tmpqueue = null; + } + // enqueue this core again + cores.add(targetCore); + } + cores = null; + // check if this object becoming shared or not + Vector allycores = cs.getAllyCores(nobj.getCurrentFS()); + if(allycores != null) { + nobj.setShared(true); + // TODO, temporarily send to at most 2 cores + int numtosend = allycores.size() > 2?2:allycores.size(); + for(int k = 0; k < numtosend; ++k) { + Integer allyCore = allycores.elementAt(k); + if(allyCore == corenum) { + cs.addObject(nobj); + } else { + if(!transObjQueues.containsKey(allyCore)) { + transObjQueues.put(allyCore, new LinkedList()); + } + Queue tmpqueue = transObjQueues.get(allyCore); + ObjectInfo nobjinfo = new ObjectInfo(nobj); + if(!tmpqueue.contains(nobjinfo)) { + tmpqueue.add(nobjinfo); + } + tmpqueue = null; + } + } + allycores = null; + } } nobjs = null; } @@ -659,53 +659,53 @@ public class ScheduleSimulator { if(transObjs != null) { totransObjs.addAll(transObjs); for(int j = 0; j < transObjs.size(); j++) { - ObjectSimulator tobj = transObjs.elementAt(j); - // send the object to target core according to pre-decide scheduling - Queue cores = cs.getTargetCores(tobj.getCurrentFS()); - tobj.setCurrentFS(cs.getTargetFState(tobj.getCurrentFS())); - if(cores == null) { - // this obj will reside on this core - cs.addObject(tobj); - } else { - Integer targetCore = cores.poll(); - if(targetCore == corenum) { - // this obj will reside on this core - cs.addObject(tobj); - } else { - if(!transObjQueues.containsKey(targetCore)) { - transObjQueues.put(targetCore, new LinkedList()); - } - Queue tmpqueue = transObjQueues.get(targetCore); - tmpqueue.add(new ObjectInfo(tobj)); - tmpqueue = null; - } - cores.add(targetCore); - } - cores = null; - // check if this object becoming shared or not - Vector allycores = cs.getAllyCores(tobj.getCurrentFS()); - if(allycores != null) { - tobj.setShared(true); - // TODO, temporarily send to at most 2 cores - int numtosend = allycores.size() > 2?2:allycores.size(); - for(int k = 0; k < numtosend; ++k) { - Integer allyCore = allycores.elementAt(k); - if(allyCore == corenum) { - cs.addObject(tobj); - } else { - if(!transObjQueues.containsKey(allyCore)) { - transObjQueues.put(allyCore, new LinkedList()); - } - Queue tmpqueue = transObjQueues.get(allyCore); - ObjectInfo nobjinfo = new ObjectInfo(tobj); - if(!tmpqueue.contains(nobjinfo)) { - tmpqueue.add(nobjinfo); - } - tmpqueue = null; - } - } - allycores = null; - } + ObjectSimulator tobj = transObjs.elementAt(j); + // send the object to target core according to pre-decide scheduling + Queue cores = cs.getTargetCores(tobj.getCurrentFS()); + tobj.setCurrentFS(cs.getTargetFState(tobj.getCurrentFS())); + if(cores == null) { + // this obj will reside on this core + cs.addObject(tobj); + } else { + Integer targetCore = cores.poll(); + if(targetCore == corenum) { + // this obj will reside on this core + cs.addObject(tobj); + } else { + if(!transObjQueues.containsKey(targetCore)) { + transObjQueues.put(targetCore, new LinkedList()); + } + Queue tmpqueue = transObjQueues.get(targetCore); + tmpqueue.add(new ObjectInfo(tobj)); + tmpqueue = null; + } + cores.add(targetCore); + } + cores = null; + // check if this object becoming shared or not + Vector allycores = cs.getAllyCores(tobj.getCurrentFS()); + if(allycores != null) { + tobj.setShared(true); + // TODO, temporarily send to at most 2 cores + int numtosend = allycores.size() > 2?2:allycores.size(); + for(int k = 0; k < numtosend; ++k) { + Integer allyCore = allycores.elementAt(k); + if(allyCore == corenum) { + cs.addObject(tobj); + } else { + if(!transObjQueues.containsKey(allyCore)) { + transObjQueues.put(allyCore, new LinkedList()); + } + Queue tmpqueue = transObjQueues.get(allyCore); + ObjectInfo nobjinfo = new ObjectInfo(tobj); + if(!tmpqueue.contains(nobjinfo)) { + tmpqueue.add(nobjinfo); + } + tmpqueue = null; + } + } + allycores = null; + } } } transObjs = null; @@ -749,27 +749,27 @@ public class ScheduleSimulator { newTask); cp.addAction(action); if(!(newTask instanceof TransTaskSimulator)) { - cp.removeSpareCore(cs.getCoreNum()); - SimExecutionNode seNode = new SimExecutionNode(corenum, this.processTime); - seNode.setSpareCores(cp.getSpareCores()); - senode2action.put(seNode, action); - action2exetime.put(action, (long)-1); - SimExecutionNode lastsenode = lastseNodes[corenum]; - // create edges between previous senode on this core to this node - if(lastsenode != null) { - Action tmpaction = senode2action.get(lastsenode); - long weight = tmpaction != null?action2exetime.get(tmpaction):0; - seEdge = new SimExecutionEdge(seNode, - lastsenode.getCoreNum(), - tmpaction!= null?tmpaction.getTd():null, - weight, - tmpaction!=null?tmpaction.getTaskParams():null); - lastsenode.addEdge(seEdge); - } - lastseNodes[corenum] = seNode; - for(int tmpindex = 0; tmpindex < tttasks.size(); tmpindex++) { - tttask2senode.put(tttasks.elementAt(tmpindex), seNode); - } + cp.removeSpareCore(cs.getCoreNum()); + SimExecutionNode seNode = new SimExecutionNode(corenum, this.processTime); + seNode.setSpareCores(cp.getSpareCores()); + senode2action.put(seNode, action); + action2exetime.put(action, (long)-1); + SimExecutionNode lastsenode = lastseNodes[corenum]; + // create edges between previous senode on this core to this node + if(lastsenode != null) { + Action tmpaction = senode2action.get(lastsenode); + long weight = tmpaction != null?action2exetime.get(tmpaction):0; + seEdge = new SimExecutionEdge(seNode, + lastsenode.getCoreNum(), + tmpaction!= null?tmpaction.getTd():null, + weight, + tmpaction!=null?tmpaction.getTaskParams():null); + lastsenode.addEdge(seEdge); + } + lastseNodes[corenum] = seNode; + for(int tmpindex = 0; tmpindex < tttasks.size(); tmpindex++) { + tttask2senode.put(tttasks.elementAt(tmpindex), seNode); + } } } else if(tttasks.size() > 0) { SimExecutionNode seNode = new SimExecutionNode(corenum, this.processTime); @@ -778,61 +778,61 @@ public class ScheduleSimulator { SimExecutionNode lastsenode = lastseNodes[corenum]; // create edges between previous senode on this core to this node if(lastsenode != null) { - Action tmpaction = senode2action.get(lastsenode); - long weight = action2exetime.get(tmpaction); - seEdge = new SimExecutionEdge(seNode, - lastsenode.getCoreNum(), - tmpaction.getTd(), - weight, - tmpaction.getTaskParams()); - lastsenode.addEdge(seEdge); + Action tmpaction = senode2action.get(lastsenode); + long weight = action2exetime.get(tmpaction); + seEdge = new SimExecutionEdge(seNode, + lastsenode.getCoreNum(), + tmpaction.getTd(), + weight, + tmpaction.getTaskParams()); + lastsenode.addEdge(seEdge); } lastseNodes[corenum] = seNode; for(int tmpindex = 0; tmpindex < tttasks.size(); tmpindex++) { - tttask2senode.put(tttasks.elementAt(tmpindex), seNode); + tttask2senode.put(tttasks.elementAt(tmpindex), seNode); } } if(seEdge != null) { // setup data dependencies for the task Vector taskparams = seEdge.getTaskparams(); if(taskparams != null) { - for(int i = 0; i < taskparams.size(); i++) { - Integer tparam = taskparams.elementAt(i); - SimExecutionEdge lastedge = obj2lastseedge.get(tparam); - if(lastedge != null) { - if(lastedge.getCoreNum() != seEdge.getCoreNum()) { - // the obj is transferred from another core - // create an seEdge for this transfer - long weight = obj2transtime.get(tparam); - SimExecutionEdge transseEdge = new SimExecutionEdge((SimExecutionNode)seEdge.getSource(), - lastedge.getCoreNum(), - null, // TODO: not sure if this is enough - weight, - null); - if(((SimExecutionNode)seEdge.getSource()).getTimepoint() < - ((SimExecutionNode)lastedge.getTarget()).getTimepoint()) { - System.err.println("ScheduleSimulator:757"); - System.exit(-1); - } - lastedge.getTarget().addEdge(transseEdge); - transseEdge.addPredicate(lastedge); - seEdge.addPredicate(transseEdge); - } else { - seEdge.addPredicate(lastedge); - } - } - // update the last edge associated to the parameter obj - obj2lastseedge.put(tparam, seEdge); - } + for(int i = 0; i < taskparams.size(); i++) { + Integer tparam = taskparams.elementAt(i); + SimExecutionEdge lastedge = obj2lastseedge.get(tparam); + if(lastedge != null) { + if(lastedge.getCoreNum() != seEdge.getCoreNum()) { + // the obj is transferred from another core + // create an seEdge for this transfer + long weight = obj2transtime.get(tparam); + SimExecutionEdge transseEdge = new SimExecutionEdge((SimExecutionNode)seEdge.getSource(), + lastedge.getCoreNum(), + null, // TODO: not sure if this is enough + weight, + null); + if(((SimExecutionNode)seEdge.getSource()).getTimepoint() < + ((SimExecutionNode)lastedge.getTarget()).getTimepoint()) { + System.err.println("ScheduleSimulator:757"); + System.exit(-1); + } + lastedge.getTarget().addEdge(transseEdge); + transseEdge.addPredicate(lastedge); + seEdge.addPredicate(transseEdge); + } else { + seEdge.addPredicate(lastedge); + } + } + // update the last edge associated to the parameter obj + obj2lastseedge.put(tparam, seEdge); + } } taskparams = null; // set seEdge as the last execution edge for all newly created objs if(nobjs != null) { - for(int i = 0; i < nobjs.size(); i++) { - ObjectSimulator nobj = nobjs.elementAt(i); - obj2lastseedge.put(nobj.getOid(), seEdge); - } + for(int i = 0; i < nobjs.size(); i++) { + ObjectSimulator nobj = nobjs.elementAt(i); + obj2lastseedge.put(nobj.getOid(), seEdge); + } } } } @@ -873,7 +873,7 @@ public class ScheduleSimulator { this.actions = new Vector(); this.spareCores = new Vector(); for(int i = 0; i < corenum; i++) { - this.spareCores.add(i); + this.spareCores.add(i); } } @@ -887,13 +887,13 @@ public class ScheduleSimulator { public void removeSpareCore(int core) { for(int i = 0; i < this.spareCores.size(); i++) { - if(this.spareCores.elementAt(i) == core) { - for(int j = i; j < this.spareCores.size() - 1; j++) { - this.spareCores.setElementAt(this.spareCores.elementAt(j + 1), j); - } - this.spareCores.remove(this.spareCores.size() - 1); - return; - } + if(this.spareCores.elementAt(i) == core) { + for(int j = i; j < this.spareCores.size() - 1; j++) { + this.spareCores.setElementAt(this.spareCores.elementAt(j + 1), j); + } + this.spareCores.remove(this.spareCores.size() - 1); + return; + } } } @@ -929,9 +929,9 @@ public class ScheduleSimulator { this.td = null; this.taskparams = null; if(this.type == TFWITHOBJ) { - this.nObjs = new Hashtable(); + this.nObjs = new Hashtable(); } else { - this.nObjs = null; + this.nObjs = null; } this.nObjNum = -1; this.transObj = null; @@ -947,19 +947,19 @@ public class ScheduleSimulator { this.td = ts.getTd(); Vector> paraQueues = ts.getParaQueues(); if(this.type == TASKSTART) { - this.taskparams = new Vector(); - for(int i = 0; i < paraQueues.size(); i++) { - ObjectSimulator tpara = paraQueues.elementAt(i).peek(); - this.taskparams.add(tpara.getOid()); - } + this.taskparams = new Vector(); + for(int i = 0; i < paraQueues.size(); i++) { + ObjectSimulator tpara = paraQueues.elementAt(i).peek(); + this.taskparams.add(tpara.getOid()); + } } else { - this.taskparams = null; + this.taskparams = null; } paraQueues = null; if(this.type == TFWITHOBJ) { - this.nObjs = new Hashtable(); + this.nObjs = new Hashtable(); } else { - this.nObjs = null; + this.nObjs = null; } this.nObjNum = -1; this.transObj = null; @@ -983,10 +983,10 @@ public class ScheduleSimulator { assert(this.type == TFWITHOBJ); if(this.nObjs.containsKey(cd)) { - Integer sum = this.nObjs.get(cd) + num; - this.nObjs.put(cd, sum); + Integer sum = this.nObjs.get(cd) + num; + this.nObjs.put(cd, sum); } else { - this.nObjs.put(cd, num); + this.nObjs.put(cd, num); } } diff --git a/Robust/src/Analysis/Scheduling/SchedulingUtil.java b/Robust/src/Analysis/Scheduling/SchedulingUtil.java index 5dceccd7..c1624334 100644 --- a/Robust/src/Analysis/Scheduling/SchedulingUtil.java +++ b/Robust/src/Analysis/Scheduling/SchedulingUtil.java @@ -53,31 +53,31 @@ public class SchedulingUtil { for(int i = 0; i < mapping.size(); i++) { Vector sNodes = mapping.elementAt(i); if(sNodes != null) { - ScheduleNode rootnode = sNodes.elementAt(0); - for(int j = 1; j < sNodes.size(); j++) { - ScheduleNode tocombine = sn2sn.get(sNodes.elementAt(j)); - ScheduleNode root = sn2sn.get(rootnode); - ScheduleEdge se = (ScheduleEdge)tocombine.inedges().next(); - try { - if(root.equals(((ScheduleNode)se.getSource()))) { - root.mergeSEdge(se); - if(ScheduleEdge.NEWEDGE == se.getType()) { - // As se has been changed into an internal edge inside a ScheduleNode, - // change the source and target of se from original ScheduleNodes into ClassNodes. - se.setTarget(se.getTargetCNode()); - //se.setSource(se.getSourceCNode()); - //se.getTargetCNode().addEdge(se); - se.getSourceCNode().addEdge(se); - } - } else { - root.mergeSNode(tocombine); - } - } catch(Exception e) { - e.printStackTrace(); - System.exit(-1); - } - result.removeElement(tocombine); - } + ScheduleNode rootnode = sNodes.elementAt(0); + for(int j = 1; j < sNodes.size(); j++) { + ScheduleNode tocombine = sn2sn.get(sNodes.elementAt(j)); + ScheduleNode root = sn2sn.get(rootnode); + ScheduleEdge se = (ScheduleEdge)tocombine.inedges().next(); + try { + if(root.equals(((ScheduleNode)se.getSource()))) { + root.mergeSEdge(se); + if(ScheduleEdge.NEWEDGE == se.getType()) { + // As se has been changed into an internal edge inside a ScheduleNode, + // change the source and target of se from original ScheduleNodes into ClassNodes. + se.setTarget(se.getTargetCNode()); + //se.setSource(se.getSourceCNode()); + //se.getTargetCNode().addEdge(se); + se.getSourceCNode().addEdge(se); + } + } else { + root.mergeSNode(tocombine); + } + } catch(Exception e) { + e.printStackTrace(); + System.exit(-1); + } + result.removeElement(tocombine); + } } } @@ -119,31 +119,31 @@ public class SchedulingUtil { // combine those nodes in combine with corresponding rootnodes for(int i = 0; i < combine.size(); i++) { if(combine.elementAt(i) != null) { - for(int j = 0; j < combine.elementAt(i).size(); j++) { - CombinationUtil.Combine tmpcombine = combine.elementAt(i).elementAt(j); - ScheduleNode tocombine = sn2sn.get(tmpcombine.node); - ScheduleNode root = sn2sn.get(rootnodes.elementAt(tmpcombine.root).elementAt(tmpcombine.index)); - ScheduleEdge se = (ScheduleEdge)tocombine.inedges().next(); - try { - if(root.equals(((ScheduleNode)se.getSource()))) { - root.mergeSEdge(se); - if(ScheduleEdge.NEWEDGE == se.getType()) { - // As se has been changed into an internal edge inside a ScheduleNode, - // change the source and target of se from original ScheduleNodes into ClassNodes. - se.setTarget(se.getTargetCNode()); - //se.setSource(se.getSourceCNode()); - //se.getTargetCNode().addEdge(se); - se.getSourceCNode().addEdge(se); - } - } else { - root.mergeSNode(tocombine); - } - } catch(Exception e) { - e.printStackTrace(); - System.exit(-1); - } - result.removeElement(tocombine); - } + for(int j = 0; j < combine.elementAt(i).size(); j++) { + CombinationUtil.Combine tmpcombine = combine.elementAt(i).elementAt(j); + ScheduleNode tocombine = sn2sn.get(tmpcombine.node); + ScheduleNode root = sn2sn.get(rootnodes.elementAt(tmpcombine.root).elementAt(tmpcombine.index)); + ScheduleEdge se = (ScheduleEdge)tocombine.inedges().next(); + try { + if(root.equals(((ScheduleNode)se.getSource()))) { + root.mergeSEdge(se); + if(ScheduleEdge.NEWEDGE == se.getType()) { + // As se has been changed into an internal edge inside a ScheduleNode, + // change the source and target of se from original ScheduleNodes into ClassNodes. + se.setTarget(se.getTargetCNode()); + //se.setSource(se.getSourceCNode()); + //se.getTargetCNode().addEdge(se); + se.getSourceCNode().addEdge(se); + } + } else { + root.mergeSNode(tocombine); + } + } catch(Exception e) { + e.printStackTrace(); + System.exit(-1); + } + result.removeElement(tocombine); + } } } @@ -187,15 +187,15 @@ public class SchedulingUtil { ScheduleEdge se = null; switch(sse.getType()) { case ScheduleEdge.NEWEDGE: { - se = new ScheduleEdge(ctarget, "new", sse.getFstate(), sse.getType(), gid); //new ScheduleEdge(ctarget, "new", sse.getClassDescriptor(), sse.getIsNew(), gid); - se.setProbability(sse.getProbability()); - se.setNewRate(sse.getNewRate()); - break; + se = new ScheduleEdge(ctarget, "new", sse.getFstate(), sse.getType(), gid); //new ScheduleEdge(ctarget, "new", sse.getClassDescriptor(), sse.getIsNew(), gid); + se.setProbability(sse.getProbability()); + se.setNewRate(sse.getNewRate()); + break; } case ScheduleEdge.TRANSEDGE: { - se = new ScheduleEdge(ctarget, "transmit", sse.getFstate(), sse.getType(), gid); //new ScheduleEdge(ctarget, "transmit", sse.getClassDescriptor(), false, gid); - break; + se = new ScheduleEdge(ctarget, "transmit", sse.getFstate(), sse.getType(), gid); //new ScheduleEdge(ctarget, "transmit", sse.getClassDescriptor(), false, gid); + break; } } se.setSourceCNode(sourcecn2cn.get(sse.getSourceCNode())); @@ -217,13 +217,13 @@ public class SchedulingUtil { tmpnode.computeHashcid(); int hcid = tmpnode.getHashcid(); if(hcid2cid.containsKey(hcid)) { - // already have a cid for this node - tmpnode.setCid(hcid2cid.get(hcid)); + // already have a cid for this node + tmpnode.setCid(hcid2cid.get(hcid)); } else { - // generate a new cid for such node - tmpnode.setCid(ncid); - hcid2cid.put(hcid, ncid); - ncid++; + // generate a new cid for such node + tmpnode.setCid(ncid); + hcid2cid.put(hcid, ncid); + ncid++; } } hcid2cid.clear(); @@ -237,37 +237,37 @@ public class SchedulingUtil { Vector> sNodeVecs = new Vector>(); for(int i = 0; i < scheduleNodes.size(); i++) { - ScheduleNode tmpn = scheduleNodes.elementAt(i); - int tmpcid = tmpn.getCid(); - int index = 0; - for(index = 0; index < sNodeVecs.size(); index++) { - if(sNodeVecs.elementAt(index).elementAt(0).getCid() > tmpcid) { - // find the place to insert - sNodeVecs.insertElementAt(new Vector(), index); - /*sNodeVecs.add(sNodeVecs.lastElement()); - for(int j = sNodeVecs.size() - 2; j > index; j--) { - sNodeVecs.setElementAt(sNodeVecs.elementAt(j - 1), j); - } - sNodeVecs.setElementAt(new Vector(), index);*/ - break; - } else if(sNodeVecs.elementAt(index).elementAt(0).getCid() == tmpcid) { - break; - } - } - if(index == sNodeVecs.size()) { - sNodeVecs.add(new Vector()); - } - - /*int index = tmpcid; - while(sNodeVecs.size() <= index) { - sNodeVecs.add(null); - } - if(sNodeVecs.elementAt(index) == null) { - sNodeVecs.setElementAt(new Vector(), index); - }*/ - if(!sNodeVecs.elementAt(index).contains(tmpn)) { - sNodeVecs.elementAt(index).addElement(tmpn); - } + ScheduleNode tmpn = scheduleNodes.elementAt(i); + int tmpcid = tmpn.getCid(); + int index = 0; + for(index = 0; index < sNodeVecs.size(); index++) { + if(sNodeVecs.elementAt(index).elementAt(0).getCid() > tmpcid) { + // find the place to insert + sNodeVecs.insertElementAt(new Vector(), index); + /*sNodeVecs.add(sNodeVecs.lastElement()); + for(int j = sNodeVecs.size() - 2; j > index; j--) { + sNodeVecs.setElementAt(sNodeVecs.elementAt(j - 1), j); + } + sNodeVecs.setElementAt(new Vector(), index);*/ + break; + } else if(sNodeVecs.elementAt(index).elementAt(0).getCid() == tmpcid) { + break; + } + } + if(index == sNodeVecs.size()) { + sNodeVecs.add(new Vector()); + } + + /*int index = tmpcid; + while(sNodeVecs.size() <= index) { + sNodeVecs.add(null); + } + if(sNodeVecs.elementAt(index) == null) { + sNodeVecs.setElementAt(new Vector(), index); + }*/ + if(!sNodeVecs.elementAt(index).contains(tmpn)) { + sNodeVecs.elementAt(index).addElement(tmpn); + } } return sNodeVecs; @@ -320,16 +320,16 @@ public class SchedulingUtil { else switch (((FlagOpNode)fen).getOp().getOp()) { case Operation.LOGIC_AND: - return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) && (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs))); + return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) && (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs))); case Operation.LOGIC_OR: - return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) || (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs))); + return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) || (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs))); case Operation.LOGIC_NOT: - return !(isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)); + return !(isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)); default: - return false; + return false; } } @@ -365,62 +365,62 @@ public class SchedulingUtil { //Draw the internal 'new' edges Iterator it_edges =gn.getScheduleEdgesIterator(); while(it_edges.hasNext()) { - ScheduleEdge se = (ScheduleEdge)it_edges.next(); - output.print("\t"); - if(se.getSourceCNode().isclone()) { - output.print(se.getSourceCNode().getLabel()); - } else { - if(se.getSourceFState() == null) { - output.print(se.getSourceCNode().getClusterLabel()); - } else { - output.print(se.getSourceFState().getLabel()); - } - } - - output.print(" -> "); - if(se.isclone()) { - if(se.getTargetCNode().isclone()) { - output.print(se.getTargetCNode().getLabel()); - } else { - output.print(se.getTargetCNode().getClusterLabel()); - } - output.println(" [label=\"" + se.getLabel() + "\", color=red];"); - } else { - output.print(se.getTargetFState().getLabel() + " [label=\"" + se.getLabel() + "\", color=red, ltail="); - if(se.getSourceCNode().isclone()) { - output.println(se.getSourceCNode().getLabel() + "];"); - } else { - output.println(se.getSourceCNode().getClusterLabel() + "];"); - } - } + ScheduleEdge se = (ScheduleEdge)it_edges.next(); + output.print("\t"); + if(se.getSourceCNode().isclone()) { + output.print(se.getSourceCNode().getLabel()); + } else { + if(se.getSourceFState() == null) { + output.print(se.getSourceCNode().getClusterLabel()); + } else { + output.print(se.getSourceFState().getLabel()); + } + } + + output.print(" -> "); + if(se.isclone()) { + if(se.getTargetCNode().isclone()) { + output.print(se.getTargetCNode().getLabel()); + } else { + output.print(se.getTargetCNode().getClusterLabel()); + } + output.println(" [label=\"" + se.getLabel() + "\", color=red];"); + } else { + output.print(se.getTargetFState().getLabel() + " [label=\"" + se.getLabel() + "\", color=red, ltail="); + if(se.getSourceCNode().isclone()) { + output.println(se.getSourceCNode().getLabel() + "];"); + } else { + output.println(se.getSourceCNode().getClusterLabel() + "];"); + } + } } output.println("\t}\n"); it_edges = null; //Draw 'new' edges of this ScheduleNode while(edges.hasNext()) { - ScheduleEdge se = (ScheduleEdge)edges.next(); - output.print("\t"); - if(se.getSourceCNode().isclone()) { - output.print(se.getSourceCNode().getLabel()); - } else { - if(se.getSourceFState() == null) { - output.print(se.getSourceCNode().getClusterLabel()); - } else { - output.print(se.getSourceFState().getLabel()); - } - } - - output.print(" -> "); - if(se.isclone()) { - if(se.getTargetCNode().isclone()) { - output.print(se.getTargetCNode().getLabel()); - } else { - output.print(se.getTargetCNode().getClusterLabel()); - } - output.println(" [label=\"" + se.getLabel() + "\", color=red, style=dashed];"); - } else { - output.println(se.getTargetFState().getLabel() + " [label=\"" + se.getLabel() + "\", color=red, style=dashed];"); - } + ScheduleEdge se = (ScheduleEdge)edges.next(); + output.print("\t"); + if(se.getSourceCNode().isclone()) { + output.print(se.getSourceCNode().getLabel()); + } else { + if(se.getSourceFState() == null) { + output.print(se.getSourceCNode().getClusterLabel()); + } else { + output.print(se.getSourceFState().getLabel()); + } + } + + output.print(" -> "); + if(se.isclone()) { + if(se.getTargetCNode().isclone()) { + output.print(se.getTargetCNode().getLabel()); + } else { + output.print(se.getTargetCNode().getClusterLabel()); + } + output.println(" [label=\"" + se.getLabel() + "\", color=red, style=dashed];"); + } else { + output.println(se.getTargetFState().getLabel() + " [label=\"" + se.getLabel() + "\", color=red, style=dashed];"); + } } edges = null; } @@ -433,13 +433,13 @@ public class SchedulingUtil { while (it.hasNext()) { ClassNode gn = (ClassNode) it.next(); if(gn.isclone()) { - output.println("\t\t" + gn.getLabel() + " [style=dashed, label=\"" + gn.getTextLabel() + "\", shape=box];"); + output.println("\t\t" + gn.getLabel() + " [style=dashed, label=\"" + gn.getTextLabel() + "\", shape=box];"); } else { - output.println("\tsubgraph " + gn.getClusterLabel() + "{"); - output.println("\t\tstyle=dashed;"); - output.println("\t\tlabel=\"" + gn.getTextLabel() + "\";"); - traverseFlagStates(output, gn.getFlagStates()); - output.println("\t}\n"); + output.println("\tsubgraph " + gn.getClusterLabel() + "{"); + output.println("\t\tstyle=dashed;"); + output.println("\t\tlabel=\"" + gn.getTextLabel() + "\";"); + traverseFlagStates(output, gn.getFlagStates()); + output.println("\t}\n"); } } } @@ -459,63 +459,63 @@ public class SchedulingUtil { String dotnodeparams=""; for(int i=0; i hashtable = ((FEdge)edge).getNewObjInfoHashtable(); - if(hashtable != null) { - Set keys = hashtable.keySet(); - Iterator it_keys = keys.iterator(); - while(it_keys.hasNext()) { - ClassDescriptor cd = (ClassDescriptor)it_keys.next(); - NewObjInfo noi = hashtable.get(cd); - edgelabel += ":{ class " + cd.getSymbol() + " | " + noi.getNewRate() + " | (" + noi.getProbability() + "%) }"; - } - keys = null; - it_keys = null; - } - output.println("\t" + gn.getLabel() + " -> " + node2.getLabel() + " [" + "label=\"" + edgelabel + "\"" + edgedotnodeparams + "];"); - } - nodeit = null; - } - } + while (edges.hasNext()) { + Edge edge = (Edge) edges.next(); + GraphNode node = edge.getTarget(); + if (nodes.contains(node)) { + Iterator nodeit=nonmerge(node, nodes).iterator(); + for(; nodeit.hasNext(); ) { + GraphNode node2=(GraphNode)nodeit.next(); + String edgelabel = ""; + String edgedotnodeparams=""; + + for(int i=0; i hashtable = ((FEdge)edge).getNewObjInfoHashtable(); + if(hashtable != null) { + Set keys = hashtable.keySet(); + Iterator it_keys = keys.iterator(); + while(it_keys.hasNext()) { + ClassDescriptor cd = (ClassDescriptor)it_keys.next(); + NewObjInfo noi = hashtable.get(cd); + edgelabel += ":{ class " + cd.getSymbol() + " | " + noi.getNewRate() + " | (" + noi.getProbability() + "%) }"; + } + keys = null; + it_keys = null; + } + output.println("\t" + gn.getLabel() + " -> " + node2.getLabel() + " [" + "label=\"" + edgelabel + "\"" + edgedotnodeparams + "];"); + } + nodeit = null; + } + } edges = null; } cycleset = null; @@ -532,16 +532,16 @@ public class SchedulingUtil { GraphNode gn2=(GraphNode)toprocess.iterator().next(); toprocess.remove(gn2); if (!gn2.merge) - newset.add(gn2); + newset.add(gn2); else { - Iterator edges = gn2.edges(); - while (edges.hasNext()) { - Edge edge = (Edge) edges.next(); - GraphNode node = edge.getTarget(); - if (!newset.contains(node)&&nodes.contains(node)) - toprocess.add(node); - } - edges = null; + Iterator edges = gn2.edges(); + while (edges.hasNext()) { + Edge edge = (Edge) edges.next(); + GraphNode node = edge.getTarget(); + if (!newset.contains(node)&&nodes.contains(node)) + toprocess.add(node); + } + edges = null; } } toprocess = null; @@ -570,7 +570,7 @@ public class SchedulingUtil { // the capital line output.print("{rank=source; \"Time\"; "); for(j = 0; j < coreNum; j++) { - output.print("\"core " + j + "\"; "); + output.print("\"core " + j + "\"; "); } output.println("}"); // time coordinate nodes @@ -579,260 +579,260 @@ public class SchedulingUtil { String[] lastTasks = new String[coreNum]; boolean[] isTaskFinish = new boolean[coreNum]; for(j = 0; j < coreNum; j++) { - lastTaskNodes[j] = "first"; - isTaskFinish[j] = true; - lastTasks[j] = ""; + lastTaskNodes[j] = "first"; + isTaskFinish[j] = true; + lastTasks[j] = ""; } timeNodes.add("0"); for(j = 0; j < checkpoints.size(); j++) { - CheckPoint tcp = checkpoints.elementAt(j); - Hashtable tmplastTasks = new Hashtable(); - Vector tmpisTaskFinish = new Vector(); - Vector tmpisset = new Vector(); - String tnode = String.valueOf(tcp.getTimepoint()); - if(!timeNodes.contains(tnode)) { - timeNodes.add(tnode); - } - Vector actions = tcp.getActions(); - Hashtable tmpTaskNodes = new Hashtable(); - for(int i = 0; i < actions.size(); i++) { - Action taction = actions.elementAt(i); - int cNum = taction.getCoreNum(); - if(!tmplastTasks.containsKey(cNum)) { - tmplastTasks.put(cNum, lastTasks[cNum]); - } - if(!(tmpisset.contains(cNum)) - && (isTaskFinish[cNum]) - && !(tmpisTaskFinish.contains(cNum))) { - tmpisTaskFinish.add(cNum); // records those with task finished the first time visit it - } - String tmpTaskNode = "\"" + tnode + "core" + cNum + "\""; - StringBuffer tmpLabel = null; - boolean isfirst = false; - if(!tmpTaskNodes.containsKey(tmpTaskNode)) { - tmpTaskNodes.put(tmpTaskNode, new StringBuffer(tnode + ":")); - isfirst = true; - } - tmpLabel = tmpTaskNodes.get(tmpTaskNode); - switch(taction.getType()) { - case Action.ADDOBJ: { - if(!isfirst) { - tmpLabel.append("\\n"); - } - tmpLabel.append("(" + taction.getTransObj().getSymbol() + ")arrives;"); - if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) { - output.print("\t"); - if(lastTaskNodes[cNum].equals("first")) { - output.print("\"core " + cNum + "\"->" + tmpTaskNode); - } else { - output.print(lastTaskNodes[cNum] + "->" + tmpTaskNode); - } - if(tmpisTaskFinish.contains(cNum)) { - output.print(" [style=invis]"); - } - output.println(";"); - lastTaskNodes[cNum] = tmpTaskNode; - } - break; - } - - case Action.TASKFINISH: { - if(!isfirst) { - tmpLabel.append("\\n"); - } - tmpLabel.append("<" + taction.getTd().getSymbol() + "("); - /*Vector taskparams = taction.getTaskParams(); - for(int ii = 0; ii < taskparams.size(); ii++) { - tmpLabel.append(taskparams.elementAt(ii)); - if(ii < taskparams.size() - 1) { - tmpLabel.append(","); - } - }*/ - tmpLabel.append(")>finishes;"); - if(!(lastTaskNodes[cNum].equals("first"))) { - if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) { - output.print("\t"); - output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";"); - lastTaskNodes[cNum] = tmpTaskNode; - } - if(tmpisset.contains(cNum)) { - isTaskFinish[cNum] &= true; - } else { - isTaskFinish[cNum] = true; - tmpisset.add(cNum); - } - lastTasks[cNum] = ""; - } else { - throw new Exception("Error: unexpected task finish"); - } - break; - } - - case Action.TFWITHOBJ: { - if(!isfirst) { - tmpLabel.append("\\n"); - } - tmpLabel.append("<" + taction.getTd().getSymbol() + "("); - /*Vector taskparams = taction.getTaskParams(); - for(int ii = 0; ii < taskparams.size(); ii++) { - tmpLabel.append(taskparams.elementAt(ii)); - if(ii < taskparams.size() - 1) { - tmpLabel.append(","); - } - }*/ - tmpLabel.append(")>finishes;"); - Iterator> it_entry = (Iterator>)taction.getNObjs().entrySet().iterator(); - while(it_entry.hasNext()) { - Entry entry = it_entry.next(); - tmpLabel.append(entry.getValue() + "(" + entry.getKey().getSymbol() + ")"); - if(it_entry.hasNext()) { - tmpLabel.append(","); - } else { - tmpLabel.append(";"); - } - entry = null; - } - it_entry = null; - if(!(lastTaskNodes[cNum].equals("first"))) { - if (!(lastTaskNodes[cNum].equals(tmpTaskNode))) { - output.print("\t"); - output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";"); - lastTaskNodes[cNum] = tmpTaskNode; - } - if(tmpisset.contains(cNum)) { - isTaskFinish[cNum] &= true; - } else { - isTaskFinish[cNum] = true; - tmpisset.add(cNum); - } - lastTasks[cNum] = ""; - } else { - throw new Exception("Error: unexpected task finish"); - } - break; - } - - case Action.TASKSTART: { - if(!isfirst) { - tmpLabel.append("\\n"); - } - tmpLabel.append("<" + taction.getTd().getSymbol() + "("); - /*Vector taskparams = taction.getTaskParams(); - for(int ii = 0; ii < taskparams.size(); ii++) { - tmpLabel.append(taskparams.elementAt(ii)); - if(ii < taskparams.size() - 1) { - tmpLabel.append(","); - } - }*/ - tmpLabel.append(")>starts;"); - lastTasks[cNum] = taction.getTd().getSymbol(); - - if (!(lastTaskNodes[cNum].equals(tmpTaskNode))) { - output.print("\t"); - if(lastTaskNodes[cNum].equals("first")) { - output.print("\"core " + cNum + "\"->" + tmpTaskNode); - } else { - output.print(lastTaskNodes[cNum] + "->" + tmpTaskNode); - } - if(tmpisTaskFinish.contains(cNum)) { - output.print(" [style=invis]"); - } - output.println(";"); - lastTaskNodes[cNum] = tmpTaskNode; - } - isTaskFinish[cNum] &= false; - break; - } - - case Action.TASKABORT: { - if(!isfirst) { - tmpLabel.append("\\n"); - } - tmpLabel.append("<" + taction.getTd().getSymbol() + "("); - /*Vector taskparams = taction.getTaskParams(); - for(int ii = 0; ii < taskparams.size(); ii++) { - tmpLabel.append(taskparams.elementAt(ii)); - if(ii < taskparams.size() - 1) { - tmpLabel.append(","); - } - }*/ - tmpLabel.append(")>aborts;"); - if(!(lastTaskNodes[cNum].equals("first")) && - (tmplastTasks.get(cNum).equals(taction.getTd().getSymbol()))) { - if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) { - output.print("\t"); - output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";"); - lastTaskNodes[cNum] = tmpTaskNode; - } - if(tmpisset.contains(cNum)) { - isTaskFinish[cNum] &= true; - } else { - isTaskFinish[cNum] = true; - tmpisset.add(cNum); - } - lastTasks[cNum] = ""; - } else { - throw new Exception("Error: unexpected task aborts"); - } - break; - } - - case Action.TASKREMOVE: { - if(!isfirst) { - tmpLabel.append("\\n"); - } - tmpLabel.append("<" + taction.getTd().getSymbol() + "("); - /*Vector taskparams = taction.getTaskParams(); - for(int ii = 0; ii < taskparams.size(); ii++) { - tmpLabel.append(taskparams.elementAt(ii)); - if(ii < taskparams.size() - 1) { - tmpLabel.append(","); - } - }*/ - tmpLabel.append(")>removes;"); - if(!(lastTaskNodes[cNum].equals("first")) && - (tmplastTasks.get(cNum).equals(taction.getTd().getSymbol()))) { - if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) { - output.print("\t"); - output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";"); - lastTaskNodes[cNum] = tmpTaskNode; - } - if(tmpisset.contains(cNum)) { - isTaskFinish[cNum] &= true; - } else { - isTaskFinish[cNum] = true; - tmpisset.add(cNum); - } - lastTasks[cNum] = ""; - } else { - throw new Exception("Error: unexpected task remove"); - } - break; - } - } - } - Enumeration keys = tmpTaskNodes.keys(); - while(keys.hasMoreElements()) { - String tmpTaskNode = keys.nextElement(); - output.print("\t"); - output.println(tmpTaskNode + "[label=\"" + tmpTaskNodes.get(tmpTaskNode).toString() + "\"]"); - } - output.print("\t"); - output.print("{rank=same; rankdir=LR; " + tnode + "; "); - keys = tmpTaskNodes.keys(); - while(keys.hasMoreElements()) { - String tmpTaskNode = keys.nextElement(); - output.print(tmpTaskNode); - output.print("; "); - } - keys = null; - output.println("}"); - output.print("\t"); - tmplastTasks = null; - tmpisTaskFinish = null; - tmpisset = null; - actions = null; - tmpTaskNodes = null; + CheckPoint tcp = checkpoints.elementAt(j); + Hashtable tmplastTasks = new Hashtable(); + Vector tmpisTaskFinish = new Vector(); + Vector tmpisset = new Vector(); + String tnode = String.valueOf(tcp.getTimepoint()); + if(!timeNodes.contains(tnode)) { + timeNodes.add(tnode); + } + Vector actions = tcp.getActions(); + Hashtable tmpTaskNodes = new Hashtable(); + for(int i = 0; i < actions.size(); i++) { + Action taction = actions.elementAt(i); + int cNum = taction.getCoreNum(); + if(!tmplastTasks.containsKey(cNum)) { + tmplastTasks.put(cNum, lastTasks[cNum]); + } + if(!(tmpisset.contains(cNum)) + && (isTaskFinish[cNum]) + && !(tmpisTaskFinish.contains(cNum))) { + tmpisTaskFinish.add(cNum); // records those with task finished the first time visit it + } + String tmpTaskNode = "\"" + tnode + "core" + cNum + "\""; + StringBuffer tmpLabel = null; + boolean isfirst = false; + if(!tmpTaskNodes.containsKey(tmpTaskNode)) { + tmpTaskNodes.put(tmpTaskNode, new StringBuffer(tnode + ":")); + isfirst = true; + } + tmpLabel = tmpTaskNodes.get(tmpTaskNode); + switch(taction.getType()) { + case Action.ADDOBJ: { + if(!isfirst) { + tmpLabel.append("\\n"); + } + tmpLabel.append("(" + taction.getTransObj().getSymbol() + ")arrives;"); + if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) { + output.print("\t"); + if(lastTaskNodes[cNum].equals("first")) { + output.print("\"core " + cNum + "\"->" + tmpTaskNode); + } else { + output.print(lastTaskNodes[cNum] + "->" + tmpTaskNode); + } + if(tmpisTaskFinish.contains(cNum)) { + output.print(" [style=invis]"); + } + output.println(";"); + lastTaskNodes[cNum] = tmpTaskNode; + } + break; + } + + case Action.TASKFINISH: { + if(!isfirst) { + tmpLabel.append("\\n"); + } + tmpLabel.append("<" + taction.getTd().getSymbol() + "("); + /*Vector taskparams = taction.getTaskParams(); + for(int ii = 0; ii < taskparams.size(); ii++) { + tmpLabel.append(taskparams.elementAt(ii)); + if(ii < taskparams.size() - 1) { + tmpLabel.append(","); + } + }*/ + tmpLabel.append(")>finishes;"); + if(!(lastTaskNodes[cNum].equals("first"))) { + if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) { + output.print("\t"); + output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";"); + lastTaskNodes[cNum] = tmpTaskNode; + } + if(tmpisset.contains(cNum)) { + isTaskFinish[cNum] &= true; + } else { + isTaskFinish[cNum] = true; + tmpisset.add(cNum); + } + lastTasks[cNum] = ""; + } else { + throw new Exception("Error: unexpected task finish"); + } + break; + } + + case Action.TFWITHOBJ: { + if(!isfirst) { + tmpLabel.append("\\n"); + } + tmpLabel.append("<" + taction.getTd().getSymbol() + "("); + /*Vector taskparams = taction.getTaskParams(); + for(int ii = 0; ii < taskparams.size(); ii++) { + tmpLabel.append(taskparams.elementAt(ii)); + if(ii < taskparams.size() - 1) { + tmpLabel.append(","); + } + }*/ + tmpLabel.append(")>finishes;"); + Iterator> it_entry = (Iterator>)taction.getNObjs().entrySet().iterator(); + while(it_entry.hasNext()) { + Entry entry = it_entry.next(); + tmpLabel.append(entry.getValue() + "(" + entry.getKey().getSymbol() + ")"); + if(it_entry.hasNext()) { + tmpLabel.append(","); + } else { + tmpLabel.append(";"); + } + entry = null; + } + it_entry = null; + if(!(lastTaskNodes[cNum].equals("first"))) { + if (!(lastTaskNodes[cNum].equals(tmpTaskNode))) { + output.print("\t"); + output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";"); + lastTaskNodes[cNum] = tmpTaskNode; + } + if(tmpisset.contains(cNum)) { + isTaskFinish[cNum] &= true; + } else { + isTaskFinish[cNum] = true; + tmpisset.add(cNum); + } + lastTasks[cNum] = ""; + } else { + throw new Exception("Error: unexpected task finish"); + } + break; + } + + case Action.TASKSTART: { + if(!isfirst) { + tmpLabel.append("\\n"); + } + tmpLabel.append("<" + taction.getTd().getSymbol() + "("); + /*Vector taskparams = taction.getTaskParams(); + for(int ii = 0; ii < taskparams.size(); ii++) { + tmpLabel.append(taskparams.elementAt(ii)); + if(ii < taskparams.size() - 1) { + tmpLabel.append(","); + } + }*/ + tmpLabel.append(")>starts;"); + lastTasks[cNum] = taction.getTd().getSymbol(); + + if (!(lastTaskNodes[cNum].equals(tmpTaskNode))) { + output.print("\t"); + if(lastTaskNodes[cNum].equals("first")) { + output.print("\"core " + cNum + "\"->" + tmpTaskNode); + } else { + output.print(lastTaskNodes[cNum] + "->" + tmpTaskNode); + } + if(tmpisTaskFinish.contains(cNum)) { + output.print(" [style=invis]"); + } + output.println(";"); + lastTaskNodes[cNum] = tmpTaskNode; + } + isTaskFinish[cNum] &= false; + break; + } + + case Action.TASKABORT: { + if(!isfirst) { + tmpLabel.append("\\n"); + } + tmpLabel.append("<" + taction.getTd().getSymbol() + "("); + /*Vector taskparams = taction.getTaskParams(); + for(int ii = 0; ii < taskparams.size(); ii++) { + tmpLabel.append(taskparams.elementAt(ii)); + if(ii < taskparams.size() - 1) { + tmpLabel.append(","); + } + }*/ + tmpLabel.append(")>aborts;"); + if(!(lastTaskNodes[cNum].equals("first")) && + (tmplastTasks.get(cNum).equals(taction.getTd().getSymbol()))) { + if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) { + output.print("\t"); + output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";"); + lastTaskNodes[cNum] = tmpTaskNode; + } + if(tmpisset.contains(cNum)) { + isTaskFinish[cNum] &= true; + } else { + isTaskFinish[cNum] = true; + tmpisset.add(cNum); + } + lastTasks[cNum] = ""; + } else { + throw new Exception("Error: unexpected task aborts"); + } + break; + } + + case Action.TASKREMOVE: { + if(!isfirst) { + tmpLabel.append("\\n"); + } + tmpLabel.append("<" + taction.getTd().getSymbol() + "("); + /*Vector taskparams = taction.getTaskParams(); + for(int ii = 0; ii < taskparams.size(); ii++) { + tmpLabel.append(taskparams.elementAt(ii)); + if(ii < taskparams.size() - 1) { + tmpLabel.append(","); + } + }*/ + tmpLabel.append(")>removes;"); + if(!(lastTaskNodes[cNum].equals("first")) && + (tmplastTasks.get(cNum).equals(taction.getTd().getSymbol()))) { + if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) { + output.print("\t"); + output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";"); + lastTaskNodes[cNum] = tmpTaskNode; + } + if(tmpisset.contains(cNum)) { + isTaskFinish[cNum] &= true; + } else { + isTaskFinish[cNum] = true; + tmpisset.add(cNum); + } + lastTasks[cNum] = ""; + } else { + throw new Exception("Error: unexpected task remove"); + } + break; + } + } + } + Enumeration keys = tmpTaskNodes.keys(); + while(keys.hasMoreElements()) { + String tmpTaskNode = keys.nextElement(); + output.print("\t"); + output.println(tmpTaskNode + "[label=\"" + tmpTaskNodes.get(tmpTaskNode).toString() + "\"]"); + } + output.print("\t"); + output.print("{rank=same; rankdir=LR; " + tnode + "; "); + keys = tmpTaskNodes.keys(); + while(keys.hasMoreElements()) { + String tmpTaskNode = keys.nextElement(); + output.print(tmpTaskNode); + output.print("; "); + } + keys = null; + output.println("}"); + output.print("\t"); + tmplastTasks = null; + tmpisTaskFinish = null; + tmpisset = null; + actions = null; + tmpTaskNodes = null; } output.print("\t"); output.print("\t"); @@ -841,37 +841,37 @@ public class SchedulingUtil { long max = 0; long max2 = 0; for(j = 1; j < timeNodes.size(); j++) { - next = Long.parseLong(timeNodes.elementAt(j)); - long delta = next - prev; - if(max < delta) { - max2 = max; - max = delta; - } else if((max != delta) && (max2 < delta)) { - max2 = delta; - } - prev = next; + next = Long.parseLong(timeNodes.elementAt(j)); + long delta = next - prev; + if(max < delta) { + max2 = max; + max = delta; + } else if((max != delta) && (max2 < delta)) { + max2 = delta; + } + prev = next; } if(max2 == 0) { - max2 = 1; + max2 = 1; } else if(max/max2 > 100) { - max2 = max/100; + max2 = max/100; } output.println("\"Time\"->" + timeNodes.elementAt(0) + "[style=invis];"); prev = Long.parseLong(timeNodes.elementAt(0)); next = 0; for(j = 1; j < timeNodes.size(); j++) { - next = Long.parseLong(timeNodes.elementAt(j)); - if(next - prev > max2) { - do { - output.print(prev + "->"); - prev += max2; - } while(next - prev > max2); - output.println(next + ";"); - } else { - output.println("{rank=same; rankdir=LR; " + prev + "; " + next + "}"); - output.println(prev + "->" + next + "[style=invis];"); - } - prev = next; + next = Long.parseLong(timeNodes.elementAt(j)); + if(next - prev > max2) { + do { + output.print(prev + "->"); + prev += max2; + } while(next - prev > max2); + output.println(next + ";"); + } else { + output.println("{rank=same; rankdir=LR; " + prev + "; " + next + "}"); + output.println(prev + "->" + next + "[style=invis];"); + } + prev = next; } /*for(j = 0; j < time; j++) { @@ -910,23 +910,23 @@ public class SchedulingUtil { String dotnodeparams=""; for(int i = 0; i < criticalPath.size(); i++) { - SimExecutionEdge seedge = criticalPath.elementAt(i); - SimExecutionNode startnode = (SimExecutionNode)seedge.getSource(); - SimExecutionNode endnode = (SimExecutionNode)seedge.getTarget(); - if(!nodes.contains(startnode)) { - label = startnode.getCoreNum() + ":" + startnode.getTimepoint(); - output.println("\t" + startnode.getLabel() + " [label=\"" - + label + "\" ];"); - nodes.addElement(startnode); - } - if(!nodes.contains(endnode)) { - label = endnode.getCoreNum() + ":" + endnode.getTimepoint(); - output.println("\t" + endnode.getLabel() + " [label=\"" - + label + "\" ];"); - nodes.addElement(endnode); - } - output.println("\t" + startnode.getLabel() + " -> " + endnode.getLabel() - + " [" + "label=\"" + seedge.getLabel() + "\"];"); + SimExecutionEdge seedge = criticalPath.elementAt(i); + SimExecutionNode startnode = (SimExecutionNode)seedge.getSource(); + SimExecutionNode endnode = (SimExecutionNode)seedge.getTarget(); + if(!nodes.contains(startnode)) { + label = startnode.getCoreNum() + ":" + startnode.getTimepoint(); + output.println("\t" + startnode.getLabel() + " [label=\"" + + label + "\" ];"); + nodes.addElement(startnode); + } + if(!nodes.contains(endnode)) { + label = endnode.getCoreNum() + ":" + endnode.getTimepoint(); + output.println("\t" + endnode.getLabel() + " [label=\"" + + label + "\" ];"); + nodes.addElement(endnode); + } + output.println("\t" + startnode.getLabel() + " -> " + endnode.getLabel() + + " [" + "label=\"" + seedge.getLabel() + "\"];"); } output.println("}"); output.close(); diff --git a/Robust/src/Analysis/Scheduling/SimExecutionEdge.java b/Robust/src/Analysis/Scheduling/SimExecutionEdge.java index 2979ba2d..d54124f2 100644 --- a/Robust/src/Analysis/Scheduling/SimExecutionEdge.java +++ b/Robust/src/Analysis/Scheduling/SimExecutionEdge.java @@ -42,27 +42,27 @@ public class SimExecutionEdge extends Edge { public long getBestStartPoint() { if(this.bestStartPoint == -1) { if((this.predicates != null) && (this.predicates.size() > 0)) { - // have predicates - long starttime = 0; - // check the latest finish time of all the predicates - for(int j = 0; j < this.predicates.size(); j++) { - SimExecutionEdge predicate = this.predicates.elementAt(j); - long tmptime = predicate.getBestStartPoint() + predicate.getWeight(); - if(tmptime > starttime) { - starttime = tmptime; - this.lastpredicateedge = predicate; - if(predicate.getTd() != null) { - this.lastpredicatenode = (SimExecutionNode)predicate.getTarget(); - } else { - // transfer edge - this.lastpredicatenode = (SimExecutionNode)predicate.getSource(); - } - } - } - this.bestStartPoint = starttime; + // have predicates + long starttime = 0; + // check the latest finish time of all the predicates + for(int j = 0; j < this.predicates.size(); j++) { + SimExecutionEdge predicate = this.predicates.elementAt(j); + long tmptime = predicate.getBestStartPoint() + predicate.getWeight(); + if(tmptime > starttime) { + starttime = tmptime; + this.lastpredicateedge = predicate; + if(predicate.getTd() != null) { + this.lastpredicatenode = (SimExecutionNode)predicate.getTarget(); + } else { + // transfer edge + this.lastpredicatenode = (SimExecutionNode)predicate.getSource(); + } + } + } + this.bestStartPoint = starttime; } else { - // no predicates - this.bestStartPoint = 0; + // no predicates + this.bestStartPoint = 0; } } return bestStartPoint; diff --git a/Robust/src/Analysis/Scheduling/TaskSimulator.java b/Robust/src/Analysis/Scheduling/TaskSimulator.java index afef4e9c..e264b6c4 100644 --- a/Robust/src/Analysis/Scheduling/TaskSimulator.java +++ b/Robust/src/Analysis/Scheduling/TaskSimulator.java @@ -48,7 +48,7 @@ public class TaskSimulator { public void addNewObj(ObjectSimulator newObj) { if(this.newObjs == null) { - this.newObjs = new Vector(); + this.newObjs = new Vector(); } this.newObjs.add(newObj); @@ -65,7 +65,7 @@ public class TaskSimulator { public void init() { finishTime = 0; if(newObjs != null) { - newObjs.clear(); + newObjs.clear(); } } } @@ -114,34 +114,34 @@ public class TaskSimulator { for(int i = 0; i < paraNum; i++) { VarDescriptor para = td.getParameter(i); if(cd.equals(para.getType().getClassDesc())) { - // check if the status is right - FlagExpressionNode fen = td.getFlag(para); - FlagState cfs = fs; - if(inherent) { - cfs = obj.getCurrentFS(); - } - if(SchedulingUtil.isTaskTrigger_flag(fen, cfs)) { - if(this.paraQueues == null) { - this.paraQueues = new Vector>(); - for(int j = 0; j < paraNum; j++) { - this.paraQueues.add(null); - } - } - if(this.paraQueues.elementAt(i) == null) { - this.paraQueues.setElementAt(new LinkedList(), i); - } - if(this.objVersionTbl == null) { - this.objVersionTbl = new Hashtable(); - } - if(!this.paraQueues.elementAt(i).contains(obj)) { - this.paraQueues.elementAt(i).add(obj); - if(inherent) { - this.objVersionTbl.put(obj, obj.getVersion()); - } else { - this.objVersionTbl.put(obj, version); - } - } - } + // check if the status is right + FlagExpressionNode fen = td.getFlag(para); + FlagState cfs = fs; + if(inherent) { + cfs = obj.getCurrentFS(); + } + if(SchedulingUtil.isTaskTrigger_flag(fen, cfs)) { + if(this.paraQueues == null) { + this.paraQueues = new Vector>(); + for(int j = 0; j < paraNum; j++) { + this.paraQueues.add(null); + } + } + if(this.paraQueues.elementAt(i) == null) { + this.paraQueues.setElementAt(new LinkedList(), i); + } + if(this.objVersionTbl == null) { + this.objVersionTbl = new Hashtable(); + } + if(!this.paraQueues.elementAt(i).contains(obj)) { + this.paraQueues.elementAt(i).add(obj); + if(inherent) { + this.objVersionTbl.put(obj, obj.getVersion()); + } else { + this.objVersionTbl.put(obj, version); + } + } + } } } } @@ -153,40 +153,40 @@ public class TaskSimulator { for(int i = 0; i < paraNum; i++) { VarDescriptor para = td.getParameter(i); if(cd.equals(para.getType().getClassDesc())) { - if(remove) { - if((this.paraQueues != null) && - (this.paraQueues.elementAt(i) != null) && - (this.paraQueues.elementAt(i).contains(obj))) { - this.paraQueues.elementAt(i).remove(obj); - this.objVersionTbl.remove(obj); - } - } else { - // check if the status is right - FlagExpressionNode fen = td.getFlag(para); - if(SchedulingUtil.isTaskTrigger_flag(fen, obj.getCurrentFS())) { - if(this.paraQueues == null) { - this.paraQueues = new Vector>(); - for(int j = 0; j < paraNum; j++) { - this.paraQueues.add(null); - } - } - if(this.paraQueues.elementAt(i) == null) { - this.paraQueues.setElementAt(new LinkedList(), i); - } - this.paraQueues.elementAt(i).add(obj); - if(this.objVersionTbl == null) { - this.objVersionTbl = new Hashtable(); - } - this.objVersionTbl.put(obj, obj.getVersion()); - } else { - if((this.paraQueues != null) && - (this.paraQueues.elementAt(i) != null) && - (this.paraQueues.elementAt(i).contains(obj))) { - this.paraQueues.elementAt(i).remove(obj); - this.objVersionTbl.remove(obj); - } - } - } + if(remove) { + if((this.paraQueues != null) && + (this.paraQueues.elementAt(i) != null) && + (this.paraQueues.elementAt(i).contains(obj))) { + this.paraQueues.elementAt(i).remove(obj); + this.objVersionTbl.remove(obj); + } + } else { + // check if the status is right + FlagExpressionNode fen = td.getFlag(para); + if(SchedulingUtil.isTaskTrigger_flag(fen, obj.getCurrentFS())) { + if(this.paraQueues == null) { + this.paraQueues = new Vector>(); + for(int j = 0; j < paraNum; j++) { + this.paraQueues.add(null); + } + } + if(this.paraQueues.elementAt(i) == null) { + this.paraQueues.setElementAt(new LinkedList(), i); + } + this.paraQueues.elementAt(i).add(obj); + if(this.objVersionTbl == null) { + this.objVersionTbl = new Hashtable(); + } + this.objVersionTbl.put(obj, obj.getVersion()); + } else { + if((this.paraQueues != null) && + (this.paraQueues.elementAt(i) != null) && + (this.paraQueues.elementAt(i).contains(obj))) { + this.paraQueues.elementAt(i).remove(obj); + this.objVersionTbl.remove(obj); + } + } + } } } } @@ -216,75 +216,75 @@ public class TaskSimulator { for(int i = 0; i < paraQueues.size(); i++) { ObjectSimulator tpara = paraQueues.elementAt(i).peek(); if(tpara == null) { - // the parameter is already removed, delete this task too - finishTime = 800; - this.currentRun.setFinishTime(finishTime); - this.currentRun.setExetype(2); - for(int j = 0; j < i; ++j) { - tpara = this.paraQueues.elementAt(j).poll(); - if(tpara.isShared() && tpara.isHold()) { - tpara.setHold(false); - } - this.paraQueues.elementAt(j).add(tpara); - } - return; + // the parameter is already removed, delete this task too + finishTime = 800; + this.currentRun.setFinishTime(finishTime); + this.currentRun.setExetype(2); + for(int j = 0; j < i; ++j) { + tpara = this.paraQueues.elementAt(j).poll(); + if(tpara.isShared() && tpara.isHold()) { + tpara.setHold(false); + } + this.paraQueues.elementAt(j).add(tpara); + } + return; } if(tpara.isShared()) { - if(tpara.isHold()) { - // shared object held by other tasks - finishTime = 800; // TODO currenly assume the effort on requesting locks are only 800 - /*this.currentRun.setFinishTime(finishTime); - this.currentRun.setExetype(1); - paraQueues.elementAt(i).poll(); - paraQueues.elementAt(i).add(tpara); - for(int j = 0; j < i; ++j) { - tpara = this.paraQueues.elementAt(j).poll(); - if(tpara.isShared() && tpara.isHold()) { - tpara.setHold(false); - } - this.paraQueues.elementAt(j).add(tpara); - }*/ - // remove it instead - this.currentRun.setFinishTime(finishTime); - this.currentRun.setExetype(2); - paraQueues.elementAt(i).poll(); - // remove this object from the remaining parameter queues - for(int j = i + 1; j < paraQueues.size(); j++) { - paraQueues.elementAt(j).remove(tpara); - } - for(int j = 0; j < i; ++j) { - tpara = this.paraQueues.elementAt(j).poll(); - if(tpara.isShared() && tpara.isHold()) { - tpara.setHold(false); - } - this.paraQueues.elementAt(j).add(tpara); - } - return; - } else if (tpara.getVersion() != this.objVersionTbl.get(tpara)) { - // shared object has been updated and no longer fitted to this task - finishTime = 800; // TODO currenly assume the effort on requesting locks are only 800 - this.currentRun.setFinishTime(finishTime); - this.currentRun.setExetype(2); - paraQueues.elementAt(i).poll(); - // remove this object from the remaining parameter queues - for(int j = i + 1; j < paraQueues.size(); j++) { - paraQueues.elementAt(j).remove(tpara); - } - for(int j = 0; j < i; ++j) { - tpara = this.paraQueues.elementAt(j).poll(); - if(tpara.isShared() && tpara.isHold()) { - tpara.setHold(false); - } - this.paraQueues.elementAt(j).add(tpara); - } - return; - } else { - tpara.setHold(true); - } + if(tpara.isHold()) { + // shared object held by other tasks + finishTime = 800; // TODO currenly assume the effort on requesting locks are only 800 + /*this.currentRun.setFinishTime(finishTime); + this.currentRun.setExetype(1); + paraQueues.elementAt(i).poll(); + paraQueues.elementAt(i).add(tpara); + for(int j = 0; j < i; ++j) { + tpara = this.paraQueues.elementAt(j).poll(); + if(tpara.isShared() && tpara.isHold()) { + tpara.setHold(false); + } + this.paraQueues.elementAt(j).add(tpara); + }*/ + // remove it instead + this.currentRun.setFinishTime(finishTime); + this.currentRun.setExetype(2); + paraQueues.elementAt(i).poll(); + // remove this object from the remaining parameter queues + for(int j = i + 1; j < paraQueues.size(); j++) { + paraQueues.elementAt(j).remove(tpara); + } + for(int j = 0; j < i; ++j) { + tpara = this.paraQueues.elementAt(j).poll(); + if(tpara.isShared() && tpara.isHold()) { + tpara.setHold(false); + } + this.paraQueues.elementAt(j).add(tpara); + } + return; + } else if (tpara.getVersion() != this.objVersionTbl.get(tpara)) { + // shared object has been updated and no longer fitted to this task + finishTime = 800; // TODO currenly assume the effort on requesting locks are only 800 + this.currentRun.setFinishTime(finishTime); + this.currentRun.setExetype(2); + paraQueues.elementAt(i).poll(); + // remove this object from the remaining parameter queues + for(int j = i + 1; j < paraQueues.size(); j++) { + paraQueues.elementAt(j).remove(tpara); + } + for(int j = 0; j < i; ++j) { + tpara = this.paraQueues.elementAt(j).poll(); + if(tpara.isShared() && tpara.isHold()) { + tpara.setHold(false); + } + this.paraQueues.elementAt(j).add(tpara); + } + return; + } else { + tpara.setHold(true); + } } // remove this object from the remaining parameter queues for(int j = i + 1; j < paraQueues.size(); j++) { - paraQueues.elementAt(j).remove(tpara); + paraQueues.elementAt(j).remove(tpara); } } long ftime = 0; @@ -296,9 +296,9 @@ public class TaskSimulator { finishTime += toexecute.getExeTime(); // TODO for test if(ftime == 0) { - ftime = toexecute.getExeTime(); + ftime = toexecute.getExeTime(); } else if(ftime != toexecute.getExeTime()) { - //System.err.println("error for simulation: " + td.getSymbol()); + //System.err.println("error for simulation: " + td.getSymbol()); } // TODO for test /*if(td.getSymbol().equals("addIYLM")) { @@ -306,20 +306,20 @@ public class TaskSimulator { }*/ if((toexecute.getNewObjInfoHashtable() != null) && (toexecute.getNewObjInfoHashtable().size() > 0)) { - // have new objects - Iterator it = toexecute.getNewObjInfoHashtable().keySet().iterator(); - int invokeNum = toexecute.getInvokeNum(); - while(it.hasNext()) { - ClassDescriptor cd = (ClassDescriptor)it.next(); - NewObjInfo noi = toexecute.getNewObjInfo(cd); - if(noi.getInvokeNum() < ((int)Math.round(((noi.getProbability() / 100) * noi.getNewRate() * invokeNum)))) { - for(int j = 0; j < noi.getNewRate(); j++) { - ObjectSimulator tmpObj = new ObjectSimulator(cd, noi.getRoot()); - this.currentRun.addNewObj(tmpObj); - noi.incInvokeNum(); - } - } - } + // have new objects + Iterator it = toexecute.getNewObjInfoHashtable().keySet().iterator(); + int invokeNum = toexecute.getInvokeNum(); + while(it.hasNext()) { + ClassDescriptor cd = (ClassDescriptor)it.next(); + NewObjInfo noi = toexecute.getNewObjInfo(cd); + if(noi.getInvokeNum() < ((int)Math.round(((noi.getProbability() / 100) * noi.getNewRate() * invokeNum)))) { + for(int j = 0; j < noi.getNewRate(); j++) { + ObjectSimulator tmpObj = new ObjectSimulator(cd, noi.getRoot()); + this.currentRun.addNewObj(tmpObj); + noi.incInvokeNum(); + } + } + } } tpara.applyEdge(toexecute); tpara.increaseVersion(); diff --git a/Robust/src/Analysis/TaskStateAnalysis/ExecutionGraph.java b/Robust/src/Analysis/TaskStateAnalysis/ExecutionGraph.java index ba0c6249..21bdb9e8 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/ExecutionGraph.java +++ b/Robust/src/Analysis/TaskStateAnalysis/ExecutionGraph.java @@ -50,28 +50,28 @@ public class ExecutionGraph { while (it.hasNext()) { FlagState fs = it.next(); if(fs.isSourceNode()) { - for (Iterator allocit = ((Vector)fs.getAllocatingTasks()).iterator(); allocit.hasNext(); ) { - TaskDescriptor alloctask=(TaskDescriptor)allocit.next(); - EGTaskNode srcnode=new EGTaskNode(alloctask.getSymbol(),alloctask, fs); - nodes.add(srcnode); - srcnode.setSource(); - for (Iterator edges = fs.edges(); edges.hasNext(); ) { - FEdge edge = (FEdge)edges.next(); - EGTaskNode targetnode=getNode(edge, map, nodes); - EGEdge newedge=new EGEdge(fs, targetnode); - srcnode.addEdge(newedge); - } - } + for (Iterator allocit = ((Vector)fs.getAllocatingTasks()).iterator(); allocit.hasNext(); ) { + TaskDescriptor alloctask=(TaskDescriptor)allocit.next(); + EGTaskNode srcnode=new EGTaskNode(alloctask.getSymbol(),alloctask, fs); + nodes.add(srcnode); + srcnode.setSource(); + for (Iterator edges = fs.edges(); edges.hasNext(); ) { + FEdge edge = (FEdge)edges.next(); + EGTaskNode targetnode=getNode(edge, map, nodes); + EGEdge newedge=new EGEdge(fs, targetnode); + srcnode.addEdge(newedge); + } + } } for(Iterator init=fs.inedges(); init.hasNext(); ) { - FEdge inedge=(FEdge)init.next(); - EGTaskNode srcnode=getNode(inedge, map, nodes); - for(Iterator outit=fs.edges(); outit.hasNext(); ) { - FEdge outedge=(FEdge)outit.next(); - EGTaskNode dstnode=getNode(outedge, map, nodes); - EGEdge newedge=new EGEdge(fs,dstnode); - srcnode.addEdge(newedge); - } + FEdge inedge=(FEdge)init.next(); + EGTaskNode srcnode=getNode(inedge, map, nodes); + for(Iterator outit=fs.edges(); outit.hasNext(); ) { + FEdge outedge=(FEdge)outit.next(); + EGTaskNode dstnode=getNode(outedge, map, nodes); + EGEdge newedge=new EGEdge(fs,dstnode); + srcnode.addEdge(newedge); + } } } @@ -135,7 +135,7 @@ public class ExecutionGraph { output.println("];"); for(Iterator it2 = tn.edges(); it2.hasNext(); ) { - output.println("\t"+tn.getLabel()+" -> "+((EGTaskNode)((EGEdge)it2.next()).getTarget()).getLabel()+";"); + output.println("\t"+tn.getLabel()+" -> "+((EGTaskNode)((EGEdge)it2.next()).getTarget()).getLabel()+";"); } } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/FEdge.java b/Robust/src/Analysis/TaskStateAnalysis/FEdge.java index c71babb6..a1029265 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/FEdge.java +++ b/Robust/src/Analysis/TaskStateAnalysis/FEdge.java @@ -72,13 +72,13 @@ public class FEdge extends Edge { public boolean equals(Object o) { if (o instanceof NewObjInfo) { - NewObjInfo e=(NewObjInfo)o; - if (e.newRate == this.newRate && - e.probability == this.probability && - e.invokeNum == this.invokeNum && - e.root.equals(this.root)) { - return true; - } + NewObjInfo e=(NewObjInfo)o; + if (e.newRate == this.newRate && + e.probability == this.probability && + e.invokeNum == this.invokeNum && + e.root.equals(this.root)) { + return true; + } } return false; } @@ -158,14 +158,14 @@ public class FEdge extends Edge { e.executeTime == executeTime && e.m_taskexitindex == m_taskexitindex && e.m_isbackedge == m_isbackedge) { - if(this.newObjInfos != null) { - if(e.newObjInfos == null) { - return false; - } else { - return e.newObjInfos.equals(this.newObjInfos); - } - } - return true; + if(this.newObjInfos != null) { + if(e.newObjInfos == null) { + return false; + } else { + return e.newObjInfos.equals(this.newObjInfos); + } + } + return true; } } return false; @@ -203,7 +203,7 @@ public class FEdge extends Edge { if(this.newObjInfos != null) { Iterator it_nobjs = this.newObjInfos.values().iterator(); while(it_nobjs.hasNext()) { - it_nobjs.next().invokeNum = 0; + it_nobjs.next().invokeNum = 0; } } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/FlagInfo.java b/Robust/src/Analysis/TaskStateAnalysis/FlagInfo.java index 80f758a7..60c2b148 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/FlagInfo.java +++ b/Robust/src/Analysis/TaskStateAnalysis/FlagInfo.java @@ -37,11 +37,11 @@ public class FlagInfo { /* Adding the flags of the super class */ ClassDescriptor tmp=cd; while(tmp!=null) { - for(Iterator it_cflags=tmp.getFlags(); it_cflags.hasNext(); ) { - FlagDescriptor fd = (FlagDescriptor)it_cflags.next(); - vFlags.add(fd); - } - tmp=tmp.getSuperDesc(); + for(Iterator it_cflags=tmp.getFlags(); it_cflags.hasNext(); ) { + FlagDescriptor fd = (FlagDescriptor)it_cflags.next(); + vFlags.add(fd); + } + tmp=tmp.getSuperDesc(); } flag=new FlagDescriptor[vFlags.size()]; diff --git a/Robust/src/Analysis/TaskStateAnalysis/FlagState.java b/Robust/src/Analysis/TaskStateAnalysis/FlagState.java index 6a02b65e..d80e4832 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/FlagState.java +++ b/Robust/src/Analysis/TaskStateAnalysis/FlagState.java @@ -153,20 +153,20 @@ public class FlagState extends GraphNode implements Cloneable { if (set) { int count=0; if (tags.containsKey(tag)) - count=tags.get(tag).intValue(); + count=tags.get(tag).intValue(); if (count newtags=(Hashtable)tags.clone(); - newtags.remove(tag); - return new FlagState[] {new FlagState(newset,cd,newtags)}; + HashSet newset=(HashSet)flagstate.clone(); + Hashtable newtags=(Hashtable)tags.clone(); + newtags.remove(tag); + return new FlagState[] {new FlagState(newset,cd,newtags)}; case MULTITAGS: - //two possibilities - count remains 2 or becomes 1 - //2 case - HashSet newset1=(HashSet)flagstate.clone(); - Hashtable newtags1=(Hashtable)tags.clone(); - - //1 case - HashSet newset2=(HashSet)flagstate.clone(); - Hashtable newtags2=(Hashtable)tags.clone(); - newtags1.put(tag,new Integer(ONETAG)); - return new FlagState[] {new FlagState(newset1, cd, newtags2), - new FlagState(newset2, cd, newtags2)}; + //two possibilities - count remains 2 or becomes 1 + //2 case + HashSet newset1=(HashSet)flagstate.clone(); + Hashtable newtags1=(Hashtable)tags.clone(); + + //1 case + HashSet newset2=(HashSet)flagstate.clone(); + Hashtable newtags2=(Hashtable)tags.clone(); + newtags1.put(tag,new Integer(ONETAG)); + return new FlagState[] {new FlagState(newset1, cd, newtags2), + new FlagState(newset2, cd, newtags2)}; default: - throw new Error(); + throw new Error(); } } else { throw new Error("Invalid Operation: Can not clear a tag that doesn't exist."); @@ -243,9 +243,9 @@ public class FlagState extends GraphNode implements Cloneable { StringBuffer sb = new StringBuffer(flagstate.size()); for(int i=0; i < flags.length; i++) { if (get(flags[i])) - sb.append(1); + sb.append(1); else - sb.append(0); + sb.append(0); } return new String(sb); @@ -284,9 +284,9 @@ public class FlagState extends GraphNode implements Cloneable { if (o instanceof FlagState) { FlagState fs=(FlagState)o; if (fs.cd!=cd) - return false; + return false; if(fs.byObj != this.byObj) { - return false; + return false; } return (fs.flagstate.equals(flagstate) & fs.tags.equals(tags)); } @@ -306,29 +306,29 @@ public class FlagState extends GraphNode implements Cloneable { for(Iterator it=getFlags(); it.hasNext(); ) { FlagDescriptor fd=(FlagDescriptor) it.next(); if (label==null) - label=fd.toString(); + label=fd.toString(); else - label+=", "+fd.toString(); + label+=", "+fd.toString(); } for (Enumeration en_tags=getTags(); en_tags.hasMoreElements(); ) { TagDescriptor td=(TagDescriptor)en_tags.nextElement(); switch (tags.get(td).intValue()) { case ONETAG: - if (label==null) - label=td.toString()+"(1)"; - else - label+=", "+td.toString()+"(1)"; - break; + if (label==null) + label=td.toString()+"(1)"; + else + label+=", "+td.toString()+"(1)"; + break; case MULTITAGS: - if (label==null) - label=td.toString()+"(n)"; - else - label+=", "+td.toString()+"(n)"; - break; + if (label==null) + label=td.toString()+"(n)"; + else + label+=", "+td.toString()+"(n)"; + break; default: - break; + break; } } if (label==null) @@ -343,15 +343,15 @@ public class FlagState extends GraphNode implements Cloneable { public long getExeTime() { try { if(this.executeTime == -1) { - if(this.visited4time == -1) { - this.visited4time = 0; - calExeTime(); - } else { - // visited, this node is in a loop - // TODO - // currently set 10 as the largest time - this.executeTime = FlagState.MAXTIME; - } + if(this.visited4time == -1) { + this.visited4time = 0; + calExeTime(); + } else { + // visited, this node is in a loop + // TODO + // currently set 10 as the largest time + this.executeTime = FlagState.MAXTIME; + } } } catch (Exception e) { e.printStackTrace(); @@ -385,19 +385,19 @@ public class FlagState extends GraphNode implements Cloneable { if(it.hasNext()) { FEdge fe = (FEdge)it.next(); while((fe != null) && (fe.getTarget().equals(this))) { - if(it.hasNext()) { - fe = (FEdge)it.next(); - } else { - fe = null; - } + if(it.hasNext()) { + fe = (FEdge)it.next(); + } else { + fe = null; + } } if(fe == null) { - this.executeTime = 0; + this.executeTime = 0; } else { - if(fe.getExeTime() == -1) { - throw new Exception("Error: Uninitiate FEdge!"); - } - this.executeTime = fe.getExeTime() + ((FlagState)fe.getTarget()).getExeTime(); + if(fe.getExeTime() == -1) { + throw new Exception("Error: Uninitiate FEdge!"); + } + this.executeTime = fe.getExeTime() + ((FlagState)fe.getTarget()).getExeTime(); } } else { this.executeTime = 0; @@ -406,7 +406,7 @@ public class FlagState extends GraphNode implements Cloneable { FEdge fe = (FEdge)it.next(); long temp = fe.getExeTime() + ((FlagState)fe.getTarget()).getExeTime(); if(temp < this.executeTime) { - this.executeTime = temp; + this.executeTime = temp; } } } @@ -445,9 +445,9 @@ public class FlagState extends GraphNode implements Cloneable { for(int i = 0; i < this.edges.size(); i++) { next = (FEdge) this.edges.elementAt(i); if(this.byObj == 0) { - next.setExpInvokeNum((int)(Math.ceil(this.invokeNum * next.getProbability() / 100))); + next.setExpInvokeNum((int)(Math.ceil(this.invokeNum * next.getProbability() / 100))); } else { - next.setExpInvokeNum((int)(Math.ceil(((this.invokeNum - 1) / this.byObj + 1) * next.getProbability() / 100))); + next.setExpInvokeNum((int)(Math.ceil(((this.invokeNum - 1) / this.byObj + 1) * next.getProbability() / 100))); } } @@ -462,22 +462,22 @@ public class FlagState extends GraphNode implements Cloneable { int temp = (this.byObj == 0)?next.getInvokeNumGap():next.getInvokeNumGapByObj(this.byObj); boolean exchange = false; if((temp > gap) && (next.getTask().equals(td))) { - exchange = true; + exchange = true; } else if(temp == gap) { - if(next.getProbability() > prob) { - exchange = true; - } else if(next.getProbability() == prob) { - if(!isbackedge && next.isbackedge()) { - // backedge has higher priority - exchange = true; - } - } + if(next.getProbability() > prob) { + exchange = true; + } else if(next.getProbability() == prob) { + if(!isbackedge && next.isbackedge()) { + // backedge has higher priority + exchange = true; + } + } } if(exchange) { - index = i; - gap = temp; - prob = next.getProbability(); - isbackedge = next.isbackedge(); + index = i; + gap = temp; + prob = next.getProbability(); + isbackedge = next.isbackedge(); } } next = (FEdge) this.edges.elementAt(index); diff --git a/Robust/src/Analysis/TaskStateAnalysis/GarbageAnalysis.java b/Robust/src/Analysis/TaskStateAnalysis/GarbageAnalysis.java index 8045bd7a..fa7cf3d4 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/GarbageAnalysis.java +++ b/Robust/src/Analysis/TaskStateAnalysis/GarbageAnalysis.java @@ -24,7 +24,7 @@ public class GarbageAnalysis extends Namer { for(Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); it.hasNext(); ) { ClassDescriptor cd=(ClassDescriptor) it.next(); if (taskanalysis.getFlagStates(cd)==null) - continue; + continue; analyzeClass(cd); } } @@ -37,7 +37,7 @@ public class GarbageAnalysis extends Namer { for(Iterator fsit=flagstatenodes.iterator(); fsit.hasNext(); ) { FlagState fs=(FlagState)fsit.next(); if (fs.numedges()==0) - garbage.add(fs); + garbage.add(fs); } Stack tovisit=new Stack(); @@ -46,12 +46,12 @@ public class GarbageAnalysis extends Namer { while(!tovisit.isEmpty()) { FlagState fs=(FlagState)tovisit.pop(); for(int i=0; i()); - table.get(node.getFS()).add(node); + if (!table.containsKey(node.getFS())) + table.put(node.getFS(), new HashSet()); + table.get(node.getFS()).add(node); } } return table; @@ -78,9 +78,9 @@ public class SafetyAnalysis { for(Iterator it=((Set)executiongraph.get(cd)).iterator(); it.hasNext(); ) { EGTaskNode node=(EGTaskNode)it.next(); if (node.getFS()!=null) { - if (!table.containsKey(node.getPostFS())) - table.put(node.getPostFS(), new HashSet()); - table.get(node.getPostFS()).add(node.getFS()); + if (!table.containsKey(node.getPostFS())) + table.put(node.getPostFS(), new HashSet()); + table.get(node.getPostFS()).add(node.getFS()); } } return table; @@ -92,7 +92,7 @@ public class SafetyAnalysis { while (classit.hasMoreElements()) { ClassDescriptor cd=(ClassDescriptor)classit.nextElement(); if (!executiongraph.containsKey(cd)) - continue; + continue; Hashtable> fstootd=new Hashtable>(); safeexecution.put(cd, fstootd); @@ -105,12 +105,12 @@ public class SafetyAnalysis { tovisit.addAll(taskanalysis.getFlagStates(cd)); while(!tovisit.isEmpty()) { - FlagState fs=tovisit.iterator().next(); - tovisit.remove(fs); - if (!fstoegmap.containsKey(fs)) - continue; //This FS has no task that can trigger on it - Set nodeset=fstoegmap.get(fs); - analyzeFS(fs, nodeset, fstootd, fsusemap, tovisit); + FlagState fs=tovisit.iterator().next(); + tovisit.remove(fs); + if (!fstoegmap.containsKey(fs)) + continue; //This FS has no task that can trigger on it + Set nodeset=fstoegmap.get(fs); + analyzeFS(fs, nodeset, fstootd, fsusemap, tovisit); } } printTEST(); @@ -124,85 +124,85 @@ public class SafetyAnalysis { EGTaskNode egnode=egit.next(); Set setotd; if (egnode.isOptional()) { - setotd=new HashSet(); - HashSet enterfsset=new HashSet(); - enterfsset.add(fs); - ClassDescriptor cd=fs.getClassDescriptor(); - OptionalTaskDescriptor newotd=new OptionalTaskDescriptor(egnode.getTD(), egnode.getIndex(), enterfsset, new Predicate()); - if(optionaltaskdescriptors.get(cd).containsKey(newotd)) { - newotd = optionaltaskdescriptors.get(cd).get(newotd); - } else { - newotd.setuid(); - resultingFS(newotd); - optionaltaskdescriptors.get(cd).put(newotd, newotd); - } - setotd.add(newotd); + setotd=new HashSet(); + HashSet enterfsset=new HashSet(); + enterfsset.add(fs); + ClassDescriptor cd=fs.getClassDescriptor(); + OptionalTaskDescriptor newotd=new OptionalTaskDescriptor(egnode.getTD(), egnode.getIndex(), enterfsset, new Predicate()); + if(optionaltaskdescriptors.get(cd).containsKey(newotd)) { + newotd = optionaltaskdescriptors.get(cd).get(newotd); + } else { + newotd.setuid(); + resultingFS(newotd); + optionaltaskdescriptors.get(cd).put(newotd, newotd); + } + setotd.add(newotd); } else if (tagChange(egnode)) { - //Conservatively handle tag changes - setotd=new HashSet(); + //Conservatively handle tag changes + setotd=new HashSet(); } else if(egnode.isMultipleParams()) { - if( goodMultiple(egnode)) { - Predicate p=returnPredicate(egnode); - Set oldsetotd; - if (fstootd.containsKey(egnode.getPostFS())) - oldsetotd=fstootd.get(egnode.getPostFS()); - else - oldsetotd=new HashSet(); - setotd=new HashSet(); - for(Iterator otdit=oldsetotd.iterator(); otdit.hasNext(); ) { - OptionalTaskDescriptor oldotd=otdit.next(); - Predicate newp=combinePredicates(oldotd.predicate, p); - OptionalTaskDescriptor newotd=new OptionalTaskDescriptor(oldotd.td, oldotd.getIndex(), oldotd.enterflagstates, newp); - ClassDescriptor cd=fs.getClassDescriptor(); - if(optionaltaskdescriptors.get(cd).containsKey(newotd)) { - newotd = optionaltaskdescriptors.get(cd).get(newotd); - } else { - newotd.setuid(); - resultingFS(newotd); - optionaltaskdescriptors.get(cd).put(newotd, newotd); - } - setotd.add(newotd); - } - } else { - //Can't propagate anything - setotd=new HashSet(); - } + if( goodMultiple(egnode)) { + Predicate p=returnPredicate(egnode); + Set oldsetotd; + if (fstootd.containsKey(egnode.getPostFS())) + oldsetotd=fstootd.get(egnode.getPostFS()); + else + oldsetotd=new HashSet(); + setotd=new HashSet(); + for(Iterator otdit=oldsetotd.iterator(); otdit.hasNext(); ) { + OptionalTaskDescriptor oldotd=otdit.next(); + Predicate newp=combinePredicates(oldotd.predicate, p); + OptionalTaskDescriptor newotd=new OptionalTaskDescriptor(oldotd.td, oldotd.getIndex(), oldotd.enterflagstates, newp); + ClassDescriptor cd=fs.getClassDescriptor(); + if(optionaltaskdescriptors.get(cd).containsKey(newotd)) { + newotd = optionaltaskdescriptors.get(cd).get(newotd); + } else { + newotd.setuid(); + resultingFS(newotd); + optionaltaskdescriptors.get(cd).put(newotd, newotd); + } + setotd.add(newotd); + } + } else { + //Can't propagate anything + setotd=new HashSet(); + } } else { - if (fstootd.containsKey(egnode.getPostFS())) - setotd=fstootd.get(egnode.getPostFS()); - else - setotd=new HashSet(); + if (fstootd.containsKey(egnode.getPostFS())) + setotd=fstootd.get(egnode.getPostFS()); + else + setotd=new HashSet(); } TaskIndex ti=egnode.isRuntime()?new TaskIndex():new TaskIndex(egnode.getTD(), egnode.getIndex()); if (!ti.runtime) { - //runtime edges don't do anything...don't have to take - //them, can't predict when we can. - if (state.selfloops.contains(egnode.getTD().getSymbol())) { - System.out.println("Self loop for: "+egnode.getTD()+" "+egnode.getIndex()); - if (timap.containsKey(ti)) { - if (egnode.getPostFS()!=fs) { - if (tiselfloops.contains(ti)) { - //dump old self loop - timap.put(ti, setotd); - tiselfloops.remove(ti); - } else { - //standard and case - timap.put(ti, createIntersection(timap.get(ti), setotd, fs.getClassDescriptor())); - } - } - } else { - //mark as self loop - timap.put(ti, setotd); - if (egnode.getPostFS()==fs) { - tiselfloops.add(ti); - } - } - } else if (timap.containsKey(ti)) { - //AND case - timap.put(ti, createIntersection(timap.get(ti), setotd, fs.getClassDescriptor())); - } else { - timap.put(ti, setotd); - } + //runtime edges don't do anything...don't have to take + //them, can't predict when we can. + if (state.selfloops.contains(egnode.getTD().getSymbol())) { + System.out.println("Self loop for: "+egnode.getTD()+" "+egnode.getIndex()); + if (timap.containsKey(ti)) { + if (egnode.getPostFS()!=fs) { + if (tiselfloops.contains(ti)) { + //dump old self loop + timap.put(ti, setotd); + tiselfloops.remove(ti); + } else { + //standard and case + timap.put(ti, createIntersection(timap.get(ti), setotd, fs.getClassDescriptor())); + } + } + } else { + //mark as self loop + timap.put(ti, setotd); + if (egnode.getPostFS()==fs) { + tiselfloops.add(ti); + } + } + } else if (timap.containsKey(ti)) { + //AND case + timap.put(ti, createIntersection(timap.get(ti), setotd, fs.getClassDescriptor())); + } else { + timap.put(ti, setotd); + } } } @@ -218,7 +218,7 @@ public class SafetyAnalysis { fstootd.put(fs, set); //Requeue all flagstates that may use our updated results if (fsusemap.containsKey(fs)) { - tovisit.addAll(fsusemap.get(fs)); + tovisit.addAll(fsusemap.get(fs)); } } fstotimap.put(fs, timap); @@ -229,22 +229,22 @@ public class SafetyAnalysis { for(Iterator b_it = B.iterator(); b_it.hasNext(); ) { OptionalTaskDescriptor otd_b = (OptionalTaskDescriptor)b_it.next(); for(Iterator a_it = A.iterator(); a_it.hasNext(); ) { - OptionalTaskDescriptor otd_a = (OptionalTaskDescriptor)a_it.next(); - if(otd_a.td==otd_b.td&& - otd_a.getIndex()==otd_b.getIndex()) { - HashSet newfs = new HashSet(); - newfs.addAll(otd_a.enterflagstates); - newfs.addAll(otd_b.enterflagstates); - OptionalTaskDescriptor newotd = new OptionalTaskDescriptor(otd_b.td, otd_b.getIndex(), newfs, combinePredicates(otd_a.predicate, otd_b.predicate)); - if(optionaltaskdescriptors.get(cd).get(newotd)!=null) { - newotd = optionaltaskdescriptors.get(cd).get(newotd); - } else { - newotd.setuid(); - resultingFS(newotd); - optionaltaskdescriptors.get(cd).put(newotd, newotd); - } - result.add(newotd); - } + OptionalTaskDescriptor otd_a = (OptionalTaskDescriptor)a_it.next(); + if(otd_a.td==otd_b.td&& + otd_a.getIndex()==otd_b.getIndex()) { + HashSet newfs = new HashSet(); + newfs.addAll(otd_a.enterflagstates); + newfs.addAll(otd_b.enterflagstates); + OptionalTaskDescriptor newotd = new OptionalTaskDescriptor(otd_b.td, otd_b.getIndex(), newfs, combinePredicates(otd_a.predicate, otd_b.predicate)); + if(optionaltaskdescriptors.get(cd).get(newotd)!=null) { + newotd = optionaltaskdescriptors.get(cd).get(newotd); + } else { + newotd.setuid(); + resultingFS(newotd); + optionaltaskdescriptors.get(cd).put(newotd, newotd); + } + result.add(newotd); + } } } return result; @@ -263,15 +263,15 @@ public class SafetyAnalysis { for(Iterator nodeit=nodeset.iterator(); nodeit.hasNext(); ) { FlatNode fn=nodeit.next(); if (fn.kind()==FKind.FlatFlagActionNode) { - FlatFlagActionNode ffan=(FlatFlagActionNode)fn; - if (ffan.getTaskType() == FlatFlagActionNode.TASKEXIT) { - for(Iterator it_tfp=ffan.getTempFlagPairs(); it_tfp.hasNext(); ) { - TempFlagPair tfp=(TempFlagPair)it_tfp.next(); - TempDescriptor tempd = tfp.getTemp(); - if(tempd!=tmp) - return false; //return false if a taskexit modifies one of the other parameters - } - } + FlatFlagActionNode ffan=(FlatFlagActionNode)fn; + if (ffan.getTaskType() == FlatFlagActionNode.TASKEXIT) { + for(Iterator it_tfp=ffan.getTempFlagPairs(); it_tfp.hasNext(); ) { + TempFlagPair tfp=(TempFlagPair)it_tfp.next(); + TempDescriptor tempd = tfp.getTemp(); + if(tempd!=tmp) + return false; //return false if a taskexit modifies one of the other parameters + } + } } } return true; @@ -282,13 +282,13 @@ public class SafetyAnalysis { TaskDescriptor td = tn.getTD(); for(int i=0; i flaglist = new HashSet(); - flaglist.add(td.getFlag(vd)); - result.flags.put(vd, flaglist); - if (td.getTag(vd)!=null) - result.tags.put(vd, td.getTag(vd)); + VarDescriptor vd = td.getParameter(i); + result.vardescriptors.add(vd); + HashSet flaglist = new HashSet(); + flaglist.add(td.getFlag(vd)); + result.flags.put(vd, flaglist); + if (td.getTag(vd)!=null) + result.tags.put(vd, td.getTag(vd)); } } return result; @@ -303,9 +303,9 @@ public class SafetyAnalysis { for(Iterator varit = c.iterator(); varit.hasNext(); ) { //maybe change that VarDescriptor vd = (VarDescriptor)varit.next(); if(result.vardescriptors.contains(vd)) - System.out.println("Already in "); + System.out.println("Already in "); else { - result.vardescriptors.add(vd); + result.vardescriptors.add(vd); } } Collection vardesc = result.vardescriptors; @@ -313,19 +313,19 @@ public class SafetyAnalysis { VarDescriptor vd = (VarDescriptor)varit.next(); HashSet bflags = B.flags.get(vd); if( bflags == null ) { - continue; + continue; } else { - if (result.flags.containsKey(vd)) - ((HashSet)result.flags.get(vd)).addAll(bflags); - else - result.flags.put(vd, bflags); + if (result.flags.containsKey(vd)) + ((HashSet)result.flags.get(vd)).addAll(bflags); + else + result.flags.put(vd, bflags); } TagExpressionList btags = B.tags.get(vd); if( btags != null ) { - if (result.tags.containsKey(vd)) - System.out.println("Tag found but there should be nothing to do because same tag"); - else - result.tags.put(vd, btags); + if (result.tags.containsKey(vd)) + System.out.println("Tag found but there should be nothing to do because same tag"); + else + result.tags.put(vd, btags); } } return result; @@ -353,70 +353,70 @@ public class SafetyAnalysis { while(!nodestack.isEmpty()) { FlatNode fn1 = (FlatNode) nodestack.pop(); if (fn1.kind()==FKind.FlatFlagActionNode) { - FlatFlagActionNode ffan=(FlatFlagActionNode)fn1; - if (ffan.getTaskType() == FlatFlagActionNode.TASKEXIT) { - HashSet tempset = new HashSet(); - for(Iterator it_fs = otd.enterflagstates.iterator(); it_fs.hasNext(); ) { - FlagState fstemp = (FlagState)it_fs.next(); - Vector processed=new Vector(); - - for(Iterator it_tfp=ffan.getTempFlagPairs(); it_tfp.hasNext(); ) { - TempFlagPair tfp=(TempFlagPair)it_tfp.next(); - if (tfp.getTemp()==temp) - fstemp=fstemp.setFlag(tfp.getFlag(),ffan.getFlagChange(tfp)); - } - - processed.add(fstemp); - //Process clears first - - for(Iterator it_ttp=ffan.getTempTagPairs(); it_ttp.hasNext(); ) { - TempTagPair ttp=(TempTagPair)it_ttp.next(); - - if (temp==ttp.getTemp()) { - Vector oldprocess=processed; - processed=new Vector(); - - for (Enumeration en=oldprocess.elements(); en.hasMoreElements(); ) { - FlagState fsworking=(FlagState)en.nextElement(); - if (!ffan.getTagChange(ttp)) { - processed.addAll(Arrays.asList(fsworking.clearTag(ttp.getTag()))); - } else processed.add(fsworking); - } - } - } - //Process sets next - for(Iterator it_ttp=ffan.getTempTagPairs(); it_ttp.hasNext(); ) { - TempTagPair ttp=(TempTagPair)it_ttp.next(); - - if (temp==ttp.getTemp()) { - Vector oldprocess=processed; - processed=new Vector(); - - for (Enumeration en=oldprocess.elements(); en.hasMoreElements(); ) { - FlagState fsworking=(FlagState)en.nextElement(); - if (ffan.getTagChange(ttp)) { - processed.addAll(Arrays.asList(fsworking.setTag(ttp.getTag()))); - } else processed.add(fsworking); - } - } - } - //Add to exit states - tempset.addAll(processed); - } - result.add(tempset); - continue; // avoid queueing the return node if reachable - } + FlatFlagActionNode ffan=(FlatFlagActionNode)fn1; + if (ffan.getTaskType() == FlatFlagActionNode.TASKEXIT) { + HashSet tempset = new HashSet(); + for(Iterator it_fs = otd.enterflagstates.iterator(); it_fs.hasNext(); ) { + FlagState fstemp = (FlagState)it_fs.next(); + Vector processed=new Vector(); + + for(Iterator it_tfp=ffan.getTempFlagPairs(); it_tfp.hasNext(); ) { + TempFlagPair tfp=(TempFlagPair)it_tfp.next(); + if (tfp.getTemp()==temp) + fstemp=fstemp.setFlag(tfp.getFlag(),ffan.getFlagChange(tfp)); + } + + processed.add(fstemp); + //Process clears first + + for(Iterator it_ttp=ffan.getTempTagPairs(); it_ttp.hasNext(); ) { + TempTagPair ttp=(TempTagPair)it_ttp.next(); + + if (temp==ttp.getTemp()) { + Vector oldprocess=processed; + processed=new Vector(); + + for (Enumeration en=oldprocess.elements(); en.hasMoreElements(); ) { + FlagState fsworking=(FlagState)en.nextElement(); + if (!ffan.getTagChange(ttp)) { + processed.addAll(Arrays.asList(fsworking.clearTag(ttp.getTag()))); + } else processed.add(fsworking); + } + } + } + //Process sets next + for(Iterator it_ttp=ffan.getTempTagPairs(); it_ttp.hasNext(); ) { + TempTagPair ttp=(TempTagPair)it_ttp.next(); + + if (temp==ttp.getTemp()) { + Vector oldprocess=processed; + processed=new Vector(); + + for (Enumeration en=oldprocess.elements(); en.hasMoreElements(); ) { + FlagState fsworking=(FlagState)en.nextElement(); + if (ffan.getTagChange(ttp)) { + processed.addAll(Arrays.asList(fsworking.setTag(ttp.getTag()))); + } else processed.add(fsworking); + } + } + } + //Add to exit states + tempset.addAll(processed); + } + result.add(tempset); + continue; // avoid queueing the return node if reachable + } } else if (fn1.kind()==FKind.FlatReturnNode) { - result.add(otd.enterflagstates); + result.add(otd.enterflagstates); } /* Queue other nodes past this one */ for(int i=0; i "+tn2.getLabel()+";"); + EGTaskNode tn2 = (EGTaskNode)((Edge)it2.next()).getTarget(); + output.println("\t"+tn.getLabel()+" -> "+tn2.getLabel()+";"); } } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/TagAnalysis.java b/Robust/src/Analysis/TaskStateAnalysis/TagAnalysis.java index 21eb1580..c9059047 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TagAnalysis.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TagAnalysis.java @@ -49,17 +49,17 @@ public class TagAnalysis { Set component=scc.getSCC(i); HashSet flagset=new HashSet(); for(Iterator compit=component.iterator(); compit.hasNext(); ) { - TagBinding tb=(TagBinding)compit.next(); - flagset.addAll(tb.getAllocations()); - for(Iterator edgeit=tb.edges(); edgeit.hasNext(); ) { - Edge e=(Edge)edgeit.next(); - TagBinding tb2=(TagBinding)e.getTarget(); - flagset.addAll(tb2.getAllocations()); - } + TagBinding tb=(TagBinding)compit.next(); + flagset.addAll(tb.getAllocations()); + for(Iterator edgeit=tb.edges(); edgeit.hasNext(); ) { + Edge e=(Edge)edgeit.next(); + TagBinding tb2=(TagBinding)e.getTarget(); + flagset.addAll(tb2.getAllocations()); + } } for(Iterator compit=component.iterator(); compit.hasNext(); ) { - TagBinding tb=(TagBinding)compit.next(); - tb.getAllocations().addAll(flagset); + TagBinding tb=(TagBinding)compit.next(); + tb.getAllocations().addAll(flagset); } } @@ -69,8 +69,8 @@ public class TagAnalysis { HashSet roottags=(HashSet)tasktotagbindings.get(task); HashSet taskflags=(HashSet)tasktoflagstates.get(task); for(Iterator tagit=roottags.iterator(); tagit.hasNext(); ) { - TagBinding tb=(TagBinding)tagit.next(); - taskflags.addAll(tb.getAllocations()); + TagBinding tb=(TagBinding)tagit.next(); + taskflags.addAll(tb.getAllocations()); } } } @@ -96,92 +96,92 @@ public class TagAnalysis { for(Iterator nodeit=nodeset.iterator(); nodeit.hasNext(); ) { FlatNode fn=(FlatNode)nodeit.next(); if(fn.kind()==FKind.FlatCall) { - FlatCall fc=(FlatCall)fn; - MethodDescriptor nodemd=fc.getMethod(); - Set methodset=fc.getThis()==null?callgraph.getMethods(nodemd): - callgraph.getMethods(nodemd, fc.getThis().getType()); - - for(Iterator methodit=methodset.iterator(); methodit.hasNext(); ) { - MethodDescriptor md=(MethodDescriptor) methodit.next(); - TagBinding nodetb=new TagBinding(md); - for(int i=0; i targetFStates = ffan.getTargetFStates4NewObj(ffantemp.getType().getClassDesc()); - FlagState fs=new FlagState(ffantemp.getType().getClassDesc()); - for(Iterator it=ffan.getTempFlagPairs(); it.hasNext(); ) { - TempFlagPair tfp=(TempFlagPair)it.next(); - if (ffan.getFlagChange(tfp)) - fs=fs.setFlag(tfp.getFlag(), true); - else - fs=fs.setFlag(tfp.getFlag(), false); - } - - HashSet fsset=new HashSet(); - fsset.add(fs); - - for(Iterator it=ffan.getTempTagPairs(); it.hasNext(); ) { - HashSet oldfsset=fsset; - fsset=new HashSet(); - - TempTagPair ttp=(TempTagPair)it.next(); - if (ffan.getTagChange(ttp)) { - TagDescriptor tag=ttp.getTag(); - if (tag==null&¶mmap!=null&¶mmap.containsKey(ttp.getTagTemp())) { - tag=(TagDescriptor)parammap.get(ttp.getTagTemp()); - } - for(Iterator setit=oldfsset.iterator(); setit.hasNext(); ) { - FlagState fs2=(FlagState)setit.next(); - fsset.addAll(Arrays.asList(fs2.setTag(tag))); - } - } else - throw new Error("Don't clear tag in new object allocation"); - } - - for(Iterator setit=fsset.iterator(); setit.hasNext(); ) { - FlagState fs2=(FlagState)setit.next(); - if (!flagmap.containsKey(fs2)) - flagmap.put(fs2,fs2); - else - fs2=(FlagState) flagmap.get(fs2); - newflags.add(fs2); - if(!targetFStates.contains(fs2)) { - targetFStates.addElement(fs2); - } - } - } + FlatFlagActionNode ffan=(FlatFlagActionNode)fn; + if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) { + TempDescriptor ffantemp=null; + { + /* Compute type */ + + Iterator it=ffan.getTempFlagPairs(); + if (it.hasNext()) { + TempFlagPair tfp=(TempFlagPair)it.next(); + ffantemp=tfp.getTemp(); + } else { + it=ffan.getTempTagPairs(); + if (!it.hasNext()) + throw new Error(); + TempTagPair ttp=(TempTagPair)it.next(); + ffantemp=ttp.getTemp(); + } + } + Vector targetFStates = ffan.getTargetFStates4NewObj(ffantemp.getType().getClassDesc()); + FlagState fs=new FlagState(ffantemp.getType().getClassDesc()); + for(Iterator it=ffan.getTempFlagPairs(); it.hasNext(); ) { + TempFlagPair tfp=(TempFlagPair)it.next(); + if (ffan.getFlagChange(tfp)) + fs=fs.setFlag(tfp.getFlag(), true); + else + fs=fs.setFlag(tfp.getFlag(), false); + } + + HashSet fsset=new HashSet(); + fsset.add(fs); + + for(Iterator it=ffan.getTempTagPairs(); it.hasNext(); ) { + HashSet oldfsset=fsset; + fsset=new HashSet(); + + TempTagPair ttp=(TempTagPair)it.next(); + if (ffan.getTagChange(ttp)) { + TagDescriptor tag=ttp.getTag(); + if (tag==null&¶mmap!=null&¶mmap.containsKey(ttp.getTagTemp())) { + tag=(TagDescriptor)parammap.get(ttp.getTagTemp()); + } + for(Iterator setit=oldfsset.iterator(); setit.hasNext(); ) { + FlagState fs2=(FlagState)setit.next(); + fsset.addAll(Arrays.asList(fs2.setTag(tag))); + } + } else + throw new Error("Don't clear tag in new object allocation"); + } + + for(Iterator setit=fsset.iterator(); setit.hasNext(); ) { + FlagState fs2=(FlagState)setit.next(); + if (!flagmap.containsKey(fs2)) + flagmap.put(fs2,fs2); + else + fs2=(FlagState) flagmap.get(fs2); + newflags.add(fs2); + if(!targetFStates.contains(fs2)) { + targetFStates.addElement(fs2); + } + } + } } } } @@ -204,15 +204,15 @@ public class TagAnalysis { for(int i=0; i=0) { - TagDescriptor tag=tb.getBinding(offsetindex); - - if (tag!=null) { - parammap.put(temp,tag); - } - } + TempDescriptor temp=fm.getParameter(i); + int offsetindex=i-offset; + if (offsetindex>=0) { + TagDescriptor tag=tb.getBinding(offsetindex); + + if (tag!=null) { + parammap.put(temp,tag); + } + } } HashSet newtags=new HashSet(); @@ -220,9 +220,9 @@ public class TagAnalysis { computeCallsFlags(fm, parammap, newtags, tb.getAllocations()); for(Iterator tagit=newtags.iterator(); tagit.hasNext(); ) { - TagBinding newtag=(TagBinding)tagit.next(); - Edge e=new Edge(newtag); - tb.addEdge(e); + TagBinding newtag=(TagBinding)tagit.next(); + Edge e=new Edge(newtag); + tb.addEdge(e); } } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/TagBinding.java b/Robust/src/Analysis/TaskStateAnalysis/TagBinding.java index adc81a5a..3ad4df58 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TagBinding.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TagBinding.java @@ -43,13 +43,13 @@ public class TagBinding extends GraphNode { if (o instanceof TagBinding) { TagBinding tb=(TagBinding)o; if (md!=tb.md) - return false; + return false; for(int i=0; i()); + tdToFEdges.put(td, new Vector()); } /** counter to keep track of the number of parameters (of the @@ -168,46 +168,46 @@ public class TaskAnalysis { int parameterindex=0; for(int i=0; i < td.numParameters(); i++) { - FlagExpressionNode fen=td.getFlag(td.getParameter(i)); - TagExpressionList tel=td.getTag(td.getParameter(i)); - - /** Checking to see if the parameter is of the same - * type/class as the flagstate's and also if the - * flagstate fs triggers the given task*/ - - if (typeutil.isSuperorType(td.getParamType(i).getClassDesc(),cd) - && isTaskTrigger_flag(fen,fs) - && isTaskTrigger_tag(tel,fs)) { - temp=fm.getParameter(i); - parameterindex=i; - trigger_ctr++; - } + FlagExpressionNode fen=td.getFlag(td.getParameter(i)); + TagExpressionList tel=td.getTag(td.getParameter(i)); + + /** Checking to see if the parameter is of the same + * type/class as the flagstate's and also if the + * flagstate fs triggers the given task*/ + + if (typeutil.isSuperorType(td.getParamType(i).getClassDesc(),cd) + && isTaskTrigger_flag(fen,fs) + && isTaskTrigger_tag(tel,fs)) { + temp=fm.getParameter(i); + parameterindex=i; + trigger_ctr++; + } } if (trigger_ctr==0) //Look at next task - continue; + continue; if (trigger_ctr>1) - System.out.println("Illegal Operation: A single flagstate cannot satisfy more than one parameter of a task:"+fs + " in "+td); + System.out.println("Illegal Operation: A single flagstate cannot satisfy more than one parameter of a task:"+fs + " in "+td); Set newstates=taganalysis.getFlagStates(td); for(Iterator fsit=newstates.iterator(); fsit.hasNext(); ) { - FlagState fsnew=(FlagState) fsit.next(); - System.out.println("SOURCE:"+fsnew); - - if (!((Hashtable)flagstates.get(fsnew.getClassDescriptor())).containsKey(fsnew)) { - ((Hashtable)flagstates.get(fsnew.getClassDescriptor())).put(fsnew, fsnew); - toprocess.add(fsnew); - } else { - fsnew=((Hashtable)flagstates.get(fsnew.getClassDescriptor())).get(fsnew); - } - fsnew.setAsSourceNode(); - fsnew.addAllocatingTask(td); - - if(!((Vector)cdtorootnodes.get(fsnew.getClassDescriptor())).contains(fsnew)) { - ((Vector)cdtorootnodes.get(fsnew.getClassDescriptor())).add(fsnew); - } + FlagState fsnew=(FlagState) fsit.next(); + System.out.println("SOURCE:"+fsnew); + + if (!((Hashtable)flagstates.get(fsnew.getClassDescriptor())).containsKey(fsnew)) { + ((Hashtable)flagstates.get(fsnew.getClassDescriptor())).put(fsnew, fsnew); + toprocess.add(fsnew); + } else { + fsnew=((Hashtable)flagstates.get(fsnew.getClassDescriptor())).get(fsnew); + } + fsnew.setAsSourceNode(); + fsnew.addAllocatingTask(td); + + if(!((Vector)cdtorootnodes.get(fsnew.getClassDescriptor())).contains(fsnew)) { + ((Vector)cdtorootnodes.get(fsnew.getClassDescriptor())).add(fsnew); + } } Stack nodestack=new Stack(); @@ -217,55 +217,55 @@ public class TaskAnalysis { //Iterating through the nodes while(!nodestack.isEmpty()) { - FlatNode fn1 = (FlatNode) nodestack.pop(); - - if (fn1.kind()==FKind.FlatReturnNode) { - /* Self edge */ - FEdge newedge=new FEdge(fs, taskname, td, parameterindex); - ((Vector)tdToFEdges.get(td)).add(newedge); - fs.addEdge(newedge); - newedge.setisbackedge(true); - continue; - } else if (fn1.kind()==FKind.FlatFlagActionNode) { - FlatFlagActionNode ffan=(FlatFlagActionNode)fn1; - if (ffan.getTaskType() == FlatFlagActionNode.PRE) { - if (ffan.getTempFlagPairs().hasNext()||ffan.getTempTagPairs().hasNext()) - throw new Error("PRE FlagActions not supported"); - - } else if (ffan.getTaskType() == FlatFlagActionNode.TASKEXIT) { - Vector fsv_taskexit=evalTaskExitNode(ffan,cd,fs,temp); - Vector initFStates = ffan.getInitFStates(temp.getType().getClassDesc()); - if(!initFStates.contains(fs)) { - initFStates.addElement(fs); - } - Vector targetFStates = ffan.getTargetFStates(fs); - for(Enumeration en=fsv_taskexit.elements(); en.hasMoreElements(); ) { - FlagState fs_taskexit=(FlagState)en.nextElement(); - if (!sourcenodes.containsKey(fs_taskexit)) { - toprocess.add(fs_taskexit); - } - //seen this node already - fs_taskexit=canonicalizeFlagState(sourcenodes,fs_taskexit); - FEdge newedge=new FEdge(fs_taskexit,taskname, td, parameterindex); - newedge.setTaskExitIndex(ffan.getTaskExitIndex()); - ((Vector)tdToFEdges.get(td)).add(newedge); - fs.addEdge(newedge); - - if(!targetFStates.contains(fs_taskexit)) { - targetFStates.addElement(fs_taskexit); - } - } - continue; - } - } - /* Queue other nodes past this one */ - for(int i=0; i)tdToFEdges.get(td)).add(newedge); + fs.addEdge(newedge); + newedge.setisbackedge(true); + continue; + } else if (fn1.kind()==FKind.FlatFlagActionNode) { + FlatFlagActionNode ffan=(FlatFlagActionNode)fn1; + if (ffan.getTaskType() == FlatFlagActionNode.PRE) { + if (ffan.getTempFlagPairs().hasNext()||ffan.getTempTagPairs().hasNext()) + throw new Error("PRE FlagActions not supported"); + + } else if (ffan.getTaskType() == FlatFlagActionNode.TASKEXIT) { + Vector fsv_taskexit=evalTaskExitNode(ffan,cd,fs,temp); + Vector initFStates = ffan.getInitFStates(temp.getType().getClassDesc()); + if(!initFStates.contains(fs)) { + initFStates.addElement(fs); + } + Vector targetFStates = ffan.getTargetFStates(fs); + for(Enumeration en=fsv_taskexit.elements(); en.hasMoreElements(); ) { + FlagState fs_taskexit=(FlagState)en.nextElement(); + if (!sourcenodes.containsKey(fs_taskexit)) { + toprocess.add(fs_taskexit); + } + //seen this node already + fs_taskexit=canonicalizeFlagState(sourcenodes,fs_taskexit); + FEdge newedge=new FEdge(fs_taskexit,taskname, td, parameterindex); + newedge.setTaskExitIndex(ffan.getTaskExitIndex()); + ((Vector)tdToFEdges.get(td)).add(newedge); + fs.addEdge(newedge); + + if(!targetFStates.contains(fs_taskexit)) { + targetFStates.addElement(fs_taskexit); + } + } + continue; + } + } + /* Queue other nodes past this one */ + for(int i=0; i oldprocess=processed; - processed=new Vector(); - - for (Enumeration en=oldprocess.elements(); en.hasMoreElements(); ) { - FlagState fsworking=(FlagState)en.nextElement(); - if (!ffan.getTagChange(ttp)) { - processed.addAll(Arrays.asList(fsworking.clearTag(ttp.getTag()))); - } else processed.add(fsworking); - } + Vector oldprocess=processed; + processed=new Vector(); + + for (Enumeration en=oldprocess.elements(); en.hasMoreElements(); ) { + FlagState fsworking=(FlagState)en.nextElement(); + if (!ffan.getTagChange(ttp)) { + processed.addAll(Arrays.asList(fsworking.clearTag(ttp.getTag()))); + } else processed.add(fsworking); + } } } //Process sets next @@ -358,15 +358,15 @@ public class TaskAnalysis { TempTagPair ttp=(TempTagPair)it_ttp.next(); if (temp==ttp.getTemp()) { - Vector oldprocess=processed; - processed=new Vector(); - - for (Enumeration en=oldprocess.elements(); en.hasMoreElements(); ) { - FlagState fsworking=(FlagState)en.nextElement(); - if (ffan.getTagChange(ttp)) { - processed.addAll(Arrays.asList(fsworking.setTag(ttp.getTag()))); - } else processed.add(fsworking); - } + Vector oldprocess=processed; + processed=new Vector(); + + for (Enumeration en=oldprocess.elements(); en.hasMoreElements(); ) { + FlagState fsworking=(FlagState)en.nextElement(); + if (ffan.getTagChange(ttp)) { + processed.addAll(Arrays.asList(fsworking.setTag(ttp.getTag()))); + } else processed.add(fsworking); + } } } return processed; @@ -422,17 +422,17 @@ public class TaskAnalysis { for(int k=0; k(); //build current state for(int i=0; i<(numtags+numobjs); i++) { - TagState tag=null; - TagWrapper tw=null; - if (i>=numtags) { - int objindex=i-numtags; - tag=tqi.ftsarray[objindex].ts; - } else { - TempDescriptor tmp=tagv.get(i); - tag=tqi.getTS(tmp); - } - int index=decisions.get(i).intValue(); - int currentsize=ttable.get(tag).size(); - if (i==incrementlevel) { - if (index==currentsize) { - if (incrementlevel==0) - return false; - incrementlevel--; - continue mainloop; - } else { - index++; - decisions.set(i, new Integer(index)); - } - } else if (i>incrementlevel) { - index=0; - decisions.set(i, new Integer(index)); - } - if (index>currentsize) { - tw=new TagWrapper(tag); - if (!ttable.containsKey(tag)) { - ttable.put(tag, new Vector()); - } - ttable.get(tag).add(tw); - } else { - //use old instance - tw=ttable.get(tag).get(index); - } - if (i>=numtags) { - int objindex=i-numtags; - FlagTagState fts=tqi.ftsarray[objindex]; - ObjWrapper ow=new ObjWrapper(fts.fs); - Hashtable > ctable=new Hashtable>(); - ctable.put(tw.getState(), new HashSet()); - ctable.get(tw.getState()).add(tw); - ow.tags.add(tw); - TagExpressionList tel=tqi.tq.task.getTag(tqi.tq.task.getParameter(i)); - for(int j=0; j()); - ctable.get(twtmp.getState()).add(twtmp); - ow.tags.add(twtmp); - int tagcount=ctable.get(twtmp.ts).size(); - int fstagcount=fts.fs.getTagCount(twtmp.getState().getTag()); - if (fstagcount>=0&&(tagcount>fstagcount)) { - //Too many unique tags of this type bound to object wrapper - incrementlevel=i; - continue mainloop; - } - } - parameterbindings[objindex]=ow; - } else { - TempDescriptor tmp=tagv.get(i); - temptotag.put(tmp, tw); - } + TagState tag=null; + TagWrapper tw=null; + if (i>=numtags) { + int objindex=i-numtags; + tag=tqi.ftsarray[objindex].ts; + } else { + TempDescriptor tmp=tagv.get(i); + tag=tqi.getTS(tmp); + } + int index=decisions.get(i).intValue(); + int currentsize=ttable.get(tag).size(); + if (i==incrementlevel) { + if (index==currentsize) { + if (incrementlevel==0) + return false; + incrementlevel--; + continue mainloop; + } else { + index++; + decisions.set(i, new Integer(index)); + } + } else if (i>incrementlevel) { + index=0; + decisions.set(i, new Integer(index)); + } + if (index>currentsize) { + tw=new TagWrapper(tag); + if (!ttable.containsKey(tag)) { + ttable.put(tag, new Vector()); + } + ttable.get(tag).add(tw); + } else { + //use old instance + tw=ttable.get(tag).get(index); + } + if (i>=numtags) { + int objindex=i-numtags; + FlagTagState fts=tqi.ftsarray[objindex]; + ObjWrapper ow=new ObjWrapper(fts.fs); + Hashtable > ctable=new Hashtable>(); + ctable.put(tw.getState(), new HashSet()); + ctable.get(tw.getState()).add(tw); + ow.tags.add(tw); + TagExpressionList tel=tqi.tq.task.getTag(tqi.tq.task.getParameter(i)); + for(int j=0; j()); + ctable.get(twtmp.getState()).add(twtmp); + ow.tags.add(twtmp); + int tagcount=ctable.get(twtmp.ts).size(); + int fstagcount=fts.fs.getTagCount(twtmp.getState().getTag()); + if (fstagcount>=0&&(tagcount>fstagcount)) { + //Too many unique tags of this type bound to object wrapper + incrementlevel=i; + continue mainloop; + } + } + parameterbindings[objindex]=ow; + } else { + TempDescriptor tmp=tagv.get(i); + temptotag.put(tmp, tw); + } } return true; } diff --git a/Robust/src/Analysis/TaskStateAnalysis/TaskGraph.java b/Robust/src/Analysis/TaskStateAnalysis/TaskGraph.java index 902bf743..54719cbd 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TaskGraph.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TaskGraph.java @@ -27,7 +27,7 @@ public class TaskGraph { for(Iterator classit=state.getClassSymbolTable().getDescriptorsIterator(); classit.hasNext(); ) { ClassDescriptor cd=(ClassDescriptor) classit.next(); if (cd.hasFlags()) - produceTaskNodes(cd); + produceTaskNodes(cd); } produceAllTaskNodes(); } @@ -38,14 +38,14 @@ public class TaskGraph { ClassDescriptor cd=(ClassDescriptor) it_classes.next(); Set tasknodes=getTaskNodes(cd); if (tasknodes!=null) { - try { - File dotfile_tasknodes=new File("graph"+cd.getSymbol()+"_task.dot"); - FileOutputStream dotstream=new FileOutputStream(dotfile_tasknodes,true); - TaskNode.DOTVisitor.visit(dotstream,tasknodes); - } catch(Exception e) { - e.printStackTrace(); - throw new Error(); - } + try { + File dotfile_tasknodes=new File("graph"+cd.getSymbol()+"_task.dot"); + FileOutputStream dotstream=new FileOutputStream(dotfile_tasknodes,true); + TaskNode.DOTVisitor.visit(dotstream,tasknodes); + } catch(Exception e) { + e.printStackTrace(); + throw new Error(); + } } } } @@ -82,23 +82,23 @@ public class TaskGraph { TaskNode tn,sn; if (fs.isSourceNode()) { - Vector src=fs.getAllocatingTasks(); - for(Iterator it2=src.iterator(); it2.hasNext(); ) { - TaskDescriptor td=(TaskDescriptor)it2.next(); - sn=new TaskNode(td.getSymbol()); - if(fs.edges().hasNext()) { - addEdges(fs,sn,tasknodes); - } - } + Vector src=fs.getAllocatingTasks(); + for(Iterator it2=src.iterator(); it2.hasNext(); ) { + TaskDescriptor td=(TaskDescriptor)it2.next(); + sn=new TaskNode(td.getSymbol()); + if(fs.edges().hasNext()) { + addEdges(fs,sn,tasknodes); + } + } } while(it_inedges.hasNext()) { - FEdge inedge=(FEdge)it_inedges.next(); - tn=new TaskNode(inedge.getLabel()); - if(fs.edges().hasNext()) { - addEdges(fs,tn,tasknodes); - } + FEdge inedge=(FEdge)it_inedges.next(); + tn=new TaskNode(inedge.getLabel()); + if(fs.edges().hasNext()) { + addEdges(fs,tn,tasknodes); + } } } } @@ -120,49 +120,49 @@ public class TaskGraph { Set fsnodes; if (cd.hasFlags()&&((fsnodes=taskanalysis.getFlagStates(cd))!=null)) { - // - System.out.println("\nWorking on fses of Class: "+cd.getSymbol()); - // - for(Iterator it=fsnodes.iterator(); it.hasNext(); ) { - FlagState fs=(FlagState)it.next(); - // - System.out.println("Evaluating fs: "+fs.getTextLabel()); - // - Iterator it_inedges=fs.inedges(); - TaskNode tn,sn; - - - if (fs.isSourceNode()) { - // - System.out.println("A sourcenode"); - // - if(fs.edges().hasNext()) { - Vector allocatingtasks=fs.getAllocatingTasks(); - // - if (allocatingtasks.iterator().hasNext()) - System.out.println("has been allocated by "+allocatingtasks.size()+" tasks"); - // - for(Iterator it_at=allocatingtasks.iterator(); it_at.hasNext(); ) { - TaskDescriptor allocatingtd=(TaskDescriptor)it_at.next(); - // - System.out.println(allocatingtd.getSymbol()); - // - tn=new TaskNode(allocatingtd.getSymbol()); - - addEdges(fs,tn,alltasknodes,ColorID); - } - } - } - - while(it_inedges.hasNext()) { - FEdge inedge=(FEdge)it_inedges.next(); - tn=new TaskNode(inedge.getLabel()); - if(fs.edges().hasNext()) { - addEdges(fs,tn,alltasknodes,ColorID); - } - } - } - ColorID++; + // + System.out.println("\nWorking on fses of Class: "+cd.getSymbol()); + // + for(Iterator it=fsnodes.iterator(); it.hasNext(); ) { + FlagState fs=(FlagState)it.next(); + // + System.out.println("Evaluating fs: "+fs.getTextLabel()); + // + Iterator it_inedges=fs.inedges(); + TaskNode tn,sn; + + + if (fs.isSourceNode()) { + // + System.out.println("A sourcenode"); + // + if(fs.edges().hasNext()) { + Vector allocatingtasks=fs.getAllocatingTasks(); + // + if (allocatingtasks.iterator().hasNext()) + System.out.println("has been allocated by "+allocatingtasks.size()+" tasks"); + // + for(Iterator it_at=allocatingtasks.iterator(); it_at.hasNext(); ) { + TaskDescriptor allocatingtd=(TaskDescriptor)it_at.next(); + // + System.out.println(allocatingtd.getSymbol()); + // + tn=new TaskNode(allocatingtd.getSymbol()); + + addEdges(fs,tn,alltasknodes,ColorID); + } + } + } + + while(it_inedges.hasNext()) { + FEdge inedge=(FEdge)it_inedges.next(); + tn=new TaskNode(inedge.getLabel()); + if(fs.edges().hasNext()) { + addEdges(fs,tn,alltasknodes,ColorID); + } + } + } + ColorID++; } } @@ -208,7 +208,7 @@ public class TaskGraph { TEdge newedge=new TEdge(target); if (!tn.edgeExists(newedge)) - tn.addEdge(newedge); + tn.addEdge(newedge); } } @@ -223,7 +223,7 @@ public class TaskGraph { TEdge newedge=new TEdge(target); newedge.setDotNodeParameters("style=bold, color = "+colors[ColorID]); if (!tn.edgeExists(newedge)) - tn.addEdge(newedge); + tn.addEdge(newedge); } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/TaskIndex.java b/Robust/src/Analysis/TaskStateAnalysis/TaskIndex.java index c158bcd4..4396557a 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TaskIndex.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TaskIndex.java @@ -29,10 +29,10 @@ public class TaskIndex { if (o instanceof TaskIndex) { TaskIndex ti=(TaskIndex) o; if (ti.runtime==runtime) - return true; + return true; if (ti.index==index && ti.td==td) - return true; + return true; } return false; } diff --git a/Robust/src/Analysis/TaskStateAnalysis/TaskQueue.java b/Robust/src/Analysis/TaskStateAnalysis/TaskQueue.java index ec9a350c..209372e8 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TaskQueue.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TaskQueue.java @@ -27,11 +27,11 @@ public class TaskQueue { this.parameterset[i]=new HashSet(); TagExpressionList tel=td.getTag(td.getParameter(i)); if (tel!=null) - for(int j=0; j=0; i--) { if (i!=index) - itarray[i]=tq.parameterset[i].iterator(); + itarray[i]=tq.parameterset[i].iterator(); VarDescriptor vd=tq.task.getParameter(i); TagExpressionList tel=tq.task.getTag(vd); if (tel!=null) - for(int j=0; j0?tel.numTags()-1:0; - needinit=false; + j=(tel!=null)&&tel.numTags()>0?tel.numTags()-1:0; + needinit=false; } else - j=0; + j=0; tagloop: for(; tel!=null&&j possts=tq.map.get(currfs); - int index=0; - if (currtag!=null) - index=possts.indexOf(new FlagTagState(currtag,currfs)); - if (needit) { - index++; - needit=false; - } - for(int k=index; k possts=tq.map.get(currfs); + int index=0; + if (currtag!=null) + index=possts.indexOf(new FlagTagState(currtag,currfs)); + if (needit) { + index++; + needit=false; + } + for(int k=index; k tagit=tsresults.keySet().iterator(); tagit.hasNext(); ) { - TagDescriptor tag=tagit.next(); - Set set=tsresults.get(tag); - File dotfile_flagstates= new File("tag"+tag.getSymbol()+".dot"); - FileOutputStream dotstream=new FileOutputStream(dotfile_flagstates,false); - TagState.DOTVisitor.visit(dotstream,set); + TagDescriptor tag=tagit.next(); + Set set=tsresults.get(tag); + File dotfile_flagstates= new File("tag"+tag.getSymbol()+".dot"); + FileOutputStream dotstream=new FileOutputStream(dotfile_flagstates,false); + TagState.DOTVisitor.visit(dotstream,set); } for(Iterator cdit=fsresults.keySet().iterator(); cdit.hasNext(); ) { - ClassDescriptor cd=cdit.next(); - Set set=fsresults.get(cd); - File dotfile_flagstates= new File("class"+cd.getSymbol()+".dot"); - FileOutputStream dotstream=new FileOutputStream(dotfile_flagstates,false); - TagState.DOTVisitor.visit(dotstream,set); + ClassDescriptor cd=cdit.next(); + Set set=fsresults.get(cd); + File dotfile_flagstates= new File("class"+cd.getSymbol()+".dot"); + FileOutputStream dotstream=new FileOutputStream(dotfile_flagstates,false); + TagState.DOTVisitor.visit(dotstream,set); } } catch (Exception e) { e.printStackTrace(); @@ -71,9 +71,9 @@ public class TaskTagAnalysis { toprocess.remove(ts); //Loop through each task for(Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator(); taskit.hasNext(); ) { - TaskDescriptor td=(TaskDescriptor)taskit.next(); - TaskQueue tq=tasktable.get(td); - processTask(td, tq, ts); + TaskDescriptor td=(TaskDescriptor)taskit.next(); + TaskQueue tq=tasktable.get(td); + processTask(td, tq, ts); } } } @@ -84,16 +84,16 @@ public class TaskTagAnalysis { FlagState fs=fsit.next(); FlagTagState fts=new FlagTagState(ts, fs); for(int i=0; i tmpit=prevtable.keySet().iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - Wrapper prevtag=prevtable.get(tmp); - if (prevtag instanceof ObjWrapper) - continue; - if (table.containsKey(tmp)) { - //merge tag states - TagWrapper currtag=(TagWrapper) table.get(tmp); - tagtable.put((TagWrapper)prevtag, currtag); - assert(currtag.initts.equals(((TagWrapper)prevtag).initts)); - for(Iterator tagit=((TagWrapper)prevtag).ts.iterator(); tagit.hasNext(); ) { - TagState tag=tagit.next(); - if (!currtag.ts.contains(tag)) { - currtag.ts.add(tag); - } - } - } else { - TagWrapper clonetag=((TagWrapper)prevtag).clone(); - tagtable.put((TagWrapper)prevtag, clonetag); - table.put(tmp, clonetag); - } + TempDescriptor tmp=tmpit.next(); + Wrapper prevtag=prevtable.get(tmp); + if (prevtag instanceof ObjWrapper) + continue; + if (table.containsKey(tmp)) { + //merge tag states + TagWrapper currtag=(TagWrapper) table.get(tmp); + tagtable.put((TagWrapper)prevtag, currtag); + assert(currtag.initts.equals(((TagWrapper)prevtag).initts)); + for(Iterator tagit=((TagWrapper)prevtag).ts.iterator(); tagit.hasNext(); ) { + TagState tag=tagit.next(); + if (!currtag.ts.contains(tag)) { + currtag.ts.add(tag); + } + } + } else { + TagWrapper clonetag=((TagWrapper)prevtag).clone(); + tagtable.put((TagWrapper)prevtag, clonetag); + table.put(tmp, clonetag); + } } //Iterator through the Objects for(Iterator tmpit=prevtable.keySet().iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - Wrapper obj=prevtable.get(tmp); - if (obj instanceof TagWrapper) - continue; - ObjWrapper prevobj=(ObjWrapper)obj; - if (!table.containsKey(tmp)) { - //merge tag states - ObjWrapper newobj=new ObjWrapper(); - newobj.initfs=prevobj.initfs; - table.put(tmp, newobj); - } - ObjWrapper currobj=(ObjWrapper) table.get(tmp); - assert(currobj.initfs.equals(prevobj.initfs)); - for(Iterator tagit=prevobj.tags.iterator(); tagit.hasNext(); ) { - TagWrapper tprev=tagit.next(); - TagWrapper t=tagtable.get(tprev); - currobj.tags.add(t); - } - for(Iterator flagit=prevobj.fs.iterator(); flagit.hasNext(); ) { - FlagState fs=flagit.next(); - currobj.fs.add(fs); - } + TempDescriptor tmp=tmpit.next(); + Wrapper obj=prevtable.get(tmp); + if (obj instanceof TagWrapper) + continue; + ObjWrapper prevobj=(ObjWrapper)obj; + if (!table.containsKey(tmp)) { + //merge tag states + ObjWrapper newobj=new ObjWrapper(); + newobj.initfs=prevobj.initfs; + table.put(tmp, newobj); + } + ObjWrapper currobj=(ObjWrapper) table.get(tmp); + assert(currobj.initfs.equals(prevobj.initfs)); + for(Iterator tagit=prevobj.tags.iterator(); tagit.hasNext(); ) { + TagWrapper tprev=tagit.next(); + TagWrapper t=tagtable.get(tprev); + currobj.tags.add(t); + } + for(Iterator flagit=prevobj.fs.iterator(); flagit.hasNext(); ) { + FlagState fs=flagit.next(); + currobj.fs.add(fs); + } } } return table; @@ -190,27 +190,27 @@ public class TaskTagAnalysis { TagWrapper tw=tagit.next(); HashSet newstates=new HashSet(); for(Iterator tgit=tw.ts.iterator(); tgit.hasNext(); ) { - TagState ts=tgit.next(); - for(Iterator flagit=ts.getFS().iterator(); flagit.hasNext(); ) { - FlagState fs=flagit.next(); - if (flagmap.containsKey(fs)) { - if (flagmap.get(fs).equals(fs)) { - newstates.add(ts); - } else { - TagState tsarray[]=ts.clearFS(fs); - //Can do strong update here because these - //must be parameter objects...therefore - //all possible aliasing relationships are - //explored - for(int i=0; i flagit=ts.getFS().iterator(); flagit.hasNext(); ) { + FlagState fs=flagit.next(); + if (flagmap.containsKey(fs)) { + if (flagmap.get(fs).equals(fs)) { + newstates.add(ts); + } else { + TagState tsarray[]=ts.clearFS(fs); + //Can do strong update here because these + //must be parameter objects...therefore + //all possible aliasing relationships are + //explored + for(int i=0; i newfsstates=new HashSet(); @@ -241,31 +241,31 @@ public class TaskTagAnalysis { TagWrapper tw=tagit.next(); HashSet newstates=new HashSet(); for(Iterator tgit=tw.ts.iterator(); tgit.hasNext(); ) { - TagState ts=tgit.next(); - for(Iterator flagit=ts.getFS().iterator(); flagit.hasNext(); ) { - FlagState fs=flagit.next(); - if (flagmap.containsKey(fs)) { - FlagState[] fmap=flagmap.get(fs); - for(int i=0; i flagit=ts.getFS().iterator(); flagit.hasNext(); ) { + FlagState fs=flagit.next(); + if (flagmap.containsKey(fs)) { + FlagState[] fmap=flagmap.get(fs); + for(int i=0; i newstates=new HashSet(); for(Iterator tgit=twnew.ts.iterator(); tgit.hasNext(); ) { - TagState ts=tgit.next(); - for(Iterator flagit=newfsstates.iterator(); flagit.hasNext(); ) { - FlagState fsnew=flagit.next(); - //Can do strong update here because these must - //be parameter objects...therefore all - //possible aliasing relationships are explored - TagState tsarray2[]; - if (value) - tsarray2=ts.addnewFS(fsnew); - else - tsarray2=ts.clearFS(fsnew); - for(int j=0; j flagit=newfsstates.iterator(); flagit.hasNext(); ) { + FlagState fsnew=flagit.next(); + //Can do strong update here because these must + //be parameter objects...therefore all + //possible aliasing relationships are explored + TagState tsarray2[]; + if (value) + tsarray2=ts.addnewFS(fsnew); + else + tsarray2=ts.clearFS(fsnew); + for(int j=0; j fsit=ow.fs.iterator(); fsit.hasNext(); ) { FlagState fs2=fsit.next(); @@ -388,8 +388,8 @@ public class TaskTagAnalysis { ts2.addSource(td); addresult(fs2.getClassDescriptor(), ts2); if (!discovered.contains(ts2)) { - discovered.add(ts2); - toprocess.add(ts2); + discovered.add(ts2); + toprocess.add(ts2); } } } @@ -423,20 +423,20 @@ public class TaskTagAnalysis { for(Iterator tsit=tw.ts.iterator(); tsit.hasNext(); ) { TagState ts=tsit.next(); if (init==null) { - ts.addSource(td); + ts.addSource(td); } else { - TagEdge te=new TagEdge(ts, td); - if (!init.containsEdge(te)) { - init.addEdge(te); - } + TagEdge te=new TagEdge(ts, td); + if (!init.containsEdge(te)) { + init.addEdge(te); + } } if (ts.getTag()!=null) - addresult(ts.getTag(), ts); + addresult(ts.getTag(), ts); else - addresult(ts.getClassDesc(), ts); + addresult(ts.getClassDesc(), ts); if (!discovered.contains(ts)) { - discovered.add(ts); - toprocess.add(ts); + discovered.add(ts); + toprocess.add(ts); } } } @@ -457,11 +457,11 @@ public class TaskTagAnalysis { TempDescriptor tmp=tmpit.next(); Wrapper w=table.get(tmp); if (w instanceof TagWrapper) { - TagWrapper tw=(TagWrapper)w; - recordtagchange(tw, td); + TagWrapper tw=(TagWrapper)w; + recordtagchange(tw, td); } else { - ObjWrapper ow=(ObjWrapper)w; - recordobj(ow, td); + ObjWrapper ow=(ObjWrapper)w; + recordobj(ow, td); } } } @@ -475,7 +475,7 @@ public class TaskTagAnalysis { for(Iterator tmpit=table1.keySet().iterator(); tmpit.hasNext(); ) { TempDescriptor tmp=tmpit.next(); if (table2.containsKey(tmp)) { - emap.put(table1.get(tmp), table2.get(tmp)); + emap.put(table1.get(tmp), table2.get(tmp)); } else return false; } @@ -484,23 +484,23 @@ public class TaskTagAnalysis { Wrapper w1=table1.get(tmp); Wrapper w2=table2.get(tmp); if (w1 instanceof TagWrapper) { - TagWrapper t1=(TagWrapper)w1; - TagWrapper t2=(TagWrapper)w2; - if (!t1.ts.equals(t2.ts)) - return false; + TagWrapper t1=(TagWrapper)w1; + TagWrapper t2=(TagWrapper)w2; + if (!t1.ts.equals(t2.ts)) + return false; } else { - ObjWrapper t1=(ObjWrapper)w1; - ObjWrapper t2=(ObjWrapper)w2; - if (!t1.fs.equals(t2.fs)) - return false; - if (t1.tags.size()!=t2.tags.size()) - return false; - for(Iterator twit=t1.tags.iterator(); twit.hasNext(); ) { - TagWrapper tw1=twit.next(); - if (!t2.tags.contains(emap.get(tw1))) - return false; - } + ObjWrapper t1=(ObjWrapper)w1; + ObjWrapper t2=(ObjWrapper)w2; + if (!t1.fs.equals(t2.fs)) + return false; + if (t1.tags.size()!=t2.tags.size()) + return false; + for(Iterator twit=t1.tags.iterator(); twit.hasNext(); ) { + TagWrapper tw1=twit.next(); + if (!t2.tags.contains(emap.get(tw1))) + return false; + } } } return true; @@ -521,34 +521,34 @@ public class TaskTagAnalysis { Hashtable table=computeInitialState(wtable, fn); switch(fn.kind()) { case FKind.FlatFlagActionNode: - processFlatFlag((FlatFlagActionNode)fn, table, td); - break; + processFlatFlag((FlatFlagActionNode)fn, table, td); + break; case FKind.FlatTagDeclaration: - processFlatTag((FlatTagDeclaration)fn, table, td); - break; + processFlatTag((FlatTagDeclaration)fn, table, td); + break; case FKind.FlatCall: - processFlatCall((FlatCall)fn, table); - break; + processFlatCall((FlatCall)fn, table); + break; case FKind.FlatReturnNode: - processFlatReturnNode((FlatReturnNode)fn, table, td); - break; + processFlatReturnNode((FlatReturnNode)fn, table, td); + break; default: } if (!equivalent(table, wtable.get(fn))) { - wtable.put(fn, table); - for(int i=0; i='a'&&ch<='z') { int val=(ch-'a')+10; if (val='A'&&ch<='Z') { int val=(ch-'A')+10; if (val0) - h+="."; + h+="."; h+=(int)address[i]; } return h; diff --git a/Robust/src/ClassLibrary/Integer.java b/Robust/src/ClassLibrary/Integer.java index df27af92..1f7909f4 100644 --- a/Robust/src/ClassLibrary/Integer.java +++ b/Robust/src/ClassLibrary/Integer.java @@ -69,18 +69,18 @@ public class Integer { byte b=chars[i]; int val; if (b>='0'&&b<='9') - val=b-'0'; + val=b-'0'; else if (b>='a'&&b<='z') - val=10+b-'a'; + val=10+b-'a'; else if (b>='A'&&b<='Z') - val=10+b-'A'; + val=10+b-'A'; else { - cont=false; + cont=false; } if (cont) { - if (val>=radix) - System.error(); - value=value*radix+val; + if (val>=radix) + System.error(); + value=value*radix+val; } } if (isNeg) diff --git a/Robust/src/ClassLibrary/LinkedList.java b/Robust/src/ClassLibrary/LinkedList.java index 0d5a6a89..2923f400 100644 --- a/Robust/src/ClassLibrary/LinkedList.java +++ b/Robust/src/ClassLibrary/LinkedList.java @@ -72,18 +72,18 @@ public class LinkedList { LinkedListElement e = head; if (o==null) { while(e!=null) { - if (e.element==null) { - return true; - } - e=e.next; + if (e.element==null) { + return true; + } + e=e.next; } return false; } else { while( e != null ) { - if (o.equals(e.element)) { - return true; - } - e = e.next; + if (o.equals(e.element)) { + return true; + } + e = e.next; } } return false; @@ -160,14 +160,14 @@ public class LinkedList { LinkedListElement e = head; while (e != null) { if (e.element == o) { - if (e.prev != null) { - e.prev.next = e.next; - } - if (e.next != null) { - e.next.prev = e.prev; - } - size--; - return true; + if (e.prev != null) { + e.prev.next = e.next; + } + if (e.next != null) { + e.next.prev = e.prev; + } + size--; + return true; } e = e.next; } diff --git a/Robust/src/ClassLibrary/Math.java b/Robust/src/ClassLibrary/Math.java index 109d76dc..9a7f1418 100644 --- a/Robust/src/ClassLibrary/Math.java +++ b/Robust/src/ClassLibrary/Math.java @@ -73,9 +73,9 @@ public class Math { double d = y - x; if( d == 0.5 ) { if( ((int)y)%2 == 0 ) { - return y; + return y; } else { - return y - 1.0; + return y - 1.0; } } else if( d < 0.5 ) { return y; diff --git a/Robust/src/ClassLibrary/Queue.java b/Robust/src/ClassLibrary/Queue.java index c5a7a3cb..45cbb0be 100644 --- a/Robust/src/ClassLibrary/Queue.java +++ b/Robust/src/ClassLibrary/Queue.java @@ -115,24 +115,24 @@ public class Queue { Object[] newElements = new Object[newCapacity]; if (newElements == null) { - return false; + return false; } int dst = 0; Object[] tmpelements = elements; if (pop < push) { - int src; - for (src = (pop + 1); src < push; src++, dst++) { - newElements[dst] = elements[src]; - } + int src; + for (src = (pop + 1); src < push; src++, dst++) { + newElements[dst] = elements[src]; + } } else { - int src; - for (src = (pop + 1); src < capacity; src++, dst++) { - newElements[dst] = elements[src]; - } - for (src = 0; src < push; src++, dst++) { - newElements[dst] = elements[src]; - } + int src; + for (src = (pop + 1); src < capacity; src++, dst++) { + newElements[dst] = elements[src]; + } + for (src = 0; src < push; src++, dst++) { + newElements[dst] = elements[src]; + } } //elements = null; diff --git a/Robust/src/ClassLibrary/SocketInputStream.java b/Robust/src/ClassLibrary/SocketInputStream.java index 807cab6d..0d12a4cd 100644 --- a/Robust/src/ClassLibrary/SocketInputStream.java +++ b/Robust/src/ClassLibrary/SocketInputStream.java @@ -25,9 +25,9 @@ public class SocketInputStream extends InputStream { byte[] t=new byte[toread]; int rd=read(t); if (rd<0) - return rd; + return rd; for(int i=0; i0; i--) if (this.charAt(i)==ch) - return i; + return i; return -1; } @@ -150,7 +150,7 @@ public class String { for(int i=0; i='a'&&x<='z') { - x=(char) ((x-'a')+'A'); + x=(char) ((x-'a')+'A'); } buffer[i]=x; } @@ -173,7 +173,7 @@ public class String { for(int i=0; i='A'&&x<='Z') { - x=(char) ((x-'A')+'a'); + x=(char) ((x-'A')+'a'); } buffer[i]=x; } @@ -187,7 +187,7 @@ public class String { public int indexOf(int ch, int fromIndex) { for(int i=fromIndex; i=0; k--) { if (regionMatches(k, str, 0, str.count)) - return k; + return k; } return -1; } @@ -238,7 +238,7 @@ public class String { for(int i=0; i='a'&&l<='z') - l=(char)((l-'a')+'A'); + l=(char)((l-'a')+'A'); if (r>='a'&&r<='z') - r=(char)((r-'a')+'A'); + r=(char)((r-'a')+'A'); if (l!=r) - return false; + return false; } return true; } @@ -439,26 +439,26 @@ public class String { // skip first spaces for(i = 0; i< count; i++) { if(value[i+offset] != '\n' && value[i+offset] != '\t' && value[i+offset] != ' ') - break; + break; } int oldi=i; while(ivalue.length) { char newvalue[]=new char[i]; for(int ii=0; iiarray.length) { int newsize; if (capacityIncrement<=0) - newsize=array.length*2; + newsize=array.length*2; else - newsize=array.length+capacityIncrement; + newsize=array.length+capacityIncrement; if (newsize>= 8; + bytes[j] = (byte) random; + random >>= 8; } } } diff --git a/Robust/src/ClassLibrary/gnu/StringTokenizer.java b/Robust/src/ClassLibrary/gnu/StringTokenizer.java index 0afd789b..e09ffc26 100644 --- a/Robust/src/ClassLibrary/gnu/StringTokenizer.java +++ b/Robust/src/ClassLibrary/gnu/StringTokenizer.java @@ -144,7 +144,7 @@ public class StringTokenizer //implements Enumeration public boolean hasMoreTokens() { if (!retDelims) { while (pos < len && delim.indexOf(str.charAt(pos)) >= 0) - pos++; + pos++; } return pos < len; } @@ -174,14 +174,14 @@ public class StringTokenizer //implements Enumeration public String nextToken() { //throws NoSuchElementException if (pos < len && delim.indexOf(str.charAt(pos)) >= 0) { if (retDelims) - return str.substring(pos, ++pos); + return str.substring(pos, ++pos); while (++pos < len && delim.indexOf(str.charAt(pos)) >= 0) - ; + ; } if (pos < len) { int start = pos; while (++pos < len && delim.indexOf(str.charAt(pos)) < 0) - ; + ; return str.substring(start, pos); } @@ -232,19 +232,19 @@ public class StringTokenizer //implements Enumeration // just do the conditional once at the end of the method while (tmpPos < len) { if (delim.indexOf(str.charAt(tmpPos++)) >= 0) { - if (tokenFound) { - // Got to the end of a token - count++; - tokenFound = false; - } - delimiterCount++; // Increment for this delimiter + if (tokenFound) { + // Got to the end of a token + count++; + tokenFound = false; + } + delimiterCount++; // Increment for this delimiter } else { - tokenFound = true; - // Get to the end of the token - while (tmpPos < len - && delim.indexOf(str.charAt(tmpPos)) < 0) - ++tmpPos; + tokenFound = true; + // Get to the end of the token + while (tmpPos < len + && delim.indexOf(str.charAt(tmpPos)) < 0) + ++tmpPos; } } diff --git a/Robust/src/IR/AnnotationDescriptor.java b/Robust/src/IR/AnnotationDescriptor.java index b8b39e02..b7282d95 100644 --- a/Robust/src/IR/AnnotationDescriptor.java +++ b/Robust/src/IR/AnnotationDescriptor.java @@ -55,9 +55,9 @@ public class AnnotationDescriptor extends Descriptor { if (o instanceof AnnotationDescriptor) { AnnotationDescriptor a = (AnnotationDescriptor) o; if (a.getType() != type) - return false; + return false; if (!a.getMarker().equals(getMarker())) - return false; + return false; return true; } diff --git a/Robust/src/IR/ClassDescriptor.java b/Robust/src/IR/ClassDescriptor.java index b9e90c13..5d4af197 100644 --- a/Robust/src/IR/ClassDescriptor.java +++ b/Robust/src/IR/ClassDescriptor.java @@ -129,11 +129,11 @@ public class ClassDescriptor extends Descriptor { st += "implements "; boolean needcomma = false; for(int i = 0; i < this.superinterfaces.size(); i++) { - if(needcomma) { - st += ", "; - } - st += this.superinterfaces.elementAt(i); - needcomma = true; + if(needcomma) { + st += ", "; + } + st += this.superinterfaces.elementAt(i); + needcomma = true; } } st+=" {\n"; @@ -173,14 +173,14 @@ public class ClassDescriptor extends Descriptor { String[] econstants = new String[keys.size()]; Iterator it_keys = keys.iterator(); while(it_keys.hasNext()) { - String key = (String)it_keys.next(); - econstants[icd.getEnumConstant(key)] = key; + String key = (String)it_keys.next(); + econstants[icd.getEnumConstant(key)] = key; } for(int i = 0; i < econstants.length; i++) { - st += econstants[i]; - if(i < econstants.length-1) { - st += ", "; - } + st += econstants[i]; + if(i < econstants.length-1) { + st += ", "; + } } st+="\n}\n"; printcr=true; @@ -202,21 +202,21 @@ public class ClassDescriptor extends Descriptor { ClassDescriptor cn=this; while(true) { if (cn==null) { - // TODO: the original code returned "null" if no super class - // ever defines the method. Is there a situation where this is - // fine and the client should take other actions? If not, we should - // change this warning to an error. - System.out.println("ClassDescriptor.java: WARNING "+md+ - " did not resolve to an actual method."); - return null; + // TODO: the original code returned "null" if no super class + // ever defines the method. Is there a situation where this is + // fine and the client should take other actions? If not, we should + // change this warning to an error. + System.out.println("ClassDescriptor.java: WARNING "+md+ + " did not resolve to an actual method."); + return null; } Set possiblematches=cn.getMethodTable().getSetFromSameScope(md.getSymbol()); for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { - MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); + MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); - if (md.matches(matchmd)) { - return matchmd; - } + if (md.matches(matchmd)) { + return matchmd; + } } //Not found...walk one level up diff --git a/Robust/src/IR/Flat/BuildCode.java b/Robust/src/IR/Flat/BuildCode.java index 0ff72336..c6e5a22d 100644 --- a/Robust/src/IR/Flat/BuildCode.java +++ b/Robust/src/IR/Flat/BuildCode.java @@ -115,15 +115,15 @@ public class BuildCode { outmethod=new CodePrinter(new FileOutputStream(PREFIX+"methods.c"), true); outvirtual=new CodePrinter(new FileOutputStream(PREFIX+"virtualtable.h"), true); if (state.TASK) { - outtask=new CodePrinter(new FileOutputStream(PREFIX+"task.h"), true); - outtaskdefs=new CodePrinter(new FileOutputStream(PREFIX+"taskdefs.c"), true); - if (state.OPTIONAL) { - outoptionalarrays=new CodePrinter(new FileOutputStream(PREFIX+"optionalarrays.c"), true); - optionalheaders=new CodePrinter(new FileOutputStream(PREFIX+"optionalstruct.h"), true); - } + outtask=new CodePrinter(new FileOutputStream(PREFIX+"task.h"), true); + outtaskdefs=new CodePrinter(new FileOutputStream(PREFIX+"taskdefs.c"), true); + if (state.OPTIONAL) { + outoptionalarrays=new CodePrinter(new FileOutputStream(PREFIX+"optionalarrays.c"), true); + optionalheaders=new CodePrinter(new FileOutputStream(PREFIX+"optionalstruct.h"), true); + } } if (state.structfile!=null) { - outrepairstructs=new CodePrinter(new FileOutputStream(PREFIX+state.structfile+".struct"), true); + outrepairstructs=new CodePrinter(new FileOutputStream(PREFIX+state.structfile+".struct"), true); } } catch (Exception e) { e.printStackTrace(); @@ -177,8 +177,8 @@ public class BuildCode { /* The runtime keeps track of flags using these integers */ it=state.getClassSymbolTable().getDescriptorsIterator(); while(it.hasNext()) { - ClassDescriptor cn=(ClassDescriptor)it.next(); - mapFlags(cn); + ClassDescriptor cn=(ClassDescriptor)it.next(); + mapFlags(cn); } /* Generate Tasks */ generateTaskStructs(outstructs, outmethodheader); @@ -282,7 +282,7 @@ public class BuildCode { ClassDescriptor cd = (ClassDescriptor)it_sclasses.next(); MethodDescriptor md = (MethodDescriptor)cd.getMethodTable().get("staticblocks"); if(md != null) { - tovisit.add(md); + tovisit.add(md); } } @@ -292,13 +292,13 @@ public class BuildCode { visited.add(current_md); Iterator it_callee = this.callgraph.getCalleeSet(current_md).iterator(); while(it_callee.hasNext()) { - Descriptor d = (Descriptor)it_callee.next(); - if(d instanceof MethodDescriptor) { - if(!visited.contains(d)) { - ((MethodDescriptor)d).setIsInvokedByStatic(true); - tovisit.add(d); - } - } + Descriptor d = (Descriptor)it_callee.next(); + if(d instanceof MethodDescriptor) { + if(!visited.contains(d)) { + ((MethodDescriptor)d).setIsInvokedByStatic(true); + tovisit.add(d); + } + } } } } @@ -312,20 +312,20 @@ public class BuildCode { Iterator it_sclasses = sctbl.getDescriptorsIterator(); if(it_sclasses.hasNext()) { while(it_sclasses.hasNext()) { - ClassDescriptor t_cd = (ClassDescriptor)it_sclasses.next(); - MethodDescriptor t_md = (MethodDescriptor)t_cd.getMethodTable().get("staticblocks"); + ClassDescriptor t_cd = (ClassDescriptor)it_sclasses.next(); + MethodDescriptor t_md = (MethodDescriptor)t_cd.getMethodTable().get("staticblocks"); - if(t_md != null&&callgraph.isInit(t_cd)) { - outmethod.println(" {"); - if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - outmethod.print(" struct "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={"); - outmethod.println("0, NULL};"); - outmethod.println(" "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);"); - } else { - outmethod.println(" "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();"); - } - outmethod.println(" }"); - } + if(t_md != null&&callgraph.isInit(t_cd)) { + outmethod.println(" {"); + if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { + outmethod.print(" struct "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={"); + outmethod.println("0, NULL};"); + outmethod.println(" "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);"); + } else { + outmethod.println(" "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();"); + } + outmethod.println(" }"); + } } } } @@ -451,9 +451,9 @@ public class BuildCode { while(taskit.hasNext()) { TaskDescriptor td=(TaskDescriptor)taskit.next(); if (first) - first=false; + first=false; else - outtaskdefs.println(","); + outtaskdefs.println(","); outtaskdefs.print("&task_"+td.getSafeSymbol()); } outtaskdefs.println("};"); @@ -485,7 +485,7 @@ public class BuildCode { } if(state.MULTICORE) { if(state.TASK) { - outmethod.println("#include \"task.h\""); + outmethod.println("#include \"task.h\""); } outmethod.println("#include \"multicoreruntime.h\""); outmethod.println("#include \"runtime_arch.h\""); @@ -530,18 +530,18 @@ public class BuildCode { ClassDescriptor cn=(ClassDescriptor)classit.next(); Iterator methodit=cn.getMethods(); while(methodit.hasNext()) { - /* Classify parameters */ - MethodDescriptor md=(MethodDescriptor)methodit.next(); - if (!callgraph.isCallable(md)&&(!md.isStaticBlock()||!callgraph.isInit(cn))) { - continue; - } + /* Classify parameters */ + MethodDescriptor md=(MethodDescriptor)methodit.next(); + if (!callgraph.isCallable(md)&&(!md.isStaticBlock()||!callgraph.isInit(cn))) { + continue; + } - FlatMethod fm=state.getMethodFlat(md); - if (!md.getModifiers().isNative()) { - generateFlatMethod(fm, outmethod); - } else if (state.JNI) { - generateNativeFlatMethod(fm, outmethod); - } + FlatMethod fm=state.getMethodFlat(md); + if (!md.getModifiers().isNative()) { + generateFlatMethod(fm, outmethod); + } else if (state.JNI) { + generateNativeFlatMethod(fm, outmethod); + } } } } @@ -617,10 +617,10 @@ public class BuildCode { outclassdefs.println("struct "+cn.getSafeSymbol()+";"); if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) { - // this class has static fields/blocks, need to add a global flag to - // indicate if its static fields have been initialized and/or if its - // static blocks have been executed - outglobaldefsprim.println(" int "+cn.getSafeSymbol()+"static_block_exe_flag;"); + // this class has static fields/blocks, need to add a global flag to + // indicate if its static fields have been initialized and/or if its + // static blocks have been executed + outglobaldefsprim.println(" int "+cn.getSafeSymbol()+"static_block_exe_flag;"); } } outclassdefs.println(""); @@ -644,26 +644,26 @@ public class BuildCode { outclassdefs.println(" volatile int notifycount;"); outclassdefs.println(" volatile int objlock;"); if(state.MULTICOREGC) { - outclassdefs.println(" int marked;"); + outclassdefs.println(" int marked;"); } } if (state.TASK) { outclassdefs.println(" int flag;"); outclassdefs.println(" int ___cachedCode___;"); if(!state.MULTICORE) { - outclassdefs.println(" void * flagptr;"); + outclassdefs.println(" void * flagptr;"); } else { - outclassdefs.println(" int version;"); - outclassdefs.println(" int * lock;"); // lock entry for this obj - outclassdefs.println(" int mutex;"); - outclassdefs.println(" volatile int lockcount;"); - if(state.MULTICOREGC) { - outclassdefs.println(" int marked;"); - } + outclassdefs.println(" int version;"); + outclassdefs.println(" int * lock;"); // lock entry for this obj + outclassdefs.println(" int mutex;"); + outclassdefs.println(" volatile int lockcount;"); + if(state.MULTICOREGC) { + outclassdefs.println(" int marked;"); + } } if(state.OPTIONAL) { - outclassdefs.println(" int numfses;"); - outclassdefs.println(" int * fses;"); + outclassdefs.println(" int numfses;"); + outclassdefs.println(" int * fses;"); } } @@ -719,10 +719,10 @@ public class BuildCode { outrepairstructs.println("structure "+cn.getSymbol()+" {"); outrepairstructs.println(" int __type__;"); if (state.TASK) { - outrepairstructs.println(" int __flag__;"); - if(!state.MULTICORE) { - outrepairstructs.println(" int __flagptr__;"); - } + outrepairstructs.println(" int __flag__;"); + if(!state.MULTICORE) { + outrepairstructs.println(" int __flagptr__;"); + } } printRepairStruct(cn, outrepairstructs); outrepairstructs.println("}\n"); @@ -749,13 +749,13 @@ public class BuildCode { for(int i=0; imaxcount) - maxcount=virtualcalls.getMethodCount(cd); + maxcount=virtualcalls.getMethodCount(cd); } MethodDescriptor[][] virtualtable=null; virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount]; @@ -864,7 +864,7 @@ public class BuildCode { while(classit.hasNext()) { ClassDescriptor cd=(ClassDescriptor)classit.next(); if(cd.isInterface()) { - continue; + continue; } fillinRow(cd, virtualtable, cd.getId()); } @@ -881,15 +881,15 @@ public class BuildCode { boolean needcomma=false; for(int i=0; i0) { - outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")"); + outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")"); } else { - outclassdefs.print("0"); + outclassdefs.print("0"); } needcomma=true; } @@ -993,18 +993,18 @@ public class BuildCode { for(int i=0; i0?cd.getSuperDesc():null; if(supercd != null && supercd.isInterface()) { - throw new Error("Super class can not be interfaces"); + throw new Error("Super class can not be interfaces"); } if (needcomma) - outclassdefs.print(", "); + outclassdefs.print(", "); if (supercd==null) - outclassdefs.print("-1"); + outclassdefs.print("-1"); else - outclassdefs.print(supercd.getId()); + outclassdefs.print(supercd.getId()); needcomma=true; } @@ -1033,26 +1033,26 @@ public class BuildCode { TypeDescriptor arraytd=arraytable[i]; ClassDescriptor arraycd=arraytd.getClassDesc(); if (arraycd==null) { - if (needcomma) - outclassdefs.print(", "); - outclassdefs.print(objectclass.getId()); - needcomma=true; - continue; + if (needcomma) + outclassdefs.print(", "); + outclassdefs.print(objectclass.getId()); + needcomma=true; + continue; } ClassDescriptor cd=arraycd.getSuperDesc(); int type=-1; while(cd!=null) { - TypeDescriptor supertd=new TypeDescriptor(cd); - supertd.setArrayCount(arraytd.getArrayCount()); - type=state.getArrayNumber(supertd); - if (type!=-1) { - type+=state.numClasses(); - break; - } - cd=cd.getSuperDesc(); + TypeDescriptor supertd=new TypeDescriptor(cd); + supertd.setArrayCount(arraytd.getArrayCount()); + type=state.getArrayNumber(supertd); + if (type!=-1) { + type+=state.numClasses(); + break; + } + cd=cd.getSuperDesc(); } if (needcomma) - outclassdefs.print(", "); + outclassdefs.print(", "); outclassdefs.print(type); needcomma=true; } @@ -1061,14 +1061,14 @@ public class BuildCode { ClassDescriptor cd=ifarray[i]; ClassDescriptor supercd=cd.getSuperDesc(); if(supercd != null && supercd.isInterface()) { - throw new Error("Super class can not be interfaces"); + throw new Error("Super class can not be interfaces"); } if (needcomma) - outclassdefs.print(", "); + outclassdefs.print(", "); if (supercd==null) - outclassdefs.print("-1"); + outclassdefs.print("-1"); else - outclassdefs.print(supercd.getId()); + outclassdefs.print(supercd.getId()); needcomma=true; } @@ -1082,26 +1082,26 @@ public class BuildCode { TypeDescriptor arraytd=arraytable[i]; ClassDescriptor arraycd=arraytd.getClassDesc(); if (arraycd==null) { - if (needcomma) - outclassdefs.print(", "); - outclassdefs.print("-1"); - needcomma=true; - continue; + if (needcomma) + outclassdefs.print(", "); + outclassdefs.print("-1"); + needcomma=true; + continue; } ClassDescriptor cd=arraycd.getSuperDesc(); int level=arraytd.getArrayCount()-1; int type=-1; for(; level>0; level--) { - TypeDescriptor supertd=new TypeDescriptor(objectclass); - supertd.setArrayCount(level); - type=state.getArrayNumber(supertd); - if (type!=-1) { - type+=state.numClasses(); - break; - } + TypeDescriptor supertd=new TypeDescriptor(objectclass); + supertd.setArrayCount(level); + type=state.getArrayNumber(supertd); + if (type!=-1) { + type+=state.numClasses(); + break; + } } if (needcomma) - outclassdefs.print(", "); + outclassdefs.print(", "); outclassdefs.print(type); needcomma=true; } @@ -1126,17 +1126,17 @@ public class BuildCode { TempDescriptor temp=fm.getParameter(i); TypeDescriptor type=temp.getType(); if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC))) - objectparams.addPtr(temp); + objectparams.addPtr(temp); else - objectparams.addPrim(temp); + objectparams.addPrim(temp); } for(int i=0; i"+ - fd.getSafeSymbol()+"))"); - } + FieldDescriptor fd=(FieldDescriptor)allit.next(); + if(fd.isStatic()) { + continue; + } + TypeDescriptor type=fd.getType(); + if (type.isPtr()) { + output.print(", "); + output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+ + fd.getSafeSymbol()+"))"); + } } output.println("};"); } @@ -1207,23 +1207,23 @@ public class BuildCode { for(int i=0; imax) - max=number.intValue()+1; - } + Hashtable superflags=(Hashtable)flagorder.get(sp); + Iterator superflagit=superflags.keySet().iterator(); + while(superflagit.hasNext()) { + FlagDescriptor fd=(FlagDescriptor)superflagit.next(); + Integer number=(Integer)superflags.get(fd); + flags.put(fd, number); + if ((number.intValue()+1)>max) + max=number.intValue()+1; + } } Iterator flagit=cn.getFlags(); while(flagit.hasNext()) { - FlagDescriptor fd=(FlagDescriptor)flagit.next(); - if (sp==null||!sp.getFlagTable().contains(fd.getSymbol())) - flags.put(fd, new Integer(max++)); + FlagDescriptor fd=(FlagDescriptor)flagit.next(); + if (sp==null||!sp.getFlagTable().contains(fd.getSymbol())) + flags.put(fd, new Integer(max++)); } } } @@ -1579,26 +1579,26 @@ fldloop: classdefout.println(" volatile int notifycount;"); classdefout.println(" volatile int objlock;"); if(state.MULTICOREGC) { - classdefout.println(" int marked;"); + classdefout.println(" int marked;"); } } if (state.TASK) { classdefout.println(" int flag;"); classdefout.println(" int ___cachedCode___;"); if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) { - classdefout.println(" void * flagptr;"); + classdefout.println(" void * flagptr;"); } else if (state.MULTICORE) { - classdefout.println(" int version;"); - classdefout.println(" int * lock;"); // lock entry for this obj - classdefout.println(" int mutex;"); - classdefout.println(" volatile int lockcount;"); - if(state.MULTICOREGC) { - classdefout.println(" int marked;"); - } + classdefout.println(" int version;"); + classdefout.println(" int * lock;"); // lock entry for this obj + classdefout.println(" int mutex;"); + classdefout.println(" volatile int lockcount;"); + if(state.MULTICOREGC) { + classdefout.println(" int marked;"); + } } if (state.OPTIONAL) { - classdefout.println(" int numfses;"); - classdefout.println(" int * fses;"); + classdefout.println(" int numfses;"); + classdefout.println(" int * fses;"); } } if (javabuilder==null||javabuilder.hasLayout(cn)) @@ -1617,11 +1617,11 @@ fldloop: FlatMethod fm=state.getMethodFlat(md); if (!callgraph.isCallable(md)&&(!md.isStaticBlock()||!callgraph.isInit(cn))) { - if (callgraph.isCalled(md)) { - generateTempStructs(fm); - generateMethodParam(cn, md, output); - } - continue; + if (callgraph.isCalled(md)) { + generateTempStructs(fm); + generateMethodParam(cn, md, output); + } + continue; } generateTempStructs(fm); @@ -1635,22 +1635,22 @@ fldloop: /* Output parameter structure */ if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { if(md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) { - // generate the staticinit version - String mdstring = md.getSafeMethodDescriptor() + "staticinit"; - - ParamsObject objectparams=(ParamsObject) paramstable.get(md); - output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params {"); - output.println(" int size;"); - output.println(" void * next;"); - for(int i=0; imaxtaskparams) { - maxtaskparams=objectparams.numPointers()+fm.numTags(); - } + output.println("};\n"); + if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) { + maxtaskparams=objectparams.numPointers()+fm.numTags(); + } } /* Output temp structure */ if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - output.println("struct "+task.getSafeSymbol()+"_locals {"); - output.println(" int size;"); - output.println(" void * next;"); - for(int i=0; ifailurecount) {instructioncount=0;injectinstructionfailure();}"); - } else - output.println("if ((--instructioncount)==0) injectinstructionfailure();"); + if (state.THREAD) { + output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}"); + } else + output.println("if ((--instructioncount)==0) injectinstructionfailure();"); } if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) { - output.print(" "); - generateFlatNode(fm, current_node, output); - - if (state.OOOJAVA && stopset!=null) { - assert first.getPrev(0) instanceof FlatSESEEnterNode; - assert current_node instanceof FlatSESEExitNode; - FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev(0); - FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node; - assert fsen.getFlatExit().equals(fsxn); - assert fsxn.getFlatEnter().equals(fsen); - } - if (current_node.kind()!=FKind.FlatReturnNode) { - if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) { - // a static block, check if it has been executed - output.println(" global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;"); - output.println(""); - } - output.println(" return;"); - } - current_node=null; + output.print(" "); + generateFlatNode(fm, current_node, output); + + if (state.OOOJAVA && stopset!=null) { + assert first.getPrev(0) instanceof FlatSESEEnterNode; + assert current_node instanceof FlatSESEExitNode; + FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev(0); + FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node; + assert fsen.getFlatExit().equals(fsxn); + assert fsxn.getFlatEnter().equals(fsen); + } + if (current_node.kind()!=FKind.FlatReturnNode) { + if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) { + // a static block, check if it has been executed + output.println(" global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;"); + output.println(""); + } + output.println(" return;"); + } + current_node=null; } else if(current_node.numNext()==1) { - FlatNode nextnode; - if (state.OOOJAVA && - current_node.kind()==FKind.FlatSESEEnterNode) { - FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node; - generateFlatNode(fm, current_node, output); - nextnode=fsen.getFlatExit().getNext(0); - } else { - output.print(" "); - generateFlatNode(fm, current_node, output); - nextnode=current_node.getNext(0); - } - if (visited.contains(nextnode)) { - output.println("goto L"+nodetolabel.get(nextnode)+";"); - current_node=null; - } else - current_node=nextnode; + FlatNode nextnode; + if (state.OOOJAVA && + current_node.kind()==FKind.FlatSESEEnterNode) { + FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node; + generateFlatNode(fm, current_node, output); + nextnode=fsen.getFlatExit().getNext(0); + } else { + output.print(" "); + generateFlatNode(fm, current_node, output); + nextnode=current_node.getNext(0); + } + if (visited.contains(nextnode)) { + output.println("goto L"+nodetolabel.get(nextnode)+";"); + current_node=null; + } else + current_node=nextnode; } else if (current_node.numNext()==2) { - /* Branch */ - output.print(" "); - generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output); - if (!visited.contains(current_node.getNext(1))) - tovisit.add(current_node.getNext(1)); - if (visited.contains(current_node.getNext(0))) { - output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";"); - current_node=null; - } else - current_node=current_node.getNext(0); + /* Branch */ + output.print(" "); + generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output); + if (!visited.contains(current_node.getNext(1))) + tovisit.add(current_node.getNext(1)); + if (visited.contains(current_node.getNext(0))) { + output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";"); + current_node=null; + } else + current_node=current_node.getNext(0); } else throw new Error(); } } @@ -2149,24 +2149,24 @@ fldloop: if(lastset!=null&&lastset.contains(fn)) { - // if last is not null and matches, don't go - // any further for assigning labels - continue; + // if last is not null and matches, don't go + // any further for assigning labels + continue; } for(int i=0; i0) { - //1) Edge >1 of node - nodetolabel.put(nn,new Integer(labelindex++)); - } - if (!visited.contains(nn)&&!tovisit.contains(nn)) { - tovisit.add(nn); - } else { - //2) Join point - nodetolabel.put(nn,new Integer(labelindex++)); - } + if(i>0) { + //1) Edge >1 of node + nodetolabel.put(nn,new Integer(labelindex++)); + } + if (!visited.contains(nn)&&!tovisit.contains(nn)) { + tovisit.add(nn); + } else { + //2) Join point + nodetolabel.put(nn,new Integer(labelindex++)); + } } } return nodetolabel; @@ -2316,9 +2316,9 @@ fldloop: if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { if(this.state.MULTICOREGC) { - output.println("if (gcflag) gc("+localsprefixaddr+");"); + output.println("if (gcflag) gc("+localsprefixaddr+");"); } else { - output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");"); + output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");"); } } else output.println("/* nop */"); @@ -2401,7 +2401,7 @@ fldloop: TempDescriptor[] temps=fcn.getTemps(); String[] vars=fcn.getVars(); for(int i=0; i"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i])+";"); + output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i])+";"); } output.println("if (doanalysis"+specname+"("+varname+")) {"); @@ -2430,50 +2430,50 @@ fldloop: if((md.isStatic() || md.isStaticBlock() || md.isConstructor()) && ((fm.getMethod() != null) && ((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())))) { if(!md.isInvokedByStatic()) { - System.err.println("Error: a method that is invoked inside a static block is not tagged!"); + System.err.println("Error: a method that is invoked inside a static block is not tagged!"); } // is a static block or is invoked in some static block ClassDescriptor cd = fm.getMethod().getClassDesc(); if(cd != cn && mgcstaticinit && callgraph.isInit(cn)) { - // generate static init check code if it has not done static init in main() - if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) { - // need to check if the class' static fields have been initialized and/or - // its static blocks have been executed - output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {"); - if(cn.getNumStaticBlocks() != 0) { - MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks"); - if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={"); - output.println("0, NULL};"); - output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);"); - } else { - output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();"); - } - } else { - output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;"); - } - output.println("}"); - } + // generate static init check code if it has not done static init in main() + if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) { + // need to check if the class' static fields have been initialized and/or + // its static blocks have been executed + output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {"); + if(cn.getNumStaticBlocks() != 0) { + MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks"); + if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { + output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={"); + output.println("0, NULL};"); + output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);"); + } else { + output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();"); + } + } else { + output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;"); + } + output.println("}"); + } } } if((md.getSymbol().equals("MonitorEnter") || md.getSymbol().equals("MonitorExit")) && fc.getThis().getSymbol().equals("classobj")) { output.println("{"); if(md.getSymbol().equals("MonitorEnter") && state.OBJECTLOCKDEBUG) { - output.println("int monitorenterline = __LINE__;"); + output.println("int monitorenterline = __LINE__;"); } // call MonitorEnter/MonitorExit on a class obj if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={"); - output.println("1," + localsprefixaddr + ", ((void **)(((char *) &(global_defs_p->classobjs->___length___))+sizeof(int)))[" + fc.getThis().getType().getClassDesc().getId() + "]};"); - if(md.getSymbol().equals("MonitorEnter") && state.OBJECTLOCKDEBUG) { - output.println(" "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__, monitorenterline);"); - } else { - output.println(" "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);"); - } + output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={"); + output.println("1," + localsprefixaddr + ", ((void **)(((char *) &(global_defs_p->classobjs->___length___))+sizeof(int)))[" + fc.getThis().getType().getClassDesc().getId() + "]};"); + if(md.getSymbol().equals("MonitorEnter") && state.OBJECTLOCKDEBUG) { + output.println(" "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__, monitorenterline);"); + } else { + output.println(" "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);"); + } } else { - output.println(" " + cn.getSafeSymbol()+md.getSafeSymbol()+"_" - + md.getSafeMethodDescriptor() + "((struct ___Object___*)(((void **)(((char *) &(global_defs_p->classobjs->___length___))+sizeof(int)))[" - + fc.getThis().getType().getClassDesc().getId() + "]));"); + output.println(" " + cn.getSafeSymbol()+md.getSafeSymbol()+"_" + + md.getSafeMethodDescriptor() + "((struct ___Object___*)(((void **)(((char *) &(global_defs_p->classobjs->___length___))+sizeof(int)))[" + + fc.getThis().getType().getClassDesc().getId() + "]));"); } output.println("}"); return; @@ -2488,26 +2488,26 @@ fldloop: output.print(objectparams.numPointers()); output.print(", "+localsprefixaddr); if (md.getThis()!=null) { - output.print(", "); - output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis())); + output.print(", "); + output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis())); } if (fc.getThis()!=null&&md.getThis()==null) { - System.out.println("WARNING!!!!!!!!!!!!"); - System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!"); + System.out.println("WARNING!!!!!!!!!!!!"); + System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!"); } for(int i=0; itype*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])"); } @@ -2567,20 +2567,20 @@ fldloop: if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) { if (fc.getThis()!=null) { - TypeDescriptor ptd=null; - if(md.getThis() != null) { - ptd = md.getThis().getType(); - } else { - ptd = fc.getThis().getType(); - } - if (needcomma) - output.print(","); - if(ptd.isClass() && ptd.getClassDesc().isEnum()) { - // do nothing - } else if (ptd.isClass()&&!ptd.isArray()) - output.print("(struct "+ptd.getSafeSymbol()+" *) "); - output.print(generateTemp(fm,fc.getThis())); - needcomma=true; + TypeDescriptor ptd=null; + if(md.getThis() != null) { + ptd = md.getThis().getType(); + } else { + ptd = fc.getThis().getType(); + } + if (needcomma) + output.print(","); + if(ptd.isClass() && ptd.getClassDesc().isEnum()) { + // do nothing + } else if (ptd.isClass()&&!ptd.isArray()) + output.print("(struct "+ptd.getSafeSymbol()+" *) "); + output.print(generateTemp(fm,fc.getThis())); + needcomma=true; } } @@ -2588,17 +2588,17 @@ fldloop: Descriptor var=md.getParameter(i); TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var); if (objectparams.isParamPrim(paramtemp)) { - TempDescriptor targ=fc.getArg(i); - if (needcomma) - output.print(", "); + TempDescriptor targ=fc.getArg(i); + if (needcomma) + output.print(", "); - TypeDescriptor ptd=md.getParamType(i); - if (ptd.isClass() && ptd.getClassDesc().isEnum()) { - // do nothing - } else if (ptd.isClass()&&!ptd.isArray()) - output.print("(struct "+ptd.getSafeSymbol()+" *) "); - output.print(generateTemp(fm, targ)); - needcomma=true; + TypeDescriptor ptd=md.getParamType(i); + if (ptd.isClass() && ptd.getClassDesc().isEnum()) { + // do nothing + } else if (ptd.isClass()&&!ptd.isArray()) + output.print("(struct "+ptd.getSafeSymbol()+" *) "); + output.print(generateTemp(fm, targ)); + needcomma=true; } } if(md.getSymbol().equals("MonitorEnter") && state.OBJECTLOCKDEBUG) { @@ -2616,15 +2616,15 @@ fldloop: } else { Set subclasses=typeutil.getSubClasses(thiscd); if (subclasses==null) - return true; + return true; for(Iterator classit=subclasses.iterator(); classit.hasNext(); ) { - ClassDescriptor cd=(ClassDescriptor)classit.next(); - Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol()); - for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { - MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); - if (md.matches(matchmd)) - return false; - } + ClassDescriptor cd=(ClassDescriptor)classit.next(); + Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol()); + for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { + MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); + if (md.matches(matchmd)) + return false; + } } } return true; @@ -2635,36 +2635,36 @@ fldloop: if(ffn.getField().isStatic()) { // static field if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) { - // is a static block or is invoked in some static block - ClassDescriptor cd = fm.getMethod().getClassDesc(); - ClassDescriptor cn = ffn.getSrc().getType().getClassDesc(); - if(cd != cn && mgcstaticinit && callgraph.isInit(cn)) { - // generate the static init check code if has not done the static init in main() - if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) { - // need to check if the class' static fields have been initialized and/or - // its static blocks have been executed - output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {"); - if(cn.getNumStaticBlocks() != 0) { - MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks"); - if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={"); - output.println("0, NULL};"); - output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);"); - } else { - output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();"); - } - } else { - output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;"); - } - output.println("}"); - } - } + // is a static block or is invoked in some static block + ClassDescriptor cd = fm.getMethod().getClassDesc(); + ClassDescriptor cn = ffn.getSrc().getType().getClassDesc(); + if(cd != cn && mgcstaticinit && callgraph.isInit(cn)) { + // generate the static init check code if has not done the static init in main() + if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) { + // need to check if the class' static fields have been initialized and/or + // its static blocks have been executed + output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {"); + if(cn.getNumStaticBlocks() != 0) { + MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks"); + if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { + output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={"); + output.println("0, NULL};"); + output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);"); + } else { + output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();"); + } + } else { + output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;"); + } + output.println("}"); + } + } } // redirect to the global_defs_p structure if (ffn.getField().getType().isPtr()) - output.println(generateTemp(fm, ffn.getDst())+"=global_defs_p->"+ffn.getField().getSafeSymbol()+";"); + output.println(generateTemp(fm, ffn.getDst())+"=global_defs_p->"+ffn.getField().getSafeSymbol()+";"); else - output.println(generateTemp(fm, ffn.getDst())+"=global_defsprim_p->"+ffn.getField().getSafeSymbol()+";"); + output.println(generateTemp(fm, ffn.getDst())+"=global_defsprim_p->"+ffn.getField().getSafeSymbol()+";"); } else if (ffn.getField().isEnum()) { // an Enum value, directly replace the field access as int output.println(generateTemp(fm, ffn.getDst()) + "=" + ffn.getField().enumValue() + ";"); @@ -2673,9 +2673,9 @@ fldloop: output.println("if (" + generateTemp(fm,ffn.getSrc()) + " == NULL) {"); output.println("printf(\" NULL ptr error: %s, %s, %d \\n\", __FILE__, __func__, __LINE__);"); if(state.MULTICOREGC) { - output.println("failednullptr(&___locals___);"); + output.println("failednullptr(&___locals___);"); } else { - output.println("failednullptr(NULL);"); + output.println("failednullptr(NULL);"); } output.println("}"); output.println("#endif //MULTICORE_DEBUG"); @@ -2692,9 +2692,9 @@ fldloop: output.println("if(!"+dst+"->"+localcopystr+") {"); /* Link object into list */ if (GENERATEPRECISEGC || this.state.MULTICOREGC) - output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");"); + output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");"); else - output.println("COPY_OBJ("+dst+");"); + output.println("COPY_OBJ("+dst+");"); output.println(dst+"->"+nextobjstr+"="+fcrevert+";"); output.println(fcrevert+"=(struct ___Object___ *)"+dst+";"); output.println("}"); @@ -2703,59 +2703,59 @@ fldloop: if(fsfn.getField().isStatic()) { // static field if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) { - // is a static block or is invoked in some static block - ClassDescriptor cd = fm.getMethod().getClassDesc(); - ClassDescriptor cn = fsfn.getDst().getType().getClassDesc(); - if(cd != cn && mgcstaticinit && callgraph.isInit(cn)) { - // generate static init check code if has not done the static init in main() - if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) { - // need to check if the class' static fields have been initialized and/or - // its static blocks have been executed - output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {"); - if(cn.getNumStaticBlocks() != 0) { - MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks"); - if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={"); - output.println("0, NULL};"); - output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);"); - } else { - output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();"); - } - } else { - output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;"); - } - output.println("}"); - } - } + // is a static block or is invoked in some static block + ClassDescriptor cd = fm.getMethod().getClassDesc(); + ClassDescriptor cn = fsfn.getDst().getType().getClassDesc(); + if(cd != cn && mgcstaticinit && callgraph.isInit(cn)) { + // generate static init check code if has not done the static init in main() + if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) { + // need to check if the class' static fields have been initialized and/or + // its static blocks have been executed + output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {"); + if(cn.getNumStaticBlocks() != 0) { + MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks"); + if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { + output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={"); + output.println("0, NULL};"); + output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);"); + } else { + output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();"); + } + } else { + output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;"); + } + output.println("}"); + } + } } // redirect to the global_defs_p structure if (fsfn.getField().getType().isPtr()) { - if (fsfn.getField().getType()!=fsfn.getSrc().getType()) - output.println("global_defs_p->" + - fsfn.getField().getSafeSymbol()+"=(struct "+ fsfn.getField().getType().getSafeSymbol()+" *)"+generateTemp(fm,fsfn.getSrc())+";"); - else - output.println("global_defs_p->" + - fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";"); + if (fsfn.getField().getType()!=fsfn.getSrc().getType()) + output.println("global_defs_p->" + + fsfn.getField().getSafeSymbol()+"=(struct "+ fsfn.getField().getType().getSafeSymbol()+" *)"+generateTemp(fm,fsfn.getSrc())+";"); + else + output.println("global_defs_p->" + + fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";"); } else - output.println("global_defsprim_p->" + - fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";"); + output.println("global_defsprim_p->" + + fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";"); } else { output.println("#ifdef MULTICORE_DEBUG"); output.println("if (" + generateTemp(fm,fsfn.getDst()) + " == NULL) {"); output.println("printf(\" NULL ptr error: %s, %s, %d \\n\", __FILE__, __func__, __LINE__);"); if(state.MULTICOREGC) { - output.println("failednullptr(&___locals___);"); + output.println("failednullptr(&___locals___);"); } else { - output.println("failednullptr(NULL);"); + output.println("failednullptr(NULL);"); } output.println("}"); output.println("#endif //MULTICORE_DEBUG"); if (fsfn.getSrc().getType().isPtr()&&fsfn.getSrc().getType()!=fsfn.getField().getType()) - output.println(generateTemp(fm, fsfn.getDst())+"->"+ - fsfn.getField().getSafeSymbol()+"=(struct "+ fsfn.getField().getType().getSafeSymbol()+"*)"+generateTemp(fm,fsfn.getSrc())+";"); + output.println(generateTemp(fm, fsfn.getDst())+"->"+ + fsfn.getField().getSafeSymbol()+"=(struct "+ fsfn.getField().getType().getSafeSymbol()+"*)"+generateTemp(fm,fsfn.getSrc())+";"); else - output.println(generateTemp(fm, fsfn.getDst())+"->"+ - fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";"); + output.println(generateTemp(fm, fsfn.getDst())+"->"+ + fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";"); } } @@ -2801,9 +2801,9 @@ fldloop: output.println("if(!"+dst+"->"+localcopystr+") {"); /* Link object into list */ if (GENERATEPRECISEGC || this.state.MULTICOREGC) - output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");"); + output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");"); else - output.println("COPY_OBJ("+dst+");"); + output.println("COPY_OBJ("+dst+");"); output.println(dst+"->"+nextobjstr+"="+fcrevert+";"); output.println(fcrevert+"=(struct ___Object___ *)"+dst+";"); output.println("}"); @@ -2816,15 +2816,15 @@ fldloop: if (fn.getType().isArray()) { int arrayid=state.getArrayNumber(fn.getType())+state.numClasses(); if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");"); + output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");"); } else { - output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize())+");"); + output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize())+");"); } } else { if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");"); + output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");"); } else { - output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+fn.getType().getClassDesc().getId()+");"); + output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+fn.getType().getClassDesc().getId()+");"); } } if (state.FASTCHECK) { @@ -2846,22 +2846,22 @@ fldloop: protected void generateFlatOpNode(FlatMethod fm, FlatOpNode fon, PrintWriter output) { if (fon.getRight()!=null) { if (fon.getOp().getOp()==Operation.URIGHTSHIFT) { - if (fon.getLeft().getType().isLong()) - output.println(generateTemp(fm, fon.getDest())+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";"); - else - output.println(generateTemp(fm, fon.getDest())+" = ((unsigned int)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";"); + if (fon.getLeft().getType().isLong()) + output.println(generateTemp(fm, fon.getDest())+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";"); + else + output.println(generateTemp(fm, fon.getDest())+" = ((unsigned int)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";"); } else { - if (fon.getLeft().getType().isPtr()&&fon.getLeft().getType()!=fon.getRight().getType()&&!fon.getRight().getType().isNull()) - output.println(generateTemp(fm, fon.getDest())+" = (struct "+fon.getRight().getType().getSafeSymbol()+"*)"+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";"); - else - output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";"); + if (fon.getLeft().getType().isPtr()&&fon.getLeft().getType()!=fon.getRight().getType()&&!fon.getRight().getType().isNull()) + output.println(generateTemp(fm, fon.getDest())+" = (struct "+fon.getRight().getType().getSafeSymbol()+"*)"+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";"); + else + output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";"); } } else if (fon.getOp().getOp()==Operation.ASSIGN) if (fon.getDest().getType().isPtr()&&fon.getDest().getType()!=fon.getLeft().getType()) - output.println(generateTemp(fm, fon.getDest())+" = (struct "+fon.getDest().getType().getSafeSymbol()+"*)"+generateTemp(fm, fon.getLeft())+";"); + output.println(generateTemp(fm, fon.getDest())+" = (struct "+fon.getDest().getType().getSafeSymbol()+"*)"+generateTemp(fm, fon.getLeft())+";"); else - output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";"); + output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";"); else if (fon.getOp().getOp()==Operation.UNARYPLUS) output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";"); else if (fon.getOp().getOp()==Operation.UNARYMINUS) @@ -2898,23 +2898,23 @@ fldloop: output.println("{"); output.print("short str"+flncount+"[]={"); for(int i=0; imaxtaskparams) - maxtaskparams=objectparams.numPrimitives()+fm.numTags(); + maxtaskparams=objectparams.numPrimitives()+fm.numTags(); } else output.println(") {"); } @@ -3045,9 +3045,9 @@ fldloop: TempDescriptor tagtmp=ttp.getTagTemp(); boolean tagstatus=ffan.getTagChange(ttp); if (tagstatus) { - tagsettable.put(objtmp, tagtmp); + tagsettable.put(objtmp, tagtmp); } else { - tagcleartable.put(objtmp, tagtmp); + tagcleartable.put(objtmp, tagtmp); } } @@ -3063,30 +3063,30 @@ fldloop: Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc()); FlagDescriptor flag=tfp.getFlag(); if (flag==null) { - //Newly allocate objects that don't set any flags case - if (flagortable.containsKey(temp)) { - throw new Error(); - } - int mask=0; - flagortable.put(temp,new Integer(mask)); + //Newly allocate objects that don't set any flags case + if (flagortable.containsKey(temp)) { + throw new Error(); + } + int mask=0; + flagortable.put(temp,new Integer(mask)); } else { - int flagid=1<<((Integer)flagtable.get(flag)).intValue(); - boolean flagstatus=ffan.getFlagChange(tfp); - if (flagstatus) { - int mask=0; - if (flagortable.containsKey(temp)) { - mask=((Integer)flagortable.get(temp)).intValue(); - } - mask|=flagid; - flagortable.put(temp,new Integer(mask)); - } else { - int mask=0xFFFFFFFF; - if (flagandtable.containsKey(temp)) { - mask=((Integer)flagandtable.get(temp)).intValue(); - } - mask&=(0xFFFFFFFF^flagid); - flagandtable.put(temp,new Integer(mask)); - } + int flagid=1<<((Integer)flagtable.get(flag)).intValue(); + boolean flagstatus=ffan.getFlagChange(tfp); + if (flagstatus) { + int mask=0; + if (flagortable.containsKey(temp)) { + mask=((Integer)flagortable.get(temp)).intValue(); + } + mask|=flagid; + flagortable.put(temp,new Integer(mask)); + } else { + int mask=0xFFFFFFFF; + if (flagandtable.containsKey(temp)) { + mask=((Integer)flagandtable.get(temp)).intValue(); + } + mask&=(0xFFFFFFFF^flagid); + flagandtable.put(temp,new Integer(mask)); + } } } @@ -3104,35 +3104,35 @@ fldloop: Set tagtmps=tagcleartable.get(temp); if (tagtmps!=null) { - Iterator tagit=tagtmps.iterator(); - while(tagit.hasNext()) { - TempDescriptor tagtmp=(TempDescriptor)tagit.next(); - if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) - output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");"); - else - output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");"); - } + Iterator tagit=tagtmps.iterator(); + while(tagit.hasNext()) { + TempDescriptor tagtmp=(TempDescriptor)tagit.next(); + if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) + output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");"); + else + output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");"); + } } tagtmps=tagsettable.get(temp); if (tagtmps!=null) { - Iterator tagit=tagtmps.iterator(); - while(tagit.hasNext()) { - TempDescriptor tagtmp=(TempDescriptor)tagit.next(); - if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) - output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");"); - else - output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");"); - } + Iterator tagit=tagtmps.iterator(); + while(tagit.hasNext()) { + TempDescriptor tagtmp=(TempDescriptor)tagit.next(); + if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) + output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");"); + else + output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");"); + } } int ormask=0; int andmask=0xFFFFFFF; if (flagortable.containsKey(temp)) - ormask=((Integer)flagortable.get(temp)).intValue(); + ormask=((Integer)flagortable.get(temp)).intValue(); if (flagandtable.containsKey(temp)) - andmask=((Integer)flagandtable.get(temp)).intValue(); + andmask=((Integer)flagandtable.get(temp)).intValue(); generateFlagOrAnd(ffan, fm, temp, output, ormask, andmask); generateObjectDistribute(ffan, fm, temp, output); } @@ -3228,33 +3228,33 @@ fldloop: output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={"); int numberterms=0; if (fen_hashset!=null) { - for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext(); ) { - FlagExpressionNode fen = (FlagExpressionNode)fen_it.next(); - if (fen!=null) { - DNFFlag dflag=fen.getDNF(); - numberterms+=dflag.size(); - - Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc()); - - for(int j=0; j fsset=new TreeSet(); - //iterate through possible FSes corresponding to - //the state when entering - - for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext(); ) { - FlagState fs = (FlagState)fses.next(); - int flagid=0; - for(Iterator flags = fs.getFlags(); flags.hasNext(); ) { - FlagDescriptor flagd = (FlagDescriptor)flags.next(); - int id=1<<((Integer)flaginfo.get(flagd)).intValue(); - flagid|=id; - } - fsset.add(new Integer(flagid)); - //tag information not needed because tag - //changes are not tolerated. - } - - output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={"); - boolean needcomma=false; - for(Iterator it=fsset.iterator(); it.hasNext(); ) { - if(needcomma) - output.print(", "); - output.println(it.next()); - } - - output.println("};\n"); - - - //generate optionaltaskdescriptor that actually - //includes exit fses, predicate and the task - //concerned - output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={"); - output.println("&task_"+otd.td.getSafeSymbol()+","); - output.println("/*index*/"+otd.getIndex()+","); - output.println("/*number of enter flags*/"+fsset.size()+","); - output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+","); - output.println("/*number of members */"+predicateindex+","); - output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+","); - output.println("};\n"); - } + for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) { + OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next(); + + //generate the int arrays for the predicate + Predicate predicate = otd.predicate; + int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output); + TreeSet fsset=new TreeSet(); + //iterate through possible FSes corresponding to + //the state when entering + + for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext(); ) { + FlagState fs = (FlagState)fses.next(); + int flagid=0; + for(Iterator flags = fs.getFlags(); flags.hasNext(); ) { + FlagDescriptor flagd = (FlagDescriptor)flags.next(); + int id=1<<((Integer)flaginfo.get(flagd)).intValue(); + flagid|=id; + } + fsset.add(new Integer(flagid)); + //tag information not needed because tag + //changes are not tolerated. + } + + output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={"); + boolean needcomma=false; + for(Iterator it=fsset.iterator(); it.hasNext(); ) { + if(needcomma) + output.print(", "); + output.println(it.next()); + } + + output.println("};\n"); + + + //generate optionaltaskdescriptor that actually + //includes exit fses, predicate and the task + //concerned + output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={"); + output.println("&task_"+otd.td.getSafeSymbol()+","); + output.println("/*index*/"+otd.getIndex()+","); + output.println("/*number of enter flags*/"+fsset.size()+","); + output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+","); + output.println("/*number of members */"+predicateindex+","); + output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+","); + output.println("};\n"); + } } else - continue; + continue; // if there are no optionals, there is no need to build the rest of the struct output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={"); c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values(); if( !c_otd.isEmpty() ) { - boolean needcomma=false; - for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) { - OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next(); - if(needcomma) - output.println(","); - needcomma=true; - output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()); - } + boolean needcomma=false; + for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) { + OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next(); + if(needcomma) + output.println(","); + needcomma=true; + output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()); + } } output.println("};\n"); @@ -3391,107 +3391,107 @@ fldloop: TreeSet fsts=new TreeSet(new FlagComparator(flaginfo)); fsts.addAll(hashtbtemp.keySet()); for(Iterator fsit=fsts.iterator(); fsit.hasNext(); ) { - FlagState fs = (FlagState)fsit.next(); - fscounter++; - - //get the set of OptionalTaskDescriptors corresponding - HashSet availabletasks = (HashSet)hashtbtemp.get(fs); - //iterate through the OptionalTaskDescriptors and - //store the pointers to the optionals struct (see on - //top) into an array - - output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {"); - for(Iterator mos = ordertd(availabletasks).iterator(); mos.hasNext(); ) { - OptionalTaskDescriptor mm = mos.next(); - if(!mos.hasNext()) - output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()); - else - output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+","); - } - - output.println("};\n"); - - //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose. - - int flagid=0; - for(Iterator flags = fs.getFlags(); flags.hasNext(); ) { - FlagDescriptor flagd = (FlagDescriptor)flags.next(); - int id=1<<((Integer)flaginfo.get(flagd)).intValue(); - flagid|=id; - } - - //process tag information - - int tagcounter = 0; - boolean first = true; - Enumeration tag_enum = fs.getTags(); - output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={"); - while(tag_enum.hasMoreElements()) { - tagcounter++; - TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement(); - if(first==true) - first = false; - else - output.println(", "); - output.println("/*tagid*/"+state.getTagId(tagd)); - } - output.println("};"); - - Set tiset=sa.getTaskIndex(fs); - for(Iterator itti=tiset.iterator(); itti.hasNext(); ) { - TaskIndex ti=itti.next(); - if (ti.isRuntime()) - continue; - - Set otdset=sa.getOptions(fs, ti); - - output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {"); - boolean needcomma=false; - for(Iterator otdit=ordertd(otdset).iterator(); otdit.hasNext(); ) { - OptionalTaskDescriptor otd=otdit.next(); - if(needcomma) - output.print(", "); - needcomma=true; - output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()); - } - output.println("};"); - - output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {"); - output.print("&task_"+ti.getTask().getSafeSymbol()+", "); - output.print(ti.getIndex()+", "); - output.print(otdset.size()+", "); - output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array"); - output.println("};"); - } - - tiset=sa.getTaskIndex(fs); - boolean needcomma=false; - int runtimeti=0; - output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={"); - for(Iterator itti=tiset.iterator(); itti.hasNext(); ) { - TaskIndex ti=itti.next(); - if (ti.isRuntime()) { - runtimeti++; - continue; - } - if (needcomma) - output.print(", "); - needcomma=true; - output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()); - } - output.println("};\n"); - - //Store the result in fsanalysiswrapper - - output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={"); - output.println("/*flag*/"+flagid+","); - output.println("/* number of tags*/"+tagcounter+","); - output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+","); - output.println("/* numtask failures */"+(tiset.size()-runtimeti)+","); - output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+","); - output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+","); - output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()); - output.println("};\n"); + FlagState fs = (FlagState)fsit.next(); + fscounter++; + + //get the set of OptionalTaskDescriptors corresponding + HashSet availabletasks = (HashSet)hashtbtemp.get(fs); + //iterate through the OptionalTaskDescriptors and + //store the pointers to the optionals struct (see on + //top) into an array + + output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {"); + for(Iterator mos = ordertd(availabletasks).iterator(); mos.hasNext(); ) { + OptionalTaskDescriptor mm = mos.next(); + if(!mos.hasNext()) + output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()); + else + output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+","); + } + + output.println("};\n"); + + //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose. + + int flagid=0; + for(Iterator flags = fs.getFlags(); flags.hasNext(); ) { + FlagDescriptor flagd = (FlagDescriptor)flags.next(); + int id=1<<((Integer)flaginfo.get(flagd)).intValue(); + flagid|=id; + } + + //process tag information + + int tagcounter = 0; + boolean first = true; + Enumeration tag_enum = fs.getTags(); + output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={"); + while(tag_enum.hasMoreElements()) { + tagcounter++; + TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement(); + if(first==true) + first = false; + else + output.println(", "); + output.println("/*tagid*/"+state.getTagId(tagd)); + } + output.println("};"); + + Set tiset=sa.getTaskIndex(fs); + for(Iterator itti=tiset.iterator(); itti.hasNext(); ) { + TaskIndex ti=itti.next(); + if (ti.isRuntime()) + continue; + + Set otdset=sa.getOptions(fs, ti); + + output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {"); + boolean needcomma=false; + for(Iterator otdit=ordertd(otdset).iterator(); otdit.hasNext(); ) { + OptionalTaskDescriptor otd=otdit.next(); + if(needcomma) + output.print(", "); + needcomma=true; + output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()); + } + output.println("};"); + + output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {"); + output.print("&task_"+ti.getTask().getSafeSymbol()+", "); + output.print(ti.getIndex()+", "); + output.print(otdset.size()+", "); + output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array"); + output.println("};"); + } + + tiset=sa.getTaskIndex(fs); + boolean needcomma=false; + int runtimeti=0; + output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={"); + for(Iterator itti=tiset.iterator(); itti.hasNext(); ) { + TaskIndex ti=itti.next(); + if (ti.isRuntime()) { + runtimeti++; + continue; + } + if (needcomma) + output.print(", "); + needcomma=true; + output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()); + } + output.println("};\n"); + + //Store the result in fsanalysiswrapper + + output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={"); + output.println("/*flag*/"+flagid+","); + output.println("/* number of tags*/"+tagcounter+","); + output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+","); + output.println("/* numtask failures */"+(tiset.size()-runtimeti)+","); + output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+","); + output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+","); + output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()); + output.println("};\n"); } @@ -3499,9 +3499,9 @@ fldloop: output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {"); boolean needcomma=false; for(int i = 0; i0) - output.print(", "); + output.print(", "); if ((cn != null) && (processedcd.contains(cn))) - output.print("&classanalysiswrapper_"+cn.getSafeSymbol()); + output.print("&classanalysiswrapper_"+cn.getSafeSymbol()); else - output.print("NULL"); + output.print("NULL"); } output.println("};"); @@ -3544,8 +3544,8 @@ fldloop: for(Iterator it=r.keySet().iterator(); it.hasNext(); ) { Set s=r.get(it.next()); for(Iterator it2=s.iterator(); it2.hasNext(); ) { - OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next(); - l.add(otd); + OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next(); + l.add(otd); } } @@ -3600,20 +3600,20 @@ fldloop: // do not generate the line number if it is same as the previous one boolean needtoprint; if(fn.prev.size()==0) { - needtoprint=true; + needtoprint=true; } else { - needtoprint=false; + needtoprint=false; } for(int i=0; i taskit = tmpschedule.getTasks().iterator(); while(taskit.hasNext()) { - /* Classify parameters */ - TaskDescriptor task=taskit.next(); - FlatMethod fm=state.getMethodFlat(task); - generateTempStructs(fm); - - ParamsObject objectparams=(ParamsObject) paramstable.get(task); - TempObject objecttemps=(TempObject) tempstable.get(task); - - /* Output parameter structure */ - if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - output.println("struct "+task.getCoreSafeSymbol(num)+"_params {"); - output.println(" int size;"); - output.println(" void * next;"); - for(int j=0; jmaxtaskparams) { - maxtaskparams=objectparams.numPointers()+fm.numTags(); - } - } - - /* Output temp structure */ - if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - output.println("struct "+task.getCoreSafeSymbol(num)+"_locals {"); - output.println(" int size;"); - output.println(" void * next;"); - for(int j=0; jmaxtaskparams) { + maxtaskparams=objectparams.numPointers()+fm.numTags(); + } + } + + /* Output temp structure */ + if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { + output.println("struct "+task.getCoreSafeSymbol(num)+"_locals {"); + output.println(" int size;"); + output.println(" void * next;"); + for(int j=0; j 0) { - output.print(", "); - } - output.print(((Integer)targetcores[j]).intValue()); - } - output.println("};"); - output.println("struct " + queuename + " " + queueins + "= {"); - output.println(/*".cores = " + */ queuename + "cores,"); - output.println(/*".index = " + */ "0,"); - output.println(/*".length = " +*/ targetcores.length + "};"); + FlagState tmpfstate = (FlagState)keys[i]; + Object[] targetcores = targetCoreTbl.get(tmpfstate).toArray(); + String queuename = this.otqueueprefix + tmpfstate.getClassDescriptor().getCoreSafeSymbol(num) + tmpfstate.getuid() + "___"; + String queueins = queuename + "ins"; + flag2qname.put(tmpfstate, queuename); + output.println("struct " + queuename + " {"); + output.println(" int * cores;"); + output.println(" int index;"); + output.println(" int length;"); + output.println("};"); + output.print("int " + queuename + "cores[] = {"); + for(int j = 0; j < targetcores.length; ++j) { + if(j > 0) { + output.print(", "); + } + output.print(((Integer)targetcores[j]).intValue()); + } + output.println("};"); + output.println("struct " + queuename + " " + queueins + "= {"); + output.println(/*".cores = " + */ queuename + "cores,"); + output.println(/*".index = " + */ "0,"); + output.println(/*".length = " +*/ targetcores.length + "};"); } } output.println(); @@ -667,7 +667,7 @@ public class BuildCodeMultiCore extends BuildCode { output.print(objecttemp.numPointers()+","); output.print(paramsprefix); for(int j=0; jfailurecount) {instructioncount=0;injectinstructionfailure();}"); @@ -775,45 +775,45 @@ public class BuildCodeMultiCore extends BuildCode { output.println("if ((--instructioncount)==0) injectinstructionfailure();"); }*/ if (current_node.numNext()==0) { - output.print(" "); - generateFlatNode(fm, current_node, output); - if (current_node.kind()!=FKind.FlatReturnNode) { - //output.println(" flushAll();"); - output.println("#ifdef CACHEFLUSH"); - output.println("BAMBOO_ENTER_RUNTIME_MODE_FROM_CLIENT();"); - output.println("#ifdef DEBUG"); - output.println("BAMBOO_DEBUGPRINT(0xec00);"); - output.println("#endif"); - output.println("BAMBOO_CACHE_FLUSH_ALL();"); - output.println("#ifdef DEBUG"); - output.println("BAMBOO_DEBUGPRINT(0xecff);"); - output.println("#endif"); - output.println("BAMBOO_ENTER_CLIENT_MODE_FROM_RUNTIME();"); - output.println("#endif"); - outputTransCode(output); - output.println(" return;"); - } - current_node=null; + output.print(" "); + generateFlatNode(fm, current_node, output); + if (current_node.kind()!=FKind.FlatReturnNode) { + //output.println(" flushAll();"); + output.println("#ifdef CACHEFLUSH"); + output.println("BAMBOO_ENTER_RUNTIME_MODE_FROM_CLIENT();"); + output.println("#ifdef DEBUG"); + output.println("BAMBOO_DEBUGPRINT(0xec00);"); + output.println("#endif"); + output.println("BAMBOO_CACHE_FLUSH_ALL();"); + output.println("#ifdef DEBUG"); + output.println("BAMBOO_DEBUGPRINT(0xecff);"); + output.println("#endif"); + output.println("BAMBOO_ENTER_CLIENT_MODE_FROM_RUNTIME();"); + output.println("#endif"); + outputTransCode(output); + output.println(" return;"); + } + current_node=null; } else if(current_node.numNext()==1) { - output.print(" "); - generateFlatNode(fm, current_node, output); - FlatNode nextnode=current_node.getNext(0); - if (visited.contains(nextnode)) { - output.println("goto L"+nodetolabel.get(nextnode)+";"); - current_node=null; - } else - current_node=nextnode; + output.print(" "); + generateFlatNode(fm, current_node, output); + FlatNode nextnode=current_node.getNext(0); + if (visited.contains(nextnode)) { + output.println("goto L"+nodetolabel.get(nextnode)+";"); + current_node=null; + } else + current_node=nextnode; } else if (current_node.numNext()==2) { - /* Branch */ - output.print(" "); - generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output); - if (!visited.contains(current_node.getNext(1))) - tovisit.add(current_node.getNext(1)); - if (visited.contains(current_node.getNext(0))) { - output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";"); - current_node=null; - } else - current_node=current_node.getNext(0); + /* Branch */ + output.print(" "); + generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output); + if (!visited.contains(current_node.getNext(1))) + tovisit.add(current_node.getNext(1)); + if (visited.contains(current_node.getNext(0))) { + output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";"); + current_node=null; + } else + current_node=current_node.getNext(0); } else throw new Error(); } @@ -838,58 +838,58 @@ public class BuildCodeMultiCore extends BuildCode { int dnfterms; if (param_flag==null) { - output.println("int parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={"); - output.println("0x0, 0x0 };"); - dnfterms=1; + output.println("int parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={"); + output.println("0x0, 0x0 };"); + dnfterms=1; } else { - DNFFlag dflag=param_flag.getDNF(); - dnfterms=dflag.size(); - - Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc()); - output.println("int parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={"); - for(int j=0; jmaxtaskparams) - maxtaskparams=objectparams.numPrimitives()+fm.numTags(); + maxtaskparams=objectparams.numPrimitives()+fm.numTags(); } else output.println(") {"); } @@ -1005,19 +1005,19 @@ public class BuildCodeMultiCore extends BuildCode { ClassDescriptor cd = temp.getType().getClassDesc(); Vector initfstates = ffan.getInitFStates(cd); for(int i = 0; i < initfstates.size(); ++i) { - FlagState tmpFState = initfstates.elementAt(i); - output.println("{"); - QueueInfo qinfo = outputqueues(tmpFState, num, output, false); - output.println("flagorand("+generateTemp(fm, temp)+", 0x"+Integer.toHexString(ormask)+ - ", 0x"+Integer.toHexString(andmask)+", " + qinfo.qname + - ", " + qinfo.length + ");"); - output.println("}"); + FlagState tmpFState = initfstates.elementAt(i); + output.println("{"); + QueueInfo qinfo = outputqueues(tmpFState, num, output, false); + output.println("flagorand("+generateTemp(fm, temp)+", 0x"+Integer.toHexString(ormask)+ + ", 0x"+Integer.toHexString(andmask)+", " + qinfo.qname + + ", " + qinfo.length + ");"); + output.println("}"); } if(ffan.getTaskType()==FlatFlagActionNode.TASKEXIT) { - // generate codes for profiling, recording which task exit it is - output.println("#ifdef PROFILE"); - output.println("setTaskExitIndex(" + ffan.getTaskExitIndex() + ");"); - output.println("#endif"); + // generate codes for profiling, recording which task exit it is + output.println("#ifdef PROFILE"); + output.println("setTaskExitIndex(" + ffan.getTaskExitIndex() + ");"); + output.println("#endif"); } } } @@ -1036,24 +1036,24 @@ public class BuildCodeMultiCore extends BuildCode { initfstates = ffan.getInitFStates(cd); targetFStates = new Vector[initfstates.size()]; for(int i = 0; i < initfstates.size(); ++i) { - FlagState fs = initfstates.elementAt(i); - targetFStates[i] = ffan.getTargetFStates(fs); - - if(!fs.isSetmask()) { - Hashtable flags=(Hashtable)flagorder.get(cd); - int andmask=0; - int checkmask=0; - Iterator it_flags = fs.getFlags(); - while(it_flags.hasNext()) { - FlagDescriptor fd = (FlagDescriptor)it_flags.next(); - int flagid=1<<((Integer)flags.get(fd)).intValue(); - andmask|=flagid; - checkmask|=flagid; - } - fs.setAndmask(andmask); - fs.setCheckmask(checkmask); - fs.setSetmask(true); - } + FlagState fs = initfstates.elementAt(i); + targetFStates[i] = ffan.getTargetFStates(fs); + + if(!fs.isSetmask()) { + Hashtable flags=(Hashtable)flagorder.get(cd); + int andmask=0; + int checkmask=0; + Iterator it_flags = fs.getFlags(); + while(it_flags.hasNext()) { + FlagDescriptor fd = (FlagDescriptor)it_flags.next(); + int flagid=1<<((Integer)flags.get(fd)).intValue(); + andmask|=flagid; + checkmask|=flagid; + } + fs.setAndmask(andmask); + fs.setCheckmask(checkmask); + fs.setSetmask(true); + } } } boolean isolate = true; // check if this flagstate can associate to some task with multiple params which can @@ -1061,22 +1061,22 @@ public class BuildCodeMultiCore extends BuildCode { if((this.currentSchedule == null) && (fm.getMethod().getClassDesc().getSymbol().equals("ServerSocket"))) { // ServerSocket object will always reside on current core for(int j = 0; j < targetFStates.length; ++j) { - if(initfstates != null) { - FlagState fs = initfstates.elementAt(j); - output.println("if(" + generateTempFlagName(fm, temp) + "&(0x" + Integer.toHexString(fs.getAndmask()) - + ")==(0x" + Integer.toHexString(fs.getCheckmask()) + ")) {"); - } - Vector tmpfstates = (Vector)targetFStates[j]; - for(int i = 0; i < tmpfstates.size(); ++i) { - FlagState tmpFState = tmpfstates.elementAt(i); - // TODO - // may have bugs here - output.println("/* reside on this core*"); - output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);"); - } - if(initfstates != null) { - output.println("}"); - } + if(initfstates != null) { + FlagState fs = initfstates.elementAt(j); + output.println("if(" + generateTempFlagName(fm, temp) + "&(0x" + Integer.toHexString(fs.getAndmask()) + + ")==(0x" + Integer.toHexString(fs.getCheckmask()) + ")) {"); + } + Vector tmpfstates = (Vector)targetFStates[j]; + for(int i = 0; i < tmpfstates.size(); ++i) { + FlagState tmpFState = tmpfstates.elementAt(i); + // TODO + // may have bugs here + output.println("/* reside on this core*"); + output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);"); + } + if(initfstates != null) { + output.println("}"); + } } return; } @@ -1086,182 +1086,182 @@ public class BuildCodeMultiCore extends BuildCode { for(int j = 0; j < targetFStates.length; ++j) { FlagState fs = null; if(initfstates != null) { - fs = initfstates.elementAt(j); - output.println("if((" + generateTempFlagName(fm, temp) + "&(0x" + Integer.toHexString(fs.getAndmask()) - + "))==(0x" + Integer.toHexString(fs.getCheckmask()) + ")) {"); + fs = initfstates.elementAt(j); + output.println("if((" + generateTempFlagName(fm, temp) + "&(0x" + Integer.toHexString(fs.getAndmask()) + + "))==(0x" + Integer.toHexString(fs.getCheckmask()) + ")) {"); } Vector tmpfstates = (Vector)targetFStates[j]; for(int i = 0; i < tmpfstates.size(); ++i) { - FlagState tmpFState = tmpfstates.elementAt(i); - - if(this.currentSchedule.getAllyCoreTable() == null) { - isolate = true; - } else { - isolate = (this.currentSchedule.getAllyCoreTable().get(tmpFState) == null) || - (this.currentSchedule.getAllyCoreTable().get(tmpFState).size() == 0); - } - - Vector sendto = new Vector(); - Queue queue = null; - if(targetCoreTbl != null) { - queue = targetCoreTbl.get(tmpFState); - } - if((queue != null) && - ((queue.size() != 1) || - ((queue.size() == 1) && (queue.element().intValue() != num)))) { - // this object may be transferred to other cores - String queuename = (String) this.fsate2qnames[num].get(tmpFState); - String queueins = queuename + "ins"; - - Object[] cores = queue.toArray(); - String index = "0"; - Integer targetcore = (Integer)cores[0]; - if(queue.size() > 1) { - index = queueins + ".index"; - } - if(queue.size() > 1) { - output.println("switch(" + queueins + ".index % " + queueins + ".length) {"); - for(int k = 0; k < cores.length; ++k) { - output.println("case " + k + ":"); - targetcore = (Integer)cores[k]; - if(targetcore.intValue() == num) { - output.println("/* reside on this core*/"); - if(isolate) { - output.println("{"); - QueueInfo qinfo = outputqueues(tmpFState, num, output, true); - output.println("enqueueObject("+generateTemp(fm, temp)+", " + qinfo.qname + - ", " + qinfo.length + ");"); - output.println("}"); - } /*else { - // TODO - // really needed? - output.println("/* possibly needed by multi-parameter tasks on this core*//*"); - output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);"); - }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now - } else { - /*if(!isolate) { - // TODO - // Is it possible to decide the actual queues? - output.println("/* possibly needed by multi-parameter tasks on this core*//*"); - output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);"); - }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now - output.println("/* transfer to core " + targetcore.toString() + "*/"); - output.println("{"); - // enqueue this object and its destinations for later process - // all the possible queues - QueueInfo qinfo = null; - TranObjInfo tmpinfo = new TranObjInfo(); - tmpinfo.name = generateTemp(fm, temp); - tmpinfo.targetcore = targetcore; - FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState); - if(targetFS != null) { - tmpinfo.fs = targetFS; - } else { - tmpinfo.fs = tmpFState; - } - qinfo = outputtransqueues(tmpinfo.fs, targetcore, output); - output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));"); - output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";"); - output.println("tmpObjInfo->targetcore = "+targetcore.toString()+";"); - output.println("tmpObjInfo->queues = " + qinfo.qname + ";"); - output.println("tmpObjInfo->length = " + qinfo.length + ";"); - output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);"); - output.println("}"); - } - output.println("break;"); - } - output.println("}"); - } else { - /*if(!isolate) { - // TODO - // Is it possible to decide the actual queues? - output.println("/* possibly needed by multi-parameter tasks on this core*//*"); - output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);"); - }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now - output.println("/* transfer to core " + targetcore.toString() + "*/"); - output.println("{"); - // enqueue this object and its destinations for later process - // all the possible queues - QueueInfo qinfo = null; - TranObjInfo tmpinfo = new TranObjInfo(); - tmpinfo.name = generateTemp(fm, temp); - tmpinfo.targetcore = targetcore; - FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState); - if(targetFS != null) { - tmpinfo.fs = targetFS; - } else { - tmpinfo.fs = tmpFState; - } - qinfo = outputtransqueues(tmpinfo.fs, targetcore, output); - output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));"); - output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";"); - output.println("tmpObjInfo->targetcore = "+targetcore.toString()+";"); - output.println("tmpObjInfo->queues = " + qinfo.qname + ";"); - output.println("tmpObjInfo->length = " + qinfo.length + ";"); - output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);"); - output.println("}"); - } - output.println("/* increase index*/"); - output.println("++" + queueins + ".index;"); - } else { - // this object will reside on current core - output.println("/* reside on this core*/"); - if(isolate) { - output.println("{"); - QueueInfo qinfo = outputqueues(tmpFState, num, output, true); - output.println("enqueueObject("+generateTemp(fm, temp)+", " + qinfo.qname + - ", " + qinfo.length + ");"); - output.println("}"); - } /*else { - // TODO - // really needed? - output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);"); - }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now - } - - // codes for multi-params tasks - if(!isolate) { - // flagstate associated with some multi-params tasks - // need to be send to other cores - Vector targetcores = this.currentSchedule.getAllyCores(tmpFState); - output.println("/* send the shared object to possible queues on other cores*/"); - // TODO, temporary solution, send to mostly the first two - int upperbound = targetcores.size() > 2?2:targetcores.size(); - for(int k = 0; k < upperbound; ++k) { - // TODO - // add the information of exactly which queue - int targetcore = targetcores.elementAt(k).intValue(); - if(!sendto.contains(targetcore)) { - // previously not sended to this target core - // enqueue this object and its destinations for later process - output.println("{"); - // all the possible queues - QueueInfo qinfo = null; - TranObjInfo tmpinfo = new TranObjInfo(); - tmpinfo.name = generateTemp(fm, temp); - tmpinfo.targetcore = targetcore; - FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState); - if(targetFS != null) { - tmpinfo.fs = targetFS; - } else { - tmpinfo.fs = tmpFState; - } - qinfo = outputtransqueues(tmpinfo.fs, targetcore, output); - output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));"); - output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";"); - output.println("tmpObjInfo->targetcore = "+targetcore+";"); - output.println("tmpObjInfo->queues = " + qinfo.qname + ";"); - output.println("tmpObjInfo->length = " + qinfo.length + ";"); - output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);"); - output.println("}"); - sendto.addElement(targetcore); - } - } - } + FlagState tmpFState = tmpfstates.elementAt(i); + + if(this.currentSchedule.getAllyCoreTable() == null) { + isolate = true; + } else { + isolate = (this.currentSchedule.getAllyCoreTable().get(tmpFState) == null) || + (this.currentSchedule.getAllyCoreTable().get(tmpFState).size() == 0); + } + + Vector sendto = new Vector(); + Queue queue = null; + if(targetCoreTbl != null) { + queue = targetCoreTbl.get(tmpFState); + } + if((queue != null) && + ((queue.size() != 1) || + ((queue.size() == 1) && (queue.element().intValue() != num)))) { + // this object may be transferred to other cores + String queuename = (String) this.fsate2qnames[num].get(tmpFState); + String queueins = queuename + "ins"; + + Object[] cores = queue.toArray(); + String index = "0"; + Integer targetcore = (Integer)cores[0]; + if(queue.size() > 1) { + index = queueins + ".index"; + } + if(queue.size() > 1) { + output.println("switch(" + queueins + ".index % " + queueins + ".length) {"); + for(int k = 0; k < cores.length; ++k) { + output.println("case " + k + ":"); + targetcore = (Integer)cores[k]; + if(targetcore.intValue() == num) { + output.println("/* reside on this core*/"); + if(isolate) { + output.println("{"); + QueueInfo qinfo = outputqueues(tmpFState, num, output, true); + output.println("enqueueObject("+generateTemp(fm, temp)+", " + qinfo.qname + + ", " + qinfo.length + ");"); + output.println("}"); + } /*else { + // TODO + // really needed? + output.println("/* possibly needed by multi-parameter tasks on this core*//*"); + output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);"); + }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now + } else { + /*if(!isolate) { + // TODO + // Is it possible to decide the actual queues? + output.println("/* possibly needed by multi-parameter tasks on this core*//*"); + output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);"); + }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now + output.println("/* transfer to core " + targetcore.toString() + "*/"); + output.println("{"); + // enqueue this object and its destinations for later process + // all the possible queues + QueueInfo qinfo = null; + TranObjInfo tmpinfo = new TranObjInfo(); + tmpinfo.name = generateTemp(fm, temp); + tmpinfo.targetcore = targetcore; + FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState); + if(targetFS != null) { + tmpinfo.fs = targetFS; + } else { + tmpinfo.fs = tmpFState; + } + qinfo = outputtransqueues(tmpinfo.fs, targetcore, output); + output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));"); + output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";"); + output.println("tmpObjInfo->targetcore = "+targetcore.toString()+";"); + output.println("tmpObjInfo->queues = " + qinfo.qname + ";"); + output.println("tmpObjInfo->length = " + qinfo.length + ";"); + output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);"); + output.println("}"); + } + output.println("break;"); + } + output.println("}"); + } else { + /*if(!isolate) { + // TODO + // Is it possible to decide the actual queues? + output.println("/* possibly needed by multi-parameter tasks on this core*//*"); + output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);"); + }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now + output.println("/* transfer to core " + targetcore.toString() + "*/"); + output.println("{"); + // enqueue this object and its destinations for later process + // all the possible queues + QueueInfo qinfo = null; + TranObjInfo tmpinfo = new TranObjInfo(); + tmpinfo.name = generateTemp(fm, temp); + tmpinfo.targetcore = targetcore; + FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState); + if(targetFS != null) { + tmpinfo.fs = targetFS; + } else { + tmpinfo.fs = tmpFState; + } + qinfo = outputtransqueues(tmpinfo.fs, targetcore, output); + output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));"); + output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";"); + output.println("tmpObjInfo->targetcore = "+targetcore.toString()+";"); + output.println("tmpObjInfo->queues = " + qinfo.qname + ";"); + output.println("tmpObjInfo->length = " + qinfo.length + ";"); + output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);"); + output.println("}"); + } + output.println("/* increase index*/"); + output.println("++" + queueins + ".index;"); + } else { + // this object will reside on current core + output.println("/* reside on this core*/"); + if(isolate) { + output.println("{"); + QueueInfo qinfo = outputqueues(tmpFState, num, output, true); + output.println("enqueueObject("+generateTemp(fm, temp)+", " + qinfo.qname + + ", " + qinfo.length + ");"); + output.println("}"); + } /*else { + // TODO + // really needed? + output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);"); + }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now + } + + // codes for multi-params tasks + if(!isolate) { + // flagstate associated with some multi-params tasks + // need to be send to other cores + Vector targetcores = this.currentSchedule.getAllyCores(tmpFState); + output.println("/* send the shared object to possible queues on other cores*/"); + // TODO, temporary solution, send to mostly the first two + int upperbound = targetcores.size() > 2?2:targetcores.size(); + for(int k = 0; k < upperbound; ++k) { + // TODO + // add the information of exactly which queue + int targetcore = targetcores.elementAt(k).intValue(); + if(!sendto.contains(targetcore)) { + // previously not sended to this target core + // enqueue this object and its destinations for later process + output.println("{"); + // all the possible queues + QueueInfo qinfo = null; + TranObjInfo tmpinfo = new TranObjInfo(); + tmpinfo.name = generateTemp(fm, temp); + tmpinfo.targetcore = targetcore; + FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState); + if(targetFS != null) { + tmpinfo.fs = targetFS; + } else { + tmpinfo.fs = tmpFState; + } + qinfo = outputtransqueues(tmpinfo.fs, targetcore, output); + output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));"); + output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";"); + output.println("tmpObjInfo->targetcore = "+targetcore+";"); + output.println("tmpObjInfo->queues = " + qinfo.qname + ";"); + output.println("tmpObjInfo->length = " + qinfo.length + ";"); + output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);"); + output.println("}"); + sendto.addElement(targetcore); + } + } + } } if(initfstates != null) { - output.println("}"); + output.println("}"); } } } @@ -1285,18 +1285,18 @@ public class BuildCodeMultiCore extends BuildCode { TaskDescriptor td = fe.getTask(); int paraindex = fe.getIndex(); if((!isEnqueue) || (isEnqueue && residetasks.contains(td))) { - if((!tasks.contains(td)) || - ((tasks.contains(td)) && (paraindex != indexes.elementAt(tasks.indexOf(td)).intValue()))) { - tasks.addElement(td); - indexes.addElement(paraindex); - if(comma) { - output.println(","); - } else { - comma = true; - } - output.print("&" + this.objqueueprefix + paraindex + "_" + td.getCoreSafeSymbol(num)); - ++qinfo.length; - } + if((!tasks.contains(td)) || + ((tasks.contains(td)) && (paraindex != indexes.elementAt(tasks.indexOf(td)).intValue()))) { + tasks.addElement(td); + indexes.addElement(paraindex); + if(comma) { + output.println(","); + } else { + comma = true; + } + output.print("&" + this.objqueueprefix + paraindex + "_" + td.getCoreSafeSymbol(num)); + ++qinfo.length; + } } } output.println("};"); @@ -1321,19 +1321,19 @@ public class BuildCodeMultiCore extends BuildCode { TaskDescriptor td = fe.getTask(); int paraindex = fe.getIndex(); if(residetasks.contains(td)) { - if((!tasks.contains(td)) || - ((tasks.contains(td)) && (paraindex != indexes.elementAt(tasks.indexOf(td)).intValue()))) { - tasks.addElement(td); - indexes.addElement(paraindex); - if(comma) { - output.println(","); - } else { - comma = true; - } - output.print(residetasks.indexOf(td) + ", "); - output.print(paraindex); - ++qinfo.length; - } + if((!tasks.contains(td)) || + ((tasks.contains(td)) && (paraindex != indexes.elementAt(tasks.indexOf(td)).intValue()))) { + tasks.addElement(td); + indexes.addElement(paraindex); + if(comma) { + output.println(","); + } else { + comma = true; + } + output.print(residetasks.indexOf(td) + ", "); + output.print(paraindex); + ++qinfo.length; + } } } output.println("};"); @@ -1394,14 +1394,14 @@ public class BuildCodeMultiCore extends BuildCode { // higher numbered parameters aliasSets.add(null); for( int j = i + 1; j < fm.numParameters(); ++j ) { - common = this.m_oa.createsPotentialAliases(td, i, j); - if(!common.isEmpty()) { - // ith parameter and jth parameter has alias, create lock to protect them - if(aliasSets.elementAt(i) == null) { - aliasSets.setElementAt(new Vector(), i); - } - aliasSets.elementAt(i).add(j); - } + common = this.m_oa.createsPotentialAliases(td, i, j); + if(!common.isEmpty()) { + // ith parameter and jth parameter has alias, create lock to protect them + if(aliasSets.elementAt(i) == null) { + aliasSets.setElementAt(new Vector(), i); + } + aliasSets.elementAt(i).add(j); + } } // for the ith parameter, check for aliases against @@ -1409,15 +1409,15 @@ public class BuildCodeMultiCore extends BuildCode { // task context aliasFNSets.add(null); for(int j = 0; j < allocSites.length; j++) { - AllocationSite as = (AllocationSite)allocSites[j]; - common = this.m_oa.createsPotentialAliases(td, i, as); - if( !common.isEmpty() ) { - // ith parameter and allocationsite as has alias - if(aliasFNSets.elementAt(i) == null) { - aliasFNSets.setElementAt(new Vector(), i); - } - aliasFNSets.elementAt(i).add(as.getFlatNew()); - } + AllocationSite as = (AllocationSite)allocSites[j]; + common = this.m_oa.createsPotentialAliases(td, i, as); + if( !common.isEmpty() ) { + // ith parameter and allocationsite as has alias + if(aliasFNSets.elementAt(i) == null) { + aliasFNSets.setElementAt(new Vector(), i); + } + aliasFNSets.elementAt(i).add(as.getFlatNew()); + } } } @@ -1427,18 +1427,18 @@ public class BuildCodeMultiCore extends BuildCode { for( int i = 0; i < allocSites.length; ++i ) { AllocationSite as1 = (AllocationSite)allocSites[i]; for(int j = i + 1; j < allocSites.length; j++) { - AllocationSite as2 = (AllocationSite)allocSites[j]; - - common = this.m_oa.createsPotentialAliases(td, as1, as2); - if( !common.isEmpty() ) { - // as1 and as2 has alias - if(!aliasFNTbl.containsKey(as1.getFlatNew())) { - aliasFNTbl.put(as1.getFlatNew(), new Vector()); - } - if(!aliasFNTbl.get(as1.getFlatNew()).contains(as2.getFlatNew())) { - aliasFNTbl.get(as1.getFlatNew()).add(as2.getFlatNew()); - } - } + AllocationSite as2 = (AllocationSite)allocSites[j]; + + common = this.m_oa.createsPotentialAliases(td, as1, as2); + if( !common.isEmpty() ) { + // as1 and as2 has alias + if(!aliasFNTbl.containsKey(as1.getFlatNew())) { + aliasFNTbl.put(as1.getFlatNew(), new Vector()); + } + if(!aliasFNTbl.get(as1.getFlatNew()).contains(as2.getFlatNew())) { + aliasFNTbl.get(as1.getFlatNew()).add(as2.getFlatNew()); + } + } } } @@ -1448,33 +1448,33 @@ public class BuildCodeMultiCore extends BuildCode { while(it.hasNext()) { FlatNew tmpfn = it.next(); if(visited.contains(tmpfn)) { - continue; + continue; } visited.add(tmpfn); Queue tovisit = new LinkedList(); Vector tmpv = aliasFNTbl.get(tmpfn); if(tmpv == null) { - continue; + continue; } for(int j = 0; j < tmpv.size(); j++) { - tovisit.add(tmpv.elementAt(j)); + tovisit.add(tmpv.elementAt(j)); } while(!tovisit.isEmpty()) { - FlatNew fn = tovisit.poll(); - visited.add(fn); - Vector tmpset = aliasFNTbl.get(fn); - if(tmpset != null) { - // merge tmpset to the alias set of the ith parameter - for(int j = 0; j < tmpset.size(); j++) { - if(!tmpv.contains(tmpset.elementAt(j))) { - tmpv.add(tmpset.elementAt(j)); - tovisit.add(tmpset.elementAt(j)); - } - } - aliasFNTbl.remove(fn); - } + FlatNew fn = tovisit.poll(); + visited.add(fn); + Vector tmpset = aliasFNTbl.get(fn); + if(tmpset != null) { + // merge tmpset to the alias set of the ith parameter + for(int j = 0; j < tmpset.size(); j++) { + if(!tmpv.contains(tmpset.elementAt(j))) { + tmpv.add(tmpset.elementAt(j)); + tovisit.add(tmpset.elementAt(j)); + } + } + aliasFNTbl.remove(fn); + } } it = aliasFNTbl.keySet().iterator(); } @@ -1484,42 +1484,42 @@ public class BuildCodeMultiCore extends BuildCode { Queue tovisit = new LinkedList(); Vector tmpv = aliasSets.elementAt(i); if(tmpv == null) { - continue; + continue; } for(int j = 0; j < tmpv.size(); j++) { - tovisit.add(tmpv.elementAt(j)); + tovisit.add(tmpv.elementAt(j)); } while(!tovisit.isEmpty()) { - int index = tovisit.poll().intValue(); - Vector tmpset = aliasSets.elementAt(index); - if(tmpset != null) { - // merge tmpset to the alias set of the ith parameter - for(int j = 0; j < tmpset.size(); j++) { - if(!tmpv.contains(tmpset.elementAt(j))) { - tmpv.add(tmpset.elementAt(j)); - tovisit.add(tmpset.elementAt(j)); - } - } - aliasSets.setElementAt(null, index); - } - - Vector tmpFNSet = aliasFNSets.elementAt(index); - if(tmpFNSet != null) { - // merge tmpFNSet to the aliasFNSet of the ith parameter - if(aliasFNSets.elementAt(i) == null) { - aliasFNSets.setElementAt(tmpFNSet, i); - } else { - Vector tmpFNv = aliasFNSets.elementAt(i); - for(int j = 0; j < tmpFNSet.size(); j++) { - if(!tmpFNv.contains(tmpFNSet.elementAt(j))) { - tmpFNv.add(tmpFNSet.elementAt(j)); - } - } - } - aliasFNSets.setElementAt(null, index); - } + int index = tovisit.poll().intValue(); + Vector tmpset = aliasSets.elementAt(index); + if(tmpset != null) { + // merge tmpset to the alias set of the ith parameter + for(int j = 0; j < tmpset.size(); j++) { + if(!tmpv.contains(tmpset.elementAt(j))) { + tmpv.add(tmpset.elementAt(j)); + tovisit.add(tmpset.elementAt(j)); + } + } + aliasSets.setElementAt(null, index); + } + + Vector tmpFNSet = aliasFNSets.elementAt(index); + if(tmpFNSet != null) { + // merge tmpFNSet to the aliasFNSet of the ith parameter + if(aliasFNSets.elementAt(i) == null) { + aliasFNSets.setElementAt(tmpFNSet, i); + } else { + Vector tmpFNv = aliasFNSets.elementAt(i); + for(int j = 0; j < tmpFNSet.size(); j++) { + if(!tmpFNv.contains(tmpFNSet.elementAt(j))) { + tmpFNv.add(tmpFNSet.elementAt(j)); + } + } + } + aliasFNSets.setElementAt(null, index); + } } } @@ -1529,17 +1529,17 @@ public class BuildCodeMultiCore extends BuildCode { for(int i = 0; i < aliasSets.size(); i++) { Vector tmpv = aliasSets.elementAt(i); if(tmpv != null) { - tmpv.add(0, i); - tmpaliasSets.add(tmpv); - numlock++; + tmpv.add(0, i); + tmpaliasSets.add(tmpv); + numlock++; } Vector tmpFNv = aliasFNSets.elementAt(i); if(tmpFNv != null) { - aliasFNTbl4Para.put(i, tmpFNv); - if(tmpv == null) { - numlock++; - } + aliasFNTbl4Para.put(i, tmpFNv); + if(tmpv == null) { + numlock++; + } } } numparalock = numlock; @@ -1559,88 +1559,88 @@ public class BuildCodeMultiCore extends BuildCode { // associate locks with parameters int lockindex = 0; for(int i = 0; i < this.m_aliasSets.size(); i++) { - Vector toadd = this.m_aliasSets.elementAt(i); - - output.println("int tmplen_" + lockindex + " = " + toadd.size()); - output.println("void * tmpptrs_" + lockindex + "[] = {"); - for(int j = 0; j < toadd.size(); j++) { - int para = toadd.elementAt(j).intValue(); - output.print(generateTemp(fm, fm.getParameter(para))); - if(j < toadd.size() - 1) { - output.print(", "); - } else { - output.println("};"); - } - } - output.println("aliaslocks[tmpi++] = getAliasLock(tmpptrs_" + lockindex + ", tmplen_" + lockindex + ", lockRedirectTbl);"); - - for(int j = 0; j < toadd.size(); j++) { - int para = toadd.elementAt(j).intValue(); - output.println("addAliasLock(" + generateTemp(fm, fm.getParameter(para)) + ", aliaslocks[" + i + "]);"); - } - // check if this lock is also associated with any FlatNew nodes - if(this.m_aliasFNTbl4Para.containsKey(toadd.elementAt(0))) { - if(this.m_aliaslocksTbl4FN == null) { - this.m_aliaslocksTbl4FN = new Hashtable>(); - } - Vector tmpv = this.m_aliasFNTbl4Para.get(toadd.elementAt(0)); - for(int j = 0; j < tmpv.size(); j++) { - FlatNew fn = tmpv.elementAt(j); - if(!this.m_aliaslocksTbl4FN.containsKey(fn)) { - this.m_aliaslocksTbl4FN.put(fn, new Vector()); - } - this.m_aliaslocksTbl4FN.get(fn).add(i); - } - this.m_aliasFNTbl4Para.remove(toadd.elementAt(0)); - } - lockindex++; + Vector toadd = this.m_aliasSets.elementAt(i); + + output.println("int tmplen_" + lockindex + " = " + toadd.size()); + output.println("void * tmpptrs_" + lockindex + "[] = {"); + for(int j = 0; j < toadd.size(); j++) { + int para = toadd.elementAt(j).intValue(); + output.print(generateTemp(fm, fm.getParameter(para))); + if(j < toadd.size() - 1) { + output.print(", "); + } else { + output.println("};"); + } + } + output.println("aliaslocks[tmpi++] = getAliasLock(tmpptrs_" + lockindex + ", tmplen_" + lockindex + ", lockRedirectTbl);"); + + for(int j = 0; j < toadd.size(); j++) { + int para = toadd.elementAt(j).intValue(); + output.println("addAliasLock(" + generateTemp(fm, fm.getParameter(para)) + ", aliaslocks[" + i + "]);"); + } + // check if this lock is also associated with any FlatNew nodes + if(this.m_aliasFNTbl4Para.containsKey(toadd.elementAt(0))) { + if(this.m_aliaslocksTbl4FN == null) { + this.m_aliaslocksTbl4FN = new Hashtable>(); + } + Vector tmpv = this.m_aliasFNTbl4Para.get(toadd.elementAt(0)); + for(int j = 0; j < tmpv.size(); j++) { + FlatNew fn = tmpv.elementAt(j); + if(!this.m_aliaslocksTbl4FN.containsKey(fn)) { + this.m_aliaslocksTbl4FN.put(fn, new Vector()); + } + this.m_aliaslocksTbl4FN.get(fn).add(i); + } + this.m_aliasFNTbl4Para.remove(toadd.elementAt(0)); + } + lockindex++; } Object[] key = this.m_aliasFNTbl4Para.keySet().toArray(); for(int i = 0; i < key.length; i++) { - int para = ((Integer)key[i]).intValue(); - - output.println("void * tmpptrs_" + lockindex + "[] = {" + generateTemp(fm, fm.getParameter(para)) + "};"); - output.println("aliaslocks[tmpi++] = getAliasLock(tmpptrs_" + lockindex + ", 1, lockRedirectTbl);"); - - output.println("addAliasLock(" + generateTemp(fm, fm.getParameter(para)) + ", aliaslocks[" + lockindex + "]);"); - Vector tmpv = this.m_aliasFNTbl4Para.get(para); - for(int j = 0; j < tmpv.size(); j++) { - FlatNew fn = tmpv.elementAt(j); - if(this.m_aliaslocksTbl4FN == null) { - this.m_aliaslocksTbl4FN = new Hashtable>(); - } - if(!this.m_aliaslocksTbl4FN.containsKey(fn)) { - this.m_aliaslocksTbl4FN.put(fn, new Vector()); - } - this.m_aliaslocksTbl4FN.get(fn).add(lockindex); - } - lockindex++; + int para = ((Integer)key[i]).intValue(); + + output.println("void * tmpptrs_" + lockindex + "[] = {" + generateTemp(fm, fm.getParameter(para)) + "};"); + output.println("aliaslocks[tmpi++] = getAliasLock(tmpptrs_" + lockindex + ", 1, lockRedirectTbl);"); + + output.println("addAliasLock(" + generateTemp(fm, fm.getParameter(para)) + ", aliaslocks[" + lockindex + "]);"); + Vector tmpv = this.m_aliasFNTbl4Para.get(para); + for(int j = 0; j < tmpv.size(); j++) { + FlatNew fn = tmpv.elementAt(j); + if(this.m_aliaslocksTbl4FN == null) { + this.m_aliaslocksTbl4FN = new Hashtable>(); + } + if(!this.m_aliaslocksTbl4FN.containsKey(fn)) { + this.m_aliaslocksTbl4FN.put(fn, new Vector()); + } + this.m_aliaslocksTbl4FN.get(fn).add(lockindex); + } + lockindex++; } // check m_aliasFNTbl for locks associated with FlatNew nodes Object[] FNkey = this.m_aliasFNTbl.keySet().toArray(); for(int i = 0; i < FNkey.length; i++) { - FlatNew fn = (FlatNew)FNkey[i]; - Vector tmpv = this.m_aliasFNTbl.get(fn); - - output.println("aliaslocks[tmpi++] = (int)(RUNMALLOC(sizeof(int)));"); - - if(this.m_aliaslocksTbl4FN == null) { - this.m_aliaslocksTbl4FN = new Hashtable>(); - } - if(!this.m_aliaslocksTbl4FN.containsKey(fn)) { - this.m_aliaslocksTbl4FN.put(fn, new Vector()); - } - this.m_aliaslocksTbl4FN.get(fn).add(lockindex); - for(int j = 0; j < tmpv.size(); j++) { - FlatNew tfn = tmpv.elementAt(j); - if(!this.m_aliaslocksTbl4FN.containsKey(tfn)) { - this.m_aliaslocksTbl4FN.put(tfn, new Vector()); - } - this.m_aliaslocksTbl4FN.get(tfn).add(lockindex); - } - lockindex++; + FlatNew fn = (FlatNew)FNkey[i]; + Vector tmpv = this.m_aliasFNTbl.get(fn); + + output.println("aliaslocks[tmpi++] = (int)(RUNMALLOC(sizeof(int)));"); + + if(this.m_aliaslocksTbl4FN == null) { + this.m_aliaslocksTbl4FN = new Hashtable>(); + } + if(!this.m_aliaslocksTbl4FN.containsKey(fn)) { + this.m_aliaslocksTbl4FN.put(fn, new Vector()); + } + this.m_aliaslocksTbl4FN.get(fn).add(lockindex); + for(int j = 0; j < tmpv.size(); j++) { + FlatNew tfn = tmpv.elementAt(j); + if(!this.m_aliaslocksTbl4FN.containsKey(tfn)) { + this.m_aliaslocksTbl4FN.put(tfn, new Vector()); + } + this.m_aliaslocksTbl4FN.get(tfn).add(lockindex); + } + lockindex++; } } } @@ -1650,23 +1650,23 @@ public class BuildCodeMultiCore extends BuildCode { PrintWriter output) { if (frn.getReturnTemp()!=null) { if (frn.getReturnTemp().getType().isPtr()) - output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp())+";"); + output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp())+";"); else - output.println("return "+generateTemp(fm, frn.getReturnTemp())+";"); + output.println("return "+generateTemp(fm, frn.getReturnTemp())+";"); } else { if(fm.getTask() != null) { - output.println("#ifdef CACHEFLUSH"); - output.println("BAMBOO_ENTER_RUNTIME_MODE_FROM_CLIENT();"); - output.println("#ifdef DEBUG"); - output.println("BAMBOO_DEBUGPRINT(0xec00);"); - output.println("#endif"); - output.println("BAMBOO_CACHE_FLUSH_ALL();"); - output.println("#ifdef DEBUG"); - output.println("BAMBOO_DEBUGPRINT(0xecff);"); - output.println("#endif"); - output.println("BAMBOO_ENTER_CLIENT_MODE_FROM_RUNTIME();"); - output.println("#endif"); - outputTransCode(output); + output.println("#ifdef CACHEFLUSH"); + output.println("BAMBOO_ENTER_RUNTIME_MODE_FROM_CLIENT();"); + output.println("#ifdef DEBUG"); + output.println("BAMBOO_DEBUGPRINT(0xec00);"); + output.println("#endif"); + output.println("BAMBOO_CACHE_FLUSH_ALL();"); + output.println("#ifdef DEBUG"); + output.println("BAMBOO_DEBUGPRINT(0xecff);"); + output.println("#endif"); + output.println("BAMBOO_ENTER_CLIENT_MODE_FROM_RUNTIME();"); + output.println("#endif"); + outputTransCode(output); } output.println("return;"); } @@ -1679,39 +1679,39 @@ public class BuildCodeMultiCore extends BuildCode { int arrayid = state.getArrayNumber(fn.getType()) + state.numClasses(); if (fn.isGlobal()) { - output.println(generateTemp(fm, fn.getDst()) - + "=allocate_newarrayglobal(trans, " + arrayid + ", " - + generateTemp(fm, fn.getSize()) + ");"); + output.println(generateTemp(fm, fn.getDst()) + + "=allocate_newarrayglobal(trans, " + arrayid + ", " + + generateTemp(fm, fn.getSize()) + ");"); } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - output.println(generateTemp(fm, fn.getDst()) - + "=allocate_newarray(&" + localsprefix + ", " - + arrayid + ", " + generateTemp(fm, fn.getSize()) - + ");"); + output.println(generateTemp(fm, fn.getDst()) + + "=allocate_newarray(&" + localsprefix + ", " + + arrayid + ", " + generateTemp(fm, fn.getSize()) + + ");"); } else { - output.println(generateTemp(fm, fn.getDst()) - + "=allocate_newarray(" + arrayid + ", " - + generateTemp(fm, fn.getSize()) + ");"); + output.println(generateTemp(fm, fn.getDst()) + + "=allocate_newarray(" + arrayid + ", " + + generateTemp(fm, fn.getSize()) + ");"); } } else { if (fn.isGlobal()) { - output.println(generateTemp(fm, fn.getDst()) - + "=allocate_newglobal(trans, " - + fn.getType().getClassDesc().getId() + ");"); + output.println(generateTemp(fm, fn.getDst()) + + "=allocate_newglobal(trans, " + + fn.getType().getClassDesc().getId() + ");"); } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - output.println(generateTemp(fm, fn.getDst()) - + "=allocate_new(&" + localsprefix + ", " - + fn.getType().getClassDesc().getId() + ");"); + output.println(generateTemp(fm, fn.getDst()) + + "=allocate_new(&" + localsprefix + ", " + + fn.getType().getClassDesc().getId() + ");"); } else { - output.println(generateTemp(fm, fn.getDst()) - + "=allocate_new(" - + fn.getType().getClassDesc().getId() + ");"); + output.println(generateTemp(fm, fn.getDst()) + + "=allocate_new(" + + fn.getType().getClassDesc().getId() + ");"); } } // create alias lock if necessary if((this.m_aliaslocksTbl4FN != null) && (this.m_aliaslocksTbl4FN.containsKey(fn))) { Vector tmpv = this.m_aliaslocksTbl4FN.get(fn); for(int i = 0; i < tmpv.size(); i++) { - output.println("addAliasLock(" + generateTemp(fm, fn.getDst()) + ", aliaslocks[" + tmpv.elementAt(i).intValue() + "]);"); + output.println("addAliasLock(" + generateTemp(fm, fn.getDst()) + ", aliaslocks[" + tmpv.elementAt(i).intValue() + "]);"); } } // generate codes for profiling, recording how many new objects are created @@ -1738,13 +1738,13 @@ public class BuildCodeMultiCore extends BuildCode { for(int i = 0; i < sendto.size(); i++) { TranObjInfo tmp = sendto.elementAt(i); if(!tmp.name.equals(t.name)) { - return false; + return false; } if(tmp.targetcore != t.targetcore) { - return false; + return false; } if(tmp.fs != t.fs) { - return false; + return false; } } return true; diff --git a/Robust/src/IR/Flat/BuildCodeTran.java b/Robust/src/IR/Flat/BuildCodeTran.java index 4c0de5fb..7be13a5c 100644 --- a/Robust/src/IR/Flat/BuildCodeTran.java +++ b/Robust/src/IR/Flat/BuildCodeTran.java @@ -88,7 +88,7 @@ public class BuildCodeTran extends BuildCode { protected void buildCodeSetup() { try { if (state.SANDBOX) { - outsandbox=new CodePrinter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true); + outsandbox=new CodePrinter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true); } } catch (Exception e) { e.printStackTrace(); @@ -133,13 +133,13 @@ public class BuildCodeTran extends BuildCode { if (state.DSM) { if (state.DSMRECOVERYSTATS) { - outmethod.println("#ifdef RECOVERYSTATS \n"); - outmethod.println("handle();\n"); - outmethod.println("#endif\n"); + outmethod.println("#ifdef RECOVERYSTATS \n"); + outmethod.println("handle();\n"); + outmethod.println("#endif\n"); } else { - outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n"); - outmethod.println("handle();\n"); - outmethod.println("#endif\n"); + outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n"); + outmethod.println("handle();\n"); + outmethod.println("#endif\n"); } } outmethod.println("initializethreads();"); @@ -147,15 +147,15 @@ public class BuildCodeTran extends BuildCode { if (state.DSM) { outmethod.println("if (dstmStartup(argv[1])) {"); if (GENERATEPRECISEGC) { - outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);"); + outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);"); } else { - outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);"); + outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);"); } } else { if (GENERATEPRECISEGC) { - outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);"); + outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);"); } else { - outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);"); + outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);"); } } if (state.DSM) { @@ -252,7 +252,7 @@ public class BuildCodeTran extends BuildCode { FlatMethod fm=state.getMethodFlat(md); wb.analyze(lb); if (!md.getModifiers().isNative()) { - generateFlatMethod(fm, lb, outmethod); + generateFlatMethod(fm, lb, outmethod); } } } @@ -269,9 +269,9 @@ public class BuildCodeTran extends BuildCode { if (state.DSMTASK) { LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false); if(state.DSM) - lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL); + lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL); else if( state.SINGLETM) - lbexecute.setGlobalThis(LocalityAnalysis.NORMAL); + lbexecute.setGlobalThis(LocalityAnalysis.NORMAL); outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute)); } } @@ -294,7 +294,7 @@ public class BuildCodeTran extends BuildCode { while(classit.hasNext()) { ClassDescriptor cd=(ClassDescriptor)classit.next(); if (virtualcalls.getMethodCount(cd)>maxcount) - maxcount=virtualcalls.getMethodCount(cd); + maxcount=virtualcalls.getMethodCount(cd); } LocalityBinding[][] lbvirtualtable=null; @@ -305,7 +305,7 @@ public class BuildCodeTran extends BuildCode { while(classit.hasNext()) { ClassDescriptor cd=(ClassDescriptor)classit.next(); if(cd.isInterface()) { - continue; + continue; } fillinRow(cd, lbvirtualtable, cd.getId()); } @@ -322,16 +322,16 @@ public class BuildCodeTran extends BuildCode { boolean needcomma=false; for(int i=0; i lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext(); ) { - LocalityBinding lb=lbit.next(); - MethodDescriptor md=lb.getMethod(); - //Is the method static or a constructor - if (md.isStatic()||md.getReturnType()==null) - continue; - int methodnum=virtualcalls.getLocalityNumber(lb); - virtualtable[rownum][methodnum]=lb; + LocalityBinding lb=lbit.next(); + MethodDescriptor md=lb.getMethod(); + //Is the method static or a constructor + if (md.isStatic()||md.getReturnType()==null) + continue; + int methodnum=virtualcalls.getLocalityNumber(lb); + virtualtable[rownum][methodnum]=lb; } } @@ -410,20 +410,20 @@ public class BuildCodeTran extends BuildCode { TempDescriptor temp=fm.getParameter(i); TypeDescriptor type=temp.getType(); if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC))) - objectparams.addPtr(temp); + objectparams.addPtr(temp); else - objectparams.addPrim(temp); + objectparams.addPrim(temp); if(lb!=null&&saveset.contains(temp)) { - backuptable.get(lb).put(temp, temp.createNew()); + backuptable.get(lb).put(temp, temp.createNew()); } } for(int i=0; i tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - TypeDescriptor type=tmp.getType(); - if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC))) - objecttemps.addPtr(tmp); - else - objecttemps.addPrim(tmp); + TempDescriptor tmp=tmpit.next(); + TypeDescriptor type=tmp.getType(); + if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC))) + objecttemps.addPtr(tmp); + else + objecttemps.addPrim(tmp); } /* Create temp to hold revert table */ if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) { - TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass)); - if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) - objecttemps.addPtr(reverttmp); - else - objecttemps.addPrim(reverttmp); - reverttable.put(lb, reverttmp); + TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass)); + if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) + objecttemps.addPtr(reverttmp); + else + objecttemps.addPrim(reverttmp); + reverttable.put(lb, reverttmp); } } } @@ -487,25 +487,25 @@ public class BuildCodeTran extends BuildCode { Iterator allit=cn.getFieldTable().getAllDescriptorsIterator(); int count=0; while(allit.hasNext()) { - FieldDescriptor fd=(FieldDescriptor)allit.next(); - TypeDescriptor type=fd.getType(); - if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now - continue; - if (type.isPtr()) - count++; + FieldDescriptor fd=(FieldDescriptor)allit.next(); + TypeDescriptor type=fd.getType(); + if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now + continue; + if (type.isPtr()) + count++; } output.print(count); allit=cn.getFieldTable().getAllDescriptorsIterator(); while(allit.hasNext()) { - FieldDescriptor fd=(FieldDescriptor)allit.next(); - TypeDescriptor type=fd.getType(); - if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now - continue; - if (type.isPtr()) { - output.println(","); - output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+ - fd.getSafeSymbol()+"))"); - } + FieldDescriptor fd=(FieldDescriptor)allit.next(); + TypeDescriptor type=fd.getType(); + if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now + continue; + if (type.isPtr()) { + output.println(","); + output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+ + fd.getSafeSymbol()+"))"); + } } output.println("};"); } @@ -514,23 +514,23 @@ public class BuildCodeTran extends BuildCode { for(int i=0; i lbset=locality.getClassBindings(cn); if (lbset!=null) { for(Iterator lbit=lbset.iterator(); lbit.hasNext(); ) { - LocalityBinding lb=lbit.next(); - MethodDescriptor md=lb.getMethod(); - if (md.getModifiers().isNative()) { - //make sure we only print a native method once - if (nativemethods.contains(md)) { - FlatMethod fm=state.getMethodFlat(md); - generateTempStructs(fm, lb); - continue; - } else - nativemethods.add(md); - } - generateMethod(cn, md, lb, headersout, output); + LocalityBinding lb=lbit.next(); + MethodDescriptor md=lb.getMethod(); + if (md.getModifiers().isNative()) { + //make sure we only print a native method once + if (nativemethods.contains(md)) { + FlatMethod fm=state.getMethodFlat(md); + generateTempStructs(fm, lb); + continue; + } else + nativemethods.add(md); + } + generateMethod(cn, md, lb, headersout, output); } } for(Iterator methodit=cn.getMethods(); methodit.hasNext(); ) { MethodDescriptor md=(MethodDescriptor)methodit.next(); if (md.getModifiers().isNative()&&!nativemethods.contains(md)) { - //Need to build param structure for library code - FlatMethod fm=state.getMethodFlat(md); - generateTempStructs(fm, null); - generateMethodParam(cn, md, null, output); + //Need to build param structure for library code + FlatMethod fm=state.getMethodFlat(md); + generateTempStructs(fm, null); + generateMethodParam(cn, md, null, output); } } } @@ -588,18 +588,18 @@ public class BuildCodeTran extends BuildCode { if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null?lb:md); if ((state.DSM||state.SINGLETM)&&lb!=null) - output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {"); + output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {"); else - output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {"); + output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {"); output.println(" int size;"); output.println(" void * next;"); for(int i=0; i(); + atomicmethodmap=new Hashtable(); //fix these so we get right strings for local variables localsprefixaddr=localsprefix; @@ -702,83 +702,83 @@ public class BuildCodeTran extends BuildCode { //Generate commit methods here for(Iterator fnit=fm.getNodeSet().iterator(); fnit.hasNext(); ) { - FlatNode fn=fnit.next(); - if (fn.kind()==FKind.FlatAtomicEnterNode&& - locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&& - delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) { - //We have an atomic enter - FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn; - Set exitset=faen.getExits(); - //generate header - String methodname=md.getSymbol()+(atomicmethodcount++); - AtomicRecord ar=new AtomicRecord(); - ar.name=methodname; - arset.add(ar); - - atomicmethodmap.put(faen, ar); - - //build data structure declaration - output.println("struct atomicprimitives_"+methodname+" {"); - - Set recordset=delaycomp.livecode(lb); - Set liveinto=delaycomp.liveinto(lb, faen, recordset); - Set liveout=delaycomp.liveout(lb, faen); - Set liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen); - ar.livein=liveinto; - ar.reallivein=new HashSet(liveinto); - ar.liveout=liveout; - ar.liveoutvirtualread=liveoutvirtualread; - - - for(Iterator it=liveinto.iterator(); it.hasNext(); ) { - TempDescriptor tmp=it.next(); - //remove the pointers - if (tmp.getType().isPtr()) { - it.remove(); - } else { - //let's print it here - output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";"); - } - } - for(Iterator it=liveout.iterator(); it.hasNext(); ) { - TempDescriptor tmp=it.next(); - //remove the pointers - if (tmp.getType().isPtr()) { - it.remove(); - } else if (!liveinto.contains(tmp)) { - //let's print it here - output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";"); - } - } - output.println("};"); - - //print out method name - output.println("void "+methodname+"(struct "+ cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix+", struct "+ cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals *"+localsprefix+", struct atomicprimitives_"+methodname+" * primitives) {"); - //build code for commit method - - //first define local primitives - Set alltemps=delaycomp.alltemps(lb, faen, recordset); - for(Iterator tmpit=alltemps.iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - if (!tmp.getType().isPtr()) { - if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) { - //read from live into set - output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";"); - } else { - //just define - output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";"); - } - } - } - //turn off write barrier generation - wb.turnoff(); - state.SINGLETM=false; - generateCode(faen, fm, lb, exitset, output, false); - state.SINGLETM=true; - //turn on write barrier generation - wb.turnon(); - output.println("}\n\n"); - } + FlatNode fn=fnit.next(); + if (fn.kind()==FKind.FlatAtomicEnterNode&& + locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&& + delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) { + //We have an atomic enter + FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn; + Set exitset=faen.getExits(); + //generate header + String methodname=md.getSymbol()+(atomicmethodcount++); + AtomicRecord ar=new AtomicRecord(); + ar.name=methodname; + arset.add(ar); + + atomicmethodmap.put(faen, ar); + + //build data structure declaration + output.println("struct atomicprimitives_"+methodname+" {"); + + Set recordset=delaycomp.livecode(lb); + Set liveinto=delaycomp.liveinto(lb, faen, recordset); + Set liveout=delaycomp.liveout(lb, faen); + Set liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen); + ar.livein=liveinto; + ar.reallivein=new HashSet(liveinto); + ar.liveout=liveout; + ar.liveoutvirtualread=liveoutvirtualread; + + + for(Iterator it=liveinto.iterator(); it.hasNext(); ) { + TempDescriptor tmp=it.next(); + //remove the pointers + if (tmp.getType().isPtr()) { + it.remove(); + } else { + //let's print it here + output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";"); + } + } + for(Iterator it=liveout.iterator(); it.hasNext(); ) { + TempDescriptor tmp=it.next(); + //remove the pointers + if (tmp.getType().isPtr()) { + it.remove(); + } else if (!liveinto.contains(tmp)) { + //let's print it here + output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";"); + } + } + output.println("};"); + + //print out method name + output.println("void "+methodname+"(struct "+ cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix+", struct "+ cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals *"+localsprefix+", struct atomicprimitives_"+methodname+" * primitives) {"); + //build code for commit method + + //first define local primitives + Set alltemps=delaycomp.alltemps(lb, faen, recordset); + for(Iterator tmpit=alltemps.iterator(); tmpit.hasNext(); ) { + TempDescriptor tmp=tmpit.next(); + if (!tmp.getType().isPtr()) { + if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) { + //read from live into set + output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";"); + } else { + //just define + output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";"); + } + } + } + //turn off write barrier generation + wb.turnoff(); + state.SINGLETM=false; + generateCode(faen, fm, lb, exitset, output, false); + state.SINGLETM=true; + //turn on write barrier generation + wb.turnon(); + output.println("}\n\n"); + } } } //redefine these back to normal @@ -791,22 +791,22 @@ public class BuildCodeTran extends BuildCode { if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) { for(Iterator arit=arset.iterator(); arit.hasNext(); ) { - AtomicRecord ar=arit.next(); - output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";"); + AtomicRecord ar=arit.next(); + output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";"); } } if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { if (md!=null&&(state.DSM||state.SINGLETM)) - output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={"); + output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={"); else if (md!=null&&!(state.DSM||state.SINGLETM)) - output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={"); + output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={"); else - output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={"); + output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={"); output.print(objecttemp.numPointers()+","); output.print(paramsprefix); for(int j=0; j(); if (state.STMARRAY&&!state.DUALVIEW) { - refset=new HashSet(); - refset.addAll(delaycomp.getDeref(lb)); - refset.removeAll(delaycomp.getCannotDelay(lb)); - refset.removeAll(delaycomp.getOther(lb)); + refset=new HashSet(); + refset.addAll(delaycomp.getDeref(lb)); + refset.removeAll(delaycomp.getCannotDelay(lb)); + refset.removeAll(delaycomp.getOther(lb)); } if (firstpass) { - genset.addAll(delaycomp.getCannotDelay(lb)); - genset.addAll(delaycomp.getOther(lb)); + genset.addAll(delaycomp.getCannotDelay(lb)); + genset.addAll(delaycomp.getOther(lb)); } else { - genset.addAll(delaycomp.getNotReady(lb)); - if (state.STMARRAY&&!state.DUALVIEW) { - genset.removeAll(refset); - } + genset.addAll(delaycomp.getNotReady(lb)); + if (state.STMARRAY&&!state.DUALVIEW) { + genset.removeAll(refset); + } } unionset=new HashSet(); unionset.addAll(storeset); unionset.addAll(genset); if (state.STMARRAY&&!state.DUALVIEW) - unionset.addAll(refset); + unionset.addAll(refset); } /* Do the actual code generation */ @@ -904,161 +904,161 @@ public class BuildCodeTran extends BuildCode { tovisit.add(first); while(current_node!=null||!tovisit.isEmpty()) { if (current_node==null) { - current_node=(FlatNode)tovisit.iterator().next(); - tovisit.remove(current_node); + current_node=(FlatNode)tovisit.iterator().next(); + tovisit.remove(current_node); } else if (tovisit.contains(current_node)) { - tovisit.remove(current_node); + tovisit.remove(current_node); } visited.add(current_node); if (nodetolabel.containsKey(current_node)) { - output.println("L"+nodetolabel.get(current_node)+":"); + output.println("L"+nodetolabel.get(current_node)+":"); } if (state.INSTRUCTIONFAILURE) { - if (state.THREAD||state.DSM||state.SINGLETM) { - output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}"); - } else - output.println("if ((--instructioncount)==0) injectinstructionfailure();"); + if (state.THREAD||state.DSM||state.SINGLETM) { + output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}"); + } else + output.println("if ((--instructioncount)==0) injectinstructionfailure();"); } if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) { - output.print(" "); - if (!state.DELAYCOMP||firstpass) { - generateFlatNode(fm, current_node, output); - } else { - //store primitive variables in out set - AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first); - Set liveout=ar.liveout; - for(Iterator tmpit=liveout.iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";"); - } - } - - if (current_node.kind()!=FKind.FlatReturnNode) { - if(state.MGC) { - // TODO add version for normal Java later - if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) { - // a static block, check if it has been executed - output.println(" global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;"); - output.println(""); - } - } - output.println(" return;"); - } - current_node=null; + output.print(" "); + if (!state.DELAYCOMP||firstpass) { + generateFlatNode(fm, current_node, output); + } else { + //store primitive variables in out set + AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first); + Set liveout=ar.liveout; + for(Iterator tmpit=liveout.iterator(); tmpit.hasNext(); ) { + TempDescriptor tmp=tmpit.next(); + output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";"); + } + } + + if (current_node.kind()!=FKind.FlatReturnNode) { + if(state.MGC) { + // TODO add version for normal Java later + if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) { + // a static block, check if it has been executed + output.println(" global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;"); + output.println(""); + } + } + output.println(" return;"); + } + current_node=null; } else if(current_node.numNext()==1) { - FlatNode nextnode; - if (state.DELAYCOMP) { - boolean specialprimitive=false; - //skip literals...no need to add extra overhead - if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) { - TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType(); - if (!typedesc.isClass()&&!typedesc.isArray()) { - specialprimitive=true; - } - } - - if (genset==null||genset.contains(current_node)||specialprimitive) { - generateFlatNode(fm, current_node, output); - } - if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) { - //need to acquire lock - handleArrayDeref(fm, lb, current_node, output, firstpass); - } - if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) { - TempDescriptor wrtmp=current_node.writesTemps()[0]; - if (firstpass) { - //need to store value written by previous node - if (wrtmp.getType().isPtr()) { - //only lock the objects that may actually need locking - if (recorddc.getNeedTrans(lb, current_node)&& - (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()|| - wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) { - output.println("STOREPTR("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */"); - } else { - output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */"); - } - } else { - output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */"); - } - } else { - //need to read value read by previous node - if (wrtmp.getType().isPtr()) { - output.println("RESTOREPTR("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */"); - } else { - output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp)+"); /* "+current_node.nodeid+" */"); - } - } - } - nextnode=current_node.getNext(0); - } else { - output.print(" "); - generateFlatNode(fm, current_node, output); - nextnode=current_node.getNext(0); - } - if (visited.contains(nextnode)) { - output.println("goto L"+nodetolabel.get(nextnode)+";"); - current_node=null; - } else - current_node=nextnode; + FlatNode nextnode; + if (state.DELAYCOMP) { + boolean specialprimitive=false; + //skip literals...no need to add extra overhead + if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) { + TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType(); + if (!typedesc.isClass()&&!typedesc.isArray()) { + specialprimitive=true; + } + } + + if (genset==null||genset.contains(current_node)||specialprimitive) { + generateFlatNode(fm, current_node, output); + } + if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) { + //need to acquire lock + handleArrayDeref(fm, lb, current_node, output, firstpass); + } + if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) { + TempDescriptor wrtmp=current_node.writesTemps()[0]; + if (firstpass) { + //need to store value written by previous node + if (wrtmp.getType().isPtr()) { + //only lock the objects that may actually need locking + if (recorddc.getNeedTrans(lb, current_node)&& + (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()|| + wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) { + output.println("STOREPTR("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */"); + } else { + output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */"); + } + } else { + output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */"); + } + } else { + //need to read value read by previous node + if (wrtmp.getType().isPtr()) { + output.println("RESTOREPTR("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */"); + } else { + output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp)+"); /* "+current_node.nodeid+" */"); + } + } + } + nextnode=current_node.getNext(0); + } else { + output.print(" "); + generateFlatNode(fm, current_node, output); + nextnode=current_node.getNext(0); + } + if (visited.contains(nextnode)) { + output.println("goto L"+nodetolabel.get(nextnode)+";"); + current_node=null; + } else + current_node=nextnode; } else if (current_node.numNext()==2) { - /* Branch */ - if (state.DELAYCOMP) { - boolean computeside=false; - if (firstpass) { - //need to record which way it should go - if (genset==null||genset.contains(current_node)) { - if (storeset!=null&&storeset.contains(current_node)) { - //need to store which way branch goes - generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output); - } else - generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output); - } else { - //which side to execute - computeside=true; - } - } else { - if (genset.contains(current_node)) { - generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output); - } else if (storeset.contains(current_node)) { - //need to do branch - branchanalysis.generateGroupCode(current_node, output, nodetolabel); - } else { - //which side to execute - computeside=true; - } - } - if (computeside) { - Set leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true); - int branch=0; - if (leftset.size()==0) - branch=1; - if (visited.contains(current_node.getNext(branch))) { - //already visited -- build jump - output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";"); - current_node=null; - } else { - current_node=current_node.getNext(branch); - } - } else { - if (!visited.contains(current_node.getNext(1))) - tovisit.add(current_node.getNext(1)); - if (visited.contains(current_node.getNext(0))) { - output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";"); - current_node=null; - } else - current_node=current_node.getNext(0); - } - } else { - output.print(" "); - generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output); - if (!visited.contains(current_node.getNext(1))) - tovisit.add(current_node.getNext(1)); - if (visited.contains(current_node.getNext(0))) { - output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";"); - current_node=null; - } else - current_node=current_node.getNext(0); - } + /* Branch */ + if (state.DELAYCOMP) { + boolean computeside=false; + if (firstpass) { + //need to record which way it should go + if (genset==null||genset.contains(current_node)) { + if (storeset!=null&&storeset.contains(current_node)) { + //need to store which way branch goes + generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output); + } else + generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output); + } else { + //which side to execute + computeside=true; + } + } else { + if (genset.contains(current_node)) { + generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output); + } else if (storeset.contains(current_node)) { + //need to do branch + branchanalysis.generateGroupCode(current_node, output, nodetolabel); + } else { + //which side to execute + computeside=true; + } + } + if (computeside) { + Set leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true); + int branch=0; + if (leftset.size()==0) + branch=1; + if (visited.contains(current_node.getNext(branch))) { + //already visited -- build jump + output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";"); + current_node=null; + } else { + current_node=current_node.getNext(branch); + } + } else { + if (!visited.contains(current_node.getNext(1))) + tovisit.add(current_node.getNext(1)); + if (visited.contains(current_node.getNext(0))) { + output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";"); + current_node=null; + } else + current_node=current_node.getNext(0); + } + } else { + output.print(" "); + generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output); + if (!visited.contains(current_node.getNext(1))) + tovisit.add(current_node.getNext(1)); + if (visited.contains(current_node.getNext(0))) { + output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";"); + current_node=null; + } else + current_node=current_node.getNext(0); + } } else throw new Error(); } } @@ -1072,18 +1072,18 @@ public class BuildCodeTran extends BuildCode { TypeDescriptor elementtype=fsen.getDst().getType().dereference(); String type=""; if (elementtype.isArray()||elementtype.isClass()) - type="void *"; + type="void *"; else - type=elementtype.getSafeSymbol()+" "; + type=elementtype.getSafeSymbol()+" "; if (firstpass) { - output.println("STOREARRAY("+dst+","+index+","+type+")"); + output.println("STOREARRAY("+dst+","+index+","+type+")"); } else { - output.println("{"); - output.println(" struct ArrayObject *array;"); - output.println(" int index;"); - output.println(" RESTOREARRAY(array,index);"); - output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";"); - output.println("}"); + output.println("{"); + output.println(" struct ArrayObject *array;"); + output.println(" int index;"); + output.println(" RESTOREARRAY(array,index);"); + output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";"); + output.println("}"); } } else if (fn.kind()==FKind.FlatElementNode) { FlatElementNode fen=(FlatElementNode) fn; @@ -1093,18 +1093,18 @@ public class BuildCodeTran extends BuildCode { String dst=generateTemp(fm, fen.getDst()); String type=""; if (elementtype.isArray()||elementtype.isClass()) - type="void *"; + type="void *"; else - type=elementtype.getSafeSymbol()+" "; + type=elementtype.getSafeSymbol()+" "; if (firstpass) { - output.println("STOREARRAY("+src+","+index+","+type+")"); + output.println("STOREARRAY("+src+","+index+","+type+")"); } else { - output.println("{"); - output.println(" struct ArrayObject *array;"); - output.println(" int index;"); - output.println(" RESTOREARRAY(array,index);"); - output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];"); - output.println("}"); + output.println("{"); + output.println(" struct ArrayObject *array;"); + output.println(" int index;"); + output.println(" RESTOREARRAY(array,index);"); + output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];"); + output.println("}"); } } } @@ -1133,24 +1133,24 @@ public class BuildCodeTran extends BuildCode { if(lastset!=null&&lastset.contains(fn)) { - // if last is not null and matches, don't go - // any further for assigning labels - continue; + // if last is not null and matches, don't go + // any further for assigning labels + continue; } for(int i=0; i0) { - //1) Edge >1 of node - nodetolabel.put(nn,new Integer(labelindex++)); - } - if (!visited.contains(nn)&&!tovisit.contains(nn)) { - tovisit.add(nn); - } else { - //2) Join point - nodetolabel.put(nn,new Integer(labelindex++)); - } + if(i>0) { + //1) Edge >1 of node + nodetolabel.put(nn,new Integer(labelindex++)); + } + if (!visited.contains(nn)&&!tovisit.contains(nn)) { + tovisit.add(nn); + } else { + //2) Join point + nodetolabel.put(nn,new Integer(labelindex++)); + } } } return nodetolabel; @@ -1187,9 +1187,9 @@ public class BuildCodeTran extends BuildCode { } if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)) { if(state.DSM&&locality.getAtomic(currlb).get(fn).intValue()>0) { - output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");"); + output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");"); } else { - output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");"); + output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");"); } } else output.println("/* nop */"); @@ -1203,20 +1203,20 @@ public class BuildCodeTran extends BuildCode { Vector endoffset = new Vector(); int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated for(Iterator it = fpn.hspp.iterator(); it.hasNext(); ) { - PrefetchPair pp = (PrefetchPair) it.next(); - Integer statusbase = locality.getNodePreTempInfo(currlb,fpn).get(pp.base); - /* Find prefetches that can generate oid */ - if(statusbase == LocalityAnalysis.GLOBAL) { - generateTransCode(fm, currlb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(currlb).get(fpn).intValue()>0, false); - tuplecount++; - } else if (statusbase == LocalityAnalysis.LOCAL) { - generateTransCode(fm,currlb,pp,oids,fieldoffset,endoffset,tuplecount,false,true); - } else { - continue; - } + PrefetchPair pp = (PrefetchPair) it.next(); + Integer statusbase = locality.getNodePreTempInfo(currlb,fpn).get(pp.base); + /* Find prefetches that can generate oid */ + if(statusbase == LocalityAnalysis.GLOBAL) { + generateTransCode(fm, currlb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(currlb).get(fpn).intValue()>0, false); + tuplecount++; + } else if (statusbase == LocalityAnalysis.LOCAL) { + generateTransCode(fm,currlb,pp,oids,fieldoffset,endoffset,tuplecount,false,true); + } else { + continue; + } } if (tuplecount==0) - return; + return; System.out.println("Adding prefetch "+fpn+ " to method:" +fm); output.println("{"); output.println("/* prefetch */"); @@ -1229,10 +1229,10 @@ public class BuildCodeTran extends BuildCode { output.print(" unsigned int oidarray_[] = {"); boolean needcomma=false; for (Iterator it = oids.iterator(); it.hasNext(); ) { - if (needcomma) - output.print(", "); - output.print(it.next()); - needcomma=true; + if (needcomma) + output.print(", "); + output.print(it.next()); + needcomma=true; } output.println("};"); @@ -1240,10 +1240,10 @@ public class BuildCodeTran extends BuildCode { output.print(" unsigned short endoffsetarry_[] = {"); needcomma=false; for (Iterator it = endoffset.iterator(); it.hasNext(); ) { - if (needcomma) - output.print(", "); - output.print(it.next()); - needcomma=true; + if (needcomma) + output.print(", "); + output.print(it.next()); + needcomma=true; } output.println("};"); @@ -1251,10 +1251,10 @@ public class BuildCodeTran extends BuildCode { output.print(" short fieldarry_[] = {"); needcomma=false; for (Iterator it = fieldoffset.iterator(); it.hasNext(); ) { - if (needcomma) - output.print(", "); - output.print(it.next()); - needcomma=true; + if (needcomma) + output.print(", "); + output.print(it.next()); + needcomma=true; } output.println("};"); /* make the prefetch call to Runtime */ @@ -1276,13 +1276,13 @@ public class BuildCodeTran extends BuildCode { breakindex=1; } else if (localbase) { for(; breakindex"+ - fd.getSafeSymbol(); - } else { - basestr=basestr+"->"+ - fd.getSafeSymbol(); - maybenull=true; - } - lasttype=fd.getType(); + FieldDescriptor fd=(FieldDescriptor)desc; + if (maybenull) { + if (!teststr.equals("")) + teststr+="&&"; + teststr+="((prefptr="+basestr+")!=NULL)"; + basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+ + fd.getSafeSymbol(); + } else { + basestr=basestr+"->"+ + fd.getSafeSymbol(); + maybenull=true; + } + lasttype=fd.getType(); } else { - IndexDescriptor id=(IndexDescriptor)desc; - indexcheck="((tmpindex="; - for(int j=0; j=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)"; + IndexDescriptor id=(IndexDescriptor)desc; + indexcheck="((tmpindex="; + for(int j=0; j=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)"; - if (!teststr.equals("")) - teststr+="&&"; - teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck; - basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]"; - maybenull=true; - lasttype=lasttype.dereference(); + if (!teststr.equals("")) + teststr+="&&"; + teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck; + basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]"; + maybenull=true; + lasttype=lasttype.dereference(); } } @@ -1343,17 +1343,17 @@ public class BuildCodeTran extends BuildCode { String newfieldoffset; Object desc = pp.getDescAt(i); if(desc instanceof FieldDescriptor) { - FieldDescriptor fd=(FieldDescriptor)desc; - newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))"); - lasttype=fd.getType(); + FieldDescriptor fd=(FieldDescriptor)desc; + newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))"); + lasttype=fd.getType(); } else { - newfieldoffset = ""; - IndexDescriptor id=(IndexDescriptor)desc; - for(int j = 0; j < id.tddesc.size(); j++) { - newfieldoffset += generateTemp(fm, id.getTempDescAt(j)) + "+"; - } - newfieldoffset += id.offset.toString(); - lasttype=lasttype.dereference(); + newfieldoffset = ""; + IndexDescriptor id=(IndexDescriptor)desc; + for(int j = 0; j < id.tddesc.size(); j++) { + newfieldoffset += generateTemp(fm, id.getTempDescAt(j)) + "+"; + } + newfieldoffset += id.offset.toString(); + lasttype=lasttype.dereference(); } fieldoffset.add(newfieldoffset); } @@ -1371,26 +1371,26 @@ public class BuildCodeTran extends BuildCode { /* Have to generate flat globalconv */ if (fgcn.getMakePtr()) { if (state.DSM) { - output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc())+", (unsigned int) "+generateTemp(fm, fgcn.getSrc())+");"); + output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc())+", (unsigned int) "+generateTemp(fm, fgcn.getSrc())+");"); } else { - if ((dc==null)||!state.READSET&&dc.getNeedTrans(currlb, fgcn)||state.READSET&&dc.getNeedWriteTrans(currlb, fgcn)) { - //need to do translation - output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc())+", "+generateTemp(fm, fgcn.getSrc())+", (void *)("+localsprefixaddr+"));"); - } else if (state.READSET&&dc.getNeedTrans(currlb, fgcn)) { - if (state.HYBRID&&delaycomp.getConv(currlb).contains(fgcn)) { - output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc())+", "+generateTemp(fm, fgcn.getSrc())+");"); - } else - output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc())+", "+generateTemp(fm, fgcn.getSrc())+");"); - } + if ((dc==null)||!state.READSET&&dc.getNeedTrans(currlb, fgcn)||state.READSET&&dc.getNeedWriteTrans(currlb, fgcn)) { + //need to do translation + output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc())+", "+generateTemp(fm, fgcn.getSrc())+", (void *)("+localsprefixaddr+"));"); + } else if (state.READSET&&dc.getNeedTrans(currlb, fgcn)) { + if (state.HYBRID&&delaycomp.getConv(currlb).contains(fgcn)) { + output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc())+", "+generateTemp(fm, fgcn.getSrc())+");"); + } else + output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc())+", "+generateTemp(fm, fgcn.getSrc())+");"); + } } } else { /* Need to convert to OID */ if ((dc==null)||dc.getNeedSrcTrans(currlb,fgcn)) { - if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(currlb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) { - output.println(generateTemp(fm, fgcn.getSrc())+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc())+");"); - } else { - output.println(generateTemp(fm, fgcn.getSrc())+"=NULL;"); - } + if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(currlb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) { + output.println(generateTemp(fm, fgcn.getSrc())+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc())+");"); + } else { + output.println(generateTemp(fm, fgcn.getSrc())+"=NULL;"); + } } } } @@ -1400,13 +1400,13 @@ public class BuildCodeTran extends BuildCode { /* Check to see if we need to generate code for this atomic */ if (locality==null) { if (GENERATEPRECISEGC) { - output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {"); - output.println("stopforgc((struct garbagelist *) &___locals___);"); - output.println("pthread_mutex_lock(&atomiclock);"); - output.println("restartaftergc();"); - output.println("}"); + output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {"); + output.println("stopforgc((struct garbagelist *) &___locals___);"); + output.println("pthread_mutex_lock(&atomiclock);"); + output.println("restartaftergc();"); + output.println("}"); } else { - output.println("pthread_mutex_lock(&atomiclock);"); + output.println("pthread_mutex_lock(&atomiclock);"); } return; } @@ -1424,15 +1424,15 @@ public class BuildCodeTran extends BuildCode { AtomicRecord ar=atomicmethodmap.get(faen); //copy in for(Iterator tmpit=ar.livein.iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";"); + TempDescriptor tmp=tmpit.next(); + output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";"); } //copy outs that depend on path for(Iterator tmpit=ar.liveoutvirtualread.iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - if (!ar.livein.contains(tmp)) - output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";"); + TempDescriptor tmp=tmpit.next(); + if (!ar.livein.contains(tmp)) + output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";"); } } @@ -1475,7 +1475,7 @@ public class BuildCodeTran extends BuildCode { if (state.ABORTREADERS||state.SANDBOX) { if (state.SANDBOX) - output.println("abortenabled=1;"); + output.println("abortenabled=1;"); output.println("if (_setjmp(aborttrans)) {"); output.println(" goto transretry"+faen.getIdentifier()+"; }"); } @@ -1518,32 +1518,32 @@ public class BuildCodeTran extends BuildCode { output.println("}"); } else { if (delaycomp.optimizeTrans(currlb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) { - AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter()); - output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");"); - //copy out - for(Iterator tmpit=ar.liveout.iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";"); - } + AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter()); + output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");"); + //copy out + for(Iterator tmpit=ar.liveout.iterator(); tmpit.hasNext(); ) { + TempDescriptor tmp=tmpit.next(); + output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";"); + } } else if (delaycomp.needsFission(currlb, faen.getAtomicEnter())) { - AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter()); - //do call - output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {"); - output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");"); - output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";"); - output.println("}"); - //copy out - output.println("else {"); - for(Iterator tmpit=ar.liveout.iterator(); tmpit.hasNext(); ) { - TempDescriptor tmp=tmpit.next(); - output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";"); - } - output.println("}"); + AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter()); + //do call + output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {"); + output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");"); + output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";"); + output.println("}"); + //copy out + output.println("else {"); + for(Iterator tmpit=ar.liveout.iterator(); tmpit.hasNext(); ) { + TempDescriptor tmp=tmpit.next(); + output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";"); + } + output.println("}"); } else { - output.println("if (transCommit(NULL, NULL, NULL, NULL)) {"); - output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");"); - output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";"); - output.println("}"); + output.println("if (transCommit(NULL, NULL, NULL, NULL)) {"); + output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");"); + output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";"); + output.println("}"); } } } @@ -1559,71 +1559,71 @@ public class BuildCodeTran extends BuildCode { // TODO add version for normal Java later if((md.isStatic() || md.isStaticBlock() || md.isConstructor()) && ((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic()))) { - if(!md.isInvokedByStatic()) { - System.err.println("Error: a method that is invoked inside a static block is not tagged!"); - } - // is a static block or is invoked in some static block - ClassDescriptor cd = fm.getMethod().getClassDesc(); - if(cd == cn) { - // the same class, do nothing - // TODO may want to invoke static field initialization here - } else { - if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) { - // need to check if the class' static fields have been initialized and/or - // its static blocks have been executed - output.println("#ifdef MGC_STATIC_INIT_CHECK"); - output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {"); - if(cn.getNumStaticBlocks() != 0) { - MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks"); - output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();"); - } else { - output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;"); - } - output.println("}"); - output.println("#endif // MGC_STATIC_INIT_CHECK"); - } - } + if(!md.isInvokedByStatic()) { + System.err.println("Error: a method that is invoked inside a static block is not tagged!"); + } + // is a static block or is invoked in some static block + ClassDescriptor cd = fm.getMethod().getClassDesc(); + if(cd == cn) { + // the same class, do nothing + // TODO may want to invoke static field initialization here + } else { + if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) { + // need to check if the class' static fields have been initialized and/or + // its static blocks have been executed + output.println("#ifdef MGC_STATIC_INIT_CHECK"); + output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {"); + if(cn.getNumStaticBlocks() != 0) { + MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks"); + output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();"); + } else { + output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;"); + } + output.println("}"); + output.println("#endif // MGC_STATIC_INIT_CHECK"); + } + } } if((md.getSymbol().equals("MonitorEnter") || md.getSymbol().equals("MonitorExit")) && fc.getThis().getSymbol().equals("classobj")) { - // call MonitorEnter/MonitorExit on a class obj - output.println(" " + cn.getSafeSymbol()+md.getSafeSymbol()+"_" - + md.getSafeMethodDescriptor() + "((struct ___Object___*)(((void **)(((char *) &(global_defs_p->classobjs->___length___))+sizeof(int)))[" - + fc.getThis().getType().getClassDesc().getId() + "]));"); - return; + // call MonitorEnter/MonitorExit on a class obj + output.println(" " + cn.getSafeSymbol()+md.getSafeSymbol()+"_" + + md.getSafeMethodDescriptor() + "((struct ___Object___*)(((void **)(((char *) &(global_defs_p->classobjs->___length___))+sizeof(int)))[" + + fc.getThis().getType().getClassDesc().getId() + "]));"); + return; } } output.println("{"); if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { if (currlb!=null) { - LocalityBinding fclb=locality.getBinding(currlb, fc); - output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={"); + LocalityBinding fclb=locality.getBinding(currlb, fc); + output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={"); } else - output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={"); + output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={"); output.print(objectparams.numPointers()); output.print(", "+localsprefixaddr); if (md.getThis()!=null) { - output.print(", "); - output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis())); + output.print(", "); + output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis())); } if (fc.getThis()!=null&&md.getThis()==null) { - System.out.println("WARNING!!!!!!!!!!!!"); - System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!"); + System.out.println("WARNING!!!!!!!!!!!!"); + System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!"); } for(int i=0; itype*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])"); + LocalityBinding fclb=locality.getBinding(currlb, fc); + output.print("))virtualtable["+generateTemp(fm,fc.getThis())+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])"); } else - output.print("))virtualtable["+generateTemp(fm,fc.getThis())+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])"); + output.print("))virtualtable["+generateTemp(fm,fc.getThis())+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])"); } output.print("("); @@ -1693,20 +1693,20 @@ public class BuildCodeTran extends BuildCode { if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) { if (fc.getThis()!=null) { - TypeDescriptor ptd=null; - if(md.getThis() != null) { - ptd = md.getThis().getType(); - } else { - ptd = fc.getThis().getType(); - } - if (needcomma) - output.print(","); - if(state.MGC && ptd.isClass() && ptd.getClassDesc().isEnum()) { - // do nothing - } else if (ptd.isClass()&&!ptd.isArray()) - output.print("(struct "+ptd.getSafeSymbol()+" *) "); - output.print(generateTemp(fm,fc.getThis())); - needcomma=true; + TypeDescriptor ptd=null; + if(md.getThis() != null) { + ptd = md.getThis().getType(); + } else { + ptd = fc.getThis().getType(); + } + if (needcomma) + output.print(","); + if(state.MGC && ptd.isClass() && ptd.getClassDesc().isEnum()) { + // do nothing + } else if (ptd.isClass()&&!ptd.isArray()) + output.print("(struct "+ptd.getSafeSymbol()+" *) "); + output.print(generateTemp(fm,fc.getThis())); + needcomma=true; } } @@ -1714,17 +1714,17 @@ public class BuildCodeTran extends BuildCode { Descriptor var=md.getParameter(i); TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var); if (objectparams.isParamPrim(paramtemp)) { - TempDescriptor targ=fc.getArg(i); - if (needcomma) - output.print(", "); + TempDescriptor targ=fc.getArg(i); + if (needcomma) + output.print(", "); - TypeDescriptor ptd=md.getParamType(i); - if (state.MGC && ptd.isClass() && ptd.getClassDesc().isEnum()) { - // do nothing - } else if (ptd.isClass()&&!ptd.isArray()) - output.print("(struct "+ptd.getSafeSymbol()+" *) "); - output.print(generateTemp(fm, targ)); - needcomma=true; + TypeDescriptor ptd=md.getParamType(i); + if (state.MGC && ptd.isClass() && ptd.getClassDesc().isEnum()) { + // do nothing + } else if (ptd.isClass()&&!ptd.isArray()) + output.print("(struct "+ptd.getSafeSymbol()+" *) "); + output.print(generateTemp(fm, targ)); + needcomma=true; } } output.println(");"); @@ -1742,50 +1742,50 @@ public class BuildCodeTran extends BuildCode { output.println(dst+"="+ src +"->"+field+ ";"); if (ffn.getField().getType().isPtr()&&locality.getAtomic(currlb).get(ffn).intValue()>0&& locality.getNodePreTempInfo(currlb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) { - if ((dc==null)||(!state.READSET&&dc.getNeedTrans(currlb, ffn))|| - (state.READSET&&dc.getNeedWriteTrans(currlb, ffn))) { - output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));"); - } else if (state.READSET&&dc.getNeedTrans(currlb, ffn)) { - if (state.HYBRID&&delaycomp.getConv(currlb).contains(ffn)) { - output.println("TRANSREADRDFISSION("+dst+", "+dst+");"); - } else - output.println("TRANSREADRD("+dst+", "+dst+");"); - } + if ((dc==null)||(!state.READSET&&dc.getNeedTrans(currlb, ffn))|| + (state.READSET&&dc.getNeedWriteTrans(currlb, ffn))) { + output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));"); + } else if (state.READSET&&dc.getNeedTrans(currlb, ffn)) { + if (state.HYBRID&&delaycomp.getConv(currlb).contains(ffn)) { + output.println("TRANSREADRDFISSION("+dst+", "+dst+");"); + } else + output.println("TRANSREADRD("+dst+", "+dst+");"); + } } } else if (state.DSM) { Integer status=locality.getNodePreTempInfo(currlb,ffn).get(ffn.getSrc()); if (status==LocalityAnalysis.GLOBAL) { - String field=ffn.getField().getSafeSymbol(); - String src=generateTemp(fm, ffn.getSrc()); - String dst=generateTemp(fm, ffn.getDst()); - - if (ffn.getField().getType().isPtr()) { - output.println(dst+"="+ src +"->"+field+ ";"); - output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");"); - } else { - output.println(dst+"="+ src+"->"+field+";"); - } + String field=ffn.getField().getSafeSymbol(); + String src=generateTemp(fm, ffn.getSrc()); + String dst=generateTemp(fm, ffn.getDst()); + + if (ffn.getField().getType().isPtr()) { + output.println(dst+"="+ src +"->"+field+ ";"); + output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");"); + } else { + output.println(dst+"="+ src+"->"+field+";"); + } } else if (status==LocalityAnalysis.LOCAL) { - if (ffn.getField().getType().isPtr()&& - ffn.getField().isGlobal()) { - String field=ffn.getField().getSafeSymbol(); - String src=generateTemp(fm, ffn.getSrc()); - String dst=generateTemp(fm, ffn.getDst()); - output.println(dst+"="+ src +"->"+field+ ";"); - if (locality.getAtomic(currlb).get(ffn).intValue()>0) - output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");"); - } else - output.println(generateTemp(fm, ffn.getDst())+"="+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";"); + if (ffn.getField().getType().isPtr()&& + ffn.getField().isGlobal()) { + String field=ffn.getField().getSafeSymbol(); + String src=generateTemp(fm, ffn.getSrc()); + String dst=generateTemp(fm, ffn.getDst()); + output.println(dst+"="+ src +"->"+field+ ";"); + if (locality.getAtomic(currlb).get(ffn).intValue()>0) + output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");"); + } else + output.println(generateTemp(fm, ffn.getDst())+"="+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";"); } else if (status==LocalityAnalysis.EITHER) { - //Code is reading from a null pointer - output.println("if ("+generateTemp(fm, ffn.getSrc())+") {"); - output.println("#ifndef RAW"); - output.println("printf(\"BIG ERROR\\n\");exit(-1);}"); - output.println("#endif"); - //This should throw a suitable null pointer error - output.println(generateTemp(fm, ffn.getDst())+"="+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";"); + //Code is reading from a null pointer + output.println("if ("+generateTemp(fm, ffn.getSrc())+") {"); + output.println("#ifndef RAW"); + output.println("printf(\"BIG ERROR\\n\");exit(-1);}"); + output.println("#endif"); + //This should throw a suitable null pointer error + output.println(generateTemp(fm, ffn.getDst())+"="+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";"); } else - throw new Error("Read from non-global/non-local in:"+currlb.getExplanation()); + throw new Error("Read from non-global/non-local in:"+currlb.getExplanation()); } } @@ -1799,28 +1799,28 @@ public class BuildCodeTran extends BuildCode { String dst=generateTemp(fm,fsfn.getDst()); output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull()); if (srcptr&&!fsfn.getSrc().getType().isNull()) { - output.println("{"); - if ((dc==null)||dc.getNeedSrcTrans(currlb, fsfn)&& - locality.getNodePreTempInfo(currlb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) { - output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);"); - } else { - output.println("INTPTR srcoid=(INTPTR)"+src+";"); - } + output.println("{"); + if ((dc==null)||dc.getNeedSrcTrans(currlb, fsfn)&& + locality.getNodePreTempInfo(currlb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) { + output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);"); + } else { + output.println("INTPTR srcoid=(INTPTR)"+src+";"); + } } if (wb.needBarrier(fsfn)&& locality.getNodePreTempInfo(currlb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) { - if (state.EVENTMONITOR) { - output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)"); - } - output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;"); + if (state.EVENTMONITOR) { + output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)"); + } + output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;"); } if (srcptr&!fsfn.getSrc().getType().isNull()) { - output.println("*((unsigned INTPTR *)&("+dst+"->"+ - fsfn.getField().getSafeSymbol()+"))=srcoid;"); - output.println("}"); + output.println("*((unsigned INTPTR *)&("+dst+"->"+ + fsfn.getField().getSafeSymbol()+"))=srcoid;"); + output.println("}"); } else { - output.println(dst+"->"+ - fsfn.getField().getSafeSymbol()+"="+ src+";"); + output.println(dst+"->"+ + fsfn.getField().getSafeSymbol()+"="+ src+";"); } } else if (state.DSM && locality.getAtomic(currlb).get(fsfn).intValue()>0) { Integer statussrc=locality.getNodePreTempInfo(currlb,fsfn).get(fsfn.getSrc()); @@ -1830,52 +1830,52 @@ public class BuildCodeTran extends BuildCode { String src=generateTemp(fm,fsfn.getSrc()); String dst=generateTemp(fm,fsfn.getDst()); if (srcglobal) { - output.println("{"); - output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);"); + output.println("{"); + output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);"); } if (statusdst.equals(LocalityAnalysis.GLOBAL)) { - String glbdst=dst; - //mark it dirty - if (wb.needBarrier(fsfn)) - output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;"); - if (srcglobal) { - output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ - fsfn.getField().getSafeSymbol()+"))=srcoid;"); - } else - output.println(glbdst+"->"+ - fsfn.getField().getSafeSymbol()+"="+ src+";"); + String glbdst=dst; + //mark it dirty + if (wb.needBarrier(fsfn)) + output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;"); + if (srcglobal) { + output.println("*((unsigned INTPTR *)&("+glbdst+"->"+ + fsfn.getField().getSafeSymbol()+"))=srcoid;"); + } else + output.println(glbdst+"->"+ + fsfn.getField().getSafeSymbol()+"="+ src+";"); } else if (statusdst.equals(LocalityAnalysis.LOCAL)) { - /** Check if we need to copy */ - output.println("if(!"+dst+"->"+localcopystr+") {"); - /* Link object into list */ - String revertptr=generateTemp(fm, reverttable.get(currlb)); - output.println(revertptr+"=revertlist;"); - if (GENERATEPRECISEGC || this.state.MULTICOREGC) - output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");"); - else - output.println("COPY_OBJ("+dst+");"); - output.println(dst+"->"+nextobjstr+"="+revertptr+";"); - output.println("revertlist=(struct ___Object___ *)"+dst+";"); - output.println("}"); - if (srcglobal) - output.println(dst+"->"+ - fsfn.getField().getSafeSymbol()+"=(void *) srcoid;"); - else - output.println(dst+"->"+ - fsfn.getField().getSafeSymbol()+"="+ src+";"); + /** Check if we need to copy */ + output.println("if(!"+dst+"->"+localcopystr+") {"); + /* Link object into list */ + String revertptr=generateTemp(fm, reverttable.get(currlb)); + output.println(revertptr+"=revertlist;"); + if (GENERATEPRECISEGC || this.state.MULTICOREGC) + output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");"); + else + output.println("COPY_OBJ("+dst+");"); + output.println(dst+"->"+nextobjstr+"="+revertptr+";"); + output.println("revertlist=(struct ___Object___ *)"+dst+";"); + output.println("}"); + if (srcglobal) + output.println(dst+"->"+ + fsfn.getField().getSafeSymbol()+"=(void *) srcoid;"); + else + output.println(dst+"->"+ + fsfn.getField().getSafeSymbol()+"="+ src+";"); } else if (statusdst.equals(LocalityAnalysis.EITHER)) { - //writing to a null...bad - output.println("if ("+dst+") {"); - output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}"); - if (srcglobal) - output.println(dst+"->"+ - fsfn.getField().getSafeSymbol()+"=(void *) srcoid;"); - else - output.println(dst+"->"+ - fsfn.getField().getSafeSymbol()+"="+ src+";"); + //writing to a null...bad + output.println("if ("+dst+") {"); + output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}"); + if (srcglobal) + output.println(dst+"->"+ + fsfn.getField().getSafeSymbol()+"=(void *) srcoid;"); + else + output.println(dst+"->"+ + fsfn.getField().getSafeSymbol()+"="+ src+";"); } if (srcglobal) { - output.println("}"); + output.println("}"); } } } @@ -1899,44 +1899,44 @@ public class BuildCodeTran extends BuildCode { //Single machine transaction case String dst=generateTemp(fm, fen.getDst()); if ((!state.STMARRAY)||(!wb.needBarrier(fen))||locality.getNodePreTempInfo(currlb, fen).get(fen.getSrc())==LocalityAnalysis.SCRATCH||locality.getAtomic(currlb).get(fen).intValue()==0||(state.READSET&&!dc.getNeedGet(currlb, fen))) { - output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];"); + output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];"); } else { - output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc())+", "+generateTemp(fm, fen.getIndex())+", "+type+");"); + output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc())+", "+generateTemp(fm, fen.getIndex())+", "+type+");"); } if (elementtype.isPtr()&&locality.getAtomic(currlb).get(fen).intValue()>0&& locality.getNodePreTempInfo(currlb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) { - if ((dc==null)||!state.READSET&&dc.getNeedTrans(currlb, fen)||state.READSET&&dc.getNeedWriteTrans(currlb, fen)) { - output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));"); - } else if (state.READSET&&dc.getNeedTrans(currlb, fen)) { - if (state.HYBRID&&delaycomp.getConv(currlb).contains(fen)) { - output.println("TRANSREADRDFISSION("+dst+", "+dst+");"); - } else - output.println("TRANSREADRD("+dst+", "+dst+");"); - } + if ((dc==null)||!state.READSET&&dc.getNeedTrans(currlb, fen)||state.READSET&&dc.getNeedWriteTrans(currlb, fen)) { + output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));"); + } else if (state.READSET&&dc.getNeedTrans(currlb, fen)) { + if (state.HYBRID&&delaycomp.getConv(currlb).contains(fen)) { + output.println("TRANSREADRDFISSION("+dst+", "+dst+");"); + } else + output.println("TRANSREADRD("+dst+", "+dst+");"); + } } } else if (state.DSM) { Integer status=locality.getNodePreTempInfo(currlb,fen).get(fen.getSrc()); if (status==LocalityAnalysis.GLOBAL) { - String dst=generateTemp(fm, fen.getDst()); - if (elementtype.isPtr()) { - output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];"); - output.println("TRANSREAD("+dst+", "+dst+");"); - } else { - output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];"); - } + String dst=generateTemp(fm, fen.getDst()); + if (elementtype.isPtr()) { + output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];"); + output.println("TRANSREAD("+dst+", "+dst+");"); + } else { + output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];"); + } } else if (status==LocalityAnalysis.LOCAL) { - output.println(generateTemp(fm, fen.getDst())+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];"); + output.println(generateTemp(fm, fen.getDst())+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];"); } else if (status==LocalityAnalysis.EITHER) { - //Code is reading from a null pointer - output.println("if ("+generateTemp(fm, fen.getSrc())+") {"); - output.println("#ifndef RAW"); - output.println("printf(\"BIG ERROR\\n\");exit(-1);}"); - output.println("#endif"); - //This should throw a suitable null pointer error - output.println(generateTemp(fm, fen.getDst())+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];"); + //Code is reading from a null pointer + output.println("if ("+generateTemp(fm, fen.getSrc())+") {"); + output.println("#ifndef RAW"); + output.println("printf(\"BIG ERROR\\n\");exit(-1);}"); + output.println("#endif"); + //This should throw a suitable null pointer error + output.println(generateTemp(fm, fen.getDst())+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];"); } else - throw new Error("Read from non-global/non-local in:"+currlb.getExplanation()); + throw new Error("Read from non-global/non-local in:"+currlb.getExplanation()); } } @@ -1963,29 +1963,29 @@ public class BuildCodeTran extends BuildCode { //Transaction set element case if (wb.needBarrier(fsen)&& locality.getNodePreTempInfo(currlb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) { - output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst())+"->___objstatus___))|=DIRTY;"); + output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst())+"->___objstatus___))|=DIRTY;"); } if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) { - output.println("{"); - String src=generateTemp(fm, fsen.getSrc()); - if ((dc==null)||dc.getNeedSrcTrans(currlb, fsen)&& - locality.getNodePreTempInfo(currlb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) { - output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);"); - } else { - output.println("INTPTR srcoid=(INTPTR)"+src+";"); - } - if (state.STMARRAY&&locality.getNodePreTempInfo(currlb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(currlb).get(fsen).intValue()>0) { - output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst())+", "+generateTemp(fm, fsen.getIndex())+", srcoid, INTPTR);"); - } else { - output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]=srcoid;"); - } - output.println("}"); + output.println("{"); + String src=generateTemp(fm, fsen.getSrc()); + if ((dc==null)||dc.getNeedSrcTrans(currlb, fsen)&& + locality.getNodePreTempInfo(currlb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) { + output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);"); + } else { + output.println("INTPTR srcoid=(INTPTR)"+src+";"); + } + if (state.STMARRAY&&locality.getNodePreTempInfo(currlb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(currlb).get(fsen).intValue()>0) { + output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst())+", "+generateTemp(fm, fsen.getIndex())+", srcoid, INTPTR);"); + } else { + output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]=srcoid;"); + } + output.println("}"); } else { - if (state.STMARRAY&&locality.getNodePreTempInfo(currlb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(currlb).get(fsen).intValue()>0) { - output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst())+", "+generateTemp(fm, fsen.getIndex())+", "+ generateTemp(fm, fsen.getSrc()) +", "+type+");"); - } else { - output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";"); - } + if (state.STMARRAY&&locality.getNodePreTempInfo(currlb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(currlb).get(fsen).intValue()>0) { + output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst())+", "+generateTemp(fm, fsen.getIndex())+", "+ generateTemp(fm, fsen.getSrc()) +", "+type+");"); + } else { + output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";"); + } } } else if (state.DSM && locality.getAtomic(currlb).get(fsen).intValue()>0) { Integer statussrc=locality.getNodePreTempInfo(currlb,fsen).get(fsen.getSrc()); @@ -1995,50 +1995,50 @@ public class BuildCodeTran extends BuildCode { boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER); if (dstglobal) { - if (wb.needBarrier(fsen)) - output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst())+"->___localcopy___))|=DIRTY;"); + if (wb.needBarrier(fsen)) + output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst())+"->___localcopy___))|=DIRTY;"); } else if (dstlocal) { - /** Check if we need to copy */ - String dst=generateTemp(fm, fsen.getDst()); - output.println("if(!"+dst+"->"+localcopystr+") {"); - /* Link object into list */ - String revertptr=generateTemp(fm, reverttable.get(currlb)); - output.println(revertptr+"=revertlist;"); - if ((GENERATEPRECISEGC) || this.state.MULTICOREGC) - output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");"); - else - output.println("COPY_OBJ("+dst+");"); - output.println(dst+"->"+nextobjstr+"="+revertptr+";"); - output.println("revertlist=(struct ___Object___ *)"+dst+";"); - output.println("}"); + /** Check if we need to copy */ + String dst=generateTemp(fm, fsen.getDst()); + output.println("if(!"+dst+"->"+localcopystr+") {"); + /* Link object into list */ + String revertptr=generateTemp(fm, reverttable.get(currlb)); + output.println(revertptr+"=revertlist;"); + if ((GENERATEPRECISEGC) || this.state.MULTICOREGC) + output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");"); + else + output.println("COPY_OBJ("+dst+");"); + output.println(dst+"->"+nextobjstr+"="+revertptr+";"); + output.println("revertlist=(struct ___Object___ *)"+dst+";"); + output.println("}"); } else { - System.out.println("Node: "+fsen); - System.out.println(currlb); - System.out.println("statusdst="+statusdst); - System.out.println(fm.printMethod()); - throw new Error("Unknown array type"); + System.out.println("Node: "+fsen); + System.out.println(currlb); + System.out.println("statusdst="+statusdst); + System.out.println(fm.printMethod()); + throw new Error("Unknown array type"); } if (srcglobal) { - output.println("{"); - String src=generateTemp(fm, fsen.getSrc()); - output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);"); - output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]=srcoid;"); - output.println("}"); + output.println("{"); + String src=generateTemp(fm, fsen.getSrc()); + output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);"); + output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]=srcoid;"); + output.println("}"); } else { - output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";"); + output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";"); } } else { if (state.FASTCHECK) { - String dst=generateTemp(fm, fsen.getDst()); - output.println("if(!"+dst+"->"+localcopystr+") {"); - /* Link object into list */ - if (GENERATEPRECISEGC || this.state.MULTICOREGC) - output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");"); - else - output.println("COPY_OBJ("+dst+");"); - output.println(dst+"->"+nextobjstr+"="+fcrevert+";"); - output.println(fcrevert+"=(struct ___Object___ *)"+dst+";"); - output.println("}"); + String dst=generateTemp(fm, fsen.getDst()); + output.println("if(!"+dst+"->"+localcopystr+") {"); + /* Link object into list */ + if (GENERATEPRECISEGC || this.state.MULTICOREGC) + output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");"); + else + output.println("COPY_OBJ("+dst+");"); + output.println(dst+"->"+nextobjstr+"="+fcrevert+";"); + output.println(fcrevert+"=(struct ___Object___ *)"+dst+";"); + output.println("}"); } output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";"); } @@ -2053,39 +2053,39 @@ public class BuildCodeTran extends BuildCode { } if (state.SINGLETM) { if (fn.getType().isArray()) { - int arrayid=state.getArrayNumber(fn.getType())+state.numClasses(); - if (locality.getAtomic(currlb).get(fn).intValue()>0) { - //inside transaction - output.println(generateTemp(fm,fn.getDst())+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");"); - } else { - //outside transaction - output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");"); - } + int arrayid=state.getArrayNumber(fn.getType())+state.numClasses(); + if (locality.getAtomic(currlb).get(fn).intValue()>0) { + //inside transaction + output.println(generateTemp(fm,fn.getDst())+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");"); + } else { + //outside transaction + output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");"); + } } else { - if (locality.getAtomic(currlb).get(fn).intValue()>0) { - //inside transaction - output.println(generateTemp(fm,fn.getDst())+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");"); - } else { - //outside transaction - output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");"); - } + if (locality.getAtomic(currlb).get(fn).intValue()>0) { + //inside transaction + output.println(generateTemp(fm,fn.getDst())+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");"); + } else { + //outside transaction + output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");"); + } } } else if (fn.getType().isArray()) { int arrayid=state.getArrayNumber(fn.getType())+state.numClasses(); if (fn.isGlobal()) { - output.println(generateTemp(fm,fn.getDst())+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize())+");"); + output.println(generateTemp(fm,fn.getDst())+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize())+");"); } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");"); + output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");"); } else { - output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize())+");"); + output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize())+");"); } } else { if (fn.isGlobal()) { - output.println(generateTemp(fm,fn.getDst())+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");"); + output.println(generateTemp(fm,fn.getDst())+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");"); } else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");"); + output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");"); } else { - output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+fn.getType().getClassDesc().getId()+");"); + output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+fn.getType().getClassDesc().getId()+");"); } } if (state.DSM && locality.getAtomic(currlb).get(fn).intValue()>0&&!fn.isGlobal()) { @@ -2106,28 +2106,28 @@ public class BuildCodeTran extends BuildCode { protected void generateFlatOpNode(FlatMethod fm, FlatOpNode fon, PrintWriter output) { if (fon.getRight()!=null) { if (fon.getOp().getOp()==Operation.URIGHTSHIFT) { - if (fon.getLeft().getType().isLong()) - output.println(generateTemp(fm, fon.getDest())+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";"); - else - output.println(generateTemp(fm, fon.getDest())+" = ((unsigned int)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";"); + if (fon.getLeft().getType().isLong()) + output.println(generateTemp(fm, fon.getDest())+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";"); + else + output.println(generateTemp(fm, fon.getDest())+" = ((unsigned int)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";"); } else if (dc!=null) { - output.print(generateTemp(fm, fon.getDest())+" = ("); - if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL)) - output.print("(void *)"); - if (dc.getNeedLeftSrcTrans(currlb, fon)) - output.print("("+generateTemp(fm, fon.getLeft())+"!=NULL?"+generateTemp(fm, fon.getLeft())+"->"+oidstr+":NULL)"); - else - output.print(generateTemp(fm, fon.getLeft())); - output.print(")"+fon.getOp().toString()+"("); - if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL)) - output.print("(void *)"); - if (dc.getNeedRightSrcTrans(currlb, fon)) - output.println("("+generateTemp(fm, fon.getRight())+"!=NULL?"+generateTemp(fm, fon.getRight())+"->"+oidstr+":NULL));"); - else - output.println(generateTemp(fm,fon.getRight())+");"); + output.print(generateTemp(fm, fon.getDest())+" = ("); + if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL)) + output.print("(void *)"); + if (dc.getNeedLeftSrcTrans(currlb, fon)) + output.print("("+generateTemp(fm, fon.getLeft())+"!=NULL?"+generateTemp(fm, fon.getLeft())+"->"+oidstr+":NULL)"); + else + output.print(generateTemp(fm, fon.getLeft())); + output.print(")"+fon.getOp().toString()+"("); + if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL)) + output.print("(void *)"); + if (dc.getNeedRightSrcTrans(currlb, fon)) + output.println("("+generateTemp(fm, fon.getRight())+"!=NULL?"+generateTemp(fm, fon.getRight())+"->"+oidstr+":NULL));"); + else + output.println(generateTemp(fm,fon.getRight())+");"); } else - output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";"); + output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";"); } else if (fon.getOp().getOp()==Operation.ASSIGN) output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";"); else if (fon.getOp().getOp()==Operation.UNARYPLUS) @@ -2149,25 +2149,25 @@ public class BuildCodeTran extends BuildCode { output.println(generateTemp(fm, fln.getDst())+"=0;"); else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) { if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { - if (state.DSM && locality.getAtomic(currlb).get(fln).intValue()>0) { - //Stash pointer in case of GC - String revertptr=generateTemp(fm, reverttable.get(currlb)); - output.println(revertptr+"=revertlist;"); - } - output.println(generateTemp(fm, fln.getDst())+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");"); - if (state.DSM && locality.getAtomic(currlb).get(fln).intValue()>0) { - //Stash pointer in case of GC - String revertptr=generateTemp(fm, reverttable.get(currlb)); - output.println("revertlist="+revertptr+";"); - } + if (state.DSM && locality.getAtomic(currlb).get(fln).intValue()>0) { + //Stash pointer in case of GC + String revertptr=generateTemp(fm, reverttable.get(currlb)); + output.println(revertptr+"=revertlist;"); + } + output.println(generateTemp(fm, fln.getDst())+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");"); + if (state.DSM && locality.getAtomic(currlb).get(fln).intValue()>0) { + //Stash pointer in case of GC + String revertptr=generateTemp(fm, reverttable.get(currlb)); + output.println("revertlist="+revertptr+";"); + } } else { - output.println(generateTemp(fm, fln.getDst())+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");"); + output.println(generateTemp(fm, fln.getDst())+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");"); } } else if (fln.getType().isBoolean()) { if (((Boolean)fln.getValue()).booleanValue()) - output.println(generateTemp(fm, fln.getDst())+"=1;"); + output.println(generateTemp(fm, fln.getDst())+"=1;"); else - output.println(generateTemp(fm, fln.getDst())+"=0;"); + output.println(generateTemp(fm, fln.getDst())+"=0;"); } else if (fln.getType().isChar()) { String st=FlatLiteralNode.escapeString(fln.getValue().toString()); output.println(generateTemp(fm, fln.getDst())+"='"+st+"';"); @@ -2210,11 +2210,11 @@ public class BuildCodeTran extends BuildCode { if (md!=null&&md.getReturnType()!=null) { if (state.MGC && md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) { - output.print("int "); + output.print("int "); } else if (md.getReturnType().isClass()||md.getReturnType().isArray()) - output.print("struct " + md.getReturnType().getSafeSymbol()+" * "); + output.print("struct " + md.getReturnType().getSafeSymbol()+" * "); else - output.print(md.getReturnType().getSafeSymbol()+" "); + output.print(md.getReturnType().getSafeSymbol()+" "); } else //catch the constructor case output.print("void "); @@ -2226,25 +2226,25 @@ public class BuildCodeTran extends BuildCode { boolean printcomma=false; if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) { if (md!=null) { - output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix); + output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix); } else - output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix); + output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix); printcomma=true; } if (md!=null) { /* Method */ for(int i=0; imaxtaskparams) - maxtaskparams=objectparams.numPrimitives()+fm.numTags(); + maxtaskparams=objectparams.numPrimitives()+fm.numTags(); } else output.println(") {"); } } diff --git a/Robust/src/IR/Flat/BuildFlat.java b/Robust/src/IR/Flat/BuildFlat.java index 4d9b15c3..fdc78e8c 100644 --- a/Robust/src/IR/Flat/BuildFlat.java +++ b/Robust/src/IR/Flat/BuildFlat.java @@ -72,19 +72,19 @@ public class BuildFlat { TagExpressionList tel=td.getTag(paramvd); //BUG added next line to fix...to test feed in any task program if (tel!=null) - for(int j=0; j1) { - NodePair np=generateNewArrayLoop(temps, td.dereference(), out_temp, 0, con.isGlobal()); - fn.addNext(np.getBegin()); - return new NodePair(first,np.getEnd()); - } else if (td.isArray()&&td.dereference().iswrapper()) { - NodePair np=generateNewArrayLoop(temps, td.dereference(), out_temp, 0, con.isGlobal()); - fn.addNext(np.getBegin()); - return new NodePair(first,np.getEnd()); - } else - return new NodePair(first, fn); + FlatNode first=null; + FlatNode last=null; + TempDescriptor[] temps=new TempDescriptor[con.numArgs()]; + for (int i=0; i1) { + NodePair np=generateNewArrayLoop(temps, td.dereference(), out_temp, 0, con.isGlobal()); + fn.addNext(np.getBegin()); + return new NodePair(first,np.getEnd()); + } else if (td.isArray()&&td.dereference().iswrapper()) { + NodePair np=generateNewArrayLoop(temps, td.dereference(), out_temp, 0, con.isGlobal()); + fn.addNext(np.getBegin()); + return new NodePair(first,np.getEnd()); + } else + return new NodePair(first, fn); } else { - // array creation with initializers - return flattenArrayInitializerNode(con.getArrayInitializer(), out_temp); + // array creation with initializers + return flattenArrayInitializerNode(con.getArrayInitializer(), out_temp); } } } @@ -504,7 +504,7 @@ public class BuildFlat { if (min.getExpression()!=null) { TypeDescriptor mtd = min.getExpression().getType(); if(mtd.isClass() && mtd.getClassDesc().isEnum()) { - mtd = new TypeDescriptor(TypeDescriptor.INT); + mtd = new TypeDescriptor(TypeDescriptor.INT); } thisarg=TempDescriptor.tempFactory("thisarg", mtd); NodePair np=flattenExpressionNode(min.getExpression(),thisarg); @@ -517,15 +517,15 @@ public class BuildFlat { ExpressionNode en=min.getArg(i); TypeDescriptor etd = en.getType(); if(etd.isClass() && etd.getClassDesc().isEnum()) { - etd = new TypeDescriptor(TypeDescriptor.INT); + etd = new TypeDescriptor(TypeDescriptor.INT); } TempDescriptor td=TempDescriptor.tempFactory("arg", etd); temps[i]=td; NodePair np=flattenExpressionNode(en, td); if (first==null) - first=np.getBegin(); + first=np.getBegin(); else - last.addNext(np.getBegin()); + last.addNext(np.getBegin()); last=np.getEnd(); } @@ -609,13 +609,13 @@ public class BuildFlat { //Get src value if (an.getSrc()!=null) { if(an.getSrc().getEval() != null) { - FlatLiteralNode fln=new FlatLiteralNode(an.getSrc().getType(), an.getSrc().getEval().longValue(), src_tmp); - fln.setNumLine(an.getSrc().getNumLine()); - first = last =fln; + FlatLiteralNode fln=new FlatLiteralNode(an.getSrc().getType(), an.getSrc().getEval().longValue(), src_tmp); + fln.setNumLine(an.getSrc().getNumLine()); + first = last =fln; } else { - NodePair np_src=flattenExpressionNode(an.getSrc(),src_tmp); - first=np_src.getBegin(); - last=np_src.getEnd(); + NodePair np_src=flattenExpressionNode(an.getSrc(),src_tmp); + first=np_src.getBegin(); + last=np_src.getEnd(); } } else if (!pre) { FlatLiteralNode fln=new FlatLiteralNode(new TypeDescriptor(TypeDescriptor.INT),new Integer(1),src_tmp); @@ -632,45 +632,45 @@ public class BuildFlat { TempDescriptor dst_tmp=null; NodePair np_baseexp=null; if(en.getType().isClassNameRef()) { - // static field dereference with class name - dst_tmp = new TempDescriptor(en.getType().getClassDesc().getSymbol(), en.getType()); - FlatNop nop=new FlatNop(); - np_baseexp = new NodePair(nop,nop); + // static field dereference with class name + dst_tmp = new TempDescriptor(en.getType().getClassDesc().getSymbol(), en.getType()); + FlatNop nop=new FlatNop(); + np_baseexp = new NodePair(nop,nop); } else { - dst_tmp=TempDescriptor.tempFactory("dst",en.getType()); - np_baseexp=flattenExpressionNode(en, dst_tmp); + dst_tmp=TempDescriptor.tempFactory("dst",en.getType()); + np_baseexp=flattenExpressionNode(en, dst_tmp); } if (first==null) - first=np_baseexp.getBegin(); + first=np_baseexp.getBegin(); else - last.addNext(np_baseexp.getBegin()); + last.addNext(np_baseexp.getBegin()); last=np_baseexp.getEnd(); //See if we need to perform an operation if (base!=null) { - //If it is a preinc we need to store the initial value - TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp; - TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType()); - FlatFieldNode ffn=new FlatFieldNode(fan.getField(), dst_tmp, src_tmp2); - ffn.setNumLine(an.getNumLine()); - last.addNext(ffn); - last=ffn; - - if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) { - ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass); - MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)}); - FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp}); - fc.setNumLine(an.getNumLine()); - src_tmp=tmp; - last.addNext(fc); - last=fc; - } else { - FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base); - fon.setNumLine(an.getNumLine()); - src_tmp=tmp; - last.addNext(fon); - last=fon; - } + //If it is a preinc we need to store the initial value + TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp; + TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType()); + FlatFieldNode ffn=new FlatFieldNode(fan.getField(), dst_tmp, src_tmp2); + ffn.setNumLine(an.getNumLine()); + last.addNext(ffn); + last=ffn; + + if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) { + ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass); + MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)}); + FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp}); + fc.setNumLine(an.getNumLine()); + src_tmp=tmp; + last.addNext(fc); + last=fc; + } else { + FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base); + fon.setNumLine(an.getNumLine()); + src_tmp=tmp; + last.addNext(fon); + last=fon; + } } FlatSetFieldNode fsfn=new FlatSetFieldNode(dst_tmp, fan.getField(), src_tmp); @@ -678,10 +678,10 @@ public class BuildFlat { last.addNext(fsfn); last=fsfn; if (pre) { - FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN)); - fon2.setNumLine(an.getNumLine()); - fsfn.addNext(fon2); - last=fon2; + FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN)); + fon2.setNumLine(an.getNumLine()); + fsfn.addNext(fon2); + last=fon2; } return new NodePair(first, last); } else if (an.getDest().kind()==Kind.ArrayAccessNode) { @@ -695,72 +695,72 @@ public class BuildFlat { NodePair np_baseexp=flattenExpressionNode(en, dst_tmp); NodePair np_indexexp=flattenExpressionNode(enindex, index_tmp); if (first==null) - first=np_baseexp.getBegin(); + first=np_baseexp.getBegin(); else - last.addNext(np_baseexp.getBegin()); + last.addNext(np_baseexp.getBegin()); np_baseexp.getEnd().addNext(np_indexexp.getBegin()); last=np_indexexp.getEnd(); //See if we need to perform an operation if (base!=null) { - //If it is a preinc we need to store the initial value - TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp; - TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType()); - - if (aan.iswrapper()) { - TypeDescriptor arrayeltype=aan.getExpression().getType().dereference(); - TempDescriptor src_tmp3=TempDescriptor.tempFactory("src3",arrayeltype); - FlatElementNode fen=new FlatElementNode(dst_tmp, index_tmp, src_tmp3); - fen.setNumLine(aan.getNumLine()); - FlatFieldNode ffn=new FlatFieldNode((FieldDescriptor)arrayeltype.getClassDesc().getFieldTable().get("value"),src_tmp3,src_tmp2); - ffn.setNumLine(aan.getNumLine()); - last.addNext(fen); - fen.addNext(ffn); - last=ffn; - } else { - FlatElementNode fen=new FlatElementNode(dst_tmp, index_tmp, src_tmp2); - fen.setNumLine(aan.getNumLine()); - last.addNext(fen); - last=fen; - } - if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) { - ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass); - MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)}); - FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp}); - fc.setNumLine(an.getNumLine()); - src_tmp=tmp; - last.addNext(fc); - last=fc; - } else { - FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base); - fon.setNumLine(an.getNumLine()); - src_tmp=tmp; - last.addNext(fon); - last=fon; - } + //If it is a preinc we need to store the initial value + TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp; + TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType()); + + if (aan.iswrapper()) { + TypeDescriptor arrayeltype=aan.getExpression().getType().dereference(); + TempDescriptor src_tmp3=TempDescriptor.tempFactory("src3",arrayeltype); + FlatElementNode fen=new FlatElementNode(dst_tmp, index_tmp, src_tmp3); + fen.setNumLine(aan.getNumLine()); + FlatFieldNode ffn=new FlatFieldNode((FieldDescriptor)arrayeltype.getClassDesc().getFieldTable().get("value"),src_tmp3,src_tmp2); + ffn.setNumLine(aan.getNumLine()); + last.addNext(fen); + fen.addNext(ffn); + last=ffn; + } else { + FlatElementNode fen=new FlatElementNode(dst_tmp, index_tmp, src_tmp2); + fen.setNumLine(aan.getNumLine()); + last.addNext(fen); + last=fen; + } + if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) { + ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass); + MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)}); + FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp}); + fc.setNumLine(an.getNumLine()); + src_tmp=tmp; + last.addNext(fc); + last=fc; + } else { + FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base); + fon.setNumLine(an.getNumLine()); + src_tmp=tmp; + last.addNext(fon); + last=fon; + } } if (aan.iswrapper()) { - TypeDescriptor arrayeltype=aan.getExpression().getType().dereference(); - TempDescriptor src_tmp3=TempDescriptor.tempFactory("src3",arrayeltype); - FlatElementNode fen=new FlatElementNode(dst_tmp, index_tmp, src_tmp3); - fen.setNumLine(aan.getNumLine()); - FlatSetFieldNode fsfn=new FlatSetFieldNode(src_tmp3,(FieldDescriptor)arrayeltype.getClassDesc().getFieldTable().get("value"),src_tmp); - fsfn.setNumLine(aan.getExpression().getNumLine()); - last.addNext(fen); - fen.addNext(fsfn); - last=fsfn; + TypeDescriptor arrayeltype=aan.getExpression().getType().dereference(); + TempDescriptor src_tmp3=TempDescriptor.tempFactory("src3",arrayeltype); + FlatElementNode fen=new FlatElementNode(dst_tmp, index_tmp, src_tmp3); + fen.setNumLine(aan.getNumLine()); + FlatSetFieldNode fsfn=new FlatSetFieldNode(src_tmp3,(FieldDescriptor)arrayeltype.getClassDesc().getFieldTable().get("value"),src_tmp); + fsfn.setNumLine(aan.getExpression().getNumLine()); + last.addNext(fen); + fen.addNext(fsfn); + last=fsfn; } else { - FlatSetElementNode fsen=new FlatSetElementNode(dst_tmp, index_tmp, src_tmp); - fsen.setNumLine(aan.getNumLine()); - last.addNext(fsen); - last=fsen; + FlatSetElementNode fsen=new FlatSetElementNode(dst_tmp, index_tmp, src_tmp); + fsen.setNumLine(aan.getNumLine()); + last.addNext(fsen); + last=fsen; } if (pre) { - FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN)); - fon2.setNumLine(an.getNumLine()); - last.addNext(fon2); - last=fon2; + FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN)); + fon2.setNumLine(an.getNumLine()); + last.addNext(fon2); + last=fon2; } return new NodePair(first, last); } else if (an.getDest().kind()==Kind.NameNode) { @@ -769,191 +769,191 @@ public class BuildFlat { if (nn.getExpression()!=null) { - //It is a field - FieldAccessNode fan=(FieldAccessNode)nn.getExpression(); - ExpressionNode en=fan.getExpression(); - TempDescriptor dst_tmp=null; - NodePair np_baseexp=null; - if(en.getType().isClassNameRef()) { - // static field dereference with class name - dst_tmp = new TempDescriptor(en.getType().getClassDesc().getSymbol(), en.getType()); - FlatNop nop=new FlatNop(); - np_baseexp = new NodePair(nop,nop); - } else { - dst_tmp=TempDescriptor.tempFactory("dst",en.getType()); - np_baseexp=flattenExpressionNode(en, dst_tmp); - } - if (first==null) - first=np_baseexp.getBegin(); - else - last.addNext(np_baseexp.getBegin()); - last=np_baseexp.getEnd(); - - //See if we need to perform an operation - if (base!=null) { - //If it is a preinc we need to store the initial value - TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp; - TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType()); - - FlatFieldNode ffn=new FlatFieldNode(fan.getField(), dst_tmp, src_tmp2); - ffn.setNumLine(an.getNumLine()); - last.addNext(ffn); - last=ffn; - - - if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) { - ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass); - MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)}); - FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp}); - fc.setNumLine(an.getNumLine()); - src_tmp=tmp; - last.addNext(fc); - last=fc; - } else { - FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base); - fon.setNumLine(an.getNumLine()); - src_tmp=tmp; - last.addNext(fon); - last=fon; - } - } - - - FlatSetFieldNode fsfn=new FlatSetFieldNode(dst_tmp, fan.getField(), src_tmp); - fsfn.setNumLine(en.getNumLine()); - last.addNext(fsfn); - last=fsfn; - if (pre) { - FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN)); - fon2.setNumLine(an.getNumLine()); - fsfn.addNext(fon2); - last=fon2; - } - return new NodePair(first, last); + //It is a field + FieldAccessNode fan=(FieldAccessNode)nn.getExpression(); + ExpressionNode en=fan.getExpression(); + TempDescriptor dst_tmp=null; + NodePair np_baseexp=null; + if(en.getType().isClassNameRef()) { + // static field dereference with class name + dst_tmp = new TempDescriptor(en.getType().getClassDesc().getSymbol(), en.getType()); + FlatNop nop=new FlatNop(); + np_baseexp = new NodePair(nop,nop); + } else { + dst_tmp=TempDescriptor.tempFactory("dst",en.getType()); + np_baseexp=flattenExpressionNode(en, dst_tmp); + } + if (first==null) + first=np_baseexp.getBegin(); + else + last.addNext(np_baseexp.getBegin()); + last=np_baseexp.getEnd(); + + //See if we need to perform an operation + if (base!=null) { + //If it is a preinc we need to store the initial value + TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp; + TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType()); + + FlatFieldNode ffn=new FlatFieldNode(fan.getField(), dst_tmp, src_tmp2); + ffn.setNumLine(an.getNumLine()); + last.addNext(ffn); + last=ffn; + + + if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) { + ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass); + MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)}); + FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp}); + fc.setNumLine(an.getNumLine()); + src_tmp=tmp; + last.addNext(fc); + last=fc; + } else { + FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base); + fon.setNumLine(an.getNumLine()); + src_tmp=tmp; + last.addNext(fon); + last=fon; + } + } + + + FlatSetFieldNode fsfn=new FlatSetFieldNode(dst_tmp, fan.getField(), src_tmp); + fsfn.setNumLine(en.getNumLine()); + last.addNext(fsfn); + last=fsfn; + if (pre) { + FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN)); + fon2.setNumLine(an.getNumLine()); + fsfn.addNext(fon2); + last=fon2; + } + return new NodePair(first, last); } else { - if (nn.getField()!=null) { - //It is a field - //Get src value - - //See if we need to perform an operation - if (base!=null) { - //If it is a preinc we need to store the initial value - TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp; - TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType()); - - TempDescriptor ftmp= null; - if((nn.getClassDesc() != null)) { - // this is a static field - ftmp = new TempDescriptor(nn.getClassDesc().getSymbol(), nn.getClassType()); - - } else { - ftmp=getTempforVar(nn.getVar()); - } - FlatFieldNode ffn=new FlatFieldNode(nn.getField(), ftmp, src_tmp2); - ffn.setNumLine(an.getNumLine()); - - if (first==null) - first=ffn; - else { - last.addNext(ffn); - } - last=ffn; - - - if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) { - ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass); - MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)}); - FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp}); - fc.setNumLine(an.getNumLine()); - src_tmp=tmp; - last.addNext(fc); - last=fc; - } else { - FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base); - fon.setNumLine(an.getNumLine()); - src_tmp=tmp; - last.addNext(fon); - last=fon; - } - } - - FlatSetFieldNode fsfn=null; - if(nn.getClassDesc()!=null) { - // this is a static field access inside of a static block - fsfn=new FlatSetFieldNode(new TempDescriptor("sfsb", nn.getClassType()), nn.getField(), src_tmp); - fsfn.setNumLine(nn.getNumLine()); - } else { - fsfn=new FlatSetFieldNode(getTempforVar(nn.getVar()), nn.getField(), src_tmp); - fsfn.setNumLine(nn.getNumLine()); - } - if (first==null) { - first=fsfn; - } else { - last.addNext(fsfn); - } - last=fsfn; - if (pre) { - FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN)); - fon2.setNumLine(an.getNumLine()); - fsfn.addNext(fon2); - last=fon2; - } - return new NodePair(first, last); - } else { - //It is a variable - //See if we need to perform an operation - - if (base!=null) { - //If it is a preinc we need to store the initial value - TempDescriptor src_tmp2=getTempforVar(nn.getVar()); - TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType()); - if (!pre) { - FlatOpNode fon=new FlatOpNode(out_temp, src_tmp2, null, new Operation(Operation.ASSIGN)); - fon.setNumLine(an.getNumLine()); - if (first==null) - first=fon; - else - last.addNext(fon); - last=fon; - } - - - if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) { - ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass); - MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)}); - FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp}); - fc.setNumLine(an.getNumLine()); - if (first==null) - first=fc; - else - last.addNext(fc); - src_tmp=tmp; - last=fc; - } else { - FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base); - fon.setNumLine(an.getNumLine()); - if (first==null) - first=fon; - else - last.addNext(fon); - src_tmp=tmp; - last=fon; - } - } - - FlatOpNode fon=new FlatOpNode(getTempforVar(nn.getVar()), src_tmp, null, new Operation(Operation.ASSIGN)); - fon.setNumLine(an.getNumLine()); - - last.addNext(fon); - last=fon; - if (pre) { - FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN)); - fon2.setNumLine(an.getNumLine()); - fon.addNext(fon2); - last=fon2; - } - return new NodePair(first, last); - } //end of else + if (nn.getField()!=null) { + //It is a field + //Get src value + + //See if we need to perform an operation + if (base!=null) { + //If it is a preinc we need to store the initial value + TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp; + TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType()); + + TempDescriptor ftmp= null; + if((nn.getClassDesc() != null)) { + // this is a static field + ftmp = new TempDescriptor(nn.getClassDesc().getSymbol(), nn.getClassType()); + + } else { + ftmp=getTempforVar(nn.getVar()); + } + FlatFieldNode ffn=new FlatFieldNode(nn.getField(), ftmp, src_tmp2); + ffn.setNumLine(an.getNumLine()); + + if (first==null) + first=ffn; + else { + last.addNext(ffn); + } + last=ffn; + + + if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) { + ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass); + MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)}); + FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp}); + fc.setNumLine(an.getNumLine()); + src_tmp=tmp; + last.addNext(fc); + last=fc; + } else { + FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base); + fon.setNumLine(an.getNumLine()); + src_tmp=tmp; + last.addNext(fon); + last=fon; + } + } + + FlatSetFieldNode fsfn=null; + if(nn.getClassDesc()!=null) { + // this is a static field access inside of a static block + fsfn=new FlatSetFieldNode(new TempDescriptor("sfsb", nn.getClassType()), nn.getField(), src_tmp); + fsfn.setNumLine(nn.getNumLine()); + } else { + fsfn=new FlatSetFieldNode(getTempforVar(nn.getVar()), nn.getField(), src_tmp); + fsfn.setNumLine(nn.getNumLine()); + } + if (first==null) { + first=fsfn; + } else { + last.addNext(fsfn); + } + last=fsfn; + if (pre) { + FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN)); + fon2.setNumLine(an.getNumLine()); + fsfn.addNext(fon2); + last=fon2; + } + return new NodePair(first, last); + } else { + //It is a variable + //See if we need to perform an operation + + if (base!=null) { + //If it is a preinc we need to store the initial value + TempDescriptor src_tmp2=getTempforVar(nn.getVar()); + TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType()); + if (!pre) { + FlatOpNode fon=new FlatOpNode(out_temp, src_tmp2, null, new Operation(Operation.ASSIGN)); + fon.setNumLine(an.getNumLine()); + if (first==null) + first=fon; + else + last.addNext(fon); + last=fon; + } + + + if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) { + ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass); + MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)}); + FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp}); + fc.setNumLine(an.getNumLine()); + if (first==null) + first=fc; + else + last.addNext(fc); + src_tmp=tmp; + last=fc; + } else { + FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base); + fon.setNumLine(an.getNumLine()); + if (first==null) + first=fon; + else + last.addNext(fon); + src_tmp=tmp; + last=fon; + } + } + + FlatOpNode fon=new FlatOpNode(getTempforVar(nn.getVar()), src_tmp, null, new Operation(Operation.ASSIGN)); + fon.setNumLine(an.getNumLine()); + + last.addNext(fon); + last=fon; + if (pre) { + FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN)); + fon2.setNumLine(an.getNumLine()); + fon.addNext(fon2); + last=fon2; + } + return new NodePair(first, last); + } //end of else } } @@ -967,11 +967,11 @@ public class BuildFlat { } else if (nn.getField()!=null) { TempDescriptor tmp= null; if((nn.getClassDesc() != null)) { - // this is a static field - tmp = new TempDescriptor(nn.getClassDesc().getSymbol(), nn.getClassType()); + // this is a static field + tmp = new TempDescriptor(nn.getClassDesc().getSymbol(), nn.getClassType()); } else { - tmp=getTempforVar(nn.getVar()); + tmp=getTempforVar(nn.getVar()); } FlatFieldNode ffn=new FlatFieldNode(nn.getField(), tmp, out_temp); ffn.setNumLine(nn.getNumLine()); @@ -979,8 +979,8 @@ public class BuildFlat { } else { TempDescriptor tmp=getTempforVar(nn.isTag()?nn.getTagVar():nn.getVar()); if (nn.isTag()) { - //propagate tag - out_temp.setTag(tmp.getTag()); + //propagate tag + out_temp.setTag(tmp.getTag()); } FlatOpNode fon=new FlatOpNode(out_temp, tmp, null, new Operation(Operation.ASSIGN)); fon.setNumLine(nn.getNumLine()); @@ -1123,16 +1123,16 @@ public class BuildFlat { return (TempDescriptor)temptovar.get(d); else { if (d instanceof VarDescriptor) { - VarDescriptor vd=(VarDescriptor)d; - TempDescriptor td=TempDescriptor.paramtempFactory(vd.getName(),vd.getType()); - temptovar.put(vd,td); - return td; + VarDescriptor vd=(VarDescriptor)d; + TempDescriptor td=TempDescriptor.paramtempFactory(vd.getName(),vd.getType()); + temptovar.put(vd,td); + return td; } else if (d instanceof TagVarDescriptor) { - TagVarDescriptor tvd=(TagVarDescriptor)d; - TypeDescriptor tagtype=new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)); - TempDescriptor td=TempDescriptor.paramtempFactory(tvd.getName(), tagtype, tvd.getTag()); - temptovar.put(tvd,td); - return td; + TagVarDescriptor tvd=(TagVarDescriptor)d; + TypeDescriptor tagtype=new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)); + TempDescriptor td=TempDescriptor.paramtempFactory(tvd.getName(), tagtype, tvd.getTag()); + temptovar.put(tvd,td); + return td; } else throw new Error("Unreconized Descriptor"); } } @@ -1142,20 +1142,20 @@ public class BuildFlat { return (TempDescriptor)temptovar.get(d); else { if (d instanceof VarDescriptor) { - VarDescriptor vd=(VarDescriptor)d; - TempDescriptor td=TempDescriptor.tempFactory(vd.getName(), vd.getType()); - temptovar.put(vd,td); - return td; + VarDescriptor vd=(VarDescriptor)d; + TempDescriptor td=TempDescriptor.tempFactory(vd.getName(), vd.getType()); + temptovar.put(vd,td); + return td; } else if (d instanceof TagVarDescriptor) { - TagVarDescriptor tvd=(TagVarDescriptor)d; - //BUGFIX TAGTYPE - add next line, modify following - //line to tag this new type descriptor, modify - //TempDescriptor constructor & factory to set type - //using this Type To test, use any program with tags - TypeDescriptor tagtype=new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)); - TempDescriptor td=TempDescriptor.tempFactory(tvd.getName(),tagtype, tvd.getTag()); - temptovar.put(tvd,td); - return td; + TagVarDescriptor tvd=(TagVarDescriptor)d; + //BUGFIX TAGTYPE - add next line, modify following + //line to tag this new type descriptor, modify + //TempDescriptor constructor & factory to set type + //using this Type To test, use any program with tags + TypeDescriptor tagtype=new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)); + TempDescriptor td=TempDescriptor.tempFactory(tvd.getName(),tagtype, tvd.getTag()); + temptovar.put(tvd,td); + return td; } else throw new Error("Unrecognized Descriptor"); } } @@ -1214,68 +1214,68 @@ public class BuildFlat { FlatNode cond_begin = null; NodePair prev_fnp = null; for(int j = 0; j < slnv.size(); j++) { - SwitchLabelNode sln = slnv.elementAt(j); - NodePair left = null; - NodePair false_np = null; - if(sln.isDefault()) { - left = body; - } else { - TempDescriptor cond_tmp=TempDescriptor.tempFactory("condition", new TypeDescriptor(TypeDescriptor.BOOLEAN)); - TempDescriptor temp_left=TempDescriptor.tempFactory("leftop", sln.getCondition().getType()); - Operation op=new Operation(Operation.EQUAL); - left=flattenExpressionNode(sln.getCondition(), temp_left); - FlatOpNode fon=new FlatOpNode(cond_tmp, temp_left, cond_temp, op); - fon.setNumLine(sln.getNumLine()); - left.getEnd().addNext(fon); - - FlatCondBranch fcb=new FlatCondBranch(cond_tmp); - fcb.setNumLine(bn.getNumLine()); - fcb.setTrueProb(State.TRUEPROB); - - FlatNop nop=new FlatNop(); - false_np=new NodePair(nop,nop); - - fon.addNext(fcb); - fcb.addTrueNext(body.getBegin()); - fcb.addFalseNext(false_np.getBegin()); - } - if((prev_fnp != null) && (prev_fnp.getEnd() != null)) { - prev_fnp.getEnd().addNext(left.getBegin()); - } - prev_fnp = false_np; - - if (begin==null) { - begin = left.getBegin(); - } - if(cond_begin == null) { - cond_begin = left.getBegin(); - } + SwitchLabelNode sln = slnv.elementAt(j); + NodePair left = null; + NodePair false_np = null; + if(sln.isDefault()) { + left = body; + } else { + TempDescriptor cond_tmp=TempDescriptor.tempFactory("condition", new TypeDescriptor(TypeDescriptor.BOOLEAN)); + TempDescriptor temp_left=TempDescriptor.tempFactory("leftop", sln.getCondition().getType()); + Operation op=new Operation(Operation.EQUAL); + left=flattenExpressionNode(sln.getCondition(), temp_left); + FlatOpNode fon=new FlatOpNode(cond_tmp, temp_left, cond_temp, op); + fon.setNumLine(sln.getNumLine()); + left.getEnd().addNext(fon); + + FlatCondBranch fcb=new FlatCondBranch(cond_tmp); + fcb.setNumLine(bn.getNumLine()); + fcb.setTrueProb(State.TRUEPROB); + + FlatNop nop=new FlatNop(); + false_np=new NodePair(nop,nop); + + fon.addNext(fcb); + fcb.addTrueNext(body.getBegin()); + fcb.addFalseNext(false_np.getBegin()); + } + if((prev_fnp != null) && (prev_fnp.getEnd() != null)) { + prev_fnp.getEnd().addNext(left.getBegin()); + } + prev_fnp = false_np; + + if (begin==null) { + begin = left.getBegin(); + } + if(cond_begin == null) { + cond_begin = left.getBegin(); + } } if((prev_false_branch != null) && (prev_false_branch.getEnd() != null)) { - prev_false_branch.getEnd().addNext(cond_begin); + prev_false_branch.getEnd().addNext(cond_begin); } prev_false_branch = prev_fnp; if((prev_true_branch != null) && (prev_true_branch.getEnd() != null)) { - prev_true_branch.getEnd().addNext(body.getBegin()); + prev_true_branch.getEnd().addNext(body.getBegin()); } prev_true_branch = body; for(Iterator breakit=breakset.iterator(); breakit.hasNext(); ) { - FlatNode fn=(FlatNode)breakit.next(); - breakit.remove(); - if (end==null) - end=new FlatNop(); - fn.addNext(end); + FlatNode fn=(FlatNode)breakit.next(); + breakit.remove(); + if (end==null) + end=new FlatNop(); + fn.addNext(end); } breakset=oldbs; } if((prev_true_branch != null) && (prev_true_branch.getEnd() != null)) { if (end==null) - end=new FlatNop(); + end=new FlatNop(); prev_true_branch.getEnd().addNext(end); } if((prev_false_branch != null) && (prev_false_branch.getEnd() != null)) { if (end==null) - end=new FlatNop(); + end=new FlatNop(); prev_false_branch.getEnd().addNext(end); } if(begin == null) { @@ -1308,21 +1308,21 @@ public class BuildFlat { initializer.getEnd().addNext(nop2); nop2.addNext(condition.getBegin()); if (body.getEnd()!=null) - body.getEnd().addNext(update.getBegin()); + body.getEnd().addNext(update.getBegin()); update.getEnd().addNext(backedge); backedge.addNext(condition.getBegin()); condition.getEnd().addNext(fcb); fcb.addFalseNext(nopend); fcb.addTrueNext(body.getBegin()); for(Iterator contit=continueset.iterator(); contit.hasNext(); ) { - FlatNode fn=(FlatNode)contit.next(); - contit.remove(); - fn.addNext(update.getBegin()); + FlatNode fn=(FlatNode)contit.next(); + contit.remove(); + fn.addNext(update.getBegin()); } for(Iterator breakit=breakset.iterator(); breakit.hasNext(); ) { - FlatNode fn=(FlatNode)breakit.next(); - breakit.remove(); - fn.addNext(nopend); + FlatNode fn=(FlatNode)breakit.next(); + breakit.remove(); + fn.addNext(nopend); } breakset=oldbs; continueset=oldcs; @@ -1340,7 +1340,7 @@ public class BuildFlat { FlatBackEdge backedge=new FlatBackEdge(); if (body.getEnd()!=null) - body.getEnd().addNext(backedge); + body.getEnd().addNext(backedge); backedge.addNext(condition.getBegin()); condition.getEnd().addNext(fcb); @@ -1348,14 +1348,14 @@ public class BuildFlat { fcb.addTrueNext(body.getBegin()); for(Iterator contit=continueset.iterator(); contit.hasNext(); ) { - FlatNode fn=(FlatNode)contit.next(); - contit.remove(); - fn.addNext(backedge); + FlatNode fn=(FlatNode)contit.next(); + contit.remove(); + fn.addNext(backedge); } for(Iterator breakit=breakset.iterator(); breakit.hasNext(); ) { - FlatNode fn=(FlatNode)breakit.next(); - breakit.remove(); - fn.addNext(nopend); + FlatNode fn=(FlatNode)breakit.next(); + breakit.remove(); + fn.addNext(nopend); } breakset=oldbs; continueset=oldcs; @@ -1373,21 +1373,21 @@ public class BuildFlat { FlatBackEdge backedge=new FlatBackEdge(); if (body.getEnd()!=null) - body.getEnd().addNext(condition.getBegin()); + body.getEnd().addNext(condition.getBegin()); condition.getEnd().addNext(fcb); fcb.addFalseNext(nopend); fcb.addTrueNext(backedge); backedge.addNext(body.getBegin()); for(Iterator contit=continueset.iterator(); contit.hasNext(); ) { - FlatNode fn=(FlatNode)contit.next(); - contit.remove(); - fn.addNext(condition.getBegin()); + FlatNode fn=(FlatNode)contit.next(); + contit.remove(); + fn.addNext(condition.getBegin()); } for(Iterator breakit=breakset.iterator(); breakit.hasNext(); ) { - FlatNode fn=(FlatNode)breakit.next(); - breakit.remove(); - fn.addNext(nopend); + FlatNode fn=(FlatNode)breakit.next(); + breakit.remove(); + fn.addNext(nopend); } breakset=oldbs; continueset=oldcs; @@ -1411,13 +1411,13 @@ public class BuildFlat { FlatNode end = null; MethodDescriptor memdex=(MethodDescriptor)typeutil.getClass("Object").getMethodTable().get("MonitorExit"); for(int j = this.lockStack.size(); j > 0; j--) { - TempDescriptor thistd = this.lockStack.elementAt(j-1); - FlatCall fcunlock = new FlatCall(memdex, null, thistd, new TempDescriptor[0]); - fcunlock.setNumLine(rntree.getNumLine()); - if(end != null) { - end.addNext(fcunlock); - } - end = fcunlock; + TempDescriptor thistd = this.lockStack.elementAt(j-1); + FlatCall fcunlock = new FlatCall(memdex, null, thistd, new TempDescriptor[0]); + fcunlock.setNumLine(rntree.getNumLine()); + if(end != null) { + end.addNext(fcunlock); + } + end = fcunlock; } end.addNext(ln); ln=end; @@ -1459,13 +1459,13 @@ public class BuildFlat { TempDescriptor[] temps=new TempDescriptor[cc.numArgs()]; String[] vars=new String[cc.numArgs()]; for(int j=0; j"+temp+";"); - } else { - output.println(" "+type+" "+temp+";"); - } + if( fsen.getReadyInVarSet().contains(temp) ) { + output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";"); + } else { + output.println(" "+type+" "+temp+";"); + } } } @@ -559,7 +559,7 @@ public class BuildOoOJavaCode extends BuildCode { TempDescriptor temp = itrOutSet.next(); TypeDescriptor type = temp.getType(); if( !type.isPtr() && !fsen.getInVarSet().contains(temp) ) { - output.println(" "+type+" "+temp+";"); + output.println(" "+type+" "+temp+";"); } } @@ -583,10 +583,10 @@ public class BuildOoOJavaCode extends BuildCode { Set lockSet = oooa.getLockMappings(graph); System.out.println("#lockSet="+lockSet); if( lockSet.size() > 0 ) { - output.println(" numMemoryQueue=" + lockSet.size() + ";"); - output.println(" runningSESE->numMemoryQueue=numMemoryQueue;"); - output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);"); - output.println(); + output.println(" numMemoryQueue=" + lockSet.size() + ";"); + output.println(" runningSESE->numMemoryQueue=numMemoryQueue;"); + output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);"); + output.println(); } output.println(" }"); } @@ -605,8 +605,8 @@ public class BuildOoOJavaCode extends BuildCode { output.println(" runningSESE->taskRecordMemPool = poolcreate( "+ maxTaskRecSizeStr+", freshTaskRecordInitializer );"); if (state.RCR && !rcr.hasEmptyTraversers(fsen)) { - output.println(" createTR();"); - output.println(" runningSESE->allHashStructures=TRqueue->allHashStructures;"); + output.println(" createTR();"); + output.println(" runningSESE->allHashStructures=TRqueue->allHashStructures;"); } } else { // make it clear we purposefully did not initialize this @@ -654,11 +654,11 @@ public class BuildOoOJavaCode extends BuildCode { String typeStr; if( type.isNull() ) { - typeStr = "void*"; + typeStr = "void*"; } else if( type.isClass() || type.isArray() ) { - typeStr = "struct "+type.getSafeSymbol()+"*"; + typeStr = "struct "+type.getSafeSymbol()+"*"; } else { - typeStr = type.getSafeSymbol(); + typeStr = type.getSafeSymbol(); } output.println(" "+generateTemp(fsen.getfmBogus(), temp)+ @@ -734,7 +734,7 @@ public class BuildOoOJavaCode extends BuildCode { outmethod.println(" "+fsen.getSESEmethodName()+"( seseRecord );"); if( fsen.getIsMainSESE() ) { - outmethod.println(" workScheduleExit();"); + outmethod.println(" workScheduleExit();"); } outmethod.println(" break;"); @@ -780,11 +780,11 @@ public class BuildOoOJavaCode extends BuildCode { for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) { WaitingElement waitingElement =(WaitingElement) iterator.next(); if (waitingElement.getStatus() >= ConflictNode.COARSE) { - output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray[" - + waitingElement.getQueueID() + "]," + waitingElement.getStatus() - + ", (SESEcommon *) stallrecord, 1LL);"); + output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray[" + + waitingElement.getQueueID() + "]," + waitingElement.getStatus() + + ", (SESEcommon *) stallrecord, 1LL);"); } else { - throw new Error("Fine-grained conflict: This should not happen in RCR"); + throw new Error("Fine-grained conflict: This should not happen in RCR"); } output.println(" rentry->queue=runningSESE->memoryQueueArray[" + waitingElement.getQueueID() + "];"); @@ -798,9 +798,9 @@ public class BuildOoOJavaCode extends BuildCode { "]->rentrypool, rentry);"); output.println("#endif"); if (stalltd==null) { - stalltd=waitingElement.getTempDesc(); + stalltd=waitingElement.getTempDesc(); } else if (stalltd!=waitingElement.getTempDesc()) { - throw new Error("Multiple temp descriptors at stall site"+stalltd+"!="+waitingElement.getTempDesc()); + throw new Error("Multiple temp descriptors at stall site"+stalltd+"!="+waitingElement.getTempDesc()); } } @@ -861,16 +861,16 @@ public class BuildOoOJavaCode extends BuildCode { FlatMethod fmContext; if( currentSESE.getIsCallerProxySESE() ) { - fmContext = oooa.getContainingFlatMethod(fn); + fmContext = oooa.getContainingFlatMethod(fn); } else { - fmContext = currentSESE.getfmBogus(); + fmContext = currentSESE.getfmBogus(); } ContextTaskNames contextTaskNames; if( currentSESE.getIsCallerProxySESE() ) { - contextTaskNames = oooa.getContextTaskNames(oooa.getContainingFlatMethod(fn) ); + contextTaskNames = oooa.getContextTaskNames(oooa.getContainingFlatMethod(fn) ); } else { - contextTaskNames = oooa.getContextTaskNames(currentSESE); + contextTaskNames = oooa.getContextTaskNames(currentSESE); } // for each sese and age pair that this parent statement @@ -878,147 +878,147 @@ public class BuildOoOJavaCode extends BuildCode { // copying of values comes after the statement Iterator vstItr = cp.getStallTokens().iterator(); while( vstItr.hasNext() ) { - VariableSourceToken vst = vstItr.next(); - - SESEandAgePair pair = new SESEandAgePair(vst.getSESE(), vst.getAge() ); - - output.println(" {"); - output.println(" "+ - pair.getSESE().getSESErecordName()+"* child = ("+ - pair.getSESE().getSESErecordName()+"*) "+pair+";"); - - output.println(" SESEcommon* childCom = (SESEcommon*) "+pair+";"); - - if( state.COREPROF ) { - output.println("#ifdef CP_EVENTID_TASKSTALLVAR"); - output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );"); - output.println("#endif"); - } - - output.println(" pthread_mutex_lock( &(childCom->lock) );"); - output.println(" if( childCom->doneExecuting == FALSE ) {"); - output.println(" psem_reset( &runningSESEstallSem );"); - output.println(" childCom->parentsStallSem = &runningSESEstallSem;"); - output.println(" pthread_mutex_unlock( &(childCom->lock) );"); - output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );"); - output.println(" } else {"); - output.println(" pthread_mutex_unlock( &(childCom->lock) );"); - output.println(" }"); - - // copy things we might have stalled for - Iterator tdItr = cp.getCopySet(vst).iterator(); - while( tdItr.hasNext() ) { - TempDescriptor td = tdItr.next(); - output.println(" "+generateTemp(fmContext, td)+ - " = child->"+vst.getAddrVar().getSafeSymbol()+";"); - } - - if( state.COREPROF ) { - output.println("#ifdef CP_EVENTID_TASKSTALLVAR"); - output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );"); - output.println("#endif"); - } - - output.println(" }"); + VariableSourceToken vst = vstItr.next(); + + SESEandAgePair pair = new SESEandAgePair(vst.getSESE(), vst.getAge() ); + + output.println(" {"); + output.println(" "+ + pair.getSESE().getSESErecordName()+"* child = ("+ + pair.getSESE().getSESErecordName()+"*) "+pair+";"); + + output.println(" SESEcommon* childCom = (SESEcommon*) "+pair+";"); + + if( state.COREPROF ) { + output.println("#ifdef CP_EVENTID_TASKSTALLVAR"); + output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );"); + output.println("#endif"); + } + + output.println(" pthread_mutex_lock( &(childCom->lock) );"); + output.println(" if( childCom->doneExecuting == FALSE ) {"); + output.println(" psem_reset( &runningSESEstallSem );"); + output.println(" childCom->parentsStallSem = &runningSESEstallSem;"); + output.println(" pthread_mutex_unlock( &(childCom->lock) );"); + output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );"); + output.println(" } else {"); + output.println(" pthread_mutex_unlock( &(childCom->lock) );"); + output.println(" }"); + + // copy things we might have stalled for + Iterator tdItr = cp.getCopySet(vst).iterator(); + while( tdItr.hasNext() ) { + TempDescriptor td = tdItr.next(); + output.println(" "+generateTemp(fmContext, td)+ + " = child->"+vst.getAddrVar().getSafeSymbol()+";"); + } + + if( state.COREPROF ) { + output.println("#ifdef CP_EVENTID_TASKSTALLVAR"); + output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );"); + output.println("#endif"); + } + + output.println(" }"); } // for each variable with a dynamic source, stall just for that variable Iterator dynItr = cp.getDynamicStallSet().iterator(); while( dynItr.hasNext() ) { - TempDescriptor dynVar = dynItr.next(); - - // only stall if the dynamic source is not yourself, denoted by src==NULL - // otherwise the dynamic write nodes will have the local var up-to-date - output.println(" {"); - output.println(" if( "+dynVar+"_srcSESE != NULL ) {"); - - output.println(" SESEcommon* childCom = (SESEcommon*) "+dynVar+"_srcSESE;"); - - if( state.COREPROF ) { - output.println("#ifdef CP_EVENTID_TASKSTALLVAR"); - output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );"); - output.println("#endif"); - } - - output.println(" pthread_mutex_lock( &(childCom->lock) );"); - output.println(" if( childCom->doneExecuting == FALSE ) {"); - output.println(" psem_reset( &runningSESEstallSem );"); - output.println(" childCom->parentsStallSem = &runningSESEstallSem;"); - output.println(" pthread_mutex_unlock( &(childCom->lock) );"); - output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );"); - output.println(" } else {"); - output.println(" pthread_mutex_unlock( &(childCom->lock) );"); - output.println(" }"); - - TypeDescriptor type = dynVar.getType(); - String typeStr; - if( type.isNull() ) { - typeStr = "void*"; - } else if( type.isClass() || type.isArray() ) { - typeStr = "struct "+type.getSafeSymbol()+"*"; - } else { - typeStr = type.getSafeSymbol(); - } - - output.println(" "+generateTemp(fmContext, dynVar)+ - " = *(("+typeStr+"*) ((void*)"+ - dynVar+"_srcSESE + "+dynVar+"_srcOffset));"); - - if( state.COREPROF ) { - output.println("#ifdef CP_EVENTID_TASKSTALLVAR"); - output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );"); - output.println("#endif"); - } - - output.println(" }"); - output.println(" }"); + TempDescriptor dynVar = dynItr.next(); + + // only stall if the dynamic source is not yourself, denoted by src==NULL + // otherwise the dynamic write nodes will have the local var up-to-date + output.println(" {"); + output.println(" if( "+dynVar+"_srcSESE != NULL ) {"); + + output.println(" SESEcommon* childCom = (SESEcommon*) "+dynVar+"_srcSESE;"); + + if( state.COREPROF ) { + output.println("#ifdef CP_EVENTID_TASKSTALLVAR"); + output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );"); + output.println("#endif"); + } + + output.println(" pthread_mutex_lock( &(childCom->lock) );"); + output.println(" if( childCom->doneExecuting == FALSE ) {"); + output.println(" psem_reset( &runningSESEstallSem );"); + output.println(" childCom->parentsStallSem = &runningSESEstallSem;"); + output.println(" pthread_mutex_unlock( &(childCom->lock) );"); + output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );"); + output.println(" } else {"); + output.println(" pthread_mutex_unlock( &(childCom->lock) );"); + output.println(" }"); + + TypeDescriptor type = dynVar.getType(); + String typeStr; + if( type.isNull() ) { + typeStr = "void*"; + } else if( type.isClass() || type.isArray() ) { + typeStr = "struct "+type.getSafeSymbol()+"*"; + } else { + typeStr = type.getSafeSymbol(); + } + + output.println(" "+generateTemp(fmContext, dynVar)+ + " = *(("+typeStr+"*) ((void*)"+ + dynVar+"_srcSESE + "+dynVar+"_srcOffset));"); + + if( state.COREPROF ) { + output.println("#ifdef CP_EVENTID_TASKSTALLVAR"); + output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );"); + output.println("#endif"); + } + + output.println(" }"); + output.println(" }"); } // for each assignment of a variable to rhs that has a dynamic source, // copy the dynamic sources Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator(); while( dynAssignItr.hasNext() ) { - Map.Entry me = (Map.Entry)dynAssignItr.next(); - TempDescriptor lhs = (TempDescriptor) me.getKey(); - TempDescriptor rhs = (TempDescriptor) me.getValue(); - - output.println(" {"); - output.println(" SESEcommon* oldSrc = "+lhs+"_srcSESE;"); - - output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;"); - output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;"); - - // no matter what we did above, track reference count of whatever - // this variable pointed to, do release last in case we're just - // copying the same value in because 1->2->1 is safe but ref count - // 1->0->1 has a window where it looks like it should be free'd - output.println("#ifndef OOO_DISABLE_TASKMEMPOOL"); - output.println(" if( "+rhs+"_srcSESE != NULL ) {"); - output.println(" ADD_REFERENCE_TO( "+rhs+"_srcSESE );"); - output.println(" }"); - output.println(" if( oldSrc != NULL ) {"); - output.println(" RELEASE_REFERENCE_TO( oldSrc );"); - output.println(" }"); - output.println(" }"); - output.println("#endif // OOO_DISABLE_TASKMEMPOOL"); + Map.Entry me = (Map.Entry)dynAssignItr.next(); + TempDescriptor lhs = (TempDescriptor) me.getKey(); + TempDescriptor rhs = (TempDescriptor) me.getValue(); + + output.println(" {"); + output.println(" SESEcommon* oldSrc = "+lhs+"_srcSESE;"); + + output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;"); + output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;"); + + // no matter what we did above, track reference count of whatever + // this variable pointed to, do release last in case we're just + // copying the same value in because 1->2->1 is safe but ref count + // 1->0->1 has a window where it looks like it should be free'd + output.println("#ifndef OOO_DISABLE_TASKMEMPOOL"); + output.println(" if( "+rhs+"_srcSESE != NULL ) {"); + output.println(" ADD_REFERENCE_TO( "+rhs+"_srcSESE );"); + output.println(" }"); + output.println(" if( oldSrc != NULL ) {"); + output.println(" RELEASE_REFERENCE_TO( oldSrc );"); + output.println(" }"); + output.println(" }"); + output.println("#endif // OOO_DISABLE_TASKMEMPOOL"); } // for each lhs that is dynamic from a non-dynamic source, set the // dynamic source vars to the current SESE dynItr = cp.getDynAssignCurr().iterator(); while( dynItr.hasNext() ) { - TempDescriptor dynVar = dynItr.next(); + TempDescriptor dynVar = dynItr.next(); - assert contextTaskNames.getDynamicVarSet().contains(dynVar); + assert contextTaskNames.getDynamicVarSet().contains(dynVar); - // first release a reference to current record - output.println("#ifndef OOO_DISABLE_TASKMEMPOOL"); - output.println(" if( "+dynVar+"_srcSESE != NULL ) {"); - output.println(" RELEASE_REFERENCE_TO( oldSrc );"); - output.println(" }"); - output.println("#endif // OOO_DISABLE_TASKMEMPOOL"); + // first release a reference to current record + output.println("#ifndef OOO_DISABLE_TASKMEMPOOL"); + output.println(" if( "+dynVar+"_srcSESE != NULL ) {"); + output.println(" RELEASE_REFERENCE_TO( oldSrc );"); + output.println(" }"); + output.println("#endif // OOO_DISABLE_TASKMEMPOOL"); - output.println(" "+dynVar+"_srcSESE = NULL;"); + output.println(" "+dynVar+"_srcSESE = NULL;"); } @@ -1033,78 +1033,78 @@ public class BuildOoOJavaCode extends BuildCode { // create a case for each class of task that might be executing Iterator taskItr = oooa.getPossibleExecutingRBlocks(fn).iterator(); while( taskItr.hasNext() ) { - FlatSESEEnterNode parent = taskItr.next(); - ConflictGraph graph = oooa.getConflictGraph(parent); - - if( graph == null ) { - continue; - } - - Set seseLockSet = oooa.getLockMappings(graph); - Set waitingElementSet = graph.getStallSiteWaitingElementSet(fn, seseLockSet); - - if( waitingElementSet.size() == 0 ) { - continue; - } - - // TODO: THIS STRATEGY CAN BE OPTIMIZED EVEN FURTHER, IF THERE - // IS EXACTLY ONE CASE, DON'T GENERATE A SWITCH AT ALL - if( atLeastOneCase == false ) { - atLeastOneCase = true; - output.println(" // potential stall site "); - output.println(" switch( runningSESE->classID ) {"); - } - - output.println(" case "+parent.getIdentifier()+": {"); - - if( state.RCR ) { - stallMEMRCR(fm, fn, waitingElementSet, output); - } else { - - output.println(" REntry* rentry;"); - - for( Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) { - WaitingElement waitingElement = (WaitingElement) iterator.next(); - - if (waitingElement.getStatus() >= ConflictNode.COARSE) { - output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray[" - + waitingElement.getQueueID() + "]," + waitingElement.getStatus() - + ", runningSESE);"); - } else { - output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray[" - + waitingElement.getQueueID() + "]," + waitingElement.getStatus() - + ", runningSESE, (void*)&" - + generateTemp(fm, waitingElement.getTempDesc()) + ");"); - } - output.println(" rentry->parentStallSem=&runningSESEstallSem;"); - output.println(" psem_reset( &runningSESEstallSem);"); - output.println(" rentry->tag=runningSESEstallSem.tag;"); - output.println(" rentry->queue=runningSESE->memoryQueueArray[" - + waitingElement.getQueueID() + "];"); - output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray[" - + waitingElement.getQueueID() + "],rentry)==NOTREADY){"); - if (state.COREPROF) { - output.println("#ifdef CP_EVENTID_TASKSTALLMEM"); - output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );"); - output.println("#endif"); - } - - output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );"); - - if (state.COREPROF) { - output.println("#ifdef CP_EVENTID_TASKSTALLMEM"); - output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );"); - output.println("#endif"); - } - output.println(" } "); - } - - } - output.println(" } break; // end case "+parent.getIdentifier()); + FlatSESEEnterNode parent = taskItr.next(); + ConflictGraph graph = oooa.getConflictGraph(parent); + + if( graph == null ) { + continue; + } + + Set seseLockSet = oooa.getLockMappings(graph); + Set waitingElementSet = graph.getStallSiteWaitingElementSet(fn, seseLockSet); + + if( waitingElementSet.size() == 0 ) { + continue; + } + + // TODO: THIS STRATEGY CAN BE OPTIMIZED EVEN FURTHER, IF THERE + // IS EXACTLY ONE CASE, DON'T GENERATE A SWITCH AT ALL + if( atLeastOneCase == false ) { + atLeastOneCase = true; + output.println(" // potential stall site "); + output.println(" switch( runningSESE->classID ) {"); + } + + output.println(" case "+parent.getIdentifier()+": {"); + + if( state.RCR ) { + stallMEMRCR(fm, fn, waitingElementSet, output); + } else { + + output.println(" REntry* rentry;"); + + for( Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) { + WaitingElement waitingElement = (WaitingElement) iterator.next(); + + if (waitingElement.getStatus() >= ConflictNode.COARSE) { + output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray[" + + waitingElement.getQueueID() + "]," + waitingElement.getStatus() + + ", runningSESE);"); + } else { + output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray[" + + waitingElement.getQueueID() + "]," + waitingElement.getStatus() + + ", runningSESE, (void*)&" + + generateTemp(fm, waitingElement.getTempDesc()) + ");"); + } + output.println(" rentry->parentStallSem=&runningSESEstallSem;"); + output.println(" psem_reset( &runningSESEstallSem);"); + output.println(" rentry->tag=runningSESEstallSem.tag;"); + output.println(" rentry->queue=runningSESE->memoryQueueArray[" + + waitingElement.getQueueID() + "];"); + output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray[" + + waitingElement.getQueueID() + "],rentry)==NOTREADY){"); + if (state.COREPROF) { + output.println("#ifdef CP_EVENTID_TASKSTALLMEM"); + output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );"); + output.println("#endif"); + } + + output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );"); + + if (state.COREPROF) { + output.println("#ifdef CP_EVENTID_TASKSTALLMEM"); + output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );"); + output.println("#endif"); + } + output.println(" } "); + } + + } + output.println(" } break; // end case "+parent.getIdentifier()); } if( atLeastOneCase ) { - output.println(" } // end stall site switch"); + output.println(" } // end stall site switch"); } } } @@ -1230,9 +1230,9 @@ public class BuildOoOJavaCode extends BuildCode { // if we're using RCR, ref count is 3 because the traverser has // a reference, too if( !fsen.getIsMainSESE() && fsen.getInVarsForDynamicCoarseConflictResolution().size()>0) { - output.println(" seseToIssue->common.refCount = 10003;"); + output.println(" seseToIssue->common.refCount = 10003;"); } else { - output.println(" seseToIssue->common.refCount = 10002;"); + output.println(" seseToIssue->common.refCount = 10002;"); } output.println(" int refCount=10000;"); } else { @@ -1249,11 +1249,11 @@ public class BuildOoOJavaCode extends BuildCode { assert !fsen.getIsCallerProxySESE(); FlatSESEEnterNode parent = fsen.getLocalParent(); if( parent != null && !parent.getIsCallerProxySESE() ) { - output.println(" seseToIssue->"+temp+" = "+ - generateTemp(parent.getfmBogus(), temp)+";"); + output.println(" seseToIssue->"+temp+" = "+ + generateTemp(parent.getfmBogus(), temp)+";"); } else { - output.println(" seseToIssue->"+temp+" = "+ - generateTemp(fsen.getfmEnclosing(), temp)+";"); + output.println(" seseToIssue->"+temp+" = "+ + generateTemp(fsen.getfmEnclosing(), temp)+";"); } } @@ -1267,77 +1267,77 @@ public class BuildOoOJavaCode extends BuildCode { // count up outstanding dependencies, static first, then dynamic Iterator staticSrcsItr = fsen.getStaticInVarSrcs().iterator(); while( staticSrcsItr.hasNext() ) { - SESEandAgePair srcPair = staticSrcsItr.next(); - output.println(" {"); - output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";"); - output.println(" pthread_mutex_lock( &(src->lock) );"); - // FORWARD TODO - ...what? make it a chain of arrays instead of true linked-list? - output.println(" if( !src->doneExecuting ) {"); - output.println(" addNewItem( &src->forwardList, seseToIssue );"); - output.println(" ++(localCount);"); - output.println(" }"); - output.println("#ifndef OOO_DISABLE_TASKMEMPOOL"); - output.println(" ADD_REFERENCE_TO( src );"); - output.println("#endif"); - output.println(" pthread_mutex_unlock( &(src->lock) );"); - output.println(" }"); - - // whether or not it is an outstanding dependency, make sure - // to pass the static name to the child's record - output.println(" seseToIssue->"+srcPair+" = "+ - "("+srcPair.getSESE().getSESErecordName()+"*)"+ - srcPair+";"); + SESEandAgePair srcPair = staticSrcsItr.next(); + output.println(" {"); + output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";"); + output.println(" pthread_mutex_lock( &(src->lock) );"); + // FORWARD TODO - ...what? make it a chain of arrays instead of true linked-list? + output.println(" if( !src->doneExecuting ) {"); + output.println(" addNewItem( &src->forwardList, seseToIssue );"); + output.println(" ++(localCount);"); + output.println(" }"); + output.println("#ifndef OOO_DISABLE_TASKMEMPOOL"); + output.println(" ADD_REFERENCE_TO( src );"); + output.println("#endif"); + output.println(" pthread_mutex_unlock( &(src->lock) );"); + output.println(" }"); + + // whether or not it is an outstanding dependency, make sure + // to pass the static name to the child's record + output.println(" seseToIssue->"+srcPair+" = "+ + "("+srcPair.getSESE().getSESErecordName()+"*)"+ + srcPair+";"); } // dynamic sources might already be accounted for in the static list, // so only add them to forwarding lists if they're not already there Iterator dynVarsItr = fsen.getDynamicInVarSet().iterator(); while( dynVarsItr.hasNext() ) { - TempDescriptor dynInVar = dynVarsItr.next(); - output.println(" {"); - output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;"); - - // the dynamic source is NULL if it comes from your own space--you can't pass - // the address off to the new child, because you're not done executing and - // might change the variable, so copy it right now - output.println(" if( src != NULL ) {"); - output.println(" pthread_mutex_lock( &(src->lock) );"); - - // FORWARD TODO - - output.println(" if( isEmpty( &src->forwardList ) ||"); - output.println(" seseToIssue != peekItem( &src->forwardList ) ) {"); - output.println(" if( !src->doneExecuting ) {"); - output.println(" addNewItem( &src->forwardList, seseToIssue );"); - output.println(" ++(localCount);"); - output.println(" }"); - output.println(" }"); - output.println("#ifndef OOO_DISABLE_TASKMEMPOOL"); - output.println(" ADD_REFERENCE_TO( src );"); - output.println("#endif"); - output.println(" pthread_mutex_unlock( &(src->lock) );"); - output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;"); - output.println(" } else {"); - - - // determine whether this new task instance is in a method context, - // or within the body of another task - assert !fsen.getIsCallerProxySESE(); - FlatSESEEnterNode parent = fsen.getLocalParent(); - if( parent != null && !parent.getIsCallerProxySESE() ) { - output.println(" seseToIssue->"+dynInVar+" = "+ - generateTemp(parent.getfmBogus(), dynInVar)+";"); - } else { - output.println(" seseToIssue->"+dynInVar+" = "+ - generateTemp(fsen.getfmEnclosing(), dynInVar)+";"); - } - - output.println(" }"); - output.println(" }"); - - // even if the value is already copied, make sure your NULL source - // gets passed so child knows it already has the dynamic value - output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;"); + TempDescriptor dynInVar = dynVarsItr.next(); + output.println(" {"); + output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;"); + + // the dynamic source is NULL if it comes from your own space--you can't pass + // the address off to the new child, because you're not done executing and + // might change the variable, so copy it right now + output.println(" if( src != NULL ) {"); + output.println(" pthread_mutex_lock( &(src->lock) );"); + + // FORWARD TODO + + output.println(" if( isEmpty( &src->forwardList ) ||"); + output.println(" seseToIssue != peekItem( &src->forwardList ) ) {"); + output.println(" if( !src->doneExecuting ) {"); + output.println(" addNewItem( &src->forwardList, seseToIssue );"); + output.println(" ++(localCount);"); + output.println(" }"); + output.println(" }"); + output.println("#ifndef OOO_DISABLE_TASKMEMPOOL"); + output.println(" ADD_REFERENCE_TO( src );"); + output.println("#endif"); + output.println(" pthread_mutex_unlock( &(src->lock) );"); + output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;"); + output.println(" } else {"); + + + // determine whether this new task instance is in a method context, + // or within the body of another task + assert !fsen.getIsCallerProxySESE(); + FlatSESEEnterNode parent = fsen.getLocalParent(); + if( parent != null && !parent.getIsCallerProxySESE() ) { + output.println(" seseToIssue->"+dynInVar+" = "+ + generateTemp(parent.getfmBogus(), dynInVar)+";"); + } else { + output.println(" seseToIssue->"+dynInVar+" = "+ + generateTemp(fsen.getfmEnclosing(), dynInVar)+";"); + } + + output.println(" }"); + output.println(" }"); + + // even if the value is already copied, make sure your NULL source + // gets passed so child knows it already has the dynamic value + output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;"); } @@ -1346,40 +1346,40 @@ public class BuildOoOJavaCode extends BuildCode { // and also release references that have become too old if( !fsen.getIsMainSESE() ) { - FlatSESEEnterNode currentSESE = fsen.getLocalParent(); - - ContextTaskNames contextTaskNames; - if( currentSESE == null ) { - contextTaskNames = oooa.getContextTaskNames(oooa.getContainingFlatMethod(fsen) ); - } else { - contextTaskNames = oooa.getContextTaskNames(currentSESE); - } - - SESEandAgePair pairNewest = new SESEandAgePair(fsen, 0); - SESEandAgePair pairOldest = new SESEandAgePair(fsen, fsen.getOldestAgeToTrack() ); - if( contextTaskNames.getNeededStaticNames().contains(pairNewest) ) { - output.println(" {"); - output.println("#ifndef OOO_DISABLE_TASKMEMPOOL"); - output.println(" SESEcommon* oldest = "+pairOldest+";"); - output.println("#endif // OOO_DISABLE_TASKMEMPOOL"); - - for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) { - SESEandAgePair pair1 = new SESEandAgePair(fsen, i); - SESEandAgePair pair2 = new SESEandAgePair(fsen, i-1); - output.println(" "+pair1+" = "+pair2+";"); - } - output.println(" "+pairNewest+" = &(seseToIssue->common);"); - - // no need to add a reference to whatever is the newest record, because - // we initialized seseToIssue->refCount to *2* - // but release a reference to whatever was the oldest BEFORE the shift - output.println("#ifndef OOO_DISABLE_TASKMEMPOOL"); - output.println(" if( oldest != NULL ) {"); - output.println(" RELEASE_REFERENCE_TO( oldest );"); - output.println(" }"); - output.println("#endif // OOO_DISABLE_TASKMEMPOOL"); - output.println(" }"); - } + FlatSESEEnterNode currentSESE = fsen.getLocalParent(); + + ContextTaskNames contextTaskNames; + if( currentSESE == null ) { + contextTaskNames = oooa.getContextTaskNames(oooa.getContainingFlatMethod(fsen) ); + } else { + contextTaskNames = oooa.getContextTaskNames(currentSESE); + } + + SESEandAgePair pairNewest = new SESEandAgePair(fsen, 0); + SESEandAgePair pairOldest = new SESEandAgePair(fsen, fsen.getOldestAgeToTrack() ); + if( contextTaskNames.getNeededStaticNames().contains(pairNewest) ) { + output.println(" {"); + output.println("#ifndef OOO_DISABLE_TASKMEMPOOL"); + output.println(" SESEcommon* oldest = "+pairOldest+";"); + output.println("#endif // OOO_DISABLE_TASKMEMPOOL"); + + for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) { + SESEandAgePair pair1 = new SESEandAgePair(fsen, i); + SESEandAgePair pair2 = new SESEandAgePair(fsen, i-1); + output.println(" "+pair1+" = "+pair2+";"); + } + output.println(" "+pairNewest+" = &(seseToIssue->common);"); + + // no need to add a reference to whatever is the newest record, because + // we initialized seseToIssue->refCount to *2* + // but release a reference to whatever was the oldest BEFORE the shift + output.println("#ifndef OOO_DISABLE_TASKMEMPOOL"); + output.println(" if( oldest != NULL ) {"); + output.println(" RELEASE_REFERENCE_TO( oldest );"); + output.println(" }"); + output.println("#endif // OOO_DISABLE_TASKMEMPOOL"); + output.println(" }"); + } } } @@ -1390,148 +1390,148 @@ public class BuildOoOJavaCode extends BuildCode { if( !fsen.getIsMainSESE() ) { if( state.COREPROF ) { - output.println("#ifdef CP_EVENTID_PREPAREMEMQ"); - output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_BEGIN );"); - output.println("#endif"); + output.println("#ifdef CP_EVENTID_PREPAREMEMQ"); + output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_BEGIN );"); + output.println("#endif"); } if(state.RCR) { - dispatchMEMRC(fm, fsen, output); + dispatchMEMRC(fm, fsen, output); } else { - // there may be several task types that can get to this - // program point (issue this new task) so create a switch - // based on task ID, each type of task has a different index - // scheme for its memory queue's, and the cases here drop the - // new task instance in the right bucket - boolean atLeastOneCase = false; - - // create a case for each class of task that might be executing - Iterator taskItr = oooa.getPossibleExecutingRBlocks(fsen).iterator(); - while( taskItr.hasNext() ) { - FlatSESEEnterNode parent = taskItr.next(); - ConflictGraph graph = oooa.getConflictGraph(parent); - - if( graph == null || !graph.hasConflictEdge() ) { - continue; - } - - Set seseLockSet = oooa.getLockMappings(graph); - - SESEWaitingQueue seseWaitingQueue = - graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet); - - if( seseWaitingQueue.getWaitingElementSize() == 0 ) { - continue; - } - - if( atLeastOneCase == false ) { - atLeastOneCase = true; - output.println(" // add new task instance to current task's memory queues if needed "); - output.println(" switch( runningSESE->classID ) {"); - } - - output.println(" case "+parent.getIdentifier()+": {"); - output.println(" REntry* rentry=NULL;"); - output.println(" INTPTR* pointer=NULL;"); - output.println(" seseToIssue->common.rentryIdx=0;"); - - Set queueIDSet=seseWaitingQueue.getQueueIDSet(); - for (Iterator iterator = queueIDSet.iterator(); iterator.hasNext(); ) { - Integer key = (Integer) iterator.next(); - int queueID=key.intValue(); - Set waitingQueueSet = - seseWaitingQueue.getWaitingElementSet(queueID); - int enqueueType=seseWaitingQueue.getType(queueID); - if(enqueueType==SESEWaitingQueue.EXCEPTION) { - output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray[" + queueID+ "]);"); - } - for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext(); ) { - WaitingElement waitingElement - = (WaitingElement) iterator2.next(); - if (waitingElement.getStatus() >= ConflictNode.COARSE) { - output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ queueID+ "]," - + waitingElement.getStatus() - + ", &(seseToIssue->common));"); - } else { - TempDescriptor td = waitingElement.getTempDesc(); - // decide whether waiting element is dynamic or static - if (fsen.getDynamicInVarSet().contains(td)) { - // dynamic in-var case - output.println(" pointer=seseToIssue->" - + waitingElement.getDynID() - + "_srcSESE+seseToIssue->" - + waitingElement.getDynID() - + "_srcOffset;"); - output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "]," - + waitingElement.getStatus() - + ", &(seseToIssue->common), pointer );"); - } else if (fsen.getStaticInVarSet().contains(td)) { - // static in-var case - VariableSourceToken vst = fsen.getStaticInVarSrc(td); - if (vst != null) { - - String srcId = "SESE_" + vst.getSESE().getPrettyIdentifier() - + vst.getSESE().getIdentifier() - + "_" + vst.getAge(); - output.println(" pointer=(void*)&seseToIssue->" - + srcId - + "->" - + waitingElement - .getDynID() - + ";"); - output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "]," - + waitingElement.getStatus() - + ", &(seseToIssue->common), pointer );"); - } - } else { - output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "]," - + waitingElement.getStatus() - + ", &(seseToIssue->common), (void*)&seseToIssue->" - + waitingElement.getDynID() - + ");"); - } - } - output.println(" rentry->queue=runningSESE->memoryQueueArray[" - + waitingElement.getQueueID() - + "];"); - - if(enqueueType==SESEWaitingQueue.NORMAL) { - output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;"); - output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray[" - + waitingElement.getQueueID() - + "],rentry)==NOTREADY) {"); - output.println(" localCount++;"); - output.println(" }"); - } else { - output.println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray[" + waitingElement.getQueueID() + "],rentry);"); - } - } - if(enqueueType!=SESEWaitingQueue.NORMAL) { - output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray[" - + queueID+ "],&seseToIssue->common);"); - } - } - output.println(" } break; // end case "+parent.getIdentifier()); - output.println(); - } - - if( atLeastOneCase ) { - output.println(" } // end stall site switch"); - } + // there may be several task types that can get to this + // program point (issue this new task) so create a switch + // based on task ID, each type of task has a different index + // scheme for its memory queue's, and the cases here drop the + // new task instance in the right bucket + boolean atLeastOneCase = false; + + // create a case for each class of task that might be executing + Iterator taskItr = oooa.getPossibleExecutingRBlocks(fsen).iterator(); + while( taskItr.hasNext() ) { + FlatSESEEnterNode parent = taskItr.next(); + ConflictGraph graph = oooa.getConflictGraph(parent); + + if( graph == null || !graph.hasConflictEdge() ) { + continue; + } + + Set seseLockSet = oooa.getLockMappings(graph); + + SESEWaitingQueue seseWaitingQueue = + graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet); + + if( seseWaitingQueue.getWaitingElementSize() == 0 ) { + continue; + } + + if( atLeastOneCase == false ) { + atLeastOneCase = true; + output.println(" // add new task instance to current task's memory queues if needed "); + output.println(" switch( runningSESE->classID ) {"); + } + + output.println(" case "+parent.getIdentifier()+": {"); + output.println(" REntry* rentry=NULL;"); + output.println(" INTPTR* pointer=NULL;"); + output.println(" seseToIssue->common.rentryIdx=0;"); + + Set queueIDSet=seseWaitingQueue.getQueueIDSet(); + for (Iterator iterator = queueIDSet.iterator(); iterator.hasNext(); ) { + Integer key = (Integer) iterator.next(); + int queueID=key.intValue(); + Set waitingQueueSet = + seseWaitingQueue.getWaitingElementSet(queueID); + int enqueueType=seseWaitingQueue.getType(queueID); + if(enqueueType==SESEWaitingQueue.EXCEPTION) { + output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray[" + queueID+ "]);"); + } + for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext(); ) { + WaitingElement waitingElement + = (WaitingElement) iterator2.next(); + if (waitingElement.getStatus() >= ConflictNode.COARSE) { + output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ queueID+ "]," + + waitingElement.getStatus() + + ", &(seseToIssue->common));"); + } else { + TempDescriptor td = waitingElement.getTempDesc(); + // decide whether waiting element is dynamic or static + if (fsen.getDynamicInVarSet().contains(td)) { + // dynamic in-var case + output.println(" pointer=seseToIssue->" + + waitingElement.getDynID() + + "_srcSESE+seseToIssue->" + + waitingElement.getDynID() + + "_srcOffset;"); + output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "]," + + waitingElement.getStatus() + + ", &(seseToIssue->common), pointer );"); + } else if (fsen.getStaticInVarSet().contains(td)) { + // static in-var case + VariableSourceToken vst = fsen.getStaticInVarSrc(td); + if (vst != null) { + + String srcId = "SESE_" + vst.getSESE().getPrettyIdentifier() + + vst.getSESE().getIdentifier() + + "_" + vst.getAge(); + output.println(" pointer=(void*)&seseToIssue->" + + srcId + + "->" + + waitingElement + .getDynID() + + ";"); + output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "]," + + waitingElement.getStatus() + + ", &(seseToIssue->common), pointer );"); + } + } else { + output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "]," + + waitingElement.getStatus() + + ", &(seseToIssue->common), (void*)&seseToIssue->" + + waitingElement.getDynID() + + ");"); + } + } + output.println(" rentry->queue=runningSESE->memoryQueueArray[" + + waitingElement.getQueueID() + + "];"); + + if(enqueueType==SESEWaitingQueue.NORMAL) { + output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;"); + output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray[" + + waitingElement.getQueueID() + + "],rentry)==NOTREADY) {"); + output.println(" localCount++;"); + output.println(" }"); + } else { + output.println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray[" + waitingElement.getQueueID() + "],rentry);"); + } + } + if(enqueueType!=SESEWaitingQueue.NORMAL) { + output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray[" + + queueID+ "],&seseToIssue->common);"); + } + } + output.println(" } break; // end case "+parent.getIdentifier()); + output.println(); + } + + if( atLeastOneCase ) { + output.println(" } // end stall site switch"); + } } if( state.COREPROF ) { - output.println("#ifdef CP_EVENTID_PREPAREMEMQ"); - output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_END );"); - output.println("#endif"); + output.println("#ifdef CP_EVENTID_PREPAREMEMQ"); + output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_END );"); + output.println("#endif"); } } // Enqueue Task Record if (state.RCR) { if( fsen != oooa.getMainSESE() && fsen.getInVarsForDynamicCoarseConflictResolution().size()>0) { - output.println(" enqueueTR(TRqueue, (void *)seseToIssue);"); + output.println(" enqueueTR(TRqueue, (void *)seseToIssue);"); } } @@ -1569,127 +1569,127 @@ public class BuildOoOJavaCode extends BuildCode { ConflictGraph graph = oooa.getConflictGraph(parent); if( graph != null && graph.hasConflictEdge() ) { - Set seseLockSet = oooa.getLockMappings(graph); - SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(newChild.getIdentifier(), seseLockSet); - if(seseWaitingQueue.getWaitingElementSize()>0) { + Set seseLockSet = oooa.getLockMappings(graph); + SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(newChild.getIdentifier(), seseLockSet); + if(seseWaitingQueue.getWaitingElementSize()>0) { - output.println(" /* "+parent.getPrettyIdentifier()+" */"); - output.println(" case "+parent.getIdentifier()+": {"); + output.println(" /* "+parent.getPrettyIdentifier()+" */"); + output.println(" case "+parent.getIdentifier()+": {"); - output.println(" REntry* rentry=NULL;"); - output.println(" INTPTR* pointer=NULL;"); - output.println(" seseToIssue->common.rentryIdx=0;"); - Vector invars=newChild.getInVarsForDynamicCoarseConflictResolution(); - //System.out.println(fm.getMethod()+"["+invars+"]"); + output.println(" REntry* rentry=NULL;"); + output.println(" INTPTR* pointer=NULL;"); + output.println(" seseToIssue->common.rentryIdx=0;"); + Vector invars=newChild.getInVarsForDynamicCoarseConflictResolution(); + //System.out.println(fm.getMethod()+"["+invars+"]"); - Vector queuetovar=new Vector(); + Vector queuetovar=new Vector(); - for(int i=0; i weset=seseWaitingQueue.getWaitingElementSet(td); + for(int i=0; i weset=seseWaitingQueue.getWaitingElementSet(td); - //TODO FIX MEEEEE!!!! - //Weset is sometimes null which breaks the following code and - //we don't know what weset = null means. For now, we bail when it's null - //until we find out what to do.... + //TODO FIX MEEEEE!!!! + //Weset is sometimes null which breaks the following code and + //we don't know what weset = null means. For now, we bail when it's null + //until we find out what to do.... // if(weset == null) { // continue; // } - //UPDATE: This hack DOES NOT FIX IT!. - - - - int numqueues=0; - Set queueSet=new HashSet(); - for (Iterator iterator = weset.iterator(); iterator.hasNext(); ) { - WaitingElement we = (WaitingElement) iterator.next(); - Integer queueID=new Integer(we.getQueueID()); - if(!queueSet.contains(queueID)) { - numqueues++; - queueSet.add(queueID); - } - } - - output.println(" seseToIssue->rcrRecords["+i+"].flag="+numqueues+";"); - output.println(" seseToIssue->rcrRecords["+i+"].index=0;"); - output.println(" seseToIssue->rcrRecords["+i+"].next=NULL;"); - output.println(" int dispCount"+i+"=0;"); - - for (Iterator wtit = weset.iterator(); wtit.hasNext(); ) { - WaitingElement waitingElement = wtit.next(); - int queueID = waitingElement.getQueueID(); - if (queueID >= queuetovar.size()) - queuetovar.setSize(queueID + 1); - Long l = queuetovar.get(queueID); - long val = (l != null)?l.longValue():0; - val = val | (1 << i); - queuetovar.set(queueID, new Long(val)); - } - } - - HashSet generatedqueueentry=new HashSet(); - for(int i=0; i weset=seseWaitingQueue.getWaitingElementSet(td); - - - - //TODO FIX MEEEEE!!!! - //Weset is sometimes null which breaks the following code and - //we don't know what weset = null means. For now, we bail when it's null - //until we find out what to do.... + //UPDATE: This hack DOES NOT FIX IT!. + + + + int numqueues=0; + Set queueSet=new HashSet(); + for (Iterator iterator = weset.iterator(); iterator.hasNext(); ) { + WaitingElement we = (WaitingElement) iterator.next(); + Integer queueID=new Integer(we.getQueueID()); + if(!queueSet.contains(queueID)) { + numqueues++; + queueSet.add(queueID); + } + } + + output.println(" seseToIssue->rcrRecords["+i+"].flag="+numqueues+";"); + output.println(" seseToIssue->rcrRecords["+i+"].index=0;"); + output.println(" seseToIssue->rcrRecords["+i+"].next=NULL;"); + output.println(" int dispCount"+i+"=0;"); + + for (Iterator wtit = weset.iterator(); wtit.hasNext(); ) { + WaitingElement waitingElement = wtit.next(); + int queueID = waitingElement.getQueueID(); + if (queueID >= queuetovar.size()) + queuetovar.setSize(queueID + 1); + Long l = queuetovar.get(queueID); + long val = (l != null)?l.longValue():0; + val = val | (1 << i); + queuetovar.set(queueID, new Long(val)); + } + } + + HashSet generatedqueueentry=new HashSet(); + for(int i=0; i weset=seseWaitingQueue.getWaitingElementSet(td); + + + + //TODO FIX MEEEEE!!!! + //Weset is sometimes null which breaks the following code and + //we don't know what weset = null means. For now, we bail when it's null + //until we find out what to do.... // if(weset == null) { // continue; // } - //UPDATE: This hack DOES NOT FIX IT!. - - - - for(Iterator wtit=weset.iterator(); wtit.hasNext(); ) { - WaitingElement waitingElement=wtit.next(); - int queueID=waitingElement.getQueueID(); - - if(waitingElement.isBogus()) { - continue; - } - - if (generatedqueueentry.contains(queueID)) - continue; - else - generatedqueueentry.add(queueID); - - assert(waitingElement.getStatus()>=ConflictNode.COARSE); - long mask=queuetovar.get(queueID); - output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "]," + waitingElement.getStatus() + ", &(seseToIssue->common), "+mask+"LL);"); - output.println(" rentry->count=2;"); - output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;"); - output.println(" rentry->queue=runningSESE->memoryQueueArray[" + waitingElement.getQueueID()+"];"); - - output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],rentry)==READY) {"); - for(int j=0; mask!=0; j++) { - if ((mask&1)==1) - output.println(" dispCount"+j+"++;"); - mask=mask>>1; - } - output.println(" } else "); - output.println(" refCount--;"); - } - - if (newChild.getDynamicInVarSet().contains(td)) { - // dynamic in-var case - //output.println(" pointer=seseToIssue->"+waitingElement.getDynID()+ - // "_srcSESE+seseToIssue->"+waitingElement.getDynID()+ - // "_srcOffset;"); - //output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ - // ", &(seseToIssue->common), pointer );"); - } - } - for(int i=0; ircrRecords["+i+"].flag)))"); - output.println(" localCount++;"); - } - output.println(" } break;"); - } + //UPDATE: This hack DOES NOT FIX IT!. + + + + for(Iterator wtit=weset.iterator(); wtit.hasNext(); ) { + WaitingElement waitingElement=wtit.next(); + int queueID=waitingElement.getQueueID(); + + if(waitingElement.isBogus()) { + continue; + } + + if (generatedqueueentry.contains(queueID)) + continue; + else + generatedqueueentry.add(queueID); + + assert(waitingElement.getStatus()>=ConflictNode.COARSE); + long mask=queuetovar.get(queueID); + output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "]," + waitingElement.getStatus() + ", &(seseToIssue->common), "+mask+"LL);"); + output.println(" rentry->count=2;"); + output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;"); + output.println(" rentry->queue=runningSESE->memoryQueueArray[" + waitingElement.getQueueID()+"];"); + + output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],rentry)==READY) {"); + for(int j=0; mask!=0; j++) { + if ((mask&1)==1) + output.println(" dispCount"+j+"++;"); + mask=mask>>1; + } + output.println(" } else "); + output.println(" refCount--;"); + } + + if (newChild.getDynamicInVarSet().contains(td)) { + // dynamic in-var case + //output.println(" pointer=seseToIssue->"+waitingElement.getDynID()+ + // "_srcSESE+seseToIssue->"+waitingElement.getDynID()+ + // "_srcOffset;"); + //output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+ + // ", &(seseToIssue->common), pointer );"); + } + } + for(int i=0; ircrRecords["+i+"].flag)))"); + output.println(" localCount++;"); + } + output.println(" } break;"); + } } } @@ -1761,7 +1761,7 @@ public class BuildOoOJavaCode extends BuildCode { temp.getType().isPrimitive() && !temp.getType().isArray() ) ) { - continue; + continue; } String from = generateTemp(fsen.getfmBogus(), temp); @@ -1888,18 +1888,18 @@ public class BuildOoOJavaCode extends BuildCode { output.println(" struct Hashtable_rcr ** hashstruct=runningSESE->parent->allHashStructures;"); for (int i = 0; i < inset.size(); i++) { - output.println(" rec=&" + paramsprefix + "->rcrRecords[" + i + "];"); - output.println(" while(rec!=NULL) {"); - output.println(" for(idx2=0;idx2index;idx2++) {"); + output.println(" rec=&" + paramsprefix + "->rcrRecords[" + i + "];"); + output.println(" while(rec!=NULL) {"); + output.println(" for(idx2=0;idx2index;idx2++) {"); - int weaklyConnectedComponentIndex = rcr.getWeakID(inset.get(i), fsen); + int weaklyConnectedComponentIndex = rcr.getWeakID(inset.get(i), fsen); - output.println(" rcr_RETIREHASHTABLE(hashstruct[" + weaklyConnectedComponentIndex - + "],&(___params___->common), rec->array[idx2], (BinItem_rcr *) rec->ptrarray[idx2]);"); + output.println(" rcr_RETIREHASHTABLE(hashstruct[" + weaklyConnectedComponentIndex + + "],&(___params___->common), rec->array[idx2], (BinItem_rcr *) rec->ptrarray[idx2]);"); - output.println(" }"); // exit idx2 for loop - output.println(" rec=rec->next;"); - output.println(" }"); // exit rec while loop + output.println(" }"); // exit idx2 for loop + output.println(" rec=rec->next;"); + output.println(" }"); // exit rec while loop } output.println("}"); } @@ -1933,7 +1933,7 @@ public class BuildOoOJavaCode extends BuildCode { if( !fsen.getIsLeafSESE() ) { output.println(" pooldestroy( runningSESE->taskRecordMemPool );"); if (state.RCR && fsen.getInVarsForDynamicCoarseConflictResolution().size() > 0 ) { - output.println(" returnTR();"); + output.println(" returnTR();"); } } output.println("#endif // OOO_DISABLE_TASKMEMPOOL"); @@ -1998,15 +1998,15 @@ public class BuildOoOJavaCode extends BuildCode { output.println(" SESEcommon* oldSrc = "+refVar+"_srcSESE;"); if( vst == null ) { - // if there is no given source, this variable is ready so - // mark src pointer NULL to signify that the var is up-to-date - output.println(" "+refVar+"_srcSESE = NULL;"); + // if there is no given source, this variable is ready so + // mark src pointer NULL to signify that the var is up-to-date + output.println(" "+refVar+"_srcSESE = NULL;"); } else { - // otherwise we track where it will come from - SESEandAgePair instance = new SESEandAgePair(vst.getSESE(), vst.getAge() ); - output.println(" "+refVar+"_srcSESE = "+instance+";"); - output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+ - vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");"); + // otherwise we track where it will come from + SESEandAgePair instance = new SESEandAgePair(vst.getSESE(), vst.getAge() ); + output.println(" "+refVar+"_srcSESE = "+instance+";"); + output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+ + vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");"); } // no matter what we did above, track reference count of whatever @@ -2035,34 +2035,34 @@ public class BuildOoOJavaCode extends BuildCode { int arrayid = state.getArrayNumber(fn.getType() )+state.numClasses(); if( GENERATEPRECISEGC ) { - output.println(generateTemp(fm, fn.getDst())+ - "=allocate_newarray_mlp("+localsprefixaddr+ - ", "+arrayid+", "+generateTemp(fm, fn.getSize())+ - ", oid, "+ - oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+ - ");"); - output.println(" oid += oidIncrement;"); + output.println(generateTemp(fm, fn.getDst())+ + "=allocate_newarray_mlp("+localsprefixaddr+ + ", "+arrayid+", "+generateTemp(fm, fn.getSize())+ + ", oid, "+ + oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+ + ");"); + output.println(" oid += oidIncrement;"); } else { - output.println(generateTemp(fm, fn.getDst())+ - "=allocate_newarray("+arrayid+ - ", "+generateTemp(fm, fn.getSize())+ - ");"); + output.println(generateTemp(fm, fn.getDst())+ + "=allocate_newarray("+arrayid+ + ", "+generateTemp(fm, fn.getSize())+ + ");"); } } else { // not an array if( GENERATEPRECISEGC ) { - output.println(generateTemp(fm, fn.getDst())+ - "=allocate_new_mlp("+localsprefixaddr+ - ", "+fn.getType().getClassDesc().getId()+ - ", oid, "+ - oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+ - ");"); - output.println(" oid += oidIncrement;"); + output.println(generateTemp(fm, fn.getDst())+ + "=allocate_new_mlp("+localsprefixaddr+ + ", "+fn.getType().getClassDesc().getId()+ + ", oid, "+ + oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+ + ");"); + output.println(" oid += oidIncrement;"); } else { - output.println(generateTemp(fm, fn.getDst())+ - "=allocate_new("+fn.getType().getClassDesc().getId()+ - ");"); + output.println(generateTemp(fm, fn.getDst())+ + "=allocate_new("+fn.getType().getClassDesc().getId()+ + ");"); } } } @@ -2075,14 +2075,14 @@ public class BuildOoOJavaCode extends BuildCode { for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext(); ) { TempDescriptor tempDescriptor = (TempDescriptor) iterator.next(); if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()) { - tdSet.add(tempDescriptor); + tdSet.add(tempDescriptor); } } for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext(); ) { TempDescriptor tempDescriptor = (TempDescriptor) iterator.next(); if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()) { - tdSet.add(tempDescriptor); + tdSet.add(tempDescriptor); } } @@ -2107,7 +2107,7 @@ public class BuildOoOJavaCode extends BuildCode { TempDescriptor temp = itr.next(); TypeDescriptor type = temp.getType(); if( !type.isPtr() ) { - inSetAndOutSetPrims.add(temp); + inSetAndOutSetPrims.add(temp); } } @@ -2116,13 +2116,13 @@ public class BuildOoOJavaCode extends BuildCode { TempDescriptor temp = itrPrims.next(); TypeDescriptor type = temp.getType(); if(type.isPrimitive()) { - Integer count=map.get(type.getSymbol()); - if(count==null) { - count=new Integer(1); - map.put(type.getSymbol(), count); - } else { - map.put(type.getSymbol(), new Integer(count.intValue()+1)); - } + Integer count=map.get(type.getSymbol()); + if(count==null) { + count=new Integer(1); + map.put(type.getSymbol(), count); + } else { + map.put(type.getSymbol(), new Integer(count.intValue()+1)); + } } } diff --git a/Robust/src/IR/Flat/FieldShadow.java b/Robust/src/IR/Flat/FieldShadow.java index 25a84217..1263503e 100644 --- a/Robust/src/IR/Flat/FieldShadow.java +++ b/Robust/src/IR/Flat/FieldShadow.java @@ -20,7 +20,7 @@ public class FieldShadow { while(it_sifs.hasNext()) { ClassDescriptor sif = (ClassDescriptor)it_sifs.next(); if (!namemap.containsKey(sif)) - handleClass(sif, state, namemap); + handleClass(sif, state, namemap); } HashMap supermap=cd.getSuperDesc()!=null?namemap.get(cd.getSuperDesc()):new HashMap(); @@ -38,14 +38,14 @@ public class FieldShadow { for(Iterator fieldit=cd.getFields(); fieldit.hasNext(); ) { FieldDescriptor fd=(FieldDescriptor)fieldit.next(); if (supermap.containsKey(fd.getSymbol())) { - Integer oldint=supermap.get(fd.getSymbol()); - int newint=oldint.intValue()+1; - fieldmap.put(fd.getSymbol(), new Integer(newint)); - fd.changeSafeSymbol(newint); + Integer oldint=supermap.get(fd.getSymbol()); + int newint=oldint.intValue()+1; + fieldmap.put(fd.getSymbol(), new Integer(newint)); + fd.changeSafeSymbol(newint); } else { - // the fields in interfaces are defaultely static & final, so do not need to - // check them, they will always have the interface name as prefix - fieldmap.put(fd.getSymbol(), new Integer(0)); + // the fields in interfaces are defaultely static & final, so do not need to + // check them, they will always have the interface name as prefix + fieldmap.put(fd.getSymbol(), new Integer(0)); } } } diff --git a/Robust/src/IR/Flat/FlatCall.java b/Robust/src/IR/Flat/FlatCall.java index 2c9de6e7..5cbe1529 100644 --- a/Robust/src/IR/Flat/FlatCall.java +++ b/Robust/src/IR/Flat/FlatCall.java @@ -97,15 +97,15 @@ public class FlatCall extends FlatNode { if( tdParamI.equals(tdParam) ) { - if( method.isStatic() ) { - return args[i]; - } + if( method.isStatic() ) { + return args[i]; + } - if( i == 0 ) { - return this_temp; - } + if( i == 0 ) { + return this_temp; + } - return args[i-1]; + return args[i-1]; } } @@ -116,21 +116,21 @@ public class FlatCall extends FlatNode { String st="FlatCall_"; if (dst==null) { if (method==null) - st+="null("; + st+="null("; else - st+=method.getSymbol()+"("; + st+=method.getSymbol()+"("; } else st+=dst+"="+method.getSymbol()+"("; if (this_temp!=null) { st+=this_temp; if (args.length!=0) - st+=", "; + st+=", "; } for(int i=0; i setit=set.iterator(); setit.hasNext(); ) { FlatNode fn=setit.next(); for(int i=0; i0) { - //1) Edge >1 of node - nodetolabel.put(nn,new Integer(labelindex++)); - } - if (!visited.contains(nn)&&!tovisit.contains(nn)) { - tovisit.add(nn); - } else { - //2) Join point - nodetolabel.put(nn,new Integer(labelindex++)); - } + FlatNode nn=fn.getNext(i); + if(i>0) { + //1) Edge >1 of node + nodetolabel.put(nn,new Integer(labelindex++)); + } + if (!visited.contains(nn)&&!tovisit.contains(nn)) { + tovisit.add(nn); + } else { + //2) Join point + nodetolabel.put(nn,new Integer(labelindex++)); + } } } @@ -174,47 +174,47 @@ public class FlatMethod extends FlatNode { tovisit.add(this); while(current_node!=null||!tovisit.isEmpty()) { if (current_node==null) { - current_node=(FlatNode)tovisit.iterator().next(); - tovisit.remove(current_node); + current_node=(FlatNode)tovisit.iterator().next(); + tovisit.remove(current_node); } else { - if (tovisit.contains(current_node)) - tovisit.remove(current_node); + if (tovisit.contains(current_node)) + tovisit.remove(current_node); } visited.add(current_node); if (nodetolabel.containsKey(current_node)) { - st+="L"+nodetolabel.get(current_node)+":\n"; - for(int i=0; i it=hspp.iterator(); it.hasNext(); ) { PrefetchPair pp=it.next(); if (!first) - st+=", "; + st+=", "; first=false; st+=pp; } diff --git a/Robust/src/IR/Flat/FlatSESEEnterNode.java b/Robust/src/IR/Flat/FlatSESEEnterNode.java index 64af20ab..d6991927 100644 --- a/Robust/src/IR/Flat/FlatSESEEnterNode.java +++ b/Robust/src/IR/Flat/FlatSESEEnterNode.java @@ -308,11 +308,11 @@ public class FlatSESEEnterNode extends FlatNode { visited.add(fn); if (fn!=exit) { - for(int i=0; i0) - atomicset.add(fnext); - visited.add(fnext); - toprocess.push(fnext); - } + FlatNode fnext=fn.getNext(i); + if (!visited.contains(fnext)) { + atomictable.put(fnext, new Integer(atomicval)); + if (atomicval>0) + atomicset.add(fnext); + visited.add(fnext); + toprocess.push(fnext); + } } } //make depth 0 be depth infinity @@ -52,20 +52,20 @@ public class Inliner { for(Iterator fnit=fnset.iterator(); fnit.hasNext(); ) { FlatNode fn=fnit.next(); if (fn.kind()==FKind.FlatCall) { - FlatCall fc=(FlatCall)fn; - MethodDescriptor md=fc.getMethod(); + FlatCall fc=(FlatCall)fn; + MethodDescriptor md=fc.getMethod(); - if (toexclude.contains(md)) - continue; + if (toexclude.contains(md)) + continue; - Set inlinefnset=inline(fc, typeutil, state); - if (inlinefnset==null) - continue; + Set inlinefnset=inline(fc, typeutil, state); + if (inlinefnset==null) + continue; - toexclude.push(md); - if (depth>1) - recursive(state, typeutil, inlinefnset, depth-1, toexclude); - toexclude.pop(); + toexclude.push(md); + if (depth>1) + recursive(state, typeutil, inlinefnset, depth-1, toexclude); + toexclude.pop(); } } } @@ -94,71 +94,71 @@ public class Inliner { //Build the clones for(Iterator fnit=nodeset.iterator(); fnit.hasNext(); ) { - FlatNode fn=fnit.next(); - if (fn.kind()==FKind.FlatReturnNode) { - //Convert FlatReturn node into move - TempDescriptor rtmp=((FlatReturnNode)fn).getReturnTemp(); - if (rtmp!=null) { - FlatOpNode fon=new FlatOpNode(rettmp, rtmp, null, new Operation(Operation.ASSIGN)); - flatmap.put(fn, fon); - } else { - flatmap.put(fn, aftercallnode); - } - } else { - FlatNode clone=fn.clone(clonemap); - newnodes.add(clone); - flatmap.put(fn,clone); - } + FlatNode fn=fnit.next(); + if (fn.kind()==FKind.FlatReturnNode) { + //Convert FlatReturn node into move + TempDescriptor rtmp=((FlatReturnNode)fn).getReturnTemp(); + if (rtmp!=null) { + FlatOpNode fon=new FlatOpNode(rettmp, rtmp, null, new Operation(Operation.ASSIGN)); + flatmap.put(fn, fon); + } else { + flatmap.put(fn, aftercallnode); + } + } else { + FlatNode clone=fn.clone(clonemap); + newnodes.add(clone); + flatmap.put(fn,clone); + } } //Build the move chain FlatNode first=new FlatNop();; newnodes.add(first); FlatNode last=first; { - int i=0; - if (fc.getThis()!=null) { - FlatOpNode fon=new FlatOpNode(fm.getParameter(i++), fc.getThis(), null, new Operation(Operation.ASSIGN)); - newnodes.add(fon); - last.addNext(fon); - last=fon; - } - for(int j=0; j fnit=nodeset.iterator(); fnit.hasNext(); ) { - FlatNode fn=fnit.next(); - FlatNode fnclone=flatmap.get(fn); - - if (fn.kind()!=FKind.FlatReturnNode) { - //don't build old edges out of a flat return node - for(int i=0; i"+allocSite+"=="+a.getUniqueAllocSiteID()+") {"); + cFile.println(" if("+prefix+"->"+allocSite+"=="+a.getUniqueAllocSiteID()+") {"); } addChecker(smfe, a, fn, tmp, state, et, prefix, depth, weakID); if (needswitch) { - cFile.println(" }"); - cFile.println(" break;"); + cFile.println(" }"); + cFile.println(" break;"); } } if (needswitch) { @@ -268,50 +268,50 @@ public class RuntimeConflictResolver { boolean first=true; for(Effect e : et.getEffects(a)) { - if (!state.transitionsTo(e).isEmpty()) { - if (first) { - cFile.println(" int i;"); - cFile.println(" struct ___Object___ * "+currPtr+";"); - cFile.println(" for(i = 0; i<((struct ArrayObject *) " + prefix + " )->___length___; i++ ) {"); - first=false; - } - printRefSwitch(smfe, fn, tmp, pdepth, childPtr, currPtr, state.transitionsTo(e), weakID); - - // only if we are traversing for a new task, not a stall site - if( (fn instanceof FlatSESEEnterNode) && - smfe.getPossiblyEvilEffects().contains(e) ) { - - FlatSESEEnterNode evilTask = (FlatSESEEnterNode)fn; - - detectPossiblyEvilExecution(evilTask, - evilTask.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp) - ); - } - } + if (!state.transitionsTo(e).isEmpty()) { + if (first) { + cFile.println(" int i;"); + cFile.println(" struct ___Object___ * "+currPtr+";"); + cFile.println(" for(i = 0; i<((struct ArrayObject *) " + prefix + " )->___length___; i++ ) {"); + first=false; + } + printRefSwitch(smfe, fn, tmp, pdepth, childPtr, currPtr, state.transitionsTo(e), weakID); + + // only if we are traversing for a new task, not a stall site + if( (fn instanceof FlatSESEEnterNode) && + smfe.getPossiblyEvilEffects().contains(e) ) { + + FlatSESEEnterNode evilTask = (FlatSESEEnterNode)fn; + + detectPossiblyEvilExecution(evilTask, + evilTask.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp) + ); + } + } } if (!first) - cFile.println("}"); + cFile.println("}"); } else { //All other cases String currPtr = "myPtr" + pdepth; cFile.println(" struct ___Object___ * "+currPtr+";"); for(Effect e : et.getEffects(a)) { - if (!state.transitionsTo(e).isEmpty()) { - String childPtr = "((struct "+a.getType().getSafeSymbol()+" *)"+prefix +")->" + e.getField().getSafeSymbol(); - printRefSwitch(smfe, fn, tmp, pdepth, childPtr, currPtr, state.transitionsTo(e), weakID); + if (!state.transitionsTo(e).isEmpty()) { + String childPtr = "((struct "+a.getType().getSafeSymbol()+" *)"+prefix +")->" + e.getField().getSafeSymbol(); + printRefSwitch(smfe, fn, tmp, pdepth, childPtr, currPtr, state.transitionsTo(e), weakID); - // only if we are traversing for a new task, not a stall site - if( (fn instanceof FlatSESEEnterNode) && - smfe.getPossiblyEvilEffects().contains(e) ) { + // only if we are traversing for a new task, not a stall site + if( (fn instanceof FlatSESEEnterNode) && + smfe.getPossiblyEvilEffects().contains(e) ) { - FlatSESEEnterNode evilTask = (FlatSESEEnterNode)fn; + FlatSESEEnterNode evilTask = (FlatSESEEnterNode)fn; - detectPossiblyEvilExecution(evilTask, - evilTask.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp) - ); - } - } + detectPossiblyEvilExecution(evilTask, + evilTask.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp) + ); + } + } } } } @@ -320,17 +320,17 @@ public class RuntimeConflictResolver { for(SMFEState tr : transitions) { if(tr.getRefCount() == 1) { //in-lineable case - //Don't need to update state counter since we don't care really if it's inlined... - cFile.println(" "+currPtr+"= (struct ___Object___ * ) " + childPtr + ";"); - cFile.println(" if (" + currPtr + " != NULL) { "); + //Don't need to update state counter since we don't care really if it's inlined... + cFile.println(" "+currPtr+"= (struct ___Object___ * ) " + childPtr + ";"); + cFile.println(" if (" + currPtr + " != NULL) { "); - printAllocChecksInsideState(smfe, tr, fn, tmp, currPtr, pdepth+1, weakID); + printAllocChecksInsideState(smfe, tr, fn, tmp, currPtr, pdepth+1, weakID); - cFile.println(" }"); //break for internal switch and if + cFile.println(" }"); //break for internal switch and if } else { //non-inlineable cases - cFile.println(" "+currPtr+"= (struct ___Object___ * ) " + childPtr + ";"); - cFile.println(" if("+queryAndAddToVisitedHashtable+"("+currPtr+","+tr.getID()+"))"); - cFile.println(" " + enqueueInC +"("+ currPtr + ", "+tr.getID()+");"); + cFile.println(" "+currPtr+"= (struct ___Object___ * ) " + childPtr + ";"); + cFile.println(" if("+queryAndAddToVisitedHashtable+"("+currPtr+","+tr.getID()+"))"); + cFile.println(" " + enqueueInC +"("+ currPtr + ", "+tr.getID()+");"); } } } @@ -351,15 +351,15 @@ public class RuntimeConflictResolver { if(et.hasWriteConflict(a)) { cFile.append(" int tmpkey" + depth + " = rcr_generateKey(" + prefix + ");\n"); if (et.conflictDereference(a)) - cFile.append(" int tmpvar" + depth + " = rcr_WTWRITEBINCASE(allHashStructures[" + weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n"); + cFile.append(" int tmpvar" + depth + " = rcr_WTWRITEBINCASE(allHashStructures[" + weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n"); else - cFile.append(" int tmpvar" + depth + " = rcr_WRITEBINCASE(allHashStructures["+ weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n"); + cFile.append(" int tmpvar" + depth + " = rcr_WRITEBINCASE(allHashStructures["+ weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n"); } else if(et.hasReadConflict(a)) { cFile.append(" int tmpkey" + depth + " = rcr_generateKey(" + prefix + ");\n"); if (et.conflictDereference(a)) - cFile.append(" int tmpvar" + depth + " = rcr_WTREADBINCASE(allHashStructures[" + weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n"); + cFile.append(" int tmpvar" + depth + " = rcr_WTREADBINCASE(allHashStructures[" + weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n"); else - cFile.append(" int tmpvar" + depth + " = rcr_READBINCASE(allHashStructures["+ weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n"); + cFile.append(" int tmpvar" + depth + " = rcr_READBINCASE(allHashStructures["+ weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n"); } if (et.hasReadConflict(a) || et.hasWriteConflict(a)) { @@ -436,8 +436,8 @@ public class RuntimeConflictResolver { s.charAt(i) == '[' || s.charAt(i) == ']' ) { - s.deleteCharAt(i); - i--; + s.deleteCharAt(i); + i--; } } return s.toString(); @@ -491,54 +491,54 @@ public class RuntimeConflictResolver { cFile.println(" "+fsen.getSESErecordName()+" * rec=("+fsen.getSESErecordName()+" *) record;"); Vector invars=fsen.getInVarsForDynamicCoarseConflictResolution(); for(int i=0; ircrstatus!=0)"); - } - - if(globalState.NOSTALLTR && isValidToPrune) { - cFile.println(" /* " + getTraverserInvocation(tmp, "rec->"+tmp+", rec", fsen)+"*/"); - } else { - cFile.println(" " + getTraverserInvocation(tmp, "rec->"+tmp+", rec", fsen)); - } + TempDescriptor tmp=invars.get(i); + + /* In some cases we don't want to a dynamic traversal if it is + * unlikely to increase parallelism...these are cases where we + * are just enabling a stall site to possible clear faster*/ + + boolean isValidToPrune=true; + for( FlatSESEEnterNode parentSESE : fsen.getParents() ) { + ConflictGraph graph = oooa.getConflictGraph(parentSESE); + if(graph!=null) { + String id = tmp + "_sese" + fsen.getPrettyIdentifier(); + ConflictNode node = graph.getId2cn().get(id); + isValidToPrune &= node.IsValidToPrune(); + } + } + + if(isValidToPrune) { + // if node is valid to prune examiner, + // also needs to turn off stall site examiners connected to this node + for( FlatSESEEnterNode parentSESE : fsen.getParents() ) { + ConflictGraph graph = oooa.getConflictGraph(parentSESE); + String id = tmp + "_sese" + fsen.getPrettyIdentifier(); + ConflictNode node = graph.getId2cn().get(id); + + for (Iterator iterator = node.getEdgeSet().iterator(); iterator.hasNext(); ) { + ConflictEdge edge = (ConflictEdge) iterator.next(); + if (edge.getVertexU() == node) { + if (edge.getVertexV().isStallSiteNode()) { + edge.getVertexV().setToBePruned(true); + } + } else { + if (edge.getVertexU().isStallSiteNode()) { + edge.getVertexU().setToBePruned(true); + } + } + } + } + } + + if (i!=0) { + cFile.println(" if (record->rcrstatus!=0)"); + } + + if(globalState.NOSTALLTR && isValidToPrune) { + cFile.println(" /* " + getTraverserInvocation(tmp, "rec->"+tmp+", rec", fsen)+"*/"); + } else { + cFile.println(" " + getTraverserInvocation(tmp, "rec->"+tmp+", rec", fsen)); + } } //release traverser reference...traversal finished... //executing thread will clean bins for us @@ -556,21 +556,21 @@ public class RuntimeConflictResolver { Set seseSet=oooa.getPossibleExecutingRBlocks(stallsite); boolean isValidToPrune=true; for (Iterator iterator = seseSet.iterator(); iterator.hasNext(); ) { - FlatSESEEnterNode sese = (FlatSESEEnterNode) iterator.next(); - ConflictGraph graph = oooa.getConflictGraph(sese); - if(graph!=null) { - String id = var + "_fn" + stallsite.hashCode(); - ConflictNode node = graph.getId2cn().get(id); - isValidToPrune &= node.isTobePruned(); - } + FlatSESEEnterNode sese = (FlatSESEEnterNode) iterator.next(); + ConflictGraph graph = oooa.getConflictGraph(sese); + if(graph!=null) { + String id = var + "_fn" + stallsite.hashCode(); + ConflictNode node = graph.getId2cn().get(id); + isValidToPrune &= node.isTobePruned(); + } } cFile.println(" case -" + getTraverserID(var, stallsite)+ ": {"); cFile.println(" SESEstall * rec=(SESEstall*) record;"); if(globalState.NOSTALLTR && isValidToPrune) { - cFile.println(" /*" + getTraverserInvocation(var, "rec->___obj___, rec", stallsite)+";*/"); + cFile.println(" /*" + getTraverserInvocation(var, "rec->___obj___, rec", stallsite)+";*/"); } else { - cFile.println(" " + getTraverserInvocation(var, "rec->___obj___, rec", stallsite)+";"); + cFile.println(" " + getTraverserInvocation(var, "rec->___obj___, rec", stallsite)+";"); } cFile.println(" record->rcrstatus=0;"); cFile.println(" }"); @@ -624,35 +624,35 @@ public class RuntimeConflictResolver { table = new Hashtable>(); this.state=state; for(Effect e : state.getEffectsAllowed()) { - Set eg; - if((eg = table.get(e.getAffectedAllocSite())) == null) { - eg = new HashSet(); - table.put(e.getAffectedAllocSite(), eg); - } - eg.add(e); + Set eg; + if((eg = table.get(e.getAffectedAllocSite())) == null) { + eg = new HashSet(); + table.put(e.getAffectedAllocSite(), eg); + } + eg.add(e); } } public boolean conflictDereference(Alloc a) { for(Effect e : getEffects(a)) { - if (!state.transitionsTo(e).isEmpty()&&state.getConflicts().contains(e)) - return true; + if (!state.transitionsTo(e).isEmpty()&&state.getConflicts().contains(e)) + return true; } return false; } public boolean hasWriteConflict(Alloc a) { for(Effect e : getEffects(a)) { - if (e.isWrite() && state.getConflicts().contains(e)) - return true; + if (e.isWrite() && state.getConflicts().contains(e)) + return true; } return false; } public boolean hasReadConflict(Alloc a) { for(Effect e : getEffects(a)) { - if (e.isRead() && state.getConflicts().contains(e)) - return true; + if (e.isRead() && state.getConflicts().contains(e)) + return true; } return false; } diff --git a/Robust/src/IR/Flat/TempObject.java b/Robust/src/IR/Flat/TempObject.java index 1c8fc215..462783fe 100644 --- a/Robust/src/IR/Flat/TempObject.java +++ b/Robust/src/IR/Flat/TempObject.java @@ -65,7 +65,7 @@ public class TempObject { if (!params.containsTemp(t)) { Position p=(Position)temptostore.get(t); if (p==null) - System.out.println(t); + System.out.println(t); return !p.inStruct; } return false; diff --git a/Robust/src/IR/Flat/TempTagPair.java b/Robust/src/IR/Flat/TempTagPair.java index e4d935d8..5cb26ec5 100644 --- a/Robust/src/IR/Flat/TempTagPair.java +++ b/Robust/src/IR/Flat/TempTagPair.java @@ -33,10 +33,10 @@ public class TempTagPair { TempTagPair ttp=(TempTagPair)o; if (ttp.tagt==tagt&&ttp.td==td) { if (ttp.tagd!=null) { - if (!ttp.tagd.equals(tagd)) - throw new Error(); + if (!ttp.tagd.equals(tagd)) + throw new Error(); } else if (tagd!=null) - throw new Error(); + throw new Error(); return true; } else return false; diff --git a/Robust/src/IR/MethodDescriptor.java b/Robust/src/IR/MethodDescriptor.java index 0cda9a0a..724983c4 100644 --- a/Robust/src/IR/MethodDescriptor.java +++ b/Robust/src/IR/MethodDescriptor.java @@ -55,7 +55,7 @@ public class MethodDescriptor extends Descriptor { TypeDescriptor td1=(d1 instanceof TagVarDescriptor)?((TagVarDescriptor)d1).getType():((VarDescriptor)d1).getType(); TypeDescriptor td2=(d2 instanceof TagVarDescriptor)?((TagVarDescriptor)d2).getType():((VarDescriptor)d2).getType(); if (!td1.equals(td2)) - return false; + return false; } return true; } @@ -117,7 +117,7 @@ public class MethodDescriptor extends Descriptor { for(int i=0; i0) { //checking if location is actually defined in the hierarchy for (Iterator iterator = spinLocSet.iterator(); iterator.hasNext(); ) { - String locID = (String) iterator.next(); - if(!locOrder.containsKey(locID)) { - throw new Error("Error: The spinning location '"+ - locID + "' is not defined in the hierarchy of the class '"+cd +"'."); - } + String locID = (String) iterator.next(); + if(!locOrder.containsKey(locID)) { + throw new Error("Error: The spinning location '"+ + locID + "' is not defined in the hierarchy of the class '"+cd +"'."); + } } state.addLocationPropertySet(cd, spinLocSet); } @@ -710,7 +710,7 @@ public class BuildIR { } else { if (!(icn.getSymbol().equals(TypeUtil.ObjectClass)|| icn.getSymbol().equals(TypeUtil.TagClass))) - icn.setSuper(TypeUtil.ObjectClass); + icn.setSuper(TypeUtil.ObjectClass); } // check inherited interfaces if (!isEmpty(pn.getChild("superIF").getTerminal())) { @@ -718,11 +718,11 @@ public class BuildIR { ParseNode snlist=pn.getChild("superIF").getChild("interface_type_list"); ParseNodeVector pnv=snlist.getChildren(); for(int i=0; i slv = new Vector(); - for(int j=0; j slv = new Vector(); + for(int j=0; j0) - str+=","; + str+=","; str+=getVar(i)+" : "; str+=getArg(i).printNode(0); } diff --git a/Robust/src/IR/Tree/CreateObjectNode.java b/Robust/src/IR/Tree/CreateObjectNode.java index a8e0b7b7..bae15edf 100644 --- a/Robust/src/IR/Tree/CreateObjectNode.java +++ b/Robust/src/IR/Tree/CreateObjectNode.java @@ -79,10 +79,10 @@ public class CreateObjectNode extends ExpressionNode { ExpressionNode en=(ExpressionNode)argumentlist.get(i); st+=en.printNode(indent); if ((i+1)!=argumentlist.size()) { - if (isarray) - st+="]["; - else - st+=", "; + if (isarray) + st+="]["; + else + st+=", "; } } if (isarray) diff --git a/Robust/src/IR/Tree/DNFFlag.java b/Robust/src/IR/Tree/DNFFlag.java index f157392e..6289dec4 100644 --- a/Robust/src/IR/Tree/DNFFlag.java +++ b/Robust/src/IR/Tree/DNFFlag.java @@ -35,22 +35,22 @@ public class DNFFlag { Vector conj=(Vector)conjunctions.get(i); DNFFlag newflag=null; for (int j=0; j()); + revCallMap.put(callmd, new HashSet()); revCallMap.get(callmd).add(md); callMap.get(md).add(callmd); canCall.get(callmd).add(callmd); @@ -211,32 +211,32 @@ public class JavaBuilder implements CallGraph { if (impSet!=null) { for(ClassDescriptor cdactual : impSet) { - searchimp : - while(cdactual!=null) { - Set possiblematches=cdactual.getMethodTable().getSetFromSameScope(callmd.getSymbol()); - - for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { - MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); - if (callmd.matches(matchmd)) { - //Found the method that will be called - if (!discovered.contains(matchmd)) { - discovered.add(matchmd); - toprocess.push(matchmd); - } - - if (!revCallMap.containsKey(matchmd)) - revCallMap.put(matchmd, new HashSet()); - revCallMap.get(matchmd).add(md); - - callMap.get(md).add(matchmd); - canCall.get(callmd).add(matchmd); - break searchimp; - } - } - - //Didn't find method...look in super class - cdactual=cdactual.getSuperDesc(); - } + searchimp : + while(cdactual!=null) { + Set possiblematches=cdactual.getMethodTable().getSetFromSameScope(callmd.getSymbol()); + + for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { + MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); + if (callmd.matches(matchmd)) { + //Found the method that will be called + if (!discovered.contains(matchmd)) { + discovered.add(matchmd); + toprocess.push(matchmd); + } + + if (!revCallMap.containsKey(matchmd)) + revCallMap.put(matchmd, new HashSet()); + revCallMap.get(matchmd).add(md); + + callMap.get(md).add(matchmd); + canCall.get(callmd).add(matchmd); + break searchimp; + } + } + + //Didn't find method...look in super class + cdactual=cdactual.getSuperDesc(); + } } } } @@ -262,46 +262,46 @@ public class JavaBuilder implements CallGraph { while(!tovisit.isEmpty()) { ClassDescriptor cdcurr=tovisit.pop(); if (!implementationMap.containsKey(cdcurr)) - implementationMap.put(cdcurr, new HashSet()); + implementationMap.put(cdcurr, new HashSet()); if (implementationMap.get(cdcurr).add(cdnew)) { - //new implementation...see if it affects implementationmap - if (invocationMap.containsKey(cdcurr)) { - for(Pair mdpair : invocationMap.get(cdcurr)) { - MethodDescriptor md=mdpair.getFirst(); - MethodDescriptor callmd=mdpair.getSecond(); - ClassDescriptor cdactual=cdnew; + //new implementation...see if it affects implementationmap + if (invocationMap.containsKey(cdcurr)) { + for(Pair mdpair : invocationMap.get(cdcurr)) { + MethodDescriptor md=mdpair.getFirst(); + MethodDescriptor callmd=mdpair.getSecond(); + ClassDescriptor cdactual=cdnew; searchimp: - while(cdactual!=null) { - Set possiblematches=cdactual.getMethodTable().getSetFromSameScope(callmd.getSymbol()); - for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { - MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); - if (callmd.matches(matchmd)) { - //Found the method that will be called - if (!discovered.contains(matchmd)) { - discovered.add(matchmd); - toprocess.push(matchmd); - } - if (!revCallMap.containsKey(matchmd)) - revCallMap.put(matchmd, new HashSet()); - revCallMap.get(matchmd).add(md); - callMap.get(md).add(matchmd); - canCall.get(callmd).add(matchmd); - break searchimp; - } - } - - //Didn't find method...look in super class - cdactual=cdactual.getSuperDesc(); - } - } - } + while(cdactual!=null) { + Set possiblematches=cdactual.getMethodTable().getSetFromSameScope(callmd.getSymbol()); + for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { + MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); + if (callmd.matches(matchmd)) { + //Found the method that will be called + if (!discovered.contains(matchmd)) { + discovered.add(matchmd); + toprocess.push(matchmd); + } + if (!revCallMap.containsKey(matchmd)) + revCallMap.put(matchmd, new HashSet()); + revCallMap.get(matchmd).add(md); + callMap.get(md).add(matchmd); + canCall.get(callmd).add(matchmd); + break searchimp; + } + } + + //Didn't find method...look in super class + cdactual=cdactual.getSuperDesc(); + } + } + } } if (cdcurr.getSuperDesc()!=null) - tovisit.push(cdcurr.getSuperDesc()); + tovisit.push(cdcurr.getSuperDesc()); for(Iterator interit=cdcurr.getSuperInterfaces(); interit.hasNext(); ) { - ClassDescriptor cdinter=(ClassDescriptor) interit.next(); - tovisit.push(cdinter); + ClassDescriptor cdinter=(ClassDescriptor) interit.next(); + tovisit.push(cdinter); } } } @@ -314,15 +314,15 @@ searchimp: for(FlatNode fn : fm.getNodeSet()) { switch(fn.kind()) { case FKind.FlatCall : { - FlatCall fcall=(FlatCall)fn; - processCall(md, fcall); - break; + FlatCall fcall=(FlatCall)fn; + processCall(md, fcall); + break; } case FKind.FlatNew: { - FlatNew fnew=(FlatNew)fn; - processNew(fnew); - break; + FlatNew fnew=(FlatNew)fn; + processNew(fnew); + break; } } } diff --git a/Robust/src/IR/Tree/LiteralNode.java b/Robust/src/IR/Tree/LiteralNode.java index a0801173..8cb08821 100644 --- a/Robust/src/IR/Tree/LiteralNode.java +++ b/Robust/src/IR/Tree/LiteralNode.java @@ -50,9 +50,9 @@ public class LiteralNode extends ExpressionNode { for(int i=0; i 0?0:1); + eval = Long.valueOf(l.longValue() > 0?0:1); else if (this.op.getOp() == Operation.COMP) - eval = Long.valueOf((long)(~l.longValue())); + eval = Long.valueOf((long)(~l.longValue())); else if (this.op.getOp() == Operation.UNARYMINUS) - eval = Long.valueOf(-l.longValue() ); + eval = Long.valueOf(-l.longValue() ); else if (this.op.getOp() == Operation.UNARYPLUS) - eval = Long.valueOf(+l.longValue()); + eval = Long.valueOf(+l.longValue()); else { - Long r = this.right.evaluate(); - if(r != null) { - //if (this.op.getOp() == Operation.LOGIC_OR) - // return Long.valueOf((long)(l.longValue() || r.longValue())); - //else if (this.op.getOp() == Operation.LOGIC_AND) - // return Long.valueOf((long)(l.longValue() && r.longValue())); - /*else */ if (this.op.getOp() == Operation.BIT_OR) - eval = Long.valueOf(l.longValue() | r.longValue()); - else if (this.op.getOp() == Operation.BIT_XOR) - eval = Long.valueOf(l.longValue() ^ r.longValue()); - else if (this.op.getOp() == Operation.BIT_AND) - eval = Long.valueOf(l.longValue() & r.longValue()); - else if (this.op.getOp() == Operation.EQUAL) - eval = Long.valueOf((l.longValue() == r.longValue())?1:0); - else if (this.op.getOp() == Operation.NOTEQUAL) - eval = Long.valueOf((l.longValue() != r.longValue())?1:0); - else if (this.op.getOp() == Operation.LT) - eval = Long.valueOf((l.longValue() < r.longValue())?1:0); - else if (this.op.getOp() == Operation.GT) - eval = Long.valueOf((l.longValue() > r.longValue())?1:0); - else if (this.op.getOp() == Operation.LTE) - eval = Long.valueOf((l.longValue() <= r.longValue())?1:0); - else if (this.op.getOp() == Operation.GTE) - eval = Long.valueOf((l.longValue() >= r.longValue())?1:0); - else if (this.op.getOp() == Operation.LEFTSHIFT) - eval = Long.valueOf(l.longValue() << r.longValue()); - else if (this.op.getOp() == Operation.RIGHTSHIFT) - eval = Long.valueOf(l.longValue() >> r.longValue()); - else if (this.op.getOp() == Operation.URIGHTSHIFT) - eval = Long.valueOf(l.longValue() >>> r.longValue()); - else if (this.op.getOp() == Operation.SUB) - eval = Long.valueOf(l.longValue() - r.longValue()); - else if (this.op.getOp() == Operation.ADD) - eval = Long.valueOf(l.longValue() + r.longValue()); - else if (this.op.getOp() == Operation.MULT) - eval = Long.valueOf(l.longValue() * r.longValue()); - else if (this.op.getOp() == Operation.DIV) - eval = Long.valueOf(l.longValue() / r.longValue()); - else if (this.op.getOp() == Operation.MOD) - eval = Long.valueOf(l.longValue() % r.longValue()); - else if (this.op.getOp() == Operation.ASSIGN) - eval = Long.valueOf(r.longValue()); - } + Long r = this.right.evaluate(); + if(r != null) { + //if (this.op.getOp() == Operation.LOGIC_OR) + // return Long.valueOf((long)(l.longValue() || r.longValue())); + //else if (this.op.getOp() == Operation.LOGIC_AND) + // return Long.valueOf((long)(l.longValue() && r.longValue())); + /*else */ if (this.op.getOp() == Operation.BIT_OR) + eval = Long.valueOf(l.longValue() | r.longValue()); + else if (this.op.getOp() == Operation.BIT_XOR) + eval = Long.valueOf(l.longValue() ^ r.longValue()); + else if (this.op.getOp() == Operation.BIT_AND) + eval = Long.valueOf(l.longValue() & r.longValue()); + else if (this.op.getOp() == Operation.EQUAL) + eval = Long.valueOf((l.longValue() == r.longValue())?1:0); + else if (this.op.getOp() == Operation.NOTEQUAL) + eval = Long.valueOf((l.longValue() != r.longValue())?1:0); + else if (this.op.getOp() == Operation.LT) + eval = Long.valueOf((l.longValue() < r.longValue())?1:0); + else if (this.op.getOp() == Operation.GT) + eval = Long.valueOf((l.longValue() > r.longValue())?1:0); + else if (this.op.getOp() == Operation.LTE) + eval = Long.valueOf((l.longValue() <= r.longValue())?1:0); + else if (this.op.getOp() == Operation.GTE) + eval = Long.valueOf((l.longValue() >= r.longValue())?1:0); + else if (this.op.getOp() == Operation.LEFTSHIFT) + eval = Long.valueOf(l.longValue() << r.longValue()); + else if (this.op.getOp() == Operation.RIGHTSHIFT) + eval = Long.valueOf(l.longValue() >> r.longValue()); + else if (this.op.getOp() == Operation.URIGHTSHIFT) + eval = Long.valueOf(l.longValue() >>> r.longValue()); + else if (this.op.getOp() == Operation.SUB) + eval = Long.valueOf(l.longValue() - r.longValue()); + else if (this.op.getOp() == Operation.ADD) + eval = Long.valueOf(l.longValue() + r.longValue()); + else if (this.op.getOp() == Operation.MULT) + eval = Long.valueOf(l.longValue() * r.longValue()); + else if (this.op.getOp() == Operation.DIV) + eval = Long.valueOf(l.longValue() / r.longValue()); + else if (this.op.getOp() == Operation.MOD) + eval = Long.valueOf(l.longValue() % r.longValue()); + else if (this.op.getOp() == Operation.ASSIGN) + eval = Long.valueOf(r.longValue()); + } } } return eval; diff --git a/Robust/src/IR/Tree/ParseNode.java b/Robust/src/IR/Tree/ParseNode.java index 8cd7ea6e..a5f3951b 100644 --- a/Robust/src/IR/Tree/ParseNode.java +++ b/Robust/src/IR/Tree/ParseNode.java @@ -78,9 +78,9 @@ public class ParseNode implements Walkable { return line; } else { if (parent != null) { - return parent.getLine(); + return parent.getLine(); } else { - return 0; + return 0; } } } @@ -145,7 +145,7 @@ public class ParseNode implements Walkable { for (i = 0; i < children.size(); i++) { p = children.elementAt(i); if (p.getLabel().equals(label)) { - return p; + return p; } } @@ -176,7 +176,7 @@ public class ParseNode implements Walkable { for (i = 0; i < children.size(); i++) { ParseNode pn = children.elementAt(i); if (pn.getLabel().equals(label)) - v.addElement(pn); + v.addElement(pn); } return v; @@ -212,15 +212,15 @@ public class ParseNode implements Walkable { indent += 2; if (recursive) { - for (int i = 0; i < children.size(); i++) { - Walkable w = (Walkable)children.elementAt(i); - output += w.PPrint(indent, true); - } + for (int i = 0; i < children.size(); i++) { + Walkable w = (Walkable)children.elementAt(i); + output += w.PPrint(indent, true); + } } else { - for (int i = 0; i < children.size(); i++) { - Walkable w = (Walkable)children.elementAt(i); - output += doIndent(indent) + "<" + w.getNodeName() + "/>\n"; - } + for (int i = 0; i < children.size(); i++) { + Walkable w = (Walkable)children.elementAt(i); + output += doIndent(indent) + "<" + w.getNodeName() + "/>\n"; + } } indent -= 2; diff --git a/Robust/src/IR/Tree/ParseNodeDOTVisitor.java b/Robust/src/IR/Tree/ParseNodeDOTVisitor.java index cbd2b653..cc9101e9 100644 --- a/Robust/src/IR/Tree/ParseNodeDOTVisitor.java +++ b/Robust/src/IR/Tree/ParseNodeDOTVisitor.java @@ -63,7 +63,7 @@ public class ParseNodeDOTVisitor { String childid = getNewID("node"); output.println("\t" + nodeid + " -> " + childid + ";"); if (child.getLabel()=="rule") { - output.println("\tnode [color=" + newColor() + "];"); + output.println("\tnode [color=" + newColor() + "];"); } traverse(child, childid); } diff --git a/Robust/src/IR/Tree/SemanticCheck.java b/Robust/src/IR/Tree/SemanticCheck.java index a90adc06..1f14bf6e 100644 --- a/Robust/src/IR/Tree/SemanticCheck.java +++ b/Robust/src/IR/Tree/SemanticCheck.java @@ -62,45 +62,45 @@ public class SemanticCheck { completed.put(cd, fullcheck); if (fullcheck>=REFERENCE&&oldstatus sifv = cd.getSuperInterface(); - for(int i = 0; i < sifv.size(); i++) { - ClassDescriptor superif = getClass(cd, sifv.elementAt(i), fullcheck); - if(!superif.isInterface()) { - throw new Error("Error! Class " + cd.getSymbol() + " implements non-interface " + superif.getSymbol()); - } - if (oldstatus sifv = cd.getSuperInterface(); + for(int i = 0; i < sifv.size(); i++) { + ClassDescriptor superif = getClass(cd, sifv.elementAt(i), fullcheck); + if(!superif.isInterface()) { + throw new Error("Error! Class " + cd.getSymbol() + " implements non-interface " + superif.getSymbol()); + } + if (oldstatus=INIT) { - /* Check to see that fields are well typed */ - for(Iterator field_it=cd.getFields(); field_it.hasNext(); ) { - FieldDescriptor fd=(FieldDescriptor)field_it.next(); - checkField(cd,fd); - } - for(Iterator method_it=cd.getMethods(); method_it.hasNext(); ) { - MethodDescriptor md=(MethodDescriptor)method_it.next(); - checkMethod(cd,md); - } + /* Check to see that fields are well typed */ + for(Iterator field_it=cd.getFields(); field_it.hasNext(); ) { + FieldDescriptor fd=(FieldDescriptor)field_it.next(); + checkField(cd,fd); + } + for(Iterator method_it=cd.getMethods(); method_it.hasNext(); ) { + MethodDescriptor md=(MethodDescriptor)method_it.next(); + checkMethod(cd,md); + } } } } @@ -114,32 +114,32 @@ public class SemanticCheck { while (!toanalyze.isEmpty()) { Object obj = toanalyze.iterator().next(); if (obj instanceof TaskDescriptor) { - toanalyze.remove(obj); - TaskDescriptor td = (TaskDescriptor) obj; - try { - checkTask(td); - } catch (Error e) { - System.out.println("Error in " + td); - throw e; - } + toanalyze.remove(obj); + TaskDescriptor td = (TaskDescriptor) obj; + try { + checkTask(td); + } catch (Error e) { + System.out.println("Error in " + td); + throw e; + } } else { - ClassDescriptor cd = (ClassDescriptor) obj; - toanalyze.remove(cd); - //set the class mappings based on imports. - singleImportMap = cd.getSingleImportMappings(); - - // need to initialize typeutil object here...only place we can - // get class descriptors without first calling getclass - getClass(cd, cd.getSymbol()); - for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) { - MethodDescriptor md = (MethodDescriptor) method_it.next(); - try { - checkMethodBody(cd, md); - } catch (Error e) { - System.out.println("Error in " + md); - throw e; - } - } + ClassDescriptor cd = (ClassDescriptor) obj; + toanalyze.remove(cd); + //set the class mappings based on imports. + singleImportMap = cd.getSingleImportMappings(); + + // need to initialize typeutil object here...only place we can + // get class descriptors without first calling getclass + getClass(cd, cd.getSymbol()); + for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) { + MethodDescriptor md = (MethodDescriptor) method_it.next(); + try { + checkMethodBody(cd, md); + } catch (Error e) { + System.out.println("Error in " + md); + throw e; + } + } } } } @@ -152,7 +152,7 @@ public class SemanticCheck { ClassDescriptor field_cd=checkAll?getClass(cd, name):getClass(cd, name, REFERENCE); if (field_cd==null) - throw new Error("Undefined class "+name); + throw new Error("Undefined class "+name); td.setClassDescriptor(field_cd); return; } else if (td.isTag()) @@ -172,8 +172,8 @@ public class SemanticCheck { ConstraintCheck cc=(ConstraintCheck) ccs.get(i); for(int j=0; j 1) { @@ -605,7 +605,7 @@ public class SemanticCheck { /* Type check */ if (td!=null) { if (!typeutil.isSuperorType(td,cast_type)) - throw new Error("Cast node returns "+cast_type+", but need "+td); + throw new Error("Cast node returns "+cast_type+", but need "+td); } ExpressionNode en=cn.getExpression(); @@ -639,23 +639,23 @@ public class SemanticCheck { if(ltd.isClassNameRef()) { // the field access is using a class name directly if(ltd.getClassDesc().isEnum()) { - int value = ltd.getClassDesc().getEnumConstant(fieldname); - if(-1 == value) { - // check if this field is an enum constant - throw new Error(fieldname + " is not an enum constant in "+fan.printNode(0)+" in "+md); - } - fd = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC|Modifiers.FINAL), new TypeDescriptor(TypeDescriptor.INT), fieldname, null, false); - fd.setAsEnum(); - fd.setEnumValue(value); + int value = ltd.getClassDesc().getEnumConstant(fieldname); + if(-1 == value) { + // check if this field is an enum constant + throw new Error(fieldname + " is not an enum constant in "+fan.printNode(0)+" in "+md); + } + fd = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC|Modifiers.FINAL), new TypeDescriptor(TypeDescriptor.INT), fieldname, null, false); + fd.setAsEnum(); + fd.setEnumValue(value); } else if(fd == null) { - throw new Error("Could not find field "+ fieldname + " in "+fan.printNode(0)+" in "+md + " (Line: "+fan.getNumLine()+")"); + throw new Error("Could not find field "+ fieldname + " in "+fan.printNode(0)+" in "+md + " (Line: "+fan.getNumLine()+")"); } else if(fd.isStatic()) { - // check if this field is a static field - if(fd.getExpressionNode() != null) { - checkExpressionNode(md,nametable,fd.getExpressionNode(),null); - } + // check if this field is a static field + if(fd.getExpressionNode() != null) { + checkExpressionNode(md,nametable,fd.getExpressionNode(),null); + } } else { - throw new Error("Dereference of the non-static field "+ fieldname + " in "+fan.printNode(0)+" in "+md); + throw new Error("Dereference of the non-static field "+ fieldname + " in "+fan.printNode(0)+" in "+md); } } @@ -675,13 +675,13 @@ public class SemanticCheck { FieldDescriptor fdwr=(FieldDescriptor) ltdwr.getClassDesc().getFieldTable().get(fieldnamewr); fan.setField(fdwr); if (fdwr==null) - throw new Error("Unknown field "+fieldnamewr + " in "+fan.printNode(0)+" in "+md); + throw new Error("Unknown field "+fieldnamewr + " in "+fan.printNode(0)+" in "+md); } else { fan.setField(fd); } if (td!=null) { if (!typeutil.isSuperorType(td,fan.getType())) - throw new Error("Field node returns "+fan.getType()+", but need "+td); + throw new Error("Field node returns "+fan.getType()+", but need "+td); } } @@ -697,7 +697,7 @@ public class SemanticCheck { if (td!=null) if (!typeutil.isSuperorType(td,aan.getType())) - throw new Error("Field node returns "+aan.getType()+", but need "+td); + throw new Error("Field node returns "+aan.getType()+", but need "+td); } void checkLiteralNode(Descriptor md, SymbolTable nametable, LiteralNode ln, TypeDescriptor td) { @@ -723,23 +723,23 @@ public class SemanticCheck { if (td!=null) if (!typeutil.isSuperorType(td,ln.getType())) { - Long l = ln.evaluate(); - if((ln.getType().isByte() || ln.getType().isShort() - || ln.getType().isChar() || ln.getType().isInt()) - && (l != null) - && (td.isByte() || td.isShort() || td.isChar() - || td.isInt() || td.isLong())) { - long lnvalue = l.longValue(); - if((td.isByte() && ((lnvalue > 127) || (lnvalue < -128))) - || (td.isShort() && ((lnvalue > 32767) || (lnvalue < -32768))) - || (td.isChar() && ((lnvalue > 65535) || (lnvalue < 0))) - || (td.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648))) - || (td.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) { - throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md); - } - } else { - throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md); - } + Long l = ln.evaluate(); + if((ln.getType().isByte() || ln.getType().isShort() + || ln.getType().isChar() || ln.getType().isInt()) + && (l != null) + && (td.isByte() || td.isShort() || td.isChar() + || td.isInt() || td.isLong())) { + long lnvalue = l.longValue(); + if((td.isByte() && ((lnvalue > 127) || (lnvalue < -128))) + || (td.isShort() && ((lnvalue > 32767) || (lnvalue < -32768))) + || (td.isChar() && ((lnvalue > 65535) || (lnvalue < 0))) + || (td.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648))) + || (td.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) { + throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md); + } + } else { + throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md); + } } } @@ -754,89 +754,89 @@ public class SemanticCheck { } else { String varname=nd.toString(); if(varname.equals("this")) { - // "this" - nn.setVar((VarDescriptor)nametable.get("this")); - return; + // "this" + nn.setVar((VarDescriptor)nametable.get("this")); + return; } Descriptor d=(Descriptor)nametable.get(varname); if (d==null) { - ClassDescriptor cd = null; - if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStaticBlock()) { - // this is a static block, all the accessed fields should be static field - cd = ((MethodDescriptor)md).getClassDesc(); - SymbolTable fieldtbl = cd.getFieldTable(); - FieldDescriptor fd=(FieldDescriptor)fieldtbl.get(varname); - if((fd == null) || (!fd.isStatic())) { - // no such field in the class, check if this is a class - if(varname.equals("this")) { - throw new Error("Error: access this obj in a static block"); - } - cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname); - if(cd != null) { - // this is a class name - nn.setClassDesc(cd); - return; - } else { - throw new Error("Name "+varname+" should not be used in static block: "+md); - } - } else { - // this is a static field - nn.setField(fd); - nn.setClassDesc(cd); - return; - } - } else { - // check if the var is a static field of the class - if(md instanceof MethodDescriptor) { - cd = ((MethodDescriptor)md).getClassDesc(); - FieldDescriptor fd = (FieldDescriptor)cd.getFieldTable().get(varname); - if((fd != null) && (fd.isStatic())) { - nn.setField(fd); - nn.setClassDesc(cd); - if (td!=null) - if (!typeutil.isSuperorType(td,nn.getType())) - throw new Error("Field node returns "+nn.getType()+", but need "+td); - return; - } else if(fd != null) { - throw new Error("Name "+varname+" should not be used in " + md); - } - } - cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname); - if(cd != null) { - // this is a class name - nn.setClassDesc(cd); - return; - } else { - throw new Error("Name "+varname+" undefined in: "+md); - } - } + ClassDescriptor cd = null; + if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStaticBlock()) { + // this is a static block, all the accessed fields should be static field + cd = ((MethodDescriptor)md).getClassDesc(); + SymbolTable fieldtbl = cd.getFieldTable(); + FieldDescriptor fd=(FieldDescriptor)fieldtbl.get(varname); + if((fd == null) || (!fd.isStatic())) { + // no such field in the class, check if this is a class + if(varname.equals("this")) { + throw new Error("Error: access this obj in a static block"); + } + cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname); + if(cd != null) { + // this is a class name + nn.setClassDesc(cd); + return; + } else { + throw new Error("Name "+varname+" should not be used in static block: "+md); + } + } else { + // this is a static field + nn.setField(fd); + nn.setClassDesc(cd); + return; + } + } else { + // check if the var is a static field of the class + if(md instanceof MethodDescriptor) { + cd = ((MethodDescriptor)md).getClassDesc(); + FieldDescriptor fd = (FieldDescriptor)cd.getFieldTable().get(varname); + if((fd != null) && (fd.isStatic())) { + nn.setField(fd); + nn.setClassDesc(cd); + if (td!=null) + if (!typeutil.isSuperorType(td,nn.getType())) + throw new Error("Field node returns "+nn.getType()+", but need "+td); + return; + } else if(fd != null) { + throw new Error("Name "+varname+" should not be used in " + md); + } + } + cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname); + if(cd != null) { + // this is a class name + nn.setClassDesc(cd); + return; + } else { + throw new Error("Name "+varname+" undefined in: "+md); + } + } } if (d instanceof VarDescriptor) { - nn.setVar(d); + nn.setVar(d); } else if (d instanceof FieldDescriptor) { - FieldDescriptor fd=(FieldDescriptor)d; - if (fd.getType().iswrapper()) { - String id=nd.getIdentifier(); - NameDescriptor base=nd.getBase(); - NameNode n=new NameNode(nn.getName()); - n.setNumLine(nn.getNumLine()); - n.setField(fd); - n.setVar((VarDescriptor)nametable.get("this")); /* Need a pointer to this */ - FieldAccessNode fan=new FieldAccessNode(n,"value"); - fan.setNumLine(n.getNumLine()); - FieldDescriptor fdval=(FieldDescriptor) fd.getType().getClassDesc().getFieldTable().get("value"); - fan.setField(fdval); - nn.setExpression(fan); - } else { - nn.setField(fd); - nn.setVar((VarDescriptor)nametable.get("this")); /* Need a pointer to this */ - } + FieldDescriptor fd=(FieldDescriptor)d; + if (fd.getType().iswrapper()) { + String id=nd.getIdentifier(); + NameDescriptor base=nd.getBase(); + NameNode n=new NameNode(nn.getName()); + n.setNumLine(nn.getNumLine()); + n.setField(fd); + n.setVar((VarDescriptor)nametable.get("this")); /* Need a pointer to this */ + FieldAccessNode fan=new FieldAccessNode(n,"value"); + fan.setNumLine(n.getNumLine()); + FieldDescriptor fdval=(FieldDescriptor) fd.getType().getClassDesc().getFieldTable().get("value"); + fan.setField(fdval); + nn.setExpression(fan); + } else { + nn.setField(fd); + nn.setVar((VarDescriptor)nametable.get("this")); /* Need a pointer to this */ + } } else if (d instanceof TagVarDescriptor) { - nn.setVar(d); + nn.setVar(d); } else throw new Error("Wrong type of descriptor"); if (td!=null) - if (!typeutil.isSuperorType(td,nn.getType())) - throw new Error("Field node returns "+nn.getType()+", but need "+td); + if (!typeutil.isSuperorType(td,nn.getType())) + throw new Error("Field node returns "+nn.getType()+", but need "+td); } } @@ -860,9 +860,9 @@ public class SemanticCheck { if (td!=null) { if (!typeutil.isSuperorType(td, ofn.getType())) { - System.out.println(td); - System.out.println(ofn.getType()); - throw new Error("Type of rside not compatible with type of lside"+ofn.printNode(0)); + System.out.println(td); + System.out.println(ofn.getType()); + throw new Error("Type of rside not compatible with type of lside"+ofn.printNode(0)); } } } @@ -893,33 +893,33 @@ public class SemanticCheck { for(int i = 1; i < vec_type.size(); i++) { TypeDescriptor tmp_type = vec_type.elementAt(i); if(out_type == null) { - if(tmp_type != null) { - out_type = tmp_type; - } + if(tmp_type != null) { + out_type = tmp_type; + } } else if(out_type.isNull()) { - if(!tmp_type.isNull() ) { - if(!tmp_type.isArray()) { - throw new Error("Error: mixed type in var initializer list"); - } else { - out_type = tmp_type; - } - } + if(!tmp_type.isNull() ) { + if(!tmp_type.isArray()) { + throw new Error("Error: mixed type in var initializer list"); + } else { + out_type = tmp_type; + } + } } else if(out_type.isArray()) { - if(tmp_type.isArray()) { - if(tmp_type.getArrayCount() > out_type.getArrayCount()) { - out_type = tmp_type; - } - } else if((tmp_type != null) && (!tmp_type.isNull())) { - throw new Error("Error: mixed type in var initializer list"); - } + if(tmp_type.isArray()) { + if(tmp_type.getArrayCount() > out_type.getArrayCount()) { + out_type = tmp_type; + } + } else if((tmp_type != null) && (!tmp_type.isNull())) { + throw new Error("Error: mixed type in var initializer list"); + } } else if(out_type.isInt()) { - if(!tmp_type.isInt()) { - throw new Error("Error: mixed type in var initializer list"); - } + if(!tmp_type.isInt()) { + throw new Error("Error: mixed type in var initializer list"); + } } else if(out_type.isString()) { - if(!tmp_type.isString()) { - throw new Error("Error: mixed type in var initializer list"); - } + if(!tmp_type.isString()) { + throw new Error("Error: mixed type in var initializer list"); + } } } if(out_type != null) { @@ -947,11 +947,11 @@ public class SemanticCheck { /* We want parameter variables to tasks to be immutable */ if (md instanceof TaskDescriptor) { if (an.getDest() instanceof NameNode) { - NameNode nn=(NameNode)an.getDest(); - if (nn.getVar()!=null) { - if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol())) - throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol()); - } + NameNode nn=(NameNode)an.getDest(); + if (nn.getVar()!=null) { + if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol())) + throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol()); + } } } @@ -963,11 +963,11 @@ public class SemanticCheck { NameDescriptor valuend=new NameDescriptor(nd, "valueOf"); if (!(an.getSrc().getType().isString()&&(an.getSrc() instanceof OpNode))) { - MethodInvokeNode rightmin=new MethodInvokeNode(valuend); - rightmin.setNumLine(an.getSrc().getNumLine()); - rightmin.addArgument(an.getSrc()); - an.right=rightmin; - checkExpressionNode(md, nametable, an.getSrc(), null); + MethodInvokeNode rightmin=new MethodInvokeNode(valuend); + rightmin.setNumLine(an.getSrc().getNumLine()); + rightmin.addArgument(an.getSrc()); + an.right=rightmin; + checkExpressionNode(md, nametable, an.getSrc(), null); } } @@ -975,36 +975,36 @@ public class SemanticCheck { TypeDescriptor dt = an.getDest().getType(); TypeDescriptor st = an.getSrc().getType(); if(an.getSrc().kind() == Kind.ArrayInitializerNode) { - if(dt.getArrayCount() != st.getArrayCount()) { - throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0)); - } else { - do { - dt = dt.dereference(); - st = st.dereference(); - } while(dt.isArray()); - if((st.isByte() || st.isShort() || st.isChar() || st.isInt()) - && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) { - return; - } else { - throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0)); - } - } + if(dt.getArrayCount() != st.getArrayCount()) { + throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0)); + } else { + do { + dt = dt.dereference(); + st = st.dereference(); + } while(dt.isArray()); + if((st.isByte() || st.isShort() || st.isChar() || st.isInt()) + && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) { + return; + } else { + throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0)); + } + } } else { - Long l = an.getSrc().evaluate(); - if((st.isByte() || st.isShort() || st.isChar() || st.isInt()) - && (l != null) - && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) { - long lnvalue = l.longValue(); - if((dt.isByte() && ((lnvalue > 127) || (lnvalue < -128))) - || (dt.isShort() && ((lnvalue > 32767) || (lnvalue < -32768))) - || (dt.isChar() && ((lnvalue > 65535) || (lnvalue < 0))) - || (dt.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648))) - || (dt.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) { - throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0)); - } - } else { - throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0)); - } + Long l = an.getSrc().evaluate(); + if((st.isByte() || st.isShort() || st.isChar() || st.isInt()) + && (l != null) + && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) { + long lnvalue = l.longValue(); + if((dt.isByte() && ((lnvalue > 127) || (lnvalue < -128))) + || (dt.isShort() && ((lnvalue > 32767) || (lnvalue < -32768))) + || (dt.isChar() && ((lnvalue > 65535) || (lnvalue < 0))) + || (dt.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648))) + || (dt.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) { + throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0)); + } + } else { + throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0)); + } } } } @@ -1020,8 +1020,8 @@ public class SemanticCheck { BlockNode bn=ln.getInitializer(); bn.getVarTable().setParent(nametable); for(int i=0; i 0) { - eval = t; - } else { - eval = f; - } - } + Long f = this.falseExpr.evaluate(); + if(f != null) { + if(c.intValue() > 0) { + eval = t; + } else { + eval = f; + } + } } } return eval; diff --git a/Robust/src/IR/TypeDescriptor.java b/Robust/src/IR/TypeDescriptor.java index 871aacbc..3cf65385 100644 --- a/Robust/src/IR/TypeDescriptor.java +++ b/Robust/src/IR/TypeDescriptor.java @@ -38,13 +38,13 @@ public class TypeDescriptor extends Descriptor { if (o instanceof TypeDescriptor) { TypeDescriptor t=(TypeDescriptor)o; if (t.type!=type) - return false; + return false; if ((type==CLASS)&&(!t.getSymbol().equals(getSymbol()))) - return false; + return false; if (t.arraycount!=arraycount) - return false; + return false; if (t.isClassNameRef != this.isClassNameRef) - return false; + return false; return true; } return false; diff --git a/Robust/src/IR/TypeUtil.java b/Robust/src/IR/TypeUtil.java index a3960c7a..9467e09c 100644 --- a/Robust/src/IR/TypeUtil.java +++ b/Robust/src/IR/TypeUtil.java @@ -48,13 +48,13 @@ public class TypeUtil { String path = (String) state.classpath.get(i); File f = new File(path, cl.replace('.', '/') + ".java"); if (f.exists()) { - try { - ParseNode pn = Main.readSourceFile(state, f.getCanonicalPath()); - bir.buildtree(pn, todo, f.getCanonicalPath()); - return; - } catch (Exception e) { - throw new Error(e); - } + try { + ParseNode pn = Main.readSourceFile(state, f.getCanonicalPath()); + bir.buildtree(pn, todo, f.getCanonicalPath()); + return; + } catch (Exception e) { + throw new Error(e); + } } } throw new Error("Couldn't find class " + cl); @@ -80,8 +80,8 @@ public class TypeUtil { if (!supertable.containsKey(cd)) { String superc=cd.getSuper(); if (superc!=null) { - ClassDescriptor cd_super=getClass(superc, todo); - supertable.put(cd,cd_super); + ClassDescriptor cd_super=getClass(superc, todo); + supertable.put(cd,cd_super); } } if (!superIFtbl.containsKey(cd)) { @@ -90,9 +90,9 @@ public class TypeUtil { HashSet hs=(HashSet)superIFtbl.get(cd); Vector superifv = cd.getSuperInterface(); for(int i = 0; i < superifv.size(); i++) { - String superif = superifv.elementAt(i); - ClassDescriptor if_super = getClass(superif, todo); - hs.add(if_super); + String superif = superifv.elementAt(i); + ClassDescriptor if_super = getClass(superif, todo); + hs.add(if_super); } } return cd; @@ -112,7 +112,7 @@ public class TypeUtil { for(Iterator methodit=cd.getMethodTable().getSet("run").iterator(); methodit.hasNext(); ) { MethodDescriptor md=(MethodDescriptor) methodit.next(); if (md.numParameters()!=0||md.getModifiers().isStatic()) - continue; + continue; return md; } throw new Error("Can't find Thread.run"); @@ -123,7 +123,7 @@ public class TypeUtil { for(Iterator methodit=cd.getMethodTable().getSet("staticStart").iterator(); methodit.hasNext(); ) { MethodDescriptor md=(MethodDescriptor) methodit.next(); if (md.numParameters()!=1||!md.getModifiers().isStatic()||!md.getParamType(0).isClass()||md.getParamType(0).getClassDesc()!=cd) - continue; + continue; return md; } throw new Error("Can't find Thread.run"); @@ -138,7 +138,7 @@ public class TypeUtil { for(Iterator methodit = cd.getMethodTable().getSet("execute").iterator(); methodit.hasNext(); ) { MethodDescriptor md = (MethodDescriptor) methodit.next(); if (md.numParameters()!=0 || md.getModifiers().isStatic()) - continue; + continue; return md; } throw new Error("Can't find Task.execute"); @@ -152,16 +152,16 @@ public class TypeUtil { for(Iterator mainit=mainset.iterator(); mainit.hasNext(); ) { MethodDescriptor md=(MethodDescriptor)mainit.next(); if (md.numParameters()!=1) - continue; + continue; Descriptor pd=md.getParameter(0); TypeDescriptor tpd=(pd instanceof TagVarDescriptor)?((TagVarDescriptor)pd).getType():((VarDescriptor)pd) .getType(); if (tpd.getArrayCount()!=1) - continue; + continue; if (!tpd.getSymbol().equals(StringClass)) - continue; + continue; if (!md.getModifiers().isStatic()) - throw new Error("Error: Non static main"); + throw new Error("Error: Non static main"); return md; } throw new Error(cd+" has no main"); @@ -177,18 +177,18 @@ public class TypeUtil { throw new Error(); for(int i=0; i it_sifs = getSuperIFs(cd2).iterator(); while(it_sifs.hasNext()) { - ClassDescriptor cd = it_sifs.next(); - if(cd == possiblesuper) { - return true; - } else if(!tovisit.contains(cd)) { - tovisit.add(cd); - } + ClassDescriptor cd = it_sifs.next(); + if(cd == possiblesuper) { + return true; + } else if(!tovisit.contains(cd)) { + tovisit.add(cd); + } } } while(cd2!=null) { cd2=getSuper(cd2); if (cd2==possiblesuper) - return true; + return true; // check cd2's interface ancestors if(cd2 != null) { - Iterator it_sifs = getSuperIFs(cd2).iterator(); - while(it_sifs.hasNext()) { - ClassDescriptor cd = (ClassDescriptor)it_sifs.next(); - if(cd == possiblesuper) { - return true; - } else if(!tovisit.contains(cd)) { - tovisit.add(cd); - } - } + Iterator it_sifs = getSuperIFs(cd2).iterator(); + while(it_sifs.hasNext()) { + ClassDescriptor cd = (ClassDescriptor)it_sifs.next(); + if(cd == possiblesuper) { + return true; + } else if(!tovisit.contains(cd)) { + tovisit.add(cd); + } + } } } @@ -474,16 +474,16 @@ NextMethod: tovisit.remove(cd); if(!visited.contains(cd)) { - Iterator it_sifs = getSuperIFs(cd).iterator(); - while(it_sifs.hasNext()) { - ClassDescriptor cdt = (ClassDescriptor)it_sifs.next(); - if(cdt == possiblesuper) { - return true; - } else if(!tovisit.contains(cdt)) { - tovisit.add(cdt); - } - } - visited.add(cd); + Iterator it_sifs = getSuperIFs(cd).iterator(); + while(it_sifs.hasNext()) { + ClassDescriptor cdt = (ClassDescriptor)it_sifs.next(); + if(cdt == possiblesuper) { + return true; + } else if(!tovisit.contains(cdt)) { + tovisit.add(cdt); + } + } + visited.add(cd); } } return false; diff --git a/Robust/src/IR/Virtual.java b/Robust/src/IR/Virtual.java index 788e6bec..61347496 100644 --- a/Robust/src/IR/Virtual.java +++ b/Robust/src/IR/Virtual.java @@ -53,16 +53,16 @@ public class Virtual { while(classit.hasNext()) { ClassDescriptor cd=(ClassDescriptor)classit.next(); if (state.DSM||state.SINGLETM) - numberLocality(cd); + numberLocality(cd); else - numberMethods(cd); + numberMethods(cd); } classit=state.getClassSymbolTable().getDescriptorsIterator(); while(classit.hasNext()) { ClassDescriptor cd=(ClassDescriptor)classit.next(); if(!cd.isInterface()) { - int count = classmethodcount.get(cd).intValue(); - classmethodcount.put(cd, new Integer(count+this.if_starts)); + int count = classmethodcount.get(cd).intValue(); + classmethodcount.put(cd, new Integer(count+this.if_starts)); } } } @@ -77,36 +77,36 @@ public class Virtual { if (locality.getClassBindings(cd)!=null) for(Iterator lbit=locality.getClassBindings(cd).iterator(); lbit.hasNext(); ) { - LocalityBinding lb=lbit.next(); - MethodDescriptor md=lb.getMethod(); - //Is it a static method or constructor - if (md.isStatic()||md.getReturnType()==null) - continue; - - if (superdesc!=null) { - Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol()); - boolean foundmatch=false; - for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { - MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); - if (md.matches(matchmd)) { - Set lbset=locality.getMethodBindings(matchmd); - if (lbset!=null) - for(Iterator suplbit=lbset.iterator(); suplbit.hasNext(); ) { - LocalityBinding suplb=suplbit.next(); - if (lb.contextMatches(suplb)) { - foundmatch=true; - localitynumber.put(lb, localitynumber.get(suplb)); - break; - } - } - break; - } - } - if (!foundmatch) - localitynumber.put(lb, new Integer(start++)); - } else { - localitynumber.put(lb, new Integer(start++)); - } + LocalityBinding lb=lbit.next(); + MethodDescriptor md=lb.getMethod(); + //Is it a static method or constructor + if (md.isStatic()||md.getReturnType()==null) + continue; + + if (superdesc!=null) { + Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol()); + boolean foundmatch=false; + for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { + MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); + if (md.matches(matchmd)) { + Set lbset=locality.getMethodBindings(matchmd); + if (lbset!=null) + for(Iterator suplbit=lbset.iterator(); suplbit.hasNext(); ) { + LocalityBinding suplb=suplbit.next(); + if (lb.contextMatches(suplb)) { + foundmatch=true; + localitynumber.put(lb, localitynumber.get(suplb)); + break; + } + } + break; + } + } + if (!foundmatch) + localitynumber.put(lb, new Integer(start++)); + } else { + localitynumber.put(lb, new Integer(start++)); + } } classmethodcount.put(cd, new Integer(start)); return start; @@ -128,26 +128,26 @@ public class Virtual { for(Iterator it=cd.getMethods(); it.hasNext(); ) { MethodDescriptor md=(MethodDescriptor)it.next(); if (md.isStatic()||md.getReturnType()==null) - continue; + continue; if (!callgraph.isCallable(md)&&!callgraph.isCalled(md)) - continue; + continue; boolean foundmatch=false; // check if there is a matched method that has been assigned method num Set possiblematches_if = if_methods.getSet(md.getSymbol()); for(Iterator matchit=possiblematches_if.iterator(); matchit.hasNext(); ) { - MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); - if (md.matches(matchmd)) { - int num=methodnumber.get(matchmd); - methodnumber.put(md, new Integer(num)); - foundmatch=true; - break; - } + MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); + if (md.matches(matchmd)) { + int num=methodnumber.get(matchmd); + methodnumber.put(md, new Integer(num)); + foundmatch=true; + break; + } } if (!foundmatch) { - methodnumber.put(md, new Integer(if_starts++)); - if_methods.add(md); - mnum++; + methodnumber.put(md, new Integer(if_starts++)); + if_methods.add(md); + mnum++; } } classmethodcount.put(cd, new Integer(mnum)); @@ -168,41 +168,41 @@ methodit: for(Iterator it=cd.getMethods(); it.hasNext(); ) { MethodDescriptor md=(MethodDescriptor)it.next(); if (md.isStatic()||md.getReturnType()==null) - continue; + continue; if (!callgraph.isCallable(md)&&!callgraph.isCalled(md)) - continue; + continue; // check if there is a matched method in methods defined in interfaces Set possiblematches_if=if_methods.getSet(md.getSymbol()); for(Iterator matchit=possiblematches_if.iterator(); matchit.hasNext(); ) { - MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); - if (md.matches(matchmd)) { - int num; - if (!methodnumber.containsKey(matchmd)) { - num=start++; - mnum++; - methodnumber.put(matchmd,num); - } else - num = methodnumber.get(matchmd); - methodnumber.put(md, new Integer(num)); - continue methodit; - } + MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); + if (md.matches(matchmd)) { + int num; + if (!methodnumber.containsKey(matchmd)) { + num=start++; + mnum++; + methodnumber.put(matchmd,num); + } else + num = methodnumber.get(matchmd); + methodnumber.put(md, new Integer(num)); + continue methodit; + } } if (superdesc!=null) { - Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol()); - for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { - MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); - if (md.matches(matchmd)) { - int num; - if (!methodnumber.containsKey(matchmd)) { - num=start++; - mnum++; - methodnumber.put(matchmd,num); - } else - num = methodnumber.get(matchmd); - methodnumber.put(md, new Integer(num)); - continue methodit; - } - } + Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol()); + for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) { + MethodDescriptor matchmd=(MethodDescriptor)matchit.next(); + if (md.matches(matchmd)) { + int num; + if (!methodnumber.containsKey(matchmd)) { + num=start++; + mnum++; + methodnumber.put(matchmd,num); + } else + num = methodnumber.get(matchmd); + methodnumber.put(md, new Integer(num)); + continue methodit; + } + } } methodnumber.put(md, new Integer(start++)); diff --git a/Robust/src/Interface/HTTPServices.java b/Robust/src/Interface/HTTPServices.java index 4391a312..aa2acb5f 100644 --- a/Robust/src/Interface/HTTPServices.java +++ b/Robust/src/Interface/HTTPServices.java @@ -37,7 +37,7 @@ public class HTTPServices { try { while((size = reader.read(buffer,0,buffer.length)) != -1) - out.write(buffer,0,size); + out.write(buffer,0,size); reader.close(); } catch(IOException e) { e.printStackTrace(); diff --git a/Robust/src/Interface/HashStrings.java b/Robust/src/Interface/HashStrings.java index 0f3bd801..37f04245 100644 --- a/Robust/src/Interface/HashStrings.java +++ b/Robust/src/Interface/HashStrings.java @@ -13,8 +13,8 @@ class HashStrings { int i = key.hashCode() % n; while (p[i] != null) { if (key.equals(p[i].key)) { - p[i] = new Pair(key, value); - return; + p[i] = new Pair(key, value); + return; } i = (i+1) % n; } @@ -27,7 +27,7 @@ class HashStrings { int i = key.hashCode() % n; while (p[i] != null) { if (key.equals(p[i].key)) - return p[i].value; + return p[i].value; i = (i+1) % n; } return null; diff --git a/Robust/src/Interface/IdentityRelation.java b/Robust/src/Interface/IdentityRelation.java index efe41fda..806befff 100644 --- a/Robust/src/Interface/IdentityRelation.java +++ b/Robust/src/Interface/IdentityRelation.java @@ -20,7 +20,7 @@ class IdentityRelation { IdentityRelation ir=(IdentityRelation) obj; if (fieldname1.equals(ir.fieldname1)&& fieldname2.equals(ir.fieldname2)) - return true; + return true; } return false; } diff --git a/Robust/src/Interface/Imap.java b/Robust/src/Interface/Imap.java index a20f43c2..b616f9c1 100644 --- a/Robust/src/Interface/Imap.java +++ b/Robust/src/Interface/Imap.java @@ -37,7 +37,7 @@ class Imap { Rectangle r=rectangles[i]; if ((r.x1<=x)&&(r.y1>=y)&& (r.x2>=x)&&(r.y2<=y)) - return r.label; + return r.label; } long mindistance=Long.MAX_VALUE; int minindex=-1; @@ -46,8 +46,8 @@ class Imap { long dx=p.x-x; long dy=p.y-y; if ((dx*dx+dy*dy)THRESHOLD) @@ -72,49 +72,49 @@ class Imap { ArrayList points=new ArrayList(); while(true) { try { - firstchar=fr.read(); + firstchar=fr.read(); } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); + e.printStackTrace(); + System.exit(-1); } /* EOF?*/ if (firstchar==-1) - break; + break; switch(firstchar) { case 'b': case '#': - while(firstchar!='\n') { - try { - firstchar=fr.read(); - } catch (IOException e) { - e.printStackTrace(); - System.exit(-1); - } - } - break; + while(firstchar!='\n') { + try { + firstchar=fr.read(); + } catch (IOException e) { + e.printStackTrace(); + System.exit(-1); + } + } + break; case 'r': { - nexttoken(fr,false); - String label=nexttoken(fr,false); - String x1=nexttoken(fr,true); - String y1=nexttoken(fr,true); - String x2=nexttoken(fr,true); - String y2=nexttoken(fr,true); - Rectangle r=new Rectangle(label,Integer.parseInt(x1),Integer.parseInt(y1), - Integer.parseInt(x2),Integer.parseInt(y2)); - rectangles.add(r); + nexttoken(fr,false); + String label=nexttoken(fr,false); + String x1=nexttoken(fr,true); + String y1=nexttoken(fr,true); + String x2=nexttoken(fr,true); + String y2=nexttoken(fr,true); + Rectangle r=new Rectangle(label,Integer.parseInt(x1),Integer.parseInt(y1), + Integer.parseInt(x2),Integer.parseInt(y2)); + rectangles.add(r); } break; case 'p': { - nexttoken(fr,false); - String label=nexttoken(fr,false); - String x=nexttoken(fr,true); - String y=nexttoken(fr,true); - Point p=new Point(label,Integer.parseInt(x),Integer.parseInt(y)); - points.add(p); + nexttoken(fr,false); + String label=nexttoken(fr,false); + String x=nexttoken(fr,true); + String y=nexttoken(fr,true); + Point p=new Point(label,Integer.parseInt(x),Integer.parseInt(y)); + points.add(p); } break; } @@ -129,17 +129,17 @@ class Imap { boolean looped=false; while(true) { try { - c=isr.read(); + c=isr.read(); } catch (IOException e) { - e.printStackTrace(); - System.exit(-1); + e.printStackTrace(); + System.exit(-1); } if ((c==' ')||(c=='\n')||(commas&&c==',')) { - if (!looped) { - looped=true; - continue; - } - return string; + if (!looped) { + looped=true; + continue; + } + return string; } string=string+new String(new char[] {(char)c}); looped=true; diff --git a/Robust/src/Interface/JhttpServer.java b/Robust/src/Interface/JhttpServer.java index 0ad96d64..e2d914a4 100644 --- a/Robust/src/Interface/JhttpServer.java +++ b/Robust/src/Interface/JhttpServer.java @@ -37,9 +37,9 @@ public class JhttpServer extends Thread { // infinite loop while (true) { try { - startWorker(server.accept()); + startWorker(server.accept()); } catch (Exception e) { - System.err.println(e); + System.err.println(e); } } } diff --git a/Robust/src/Interface/JhttpWorker.java b/Robust/src/Interface/JhttpWorker.java index f64c1b48..f7e3f352 100644 --- a/Robust/src/Interface/JhttpWorker.java +++ b/Robust/src/Interface/JhttpWorker.java @@ -58,38 +58,38 @@ public class JhttpWorker extends Thread { switch(method(in)) { case 0: - if (webinterface.specialRequest(fileName)) { - String newfile=webinterface.handleresponse(fileName, out, resp); - if (newfile!=null) { - HTTPServices.GET_handler(newfile, out, resp); - } - } else - HTTPServices.GET_handler(fileName, out, resp); - break; + if (webinterface.specialRequest(fileName)) { + String newfile=webinterface.handleresponse(fileName, out, resp); + if (newfile!=null) { + HTTPServices.GET_handler(newfile, out, resp); + } + } else + HTTPServices.GET_handler(fileName, out, resp); + break; case 1: - HTTPServices.HEAD_handler(fileName, out, resp); - break; + HTTPServices.HEAD_handler(fileName, out, resp); + break; case 2: - HTTPServices.POST_handler(fileName, out, resp); - break; + HTTPServices.POST_handler(fileName, out, resp); + break; default: - resp.returnCode = 501; //error + resp.returnCode = 501; //error } try { - out.flush(); - if (logging) - LogFile.write_log(client,methodType,fileName,httpVersion, - resp.returnCode,resp.sentBytes); - - out.close(); - in.close(); - client.close(); + out.flush(); + if (logging) + LogFile.write_log(client,methodType,fileName,httpVersion, + resp.returnCode,resp.sentBytes); + + out.close(); + in.close(); + client.close(); } catch(IOException e) { - ; // do nothing + ; // do nothing } } @@ -116,58 +116,58 @@ public class JhttpWorker extends Thread { // only spaces used StringTokenizer tok = new StringTokenizer(line, " "); if (tok.hasMoreTokens()) { // make sure there is a request - String str = tok.nextToken(); - - if ( str.equals("GET") ) { - ret = 0; - methodType = "GET"; - } else if ( str.equals("HEAD") ) { - ret = 1; - methodType = "HEAD"; - } else if ( str.equals("POST") ) { - ret = 2; - methodType = "POST"; - } else { - System.out.println("501 - unsupported request:" +str); - return -1; - } + String str = tok.nextToken(); + + if ( str.equals("GET") ) { + ret = 0; + methodType = "GET"; + } else if ( str.equals("HEAD") ) { + ret = 1; + methodType = "HEAD"; + } else if ( str.equals("POST") ) { + ret = 2; + methodType = "POST"; + } else { + System.out.println("501 - unsupported request:" +str); + return -1; + } } else { - // System.out.println("Request from browser was empty!"); - return -1; + // System.out.println("Request from browser was empty!"); + return -1; } // get the filename if (tok.hasMoreTokens()) { - fileName = tok.nextToken(); - if(fileName.equals("/")) { - fileName = "/index.html"; - } + fileName = tok.nextToken(); + if(fileName.equals("/")) { + fileName = "/index.html"; + } } else { - // this is weird... why am i taking the first character of - // the filename if there are no more tokens? - // - catch should take care of this - fileName = fileName.substring(1); + // this is weird... why am i taking the first character of + // the filename if there are no more tokens? + // - catch should take care of this + fileName = fileName.substring(1); } // read the http version number // - right now nothing is done with this information if (tok.hasMoreTokens()) { - httpVersion = tok.nextToken(); + httpVersion = tok.nextToken(); } else { - httpVersion = "http/1.0"; // default + httpVersion = "http/1.0"; // default } // read remainder of the browser's header // - nothing done right now with this info... placeholder while((line = in.readLine()) != null) { - StringTokenizer token = new StringTokenizer(line," "); + StringTokenizer token = new StringTokenizer(line," "); - // do processing here - if(!token.hasMoreTokens()) { - break; - } + // do processing here + if(!token.hasMoreTokens()) { + break; + } } } catch(Exception e) { System.err.println(e); diff --git a/Robust/src/Interface/WebInterface.java b/Robust/src/Interface/WebInterface.java index 3226b6df..4f6fd269 100644 --- a/Robust/src/Interface/WebInterface.java +++ b/Robust/src/Interface/WebInterface.java @@ -36,19 +36,19 @@ public class WebInterface { for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext(); ) { ClassDescriptor cd=(ClassDescriptor) it_classes.next(); if(cd.hasFlags()) { - Vector rootnodes=taskanalysis.getRootNodes(cd); - - if(rootnodes!=null) - for(Iterator it_rootnodes=rootnodes.iterator(); it_rootnodes.hasNext(); ) { - FlagState root=(FlagState)it_rootnodes.next(); - Vector cd_nodeid=new Vector(); //Vector is designed to contain only 2 elements: ClassDescriptor,Node label - // Both the values are required to correctly resolve the rootnode. - // Should think of a better way to do this, instead of using a vector(maybe a class) - cd_nodeid.addElement(cd); //adding the ClassDescriptor - cd_nodeid.addElement(root.getLabel()); //adding the Node label - System.out.println(cd+" "+root.getLabel()); - sourcenodemap.put("/"+cd.getSymbol()+"_"+root.getLabel()+".html",cd_nodeid); - } + Vector rootnodes=taskanalysis.getRootNodes(cd); + + if(rootnodes!=null) + for(Iterator it_rootnodes=rootnodes.iterator(); it_rootnodes.hasNext(); ) { + FlagState root=(FlagState)it_rootnodes.next(); + Vector cd_nodeid=new Vector(); //Vector is designed to contain only 2 elements: ClassDescriptor,Node label + // Both the values are required to correctly resolve the rootnode. + // Should think of a better way to do this, instead of using a vector(maybe a class) + cd_nodeid.addElement(cd); //adding the ClassDescriptor + cd_nodeid.addElement(root.getLabel()); //adding the Node label + System.out.println(cd+" "+root.getLabel()); + sourcenodemap.put("/"+cd.getSymbol()+"_"+root.getLabel()+".html",cd_nodeid); + } } } } @@ -96,10 +96,10 @@ public class WebInterface { pw.println("

Instantiated Classes:

"); Set newstates=taganalysis.getFlagStates(td); for(Iterator fsit=newstates.iterator(); fsit.hasNext(); ) { - FlagState fsnew=(FlagState) fsit.next(); - ClassDescriptor cd=fsnew.getClassDescriptor(); - pw.println("  "+cd.getSymbol()+"
"); - pw.println("    "+fsnew.getTextLabel()+"
"); + FlagState fsnew=(FlagState) fsit.next(); + ClassDescriptor cd=fsnew.getClassDescriptor(); + pw.println("  "+cd.getSymbol()+"
"); + pw.println("    "+fsnew.getTextLabel()+"
"); } pw.flush(); @@ -113,9 +113,9 @@ public class WebInterface { try { for(int i=0; i < td.numParameters(); i++) { - pw.println("FlagState Graph:  "+td.getParamType(i)+"
"); - pw.println("Task Graph:        " - +td.getParamType(i)+"
"); + pw.println("FlagState Graph:  "+td.getParamType(i)+"
"); + pw.println("Task Graph:        " + +td.getParamType(i)+"
"); } pw.flush(); } catch(Exception e) { @@ -129,20 +129,20 @@ public class WebInterface { for(Iterator it_rootnodes=rootnodes.iterator(); it_rootnodes.hasNext(); ) { FlagState root=(FlagState)it_rootnodes.next(); if (root.getLabel().equals((String)cd_nodeid.elementAt(1))) { - try { - PrintWriter pw=new PrintWriter(out); - pw.println("

Allocating tasks for "+root.getTextLabel()+":


"); - Vector tasks=root.getAllocatingTasks(); - for(Iterator it_tasks=tasks.iterator(); it_tasks.hasNext(); ) { - TaskDescriptor td=(TaskDescriptor)it_tasks.next(); - pw.println("
Task:   "+td.toString()+"
"); - printTask(td,pw); - } - - } catch (Exception e) { - e.printStackTrace(); System.exit(-1); - } - break; + try { + PrintWriter pw=new PrintWriter(out); + pw.println("

Allocating tasks for "+root.getTextLabel()+":


"); + Vector tasks=root.getAllocatingTasks(); + for(Iterator it_tasks=tasks.iterator(); it_tasks.hasNext(); ) { + TaskDescriptor td=(TaskDescriptor)it_tasks.next(); + pw.println("
Task:   "+td.toString()+"
"); + printTask(td,pw); + } + + } catch (Exception e) { + e.printStackTrace(); System.exit(-1); + } + break; } } @@ -178,7 +178,7 @@ public class WebInterface { //pw.println(""); pw.println(""); while((str=mapbr.readLine())!=null) { - pw.println(str); + pw.println(str); } pw.flush(); @@ -217,7 +217,7 @@ public class WebInterface { pw.println(""); while((str=mapbr.readLine())!=null) { - pw.println(str); + pw.println(str); } pw.flush(); } catch (Exception e) { @@ -235,16 +235,16 @@ public class WebInterface { for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext(); ) { ClassDescriptor cd=(ClassDescriptor) it_classes.next(); if (cd.hasFlags()) { - if (taskanalysis.getFlagStates(cd)!=null) { - pw.println(""+ cd.getSymbol() +""); - pw.println("
"); - flagstatemap.put("/"+cd.getSymbol()+".html", cd); - } - if (taskgraph.getTaskNodes(cd)!=null) { - pw.println("Task Graph "+ cd.getSymbol() +""); - pw.println("
"); - taskgraphmap.put("/"+cd.getSymbol()+"-t.html", cd); - } + if (taskanalysis.getFlagStates(cd)!=null) { + pw.println(""+ cd.getSymbol() +""); + pw.println("
"); + flagstatemap.put("/"+cd.getSymbol()+".html", cd); + } + if (taskgraph.getTaskNodes(cd)!=null) { + pw.println("Task Graph "+ cd.getSymbol() +""); + pw.println("
"); + taskgraphmap.put("/"+cd.getSymbol()+"-t.html", cd); + } } } pw.println("

Program flow"); @@ -280,7 +280,7 @@ public class WebInterface { pw.println(""); while((str=mapbr.readLine())!=null) - pw.println(str); + pw.println(str); pw.flush(); } catch (Exception e) { diff --git a/Robust/src/Lex/Comment.java b/Robust/src/Lex/Comment.java index 2e02ff41..a9c55048 100644 --- a/Robust/src/Lex/Comment.java +++ b/Robust/src/Lex/Comment.java @@ -13,12 +13,12 @@ abstract class Comment extends InputElement { // skip leading white space. for (; i' && second=='>')) { // >> String op = new String(new char[] {first, consume()}); if (first=='>' && line.charAt(line_pos)=='>') // >>> - op += consume(); + op += consume(); if (line.charAt(line_pos)=='=') // <<=, >>=, >>>= - op += consume(); + op += consume(); return new Operator(op); } @@ -472,15 +472,15 @@ public class Lexer { while (line.charAt(line_pos)!='\"') { switch(line.charAt(line_pos)) { case '\\': - val.append(getEscapeSequence()); - break; + val.append(getEscapeSequence()); + break; case '\n': - throw new IOException("Invalid string literal on line " + line_num); + throw new IOException("Invalid string literal on line " + line_num); default: - val.append(consume()); - break; + val.append(consume()); + break; } } char closequote = consume(); @@ -538,7 +538,7 @@ public class Lexer { int i, val=0; for (i=0; i0xFF)) // impossible. throw new IOException("Invalid octal escape sequence in line " + line_num); @@ -561,7 +561,7 @@ public class Lexer { int n=line_num, c=info.left-lineL.head; for (LineList p = lineL; p!=null; p=p.tail, n--) if (p.head<=info.left) { - c=info.left-p.head; break; + c=info.left-p.head; break; } System.err.println(msg+" at line "+n); num_errors++; diff --git a/Robust/src/Lex/Token.java b/Robust/src/Lex/Token.java index 8cfb5c59..ad62554a 100644 --- a/Robust/src/Lex/Token.java +++ b/Robust/src/Lex/Token.java @@ -14,10 +14,10 @@ abstract class Token extends InputElement { case '\n': sb.append("\\n"); break; default: - if ((int)s.charAt(i)<32) - sb.append("\\"+Integer.toOctalString((int)s.charAt(i))); - else - sb.append(s.charAt(i)); + if ((int)s.charAt(i)<32) + sb.append("\\"+Integer.toOctalString((int)s.charAt(i))); + else + sb.append(s.charAt(i)); } return sb.toString(); } diff --git a/Robust/src/Main/Main.java b/Robust/src/Main/Main.java index 63fa75a0..d573dabf 100644 --- a/Robust/src/Main/Main.java +++ b/Robust/src/Main/Main.java @@ -81,324 +81,324 @@ public class Main { for(int i=0; i"); - } + state.DISJOINTWRITEDOTS = true; + String arg = args[++i]; + if( arg.equals("all") ) { + state.DISJOINTWRITEALL = true; + } else if( arg.equals("final") ) { + state.DISJOINTWRITEALL = false; + } else { + throw new Error("disjoint-write-dots requires argument "); + } } else if (option.equals("-disjoint-write-initial-contexts")) { - state.DISJOINTWRITEINITCONTEXTS = true; + state.DISJOINTWRITEINITCONTEXTS = true; } else if (option.equals("-disjoint-write-ihms")) { - state.DISJOINTWRITEIHMS = true; + state.DISJOINTWRITEIHMS = true; } else if (option.equals("-disjoint-alias-file")) { - state.DISJOINTALIASFILE = args[++i]; - String arg = args[++i]; - if( arg.equals("normal") ) { - state.DISJOINTALIASTAB = false; - } else if( arg.equals("tabbed") ) { - state.DISJOINTALIASTAB = true; - } else { - throw new Error("disjoint-alias-file requires arguments: "); - } + state.DISJOINTALIASFILE = args[++i]; + String arg = args[++i]; + if( arg.equals("normal") ) { + state.DISJOINTALIASTAB = false; + } else if( arg.equals("tabbed") ) { + state.DISJOINTALIASTAB = true; + } else { + throw new Error("disjoint-alias-file requires arguments: "); + } } else if (option.equals("-disjoint-debug-callsite")) { - state.DISJOINTDEBUGCALLEE=args[++i]; - state.DISJOINTDEBUGCALLER=args[++i]; - state.DISJOINTDEBUGCALLVISITTOSTART=Integer.parseInt(args[++i]); - state.DISJOINTDEBUGCALLNUMVISITS=Integer.parseInt(args[++i]); - String arg = args[++i]; - if( arg.equals("true") ) { - state.DISJOINTDEBUGCALLSTOPAFTER = true; - } else if( arg.equals("false") ) { - state.DISJOINTDEBUGCALLSTOPAFTER = false; - } else { - throw new Error("disjoint-debug-callsite requires arguments:\n"+ - " <# visit to start> <# visits to capture> "); - } + state.DISJOINTDEBUGCALLEE=args[++i]; + state.DISJOINTDEBUGCALLER=args[++i]; + state.DISJOINTDEBUGCALLVISITTOSTART=Integer.parseInt(args[++i]); + state.DISJOINTDEBUGCALLNUMVISITS=Integer.parseInt(args[++i]); + String arg = args[++i]; + if( arg.equals("true") ) { + state.DISJOINTDEBUGCALLSTOPAFTER = true; + } else if( arg.equals("false") ) { + state.DISJOINTDEBUGCALLSTOPAFTER = false; + } else { + throw new Error("disjoint-debug-callsite requires arguments:\n"+ + " <# visit to start> <# visits to capture> "); + } } else if (option.equals("-disjoint-debug-snap-method")) { - state.DISJOINTSNAPSYMBOL=args[++i]; - state.DISJOINTSNAPVISITTOSTART=Integer.parseInt(args[++i]); - state.DISJOINTSNAPNUMVISITS=Integer.parseInt(args[++i]); - String arg = args[++i]; - if( arg.equals("true") ) { - state.DISJOINTSNAPSTOPAFTER = true; - } else if( arg.equals("false") ) { - state.DISJOINTSNAPSTOPAFTER = false; - } else { - throw new Error("disjoint-debug-snap-method requires arguments:\n"+ - " <# visit to start> <# visits to snap> "); - } + state.DISJOINTSNAPSYMBOL=args[++i]; + state.DISJOINTSNAPVISITTOSTART=Integer.parseInt(args[++i]); + state.DISJOINTSNAPNUMVISITS=Integer.parseInt(args[++i]); + String arg = args[++i]; + if( arg.equals("true") ) { + state.DISJOINTSNAPSTOPAFTER = true; + } else if( arg.equals("false") ) { + state.DISJOINTSNAPSTOPAFTER = false; + } else { + throw new Error("disjoint-debug-snap-method requires arguments:\n"+ + " <# visit to start> <# visits to snap> "); + } } else if( option.equals("-disjoint-release-mode") ) { - state.DISJOINTRELEASEMODE = true; + state.DISJOINTRELEASEMODE = true; } else if( option.equals("-disjoint-dvisit-stack") ) { - state.DISJOINTDVISITSTACK = true; - state.DISJOINTDVISITPQUE = false; - state.DISJOINTDVISITSTACKEESONTOP = false; + state.DISJOINTDVISITSTACK = true; + state.DISJOINTDVISITPQUE = false; + state.DISJOINTDVISITSTACKEESONTOP = false; } else if( option.equals("-disjoint-dvisit-pqueue") ) { - state.DISJOINTDVISITPQUE = true; - state.DISJOINTDVISITSTACK = false; - state.DISJOINTDVISITSTACKEESONTOP = false; + state.DISJOINTDVISITPQUE = true; + state.DISJOINTDVISITSTACK = false; + state.DISJOINTDVISITSTACKEESONTOP = false; } else if( option.equals("-disjoint-dvisit-stack-callees-on-top") ) { - state.DISJOINTDVISITSTACKEESONTOP = true; - state.DISJOINTDVISITPQUE = false; - state.DISJOINTDVISITSTACK = false; + state.DISJOINTDVISITSTACKEESONTOP = true; + state.DISJOINTDVISITPQUE = false; + state.DISJOINTDVISITSTACK = false; } else if( option.equals("-disjoint-desire-determinism") ) { - state.DISJOINTDETERMINISM = true; + state.DISJOINTDETERMINISM = true; - // when asking analysis for a deterministic result, force - // a stack-based visiting scheme, because the priority queue - // requires a non-deterministic topological sort - state.DISJOINTDVISITSTACKEESONTOP = true; - state.DISJOINTDVISITPQUE = false; - state.DISJOINTDVISITSTACK = false; + // when asking analysis for a deterministic result, force + // a stack-based visiting scheme, because the priority queue + // requires a non-deterministic topological sort + state.DISJOINTDVISITSTACKEESONTOP = true; + state.DISJOINTDVISITPQUE = false; + state.DISJOINTDVISITSTACK = false; } else if( option.equals("-disjoint-debug-scheduling") ) { - state.DISJOINTDEBUGSCHEDULING = true; + state.DISJOINTDEBUGSCHEDULING = true; } else if (option.equals("-optional")) - state.OPTIONAL=true; + state.OPTIONAL=true; else if (option.equals("-optimize")) - state.OPTIMIZE=true; + state.OPTIMIZE=true; else if (option.equals("-noloop")) - state.NOLOOP=true; + state.NOLOOP=true; else if (option.equals("-dcopts")) - state.DCOPTS=true; + state.DCOPTS=true; else if (option.equals("-arraypad")) - state.ARRAYPAD=true; + state.ARRAYPAD=true; else if (option.equals("-delaycomp")) - state.DELAYCOMP=true; + state.DELAYCOMP=true; else if (option.equals("-raw")) - state.RAW=true; + state.RAW=true; else if (option.equals("-scheduling")) - state.SCHEDULING=true; + state.SCHEDULING=true; else if (option.equals("-distributioninfo")) - isDistributeInfo=true; + isDistributeInfo=true; else if (option.equals("-disall")) - isDisAll=true; + isDisAll=true; else if (option.equals("-disstart")) - startnum = Integer.parseInt(args[++i]); + startnum = Integer.parseInt(args[++i]); else if (option.equals("-useprofile")) { - state.USEPROFILE=true; - state.profilename = args[++i]; + state.USEPROFILE=true; + state.profilename = args[++i]; } else if (option.equals("-thread")) - state.THREAD=true; + state.THREAD=true; else if (option.equals("-dsm")) - state.DSM=true; + state.DSM=true; else if (option.equals("-recoverystats")) - state.DSMRECOVERYSTATS=true; + state.DSMRECOVERYSTATS=true; else if (option.equals("-dsmtask")) - state.DSMTASK=true; + state.DSMTASK=true; else if (option.equals("-singleTM")) - state.SINGLETM=true; + state.SINGLETM=true; else if (option.equals("-readset")) - state.READSET=true; + state.READSET=true; else if (option.equals("-webinterface")) - state.WEBINTERFACE=true; + state.WEBINTERFACE=true; else if (option.equals("-instructionfailures")) - state.INSTRUCTIONFAILURE=true; + state.INSTRUCTIONFAILURE=true; else if (option.equals("-abcclose")) - state.ARRAYBOUNDARYCHECK=false; + state.ARRAYBOUNDARYCHECK=false; else if (option.equals("-methodeffects")) { - state.METHODEFFECTS=true; + state.METHODEFFECTS=true; } else if (option.equals("-coreprof")) { - state.COREPROF=true; + state.COREPROF=true; } else if (option.equals("-ooojava")) { - state.OOOJAVA = true; - state.DISJOINT = true; - state.OOO_NUMCORES = Integer.parseInt(args[++i]); - state.OOO_MAXSESEAGE = Integer.parseInt(args[++i]); + state.OOOJAVA = true; + state.DISJOINT = true; + state.OOO_NUMCORES = Integer.parseInt(args[++i]); + state.OOO_MAXSESEAGE = Integer.parseInt(args[++i]); } else if (option.equals("-ooodebug") ) { - state.OOODEBUG = true; + state.OOODEBUG = true; } else if (option.equals("-rcr")) { - state.RCR = true; - state.KEEP_RG_FOR_ALL_PROGRAM_POINTS=true; + state.RCR = true; + state.KEEP_RG_FOR_ALL_PROGRAM_POINTS=true; } else if (option.equals("-rcr_debug")) { - state.RCR_DEBUG = true; - state.KEEP_RG_FOR_ALL_PROGRAM_POINTS=true; + state.RCR_DEBUG = true; + state.KEEP_RG_FOR_ALL_PROGRAM_POINTS=true; } else if (option.equals("-rcr_debug_verbose")) { - state.RCR_DEBUG_VERBOSE = true; - state.KEEP_RG_FOR_ALL_PROGRAM_POINTS=true; + state.RCR_DEBUG_VERBOSE = true; + state.KEEP_RG_FOR_ALL_PROGRAM_POINTS=true; } else if (option.equals("-nostalltr")) { - state.NOSTALLTR = true; + state.NOSTALLTR = true; } else if (option.equals("-ssjava")) { - state.SSJAVA = true; + state.SSJAVA = true; } else if (option.equals("-printlinenum")) { - state.LINENUM=true; + state.LINENUM=true; } else if (option.equals("-help")) { - System.out.println("-classlibrary classlibrarydirectory -- directory where classlibrary is located"); - System.out.println("-selfloop task -- this task doesn't self loop its parameters forever"); - System.out.println("-dir outputdirectory -- output code in outputdirectory"); - System.out.println("-struct structfile -- output structure declarations for repair tool"); - System.out.println("-mainclass -- main function to call"); - System.out.println("-dsm -- distributed shared memory support"); - System.out.println("-singleTM -- single machine committing transactions"); - System.out.println("-abortreaders -- abort readers"); - System.out.println("-precise -- use precise garbage collection"); - System.out.println("-conscheck -- turn on consistency checking"); - System.out.println("-task -- compiler for tasks"); - System.out.println("-fastcheck -- fastcheckpointing for Bristlecone"); - System.out.println("-thread -- threads"); - System.out.println("-trueprob -- probability of true branch"); - System.out.println("-printflat -- print out flat representation"); - System.out.println("-instructionfailures -- insert code for instruction level failures"); - System.out.println("-taskstate -- do task state analysis"); - System.out.println("-flatirtasks -- create dot files for flat IR graphs of tasks"); - System.out.println("-flatirusermethods -- create dot files for flat IR graphs of user methods"); - System.out.println("-flatirlibmethods -- create dot files for flat IR graphs of library class methods"); - System.out.println(" note: -flatirusermethods or -flatirlibmethods currently generate all class method flat IR graphs"); - System.out.println("-ownership -- do ownership analysis"); - System.out.println("-ownallocdepth -- set allocation depth for ownership analysis"); - System.out.println("-ownwritedots -- write ownership graphs; can be all results or just final results"); - System.out.println("-ownaliasfile -- write a text file showing all detected aliases in program tasks"); - System.out.println("-optimize -- enable optimizations"); - System.out.println("-noloop -- disable loop optimizations"); - System.out.println("-optional -- enable optional arguments"); - System.out.println("-abcclose close the array boundary check"); - System.out.println("-scheduling do task scheduling"); - System.out.println("-mlp build mlp code"); - System.out.println("-mlpdebug if mlp, report progress and interim results"); - System.out.println("-multicore generate multi-core version binary"); - System.out.println("-numcore set the number of cores (should be used together with -multicore), defaultly set as 1"); - System.out.println("-interrupt generate raw version binary with interruption (should be used togethere with -raw)"); - System.out.println("-rawconfig config raw simulator as 4xn (should be used together with -raw)"); - System.out.println("-rawpath print out execute path information for raw version (should be used together with -raw)"); - System.out.println("-useprofile use profiling data for scheduling (should be used together with -raw)"); - System.out.println("-threadsimulate generate multi-thread simulate version binary"); - System.out.println("-rawuseio use standard io to output profiling data (should be used together with -raw and -profile), it only works with single core version"); - System.out.println("-printscheduling -- print out scheduling graphs"); - System.out.println("-printschedulesim -- print out scheduling simulation result graphs"); - System.out.println("-webinterface -- enable web interface"); - System.out.println("-linenum print out line numbers in generated C codes"); - System.out.println("-help -- print out help"); - System.exit(0); + System.out.println("-classlibrary classlibrarydirectory -- directory where classlibrary is located"); + System.out.println("-selfloop task -- this task doesn't self loop its parameters forever"); + System.out.println("-dir outputdirectory -- output code in outputdirectory"); + System.out.println("-struct structfile -- output structure declarations for repair tool"); + System.out.println("-mainclass -- main function to call"); + System.out.println("-dsm -- distributed shared memory support"); + System.out.println("-singleTM -- single machine committing transactions"); + System.out.println("-abortreaders -- abort readers"); + System.out.println("-precise -- use precise garbage collection"); + System.out.println("-conscheck -- turn on consistency checking"); + System.out.println("-task -- compiler for tasks"); + System.out.println("-fastcheck -- fastcheckpointing for Bristlecone"); + System.out.println("-thread -- threads"); + System.out.println("-trueprob -- probability of true branch"); + System.out.println("-printflat -- print out flat representation"); + System.out.println("-instructionfailures -- insert code for instruction level failures"); + System.out.println("-taskstate -- do task state analysis"); + System.out.println("-flatirtasks -- create dot files for flat IR graphs of tasks"); + System.out.println("-flatirusermethods -- create dot files for flat IR graphs of user methods"); + System.out.println("-flatirlibmethods -- create dot files for flat IR graphs of library class methods"); + System.out.println(" note: -flatirusermethods or -flatirlibmethods currently generate all class method flat IR graphs"); + System.out.println("-ownership -- do ownership analysis"); + System.out.println("-ownallocdepth -- set allocation depth for ownership analysis"); + System.out.println("-ownwritedots -- write ownership graphs; can be all results or just final results"); + System.out.println("-ownaliasfile -- write a text file showing all detected aliases in program tasks"); + System.out.println("-optimize -- enable optimizations"); + System.out.println("-noloop -- disable loop optimizations"); + System.out.println("-optional -- enable optional arguments"); + System.out.println("-abcclose close the array boundary check"); + System.out.println("-scheduling do task scheduling"); + System.out.println("-mlp build mlp code"); + System.out.println("-mlpdebug if mlp, report progress and interim results"); + System.out.println("-multicore generate multi-core version binary"); + System.out.println("-numcore set the number of cores (should be used together with -multicore), defaultly set as 1"); + System.out.println("-interrupt generate raw version binary with interruption (should be used togethere with -raw)"); + System.out.println("-rawconfig config raw simulator as 4xn (should be used together with -raw)"); + System.out.println("-rawpath print out execute path information for raw version (should be used together with -raw)"); + System.out.println("-useprofile use profiling data for scheduling (should be used together with -raw)"); + System.out.println("-threadsimulate generate multi-thread simulate version binary"); + System.out.println("-rawuseio use standard io to output profiling data (should be used together with -raw and -profile), it only works with single core version"); + System.out.println("-printscheduling -- print out scheduling graphs"); + System.out.println("-printschedulesim -- print out scheduling simulation result graphs"); + System.out.println("-webinterface -- enable web interface"); + System.out.println("-linenum print out line numbers in generated C codes"); + System.out.println("-help -- print out help"); + System.exit(0); } else { - sourcefiles.add(args[i]); + sourcefiles.add(args[i]); } } @@ -420,12 +420,12 @@ public class Main { SemanticCheck sc=new SemanticCheck(state,tu); for(int i=0; i scheduling = mcImplSynthesis.synthesis(); - - double timeEndAnalysis = (double) System.nanoTime(); - if(state.BAMBOOCOMPILETIME) { - double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow(10.0, 9.0) ); - System.err.println("The analysis took" + dt + "sec."); - System.exit(0); - } - - // generate multicore codes - if(state.MULTICORE) { - BuildCodeMultiCore bcm=new BuildCodeMultiCore(state, - bf.getMap(), - tu, - sa, - scheduling, - mcImplSynthesis.getCoreNum(), - state.CORENUM4GC, callgraph); - bcm.setOwnershipAnalysis(oa); - bcm.buildCode(); - } - scheduling.clear(); - scheduling = null; - } + // Use ownership analysis to get alias information + Liveness liveness = new Liveness(); + ArrayReferencees ar = new ArrayReferencees(state, tu, callgraph); + OwnershipAnalysis oa = null; /*new OwnershipAnalysis(state, + tu, + callGraph, + liveness, + ar, + state.OWNERSHIPALLOCDEPTH, + state.OWNERSHIPWRITEDOTS, + state.OWNERSHIPWRITEALL, + state.OWNERSHIPALIASFILE);*/ + + // synthesis a layout according to target multicore processor + MCImplSynthesis mcImplSynthesis = new MCImplSynthesis(state, + ta, + oa); + if(isDistributeInfo) { + mcImplSynthesis.distribution(isDisAll, startnum); + } else { + double timeStartAnalysis = (double) System.nanoTime(); + mcImplSynthesis.setScheduleThreshold(20); + mcImplSynthesis.setProbThreshold(0); + mcImplSynthesis.setGenerateThreshold(30); + Vector scheduling = mcImplSynthesis.synthesis(); + + double timeEndAnalysis = (double) System.nanoTime(); + if(state.BAMBOOCOMPILETIME) { + double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow(10.0, 9.0) ); + System.err.println("The analysis took" + dt + "sec."); + System.exit(0); + } + + // generate multicore codes + if(state.MULTICORE) { + BuildCodeMultiCore bcm=new BuildCodeMultiCore(state, + bf.getMap(), + tu, + sa, + scheduling, + mcImplSynthesis.getCoreNum(), + state.CORENUM4GC, callgraph); + bcm.setOwnershipAnalysis(oa); + bcm.buildCode(); + } + scheduling.clear(); + scheduling = null; + } } } if (state.MGC) { // generate multicore codes if(state.MULTICORE) { - BuildCodeMGC bcmgc=new BuildCodeMGC(state, - bf.getMap(), - tu, - sa, - state.CORENUM, - state.CORENUM, - state.CORENUM4GC, callgraph); - bcmgc.buildCode(); + BuildCodeMGC bcmgc=new BuildCodeMGC(state, + bf.getMap(), + tu, + sa, + state.CORENUM, + state.CORENUM, + state.CORENUM4GC, callgraph); + bcmgc.buildCode(); } } @@ -638,20 +638,20 @@ public class Main { BuildCode bc; if (state.DSM||state.SINGLETM) { - if (state.PREFETCH) { - //speed up prefetch generation using locality analysis results - LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu); - pa=new PrefetchAnalysis(state, callgraph, tu, la); - } - LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu); - GenerateConversions gc=new GenerateConversions(la, state); - bc=new BuildCodeTran(state, bf.getMap(), tu, la, pa, callgraph); + if (state.PREFETCH) { + //speed up prefetch generation using locality analysis results + LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu); + pa=new PrefetchAnalysis(state, callgraph, tu, la); + } + LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu); + GenerateConversions gc=new GenerateConversions(la, state); + bc=new BuildCodeTran(state, bf.getMap(), tu, la, pa, callgraph); } else { - if( state.OOOJAVA ) { - bc=new BuildOoOJavaCode(state, bf.getMap(), tu, sa, oooa, callgraph); - } else { - bc=new BuildCode(state, bf.getMap(), tu, sa, callgraph, jb); - } + if( state.OOOJAVA ) { + bc=new BuildOoOJavaCode(state, bf.getMap(), tu, sa, oooa, callgraph); + } else { + bc=new BuildCode(state, bf.getMap(), tu, sa, callgraph, jb); + } } bc.buildCode(); @@ -688,16 +688,16 @@ public class Main { g = new Parse.Parser(l); ParseNode p=null; try { - p=(ParseNode) g./*debug_*/ parse().value; + p=(ParseNode) g./*debug_*/ parse().value; } catch (Exception e) { - System.err.println("Error parsing file:"+sourcefile); - e.printStackTrace(); - System.exit(-1); + System.err.println("Error parsing file:"+sourcefile); + e.printStackTrace(); + System.exit(-1); } state.addParseNode(p); if (l.numErrors()!=0) { - System.out.println("Error parsing "+sourcefile); - System.exit(l.numErrors()); + System.out.println("Error parsing "+sourcefile); + System.exit(l.numErrors()); } state.lines+=l.line_num; return p; diff --git a/Robust/src/Runtime/DSTM/interface/abortreaders.c b/Robust/src/Runtime/DSTM/interface/abortreaders.c index 1db84209..dcd0d6c9 100644 --- a/Robust/src/Runtime/DSTM/interface/abortreaders.c +++ b/Robust/src/Runtime/DSTM/interface/abortreaders.c @@ -60,12 +60,12 @@ void removetransaction(unsigned int oidarray[], unsigned int numoids) { int count=rl->numreaders; int j; for(j=0; count; j++) { - int *t_abort=rl->array[j]; - if (t_abort!=NULL) { - *t_abort=1; //It's okay to set our own abort flag...it is - //too late to abort us - count--; - } + int *t_abort=rl->array[j]; + if (t_abort!=NULL) { + *t_abort=1; //It's okay to set our own abort flag...it is + //too late to abort us + count--; + } } tmp=rl; rl=rl->next; @@ -86,23 +86,23 @@ void removethisreadtransaction(unsigned char* oidverread, unsigned int numoids) oidverread+=(sizeof(unsigned int)+sizeof(unsigned short)); while(rl!=NULL) { for(j=0; jarray[j]==&t_abort) { - rl->array[j]=NULL; - if ((--rl->numreaders)==0) { - if (first==rl) { - chashRemove2(aborttable, oid); - if (rl->next!=NULL) - chashInsert(aborttable, oid, rl->next); - rl->next=freelist; - freelist=rl; - } else { - first->next=rl->next; - rl->next=freelist; - freelist=rl; - } - } - goto nextitem; - } + if (rl->array[j]==&t_abort) { + rl->array[j]=NULL; + if ((--rl->numreaders)==0) { + if (first==rl) { + chashRemove2(aborttable, oid); + if (rl->next!=NULL) + chashInsert(aborttable, oid, rl->next); + rl->next=freelist; + freelist=rl; + } else { + first->next=rl->next; + rl->next=freelist; + freelist=rl; + } + } + goto nextitem; + } } first=rl; rl=rl->next; @@ -122,31 +122,31 @@ void removetransactionhash() { do { unsigned int oid=curr->key; if (oid==0) - break; + break; struct readerlist * rl=chashSearch(aborttable, oid); struct readerlist *first=rl; while(rl!=NULL) { - for(j=0; jarray[j]==&t_abort) { - rl->array[j]=NULL; - if ((--rl->numreaders)==0) { - if (first==rl) { - chashRemove2(aborttable, oid); - if (rl->next!=NULL) - chashInsert(aborttable, oid, rl->next); - rl->next=freelist; - freelist=rl; - } else { - first->next=rl->next; - rl->next=freelist; - freelist=rl; - } - } - goto nextitem; - } - } - first=rl; - rl=rl->next; + for(j=0; jarray[j]==&t_abort) { + rl->array[j]=NULL; + if ((--rl->numreaders)==0) { + if (first==rl) { + chashRemove2(aborttable, oid); + if (rl->next!=NULL) + chashInsert(aborttable, oid, rl->next); + rl->next=freelist; + freelist=rl; + } else { + first->next=rl->next; + rl->next=freelist; + freelist=rl; + } + } + goto nextitem; + } + } + first=rl; + rl=rl->next; } nextitem: curr=curr->next; @@ -166,23 +166,23 @@ void removethistransaction(unsigned int oidarray[], unsigned int numoids) { struct readerlist *first=rl; while(rl!=NULL) { for(j=0; jarray[j]==&t_abort) { - rl->array[j]=NULL; - if ((--rl->numreaders)==0) { - if (first==rl) { - chashRemove2(aborttable, oid); - if (rl->next!=NULL) - chashInsert(aborttable, oid, rl->next); - rl->next=freelist; - freelist=rl; - } else { - first->next=rl->next; - rl->next=freelist; - freelist=rl; - } - } - goto nextitem; - } + if (rl->array[j]==&t_abort) { + rl->array[j]=NULL; + if ((--rl->numreaders)==0) { + if (first==rl) { + chashRemove2(aborttable, oid); + if (rl->next!=NULL) + chashInsert(aborttable, oid, rl->next); + rl->next=freelist; + freelist=rl; + } else { + first->next=rl->next; + rl->next=freelist; + freelist=rl; + } + } + goto nextitem; + } } first=rl; rl=rl->next; diff --git a/Robust/src/Runtime/DSTM/interface/addPrefetchEnhance.c b/Robust/src/Runtime/DSTM/interface/addPrefetchEnhance.c index 66471712..eda8cc3f 100644 --- a/Robust/src/Runtime/DSTM/interface/addPrefetchEnhance.c +++ b/Robust/src/Runtime/DSTM/interface/addPrefetchEnhance.c @@ -65,8 +65,8 @@ void handleDynPrefetching(int numLocal, int ntuples, int siteid) { if(getOperationMode(siteid) != 0) { evalPrefetch[siteid].uselesscount--; if(evalPrefetch[siteid].uselesscount <= 0) { - LOGEVENT('O'); - evalPrefetch[siteid].operMode = 0; + LOGEVENT('O'); + evalPrefetch[siteid].operMode = 0; } } } @@ -83,12 +83,12 @@ void cleanPCache() { chashlistnode_t *curr = &ptr[i]; //for each entry in the cache lookupTable while(curr != NULL) { if(curr->key == 0) - break; + break; objheader_t *header1, *header2; /* Not found in local machine's object store and found in prefetch cache */ if((header1 = mhashSearch(curr->key)) == NULL && ((header2 = prehashSearch(curr->key)) != NULL)) { - /* Remove from prefetch cache */ - prehashRemove(curr->key); + /* Remove from prefetch cache */ + prehashRemove(curr->key); } curr = curr->next; } diff --git a/Robust/src/Runtime/DSTM/interface/addUdpEnhance.c b/Robust/src/Runtime/DSTM/interface/addUdpEnhance.c index 480b93f4..bad7fdee 100644 --- a/Robust/src/Runtime/DSTM/interface/addUdpEnhance.c +++ b/Robust/src/Runtime/DSTM/interface/addUdpEnhance.c @@ -93,8 +93,8 @@ void *udpListenBroadcast(void *sockfd) { switch (status) { case INVALIDATE_OBJS: if((retval = invalidateFromPrefetchCache(readBuffer))!= 0) { - printf("Error: In invalidateFromPrefetchCache() at %s, %d\n", __FILE__, __LINE__); - break; + printf("Error: In invalidateFromPrefetchCache() at %s, %d\n", __FILE__, __LINE__); + break; } break; @@ -157,12 +157,12 @@ int sendUdpMsg(trans_req_data_t *tdata, int pilecount, int nummod, struct sockad for(; j < pilecount; j++) { for(; i < tdata[j].f.nummod; i++) { - *((unsigned int *) (writeBuffer+localoffset)) = tdata[j].oidmod[i]; //copy objects - localoffset += sizeof(unsigned int); - if ((++sentmsgs)==numtosend) { - i++; - goto send; - } + *((unsigned int *) (writeBuffer+localoffset)) = tdata[j].oidmod[i]; //copy objects + localoffset += sizeof(unsigned int); + if ((++sentmsgs)==numtosend) { + i++; + goto send; + } } i=0; } @@ -199,9 +199,9 @@ int invalidateFromPrefetchCache(char *buffer) { objheader_t *header; /* Lookup Objects in prefetch cache and remove them */ if(((header = prehashSearch(oid)) != NULL)) { - //Keep invalid objects - STATUS(header)=DIRTY; - //prehashRemove(oid); + //Keep invalid objects + STATUS(header)=DIRTY; + //prehashRemove(oid); } offset += sizeof(unsigned int); } diff --git a/Robust/src/Runtime/DSTM/interface/altmlookup.c b/Robust/src/Runtime/DSTM/interface/altmlookup.c index c1e01668..b9cc184a 100644 --- a/Robust/src/Runtime/DSTM/interface/altmlookup.c +++ b/Robust/src/Runtime/DSTM/interface/altmlookup.c @@ -107,17 +107,17 @@ unsigned int mhashRemove(unsigned int key) { if (curr->key == key) { atomic_dec(&(mlookup.numelements)); if ((curr == &ptr[index]) && (curr->next == NULL)) { - curr->key = 0; - curr->val = NULL; + curr->key = 0; + curr->val = NULL; } else if ((curr == &ptr[index]) && (curr->next != NULL)) { - curr->key = curr->next->key; - curr->val = curr->next->val; - node = curr->next; - curr->next = curr->next->next; - free(node); + curr->key = curr->next->key; + curr->val = curr->next->val; + node = curr->next; + curr->next = curr->next->next; + free(node); } else { - prev->next = curr->next; - free(curr); + prev->next = curr->next; + free(curr); } write_unlock(lockptr); return 0; @@ -173,31 +173,31 @@ void mhashResize(unsigned int newsize) { mhashlistnode_t *tmp,*next; if ((key=curr->key) == 0) { - break; + break; } next = curr->next; index = (key >> 1) & mask; tmp=&mlookup.table[index]; if(tmp->key ==0) { - tmp->key=curr->key; - tmp->val=curr->val; - if (!isfirst) - free(curr); + tmp->key=curr->key; + tmp->val=curr->val; + if (!isfirst) + free(curr); } /* - NOTE: Add this case if you change this... - This case currently never happens because of the way things rehash.... - else if (isfirst) { - mhashlistnode_t *newnode = calloc(1, sizeof(mhashlistnode_t)); - newnode->key = curr->key; - newnode->val = curr->val; - newnode->next = tmp->next; - tmp->next=newnode; - } */ + NOTE: Add this case if you change this... + This case currently never happens because of the way things rehash.... + else if (isfirst) { + mhashlistnode_t *newnode = calloc(1, sizeof(mhashlistnode_t)); + newnode->key = curr->key; + newnode->val = curr->val; + newnode->next = tmp->next; + tmp->next=newnode; + } */ else { - curr->next=tmp->next; - tmp->next=curr; + curr->next=tmp->next; + tmp->next=curr; } isfirst = 0; curr = next; diff --git a/Robust/src/Runtime/DSTM/interface/altprelookup.c b/Robust/src/Runtime/DSTM/interface/altprelookup.c index 5c9fd4ff..1585601e 100644 --- a/Robust/src/Runtime/DSTM/interface/altprelookup.c +++ b/Robust/src/Runtime/DSTM/interface/altprelookup.c @@ -77,10 +77,10 @@ void prehashInsert(unsigned int key, void *val) { tmp = ptr; while(tmp != NULL) { if(tmp->key == key) { - isFound=1; - tmp->val = val; //Replace value for an exsisting key - write_unlock(lockptr); - return; + isFound=1; + tmp->val = val; //Replace value for an exsisting key + write_unlock(lockptr); + return; } tmp=tmp->next; } @@ -210,7 +210,7 @@ unsigned int prehashResize(unsigned int newsize) { do { unsigned int key; if ((key=curr->key) == 0) { //Exit inner loop if there the first element for a given bin/index is NULL - break; //key = val =0 for element if not present within the hash table + break; //key = val =0 for element if not present within the hash table } next = curr->next; //index = (key & mask)>>1; @@ -218,23 +218,23 @@ unsigned int prehashResize(unsigned int newsize) { tmp=&pflookup.table[index]; // Insert into the new table if(tmp->key==0) { - tmp->key=curr->key; - tmp->val=curr->val; - if (!isfirst) - free(curr); + tmp->key=curr->key; + tmp->val=curr->val; + if (!isfirst) + free(curr); } /* - NOTE: Add this case if you change this... - This case currently never happens because of the way things rehash.... - else if (isfirst) { - prehashlistnode_t * newnode = calloc(1, sizeof(prehashlistnode_t)); - newnode->key = curr->key; - newnode->val = curr->val; - newnode->next = tmp->next; - tmp->next=newnode; - } */ + NOTE: Add this case if you change this... + This case currently never happens because of the way things rehash.... + else if (isfirst) { + prehashlistnode_t * newnode = calloc(1, sizeof(prehashlistnode_t)); + newnode->key = curr->key; + newnode->val = curr->val; + newnode->next = tmp->next; + tmp->next=newnode; + } */ else { - curr->next=tmp->next; - tmp->next=curr; + curr->next=tmp->next; + tmp->next=curr; } isfirst = 0; diff --git a/Robust/src/Runtime/DSTM/interface/clocksyncserver.c b/Robust/src/Runtime/DSTM/interface/clocksyncserver.c index f2a0ce5a..6be2fa5b 100644 --- a/Robust/src/Runtime/DSTM/interface/clocksyncserver.c +++ b/Robust/src/Runtime/DSTM/interface/clocksyncserver.c @@ -27,7 +27,7 @@ static __inline__ unsigned long long rdtsc(void) { int main() { unsigned long long dir[DIRSIZE]; /* used for incomming dir name, and - outgoing data */ + outgoing data */ int sd, sd_current; socklen_t addrlen; struct sockaddr_in sin; diff --git a/Robust/src/Runtime/DSTM/interface/clookup.c b/Robust/src/Runtime/DSTM/interface/clookup.c index 3b9df443..9e5c4c71 100644 --- a/Robust/src/Runtime/DSTM/interface/clookup.c +++ b/Robust/src/Runtime/DSTM/interface/clookup.c @@ -176,20 +176,20 @@ void * chashRemove2(chashtable_t *table, unsigned int key) { if (curr->key == key) { // Find a match in the hash table table->numelements--; // Decrement the number of elements in the global hashtable if ((curr == &ptr[index]) && (curr->next == NULL)) { // Delete the first item inside the hashtable with no linked list of chashlistnode_t - curr->key = 0; - value=curr->val; - curr->val = NULL; + curr->key = 0; + value=curr->val; + curr->val = NULL; } else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first item with a linked list of chashlistnode_t connected - curr->key = curr->next->key; - value=curr->val; - curr->val = curr->next->val; - node = curr->next; - curr->next = curr->next->next; - free(node); + curr->key = curr->next->key; + value=curr->val; + curr->val = curr->next->val; + node = curr->next; + curr->next = curr->next->next; + free(node); } else { // Regular delete from linked listed - prev->next = curr->next; - value=curr->val; - free(curr); + prev->next = curr->next; + value=curr->val; + free(curr); } return value; } @@ -226,31 +226,31 @@ unsigned int chashResize(chashtable_t *table, unsigned int newsize) { chashlistnode_t *tmp,*next; if ((key=curr->key) == 0) { //Exit inner loop if there the first element is 0 - break; //key = val =0 for element if not present within the hash table + break; //key = val =0 for element if not present within the hash table } next = curr->next; index = (key & mask) >>1; tmp=&node[index]; // Insert into the new table if(tmp->key == 0) { - tmp->key = curr->key; - tmp->val = curr->val; - if (!isfirst) { - free(curr); - } + tmp->key = curr->key; + tmp->val = curr->val; + if (!isfirst) { + free(curr); + } } /* - NOTE: Add this case if you change this... - This case currently never happens because of the way things rehash.... - else if (isfirst) { - chashlistnode_t *newnode= calloc(1, sizeof(chashlistnode_t)); - newnode->key = curr->key; - newnode->val = curr->val; - newnode->next = tmp->next; - tmp->next=newnode; - } */ + NOTE: Add this case if you change this... + This case currently never happens because of the way things rehash.... + else if (isfirst) { + chashlistnode_t *newnode= calloc(1, sizeof(chashlistnode_t)); + newnode->key = curr->key; + newnode->val = curr->val; + newnode->next = tmp->next; + tmp->next=newnode; + } */ else { - curr->next=tmp->next; - tmp->next=curr; + curr->next=tmp->next; + tmp->next=curr; } isfirst = 0; @@ -290,28 +290,28 @@ unsigned int t_chashResize(unsigned int newsize) { chashlistnode_t *tmp,*next; if ((key=curr->key) == 0) { //Exit inner loop if there the first element is 0 - break; //key = val =0 for element if not present within the hash table + break; //key = val =0 for element if not present within the hash table } index = (key & mask) >>1; tmp=&node[index]; next = curr->next; // Insert into the new table if(tmp->key == 0) { - tmp->key = key; - tmp->val = curr->val; + tmp->key = key; + tmp->val = curr->val; } /* - NOTE: Add this case if you change this... - This case currently never happens because of the way things rehash.... - else if (isfirst) { - chashlistnode_t *newnode= calloc(1, sizeof(chashlistnode_t)); - newnode->key = curr->key; - newnode->val = curr->val; - newnode->next = tmp->next; - tmp->next=newnode; - } */ + NOTE: Add this case if you change this... + This case currently never happens because of the way things rehash.... + else if (isfirst) { + chashlistnode_t *newnode= calloc(1, sizeof(chashlistnode_t)); + newnode->key = curr->key; + newnode->val = curr->val; + newnode->next = tmp->next; + tmp->next=newnode; + } */ else { - curr->next=tmp->next; - tmp->next=curr; + curr->next=tmp->next; + tmp->next=curr; } isfirst = 0; diff --git a/Robust/src/Runtime/DSTM/interface/clookup2.c b/Robust/src/Runtime/DSTM/interface/clookup2.c index e0a8b2c3..0dfc9fc9 100644 --- a/Robust/src/Runtime/DSTM/interface/clookup2.c +++ b/Robust/src/Runtime/DSTM/interface/clookup2.c @@ -114,18 +114,18 @@ void chashResize(chashtable_t *table, unsigned int newsize) { if (key != 0) { newnode= &table->table[(key&mask)>>1]; if (newnode->key==0) { - newnode->key=key; - newnode->ptr=curr->ptr; - continue; + newnode->key=key; + newnode->ptr=curr->ptr; + continue; } for(bin=1; 1; bin++) { - newnode = &table->table[((key+bin*331) & mask)>>1]; - if (newnode->key==0) { - newnode->key=key; - newnode->ptr=curr->ptr; - break; - } + newnode = &table->table[((key+bin*331) & mask)>>1]; + if (newnode->key==0) { + newnode->key=key; + newnode->ptr=curr->ptr; + break; + } } } } diff --git a/Robust/src/Runtime/DSTM/interface/dht.c b/Robust/src/Runtime/DSTM/interface/dht.c index 3fd73494..1b9785d2 100644 --- a/Robust/src/Runtime/DSTM/interface/dht.c +++ b/Robust/src/Runtime/DSTM/interface/dht.c @@ -407,23 +407,23 @@ int dhtInsert(unsigned int key, unsigned int val) { for (i = 0; i < INSERT_RETRIES; i++) { if (sendto(pollsock.fd, outBuffer, 9, 0, (struct sockaddr *)&toAddr, socklen) < 0) { - perror("dhtInsert():sendto()"); - break; + perror("dhtInsert():sendto()"); + break; } retval = poll(&pollsock, 1, INSERT_TIMEOUT_MS); if (retval < 0) { - perror("dhtInsert():poll()"); - break; + perror("dhtInsert():poll()"); + break; } if (retval > 0) { - bytesRcvd = recvfrom(pollsock.fd, inBuffer, 2, 0, - (struct sockaddr *)&fromAddr, &socklen); - if (fromAddr.sin_addr.s_addr == toAddr.sin_addr.s_addr - && fromAddr.sin_port == toAddr.sin_port - && bytesRcvd == 2 && inBuffer[0] == INSERT_RES) { - status = inBuffer[1]; //status from remote host - break; - } + bytesRcvd = recvfrom(pollsock.fd, inBuffer, 2, 0, + (struct sockaddr *)&fromAddr, &socklen); + if (fromAddr.sin_addr.s_addr == toAddr.sin_addr.s_addr + && fromAddr.sin_port == toAddr.sin_port + && bytesRcvd == 2 && inBuffer[0] == INSERT_RES) { + status = inBuffer[1]; //status from remote host + break; + } } } if (status != OPERATION_OK) { @@ -488,23 +488,23 @@ int dhtRemove(unsigned int key) { for (i = 0; i < REMOVE_RETRIES; i++) { if (sendto(pollsock.fd, outBuffer, 5, 0, (struct sockaddr *)&toAddr, socklen) < 0) { - perror("dhtRemove():sendto()"); - break; + perror("dhtRemove():sendto()"); + break; } retval = poll(&pollsock, 1, REMOVE_TIMEOUT_MS); if (retval < 0) { - perror("dhtRemove():poll()"); - break; + perror("dhtRemove():poll()"); + break; } if (retval > 0) { - bytesRcvd = recvfrom(pollsock.fd, inBuffer, 2, 0, - (struct sockaddr *)&fromAddr, &socklen); - if (fromAddr.sin_addr.s_addr == toAddr.sin_addr.s_addr - && fromAddr.sin_port == toAddr.sin_port - && bytesRcvd == 2 && inBuffer[0] == REMOVE_RES) { - status = inBuffer[1]; //status from remote host - break; - } + bytesRcvd = recvfrom(pollsock.fd, inBuffer, 2, 0, + (struct sockaddr *)&fromAddr, &socklen); + if (fromAddr.sin_addr.s_addr == toAddr.sin_addr.s_addr + && fromAddr.sin_port == toAddr.sin_port + && bytesRcvd == 2 && inBuffer[0] == REMOVE_RES) { + status = inBuffer[1]; //status from remote host + break; + } } } if (!(status == OPERATION_OK || status == KEY_NOT_FOUND)) { @@ -568,24 +568,24 @@ int dhtSearch(unsigned int key, unsigned int *val) { for (i = 0; i < SEARCH_RETRIES; i++) { if (sendto(pollsock.fd, outBuffer, 5, 0, (struct sockaddr *)&toAddr, socklen) < 0) { - perror("dhtSearch():sendto()"); - break; + perror("dhtSearch():sendto()"); + break; } retval = poll(&pollsock, 1, SEARCH_TIMEOUT_MS); if (retval < 0) { - perror("dhtSearch():poll()"); - break; + perror("dhtSearch():poll()"); + break; } if (retval > 0) { - bytesRcvd = recvfrom(pollsock.fd, inBuffer, 6, 0, - (struct sockaddr *)&fromAddr, &socklen); - if (fromAddr.sin_addr.s_addr == toAddr.sin_addr.s_addr - && fromAddr.sin_port == toAddr.sin_port - && bytesRcvd == 6 && inBuffer[0] == SEARCH_RES) { - status = inBuffer[1]; //status from remote host - *val = read4(&inBuffer[2]); - break; - } + bytesRcvd = recvfrom(pollsock.fd, inBuffer, 6, 0, + (struct sockaddr *)&fromAddr, &socklen); + if (fromAddr.sin_addr.s_addr == toAddr.sin_addr.s_addr + && fromAddr.sin_port == toAddr.sin_port + && bytesRcvd == 6 && inBuffer[0] == SEARCH_RES) { + status = inBuffer[1]; //status from remote host + *val = read4(&inBuffer[2]); + break; + } } } if (!(status == OPERATION_OK || status == KEY_NOT_FOUND)) { @@ -762,7 +762,7 @@ int udpSendAll(unsigned char *msg, unsigned int size) { for (i = 0; i < numHosts; i++) { if ((hostReplied[i] == 0) && (hostArray[i].ipAddr != myHostData.ipAddr)) { if (udpSend(msg, size, hostArray[i].ipAddr) != 0) - status = -1; + status = -1; } } return status; @@ -890,33 +890,33 @@ int addHost(struct hostData newHost) { return 0; } else if (hostArray[i].ipAddr > newHost.ipAddr) { if (numHosts == hostArraySize) { - newHostArray = calloc(2 * hostArraySize, sizeof(struct hostData)); - newHostReplied = calloc(2 * hostArraySize, sizeof(unsigned char)); - memcpy(newHostArray, hostArray, (i * sizeof(struct hostData))); - memcpy(newHostReplied, hostReplied, (i * sizeof(unsigned char))); - newHostArray[i] = newHost; - newHostReplied[i] = 0; - memcpy(&newHostArray[i+1], &hostArray[i], ((numHosts - i) * - sizeof(struct hostData))); - memcpy(&newHostReplied[i+1], &hostReplied[i], ((numHosts - i) * - sizeof(unsigned char))); - free(hostArray); - free(hostReplied); - hostArray = newHostArray; - hostReplied = newHostReplied; - hostArraySize = 2 * hostArraySize; + newHostArray = calloc(2 * hostArraySize, sizeof(struct hostData)); + newHostReplied = calloc(2 * hostArraySize, sizeof(unsigned char)); + memcpy(newHostArray, hostArray, (i * sizeof(struct hostData))); + memcpy(newHostReplied, hostReplied, (i * sizeof(unsigned char))); + newHostArray[i] = newHost; + newHostReplied[i] = 0; + memcpy(&newHostArray[i+1], &hostArray[i], ((numHosts - i) * + sizeof(struct hostData))); + memcpy(&newHostReplied[i+1], &hostReplied[i], ((numHosts - i) * + sizeof(unsigned char))); + free(hostArray); + free(hostReplied); + hostArray = newHostArray; + hostReplied = newHostReplied; + hostArraySize = 2 * hostArraySize; } else { - for (j = numHosts; j > i; j--) { - hostArray[j] = hostArray[j-1]; - hostReplied[j] = hostReplied[j-1]; - } - hostArray[i] = newHost; - hostReplied[i] = 0; + for (j = numHosts; j > i; j--) { + hostArray[j] = hostArray[j-1]; + hostReplied[j] = hostReplied[j-1]; + } + hostArray[i] = newHost; + hostReplied[i] = 0; } for(j = 0; j < numBlocks; j++) { - if (blockOwnerArray[j] >= i) - blockOwnerArray[j]++; + if (blockOwnerArray[j] >= i) + blockOwnerArray[j]++; } numHosts++; return 1; @@ -1043,591 +1043,591 @@ void *udpListen() { bytesRcvd = recvfrom(udpPollSock.fd, inBuffer, MAX_MSG_SIZE, 0, (struct sockaddr *)&peerAddr, &socklen); if (bytesRcvd < 1) { - dhtLog("udpListen(): ERROR: bytesRcvd = %d\n", bytesRcvd); + dhtLog("udpListen(): ERROR: bytesRcvd = %d\n", bytesRcvd); } else if (inBuffer[0] >= NUM_MSG_TYPES) { - dhtLog("udpListen(): ERROR: unknown msg type = %d\n", inBuffer[0]); + dhtLog("udpListen(): ERROR: unknown msg type = %d\n", inBuffer[0]); } else if (!msgSizeOk(inBuffer, bytesRcvd)) { - dhtLog("udpListen(): ERROR: msg size not ok: type = %s\n, size = %d\n", - msg_types[inBuffer[0]], bytesRcvd); + dhtLog("udpListen(): ERROR: msg size not ok: type = %s\n, size = %d\n", + msg_types[inBuffer[0]], bytesRcvd); } else if (state == EXIT2_STATE) { - //do nothing + //do nothing } else if (state == INIT1_STATE) { //after initialization with seed, do not proceed until seed replies - dhtLog("udpListen(): received %s from %s, %d bytes\n", - msg_types[inBuffer[0]], inet_ntoa(peerAddr.sin_addr), bytesRcvd); - for (i = 0; i < bytesRcvd; i++) - dhtLog(" %x", inBuffer[i]); - dhtLog("\n"); - peerIp = ntohl(peerAddr.sin_addr.s_addr); - if (peerIp == seed && inBuffer[0] == WHO_IS_LEADER_RES) { - tmpHost.ipAddr = peerIp; - tmpHost.maxKeyCapacity = 0; - addHost(tmpHost); - writeHostList(); - leader = read4(&inBuffer[1]); - tmpAddr.s_addr = htonl(leader); - dhtLog("leader = %s\n", inet_ntoa(tmpAddr)); - if (leader != 0) { - setState(INIT2_STATE); - outBuffer[0] = JOIN_REQ; - write4(&outBuffer[1], myHostData.maxKeyCapacity); - udpSend(outBuffer, 5, leader); - } else - { - electionOriginator = myHostData.ipAddr; - setState(ELECT1_STATE); - outBuffer[0] = ELECT_LEADER_CMD; - write4(&outBuffer[1], myHostData.ipAddr); //originator = me - udpSendAll(outBuffer, 5); - } - } + dhtLog("udpListen(): received %s from %s, %d bytes\n", + msg_types[inBuffer[0]], inet_ntoa(peerAddr.sin_addr), bytesRcvd); + for (i = 0; i < bytesRcvd; i++) + dhtLog(" %x", inBuffer[i]); + dhtLog("\n"); + peerIp = ntohl(peerAddr.sin_addr.s_addr); + if (peerIp == seed && inBuffer[0] == WHO_IS_LEADER_RES) { + tmpHost.ipAddr = peerIp; + tmpHost.maxKeyCapacity = 0; + addHost(tmpHost); + writeHostList(); + leader = read4(&inBuffer[1]); + tmpAddr.s_addr = htonl(leader); + dhtLog("leader = %s\n", inet_ntoa(tmpAddr)); + if (leader != 0) { + setState(INIT2_STATE); + outBuffer[0] = JOIN_REQ; + write4(&outBuffer[1], myHostData.maxKeyCapacity); + udpSend(outBuffer, 5, leader); + } else + { + electionOriginator = myHostData.ipAddr; + setState(ELECT1_STATE); + outBuffer[0] = ELECT_LEADER_CMD; + write4(&outBuffer[1], myHostData.ipAddr); //originator = me + udpSendAll(outBuffer, 5); + } + } } else { - dhtLog("udpListen(): received %s from %s, %d bytes\n", - msg_types[inBuffer[0]], inet_ntoa(peerAddr.sin_addr), bytesRcvd); - for (i = 0; i < bytesRcvd; i++) - dhtLog(" %x", inBuffer[i]); - dhtLog("\n"); - peerIp = ntohl(peerAddr.sin_addr.s_addr); - switch (inBuffer[0]) { - case INSERT_CMD: - if (state == NORMAL_STATE || state == LEAD_NORMAL1_STATE - || state == LEAD_NORMAL2_STATE || state == REBUILD4_STATE - || state == REBUILD5_STATE || state == LEAD_REBUILD3_STATE) { - tmpKey = read4(&inBuffer[1]); - tmpVal = read4(&inBuffer[5]); - outBuffer[0] = INSERT_RES; - if (getKeyOwner(tmpKey) == myHostData.ipAddr) { - if (chashInsert(myHashTable, tmpKey, (void *)tmpVal) == 0) - outBuffer[1] = OPERATION_OK; - else - outBuffer[1] = INTERNAL_ERROR; - } else - { - outBuffer[1] = NOT_KEY_OWNER; - } - //reply to client socket - sendto(udpPollSock.fd, outBuffer, 2, 0, - (struct sockaddr *)&peerAddr, socklen); - } - break; - - case REMOVE_CMD: - if (state == NORMAL_STATE || state == LEAD_NORMAL1_STATE - || state == LEAD_NORMAL2_STATE) { - tmpKey = read4(&inBuffer[1]); - outBuffer[0] = REMOVE_RES; - if (getKeyOwner(tmpKey) == myHostData.ipAddr) { - if (chashRemove(myHashTable, tmpKey) == 0) - outBuffer[1] = OPERATION_OK; - else - outBuffer[1] = KEY_NOT_FOUND; - } else - { - outBuffer[1] = NOT_KEY_OWNER; - } - //reply to client socket - sendto(udpPollSock.fd, outBuffer, 2, 0, - (struct sockaddr *)&peerAddr, socklen); - } - break; - - case SEARCH_CMD: - if (state == NORMAL_STATE || state == LEAD_NORMAL1_STATE - || state == LEAD_NORMAL2_STATE) { - tmpKey = read4(&inBuffer[1]); - outBuffer[0] = SEARCH_RES; - if (getKeyOwner(tmpKey) == myHostData.ipAddr) { - if ((tmpVal = (unsigned int)chashSearch(myHashTable, tmpKey)) != 0) { - outBuffer[1] = OPERATION_OK; - write4(&outBuffer[2], tmpVal); - } else - { - outBuffer[1] = KEY_NOT_FOUND; - write4(&outBuffer[2], 0); - } - } else - { - outBuffer[1] = NOT_KEY_OWNER; - write4(&outBuffer[2], 0); - } - //reply to client socket - sendto(udpPollSock.fd, outBuffer, 6, 0, - (struct sockaddr *)&peerAddr, socklen); - } - break; - - case WHO_IS_LEADER_CMD: - tmpHost.ipAddr = peerIp; - tmpHost.maxKeyCapacity = 0; - addHost(tmpHost); - writeHostList(); - outBuffer[0] = WHO_IS_LEADER_RES; - //leader == 0 means I don't know who it is - write4(&outBuffer[1], leader); - udpSend(outBuffer, 5, peerIp); - break; - - case JOIN_REQ: - if (state == LEAD_NORMAL1_STATE || state == LEAD_NORMAL2_STATE) { - tmpHost.ipAddr = peerIp; - tmpHost.maxKeyCapacity = read4(&inBuffer[1]); - addHost(tmpHost); - writeHostList(); - if (state == LEAD_NORMAL1_STATE) - setState(LEAD_NORMAL2_STATE); - outBuffer[0] = JOIN_RES; - outBuffer[1] = 0; //status, success - udpSend(outBuffer, 2, peerIp); - } else if (state == LEAD_REBUILD1_STATE) { - //note: I don't need to addHost(). - checkReplied(peerIp); - outBuffer[0] = JOIN_RES; - outBuffer[1] = 0; //status, success - udpSend(outBuffer, 2, peerIp); - if (allReplied()) { - makeAssignments(); - setState(LEAD_REBUILD2_STATE); - outBuffer[0] = DHT_UPDATE_CMD; - write2(&outBuffer[1], numHosts); - write2(&outBuffer[3], numBlocks); - memcpy(&outBuffer[5], hostArray, numHosts*sizeof(struct hostData)); - memcpy(&outBuffer[5+numHosts*sizeof(struct hostData)], - blockOwnerArray, numBlocks*2); - udpSendAll(outBuffer, 5 + sizeof(struct hostData) * numHosts - + 2 * numBlocks); - } - } - break; - - case JOIN_RES: - if (state == REBUILD1_STATE) { - setState(REBUILD2_STATE); - } else if (state == INIT2_STATE) { - setState(NORMAL_STATE); - } - break; - - case LEAVE_REQ: - if (state == LEAD_NORMAL1_STATE || state == LEAD_NORMAL2_STATE) { //TODO: make this graceful, instead of just rebuilding - removeHost(peerIp); - if (state != LEAD_NORMAL2_STATE) - setState(LEAD_NORMAL2_STATE); - } - break; - - case DHT_UPDATE_CMD: - if (state == REBUILD2_STATE && peerIp == leader) { - free(hostArray); - free(blockOwnerArray); - numHosts = read2(&inBuffer[1]); - numBlocks = read2(&inBuffer[3]); - while (hostArraySize < numHosts) - hostArraySize *= 2; - hostArray = calloc(hostArraySize, sizeof(struct hostData)); - blockOwnerArray = calloc(numBlocks, 2); - memcpy(hostArray, &inBuffer[5], numHosts*sizeof(struct hostData)); - memcpy(blockOwnerArray, &inBuffer[5+numHosts*sizeof(struct hostData)], numBlocks*2); - writeHostList(); - setState(REBUILD3_STATE); - outBuffer[0] = DHT_UPDATE_RES; - udpSend(outBuffer, 1, peerIp); - } - break; - - case DHT_UPDATE_RES: - if (state == LEAD_REBUILD2_STATE) { - checkReplied(peerIp); - if (allReplied()) { - setState(LEAD_REBUILD3_STATE); - outBuffer[0] = FILL_DHT_CMD; - udpSendAll(outBuffer, 1); - if (fillStatus != 0) - dhtLog("udpListen(): ERROR: fillTask already running\n"); - fillStatus = 1; - if (pthread_create(&threadFillTask, NULL, fillTask, NULL) != 0) - dhtLog("udpListen(): ERROR creating threadFillTask\n"); - } - } - break; - - case ELECT_LEADER_CMD: - tmpUInt = read4(&inBuffer[1]); - if ((state == ELECT1_STATE || state == ELECT2_STATE) - && tmpUInt >= electionOriginator) { //already participating in a higher-priority election - outBuffer[0] = ELECT_LEADER_RES; - outBuffer[1] = 0xFF; - udpSend(outBuffer, 2, peerIp); - } else - { //join election - electionOriginator = tmpUInt; - electionParent = peerIp; - setState(ELECT1_STATE); - outBuffer[0] = ELECT_LEADER_CMD; - write4(&outBuffer[1], electionOriginator); - //don't bother forwarding the message to originator or parent - checkReplied(electionOriginator); - checkReplied(electionParent); - if (allReplied()) { //in case that is everybody I know of - setState(ELECT2_STATE); - outBuffer[0] = ELECT_LEADER_RES; - outBuffer[1] = 0; - write2(&outBuffer[2], numHosts); - memcpy(&outBuffer[4], hostArray, sizeof(struct hostData) - * numHosts); - udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts, - electionParent); - } else - { - udpSendAll(outBuffer, 5); - } - } - break; - - case ELECT_LEADER_RES: - if (state == ELECT1_STATE) { - checkReplied(peerIp); - if (inBuffer[1] != 0xFF) { - tmpUShort = read2(&inBuffer[2]); - hostDataPtr = (struct hostData *)&inBuffer[4]; - for (i = 0; i < tmpUShort; i++) - addHost(hostDataPtr[i]); - writeHostList(); - } - if (allReplied()) { - setState(ELECT2_STATE); - if (electionOriginator == myHostData.ipAddr) { - leader = hostArray[0].ipAddr; - if (leader == myHostData.ipAddr) { //I am the leader - dhtLog("I am the leader!\n"); - setState(LEAD_REBUILD1_STATE); - outBuffer[0] = REBUILD_CMD; - udpSendAll(outBuffer, 1); - } else - { //notify leader - outBuffer[0] = CONGRATS_CMD; - write2(&outBuffer[1], numHosts); - hostDataPtr = (struct hostData *)&outBuffer[3]; - for (i = 0; i < numHosts; i++) - hostDataPtr[i] = hostArray[i]; - udpSend(outBuffer, 3 + sizeof(struct hostData) * numHosts, - leader); - } - } else - { - outBuffer[0] = ELECT_LEADER_RES; - outBuffer[1] = 0; - write2(&outBuffer[2], numHosts); - hostDataPtr = (struct hostData *)&outBuffer[4]; - for (i = 0; i < numHosts; i++) - hostDataPtr[i] = hostArray[i]; - udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts, - electionParent); - } - } - } - break; - - case CONGRATS_CMD: - if (state == ELECT2_STATE) { //I am the leader - leader = myHostData.ipAddr; - dhtLog("I am the leader!\n"); - tmpUShort = read2(&inBuffer[1]); - hostDataPtr = (struct hostData *)&inBuffer[3]; - for (i = 0; i < tmpUShort; i++) - addHost(hostDataPtr[i]); - writeHostList(); - setState(LEAD_REBUILD1_STATE); - outBuffer[0] = REBUILD_CMD; - udpSendAll(outBuffer, 1); - } - break; - - case REBUILD_REQ: - if (state == LEAD_NORMAL1_STATE || state == LEAD_NORMAL2_STATE) { - setState(LEAD_REBUILD1_STATE); - outBuffer[0] = REBUILD_CMD; - udpSendAll(outBuffer, 1); - } - break; - - case REBUILD_CMD: - leader = peerIp; //consider this a declaration of authority - setState(REBUILD1_STATE); - outBuffer[0] = JOIN_REQ; - write4(&outBuffer[1], myHostData.maxKeyCapacity); - udpSend(outBuffer, 5, leader); - break; - - case FILL_DHT_CMD: - if (state == REBUILD3_STATE && peerIp == leader) { - setState(REBUILD4_STATE); - if (fillStatus != 0) - dhtLog("udpListen(): ERROR: fillTask already running\n"); - fillStatus = 1; - if (pthread_create(&threadFillTask, NULL, fillTask, NULL) != 0) - dhtLog("udpListen(): ERROR creating threadFillTask\n"); - } - break; - - case FILL_DHT_RES: - if (state == LEAD_REBUILD3_STATE) { - checkReplied(peerIp); - if (allReplied() && fillStatus == 2) { - fillStatus = 0; - setState(LEAD_REBUILD4_STATE); - outBuffer[0] = RESUME_NORMAL_CMD; - udpSendAll(outBuffer, 1); - } - } - break; - - case RESUME_NORMAL_CMD: - if (state == REBUILD5_STATE && peerIp == leader) { - setState(NORMAL_STATE); - outBuffer[0] = RESUME_NORMAL_RES; - udpSend(outBuffer, 1, leader); - } - break; - - case RESUME_NORMAL_RES: - if (state == LEAD_REBUILD4_STATE) { - checkReplied(peerIp); - if (allReplied()) { - setState(LEAD_NORMAL1_STATE); - } - } - break; - } + dhtLog("udpListen(): received %s from %s, %d bytes\n", + msg_types[inBuffer[0]], inet_ntoa(peerAddr.sin_addr), bytesRcvd); + for (i = 0; i < bytesRcvd; i++) + dhtLog(" %x", inBuffer[i]); + dhtLog("\n"); + peerIp = ntohl(peerAddr.sin_addr.s_addr); + switch (inBuffer[0]) { + case INSERT_CMD: + if (state == NORMAL_STATE || state == LEAD_NORMAL1_STATE + || state == LEAD_NORMAL2_STATE || state == REBUILD4_STATE + || state == REBUILD5_STATE || state == LEAD_REBUILD3_STATE) { + tmpKey = read4(&inBuffer[1]); + tmpVal = read4(&inBuffer[5]); + outBuffer[0] = INSERT_RES; + if (getKeyOwner(tmpKey) == myHostData.ipAddr) { + if (chashInsert(myHashTable, tmpKey, (void *)tmpVal) == 0) + outBuffer[1] = OPERATION_OK; + else + outBuffer[1] = INTERNAL_ERROR; + } else + { + outBuffer[1] = NOT_KEY_OWNER; + } + //reply to client socket + sendto(udpPollSock.fd, outBuffer, 2, 0, + (struct sockaddr *)&peerAddr, socklen); + } + break; + + case REMOVE_CMD: + if (state == NORMAL_STATE || state == LEAD_NORMAL1_STATE + || state == LEAD_NORMAL2_STATE) { + tmpKey = read4(&inBuffer[1]); + outBuffer[0] = REMOVE_RES; + if (getKeyOwner(tmpKey) == myHostData.ipAddr) { + if (chashRemove(myHashTable, tmpKey) == 0) + outBuffer[1] = OPERATION_OK; + else + outBuffer[1] = KEY_NOT_FOUND; + } else + { + outBuffer[1] = NOT_KEY_OWNER; + } + //reply to client socket + sendto(udpPollSock.fd, outBuffer, 2, 0, + (struct sockaddr *)&peerAddr, socklen); + } + break; + + case SEARCH_CMD: + if (state == NORMAL_STATE || state == LEAD_NORMAL1_STATE + || state == LEAD_NORMAL2_STATE) { + tmpKey = read4(&inBuffer[1]); + outBuffer[0] = SEARCH_RES; + if (getKeyOwner(tmpKey) == myHostData.ipAddr) { + if ((tmpVal = (unsigned int)chashSearch(myHashTable, tmpKey)) != 0) { + outBuffer[1] = OPERATION_OK; + write4(&outBuffer[2], tmpVal); + } else + { + outBuffer[1] = KEY_NOT_FOUND; + write4(&outBuffer[2], 0); + } + } else + { + outBuffer[1] = NOT_KEY_OWNER; + write4(&outBuffer[2], 0); + } + //reply to client socket + sendto(udpPollSock.fd, outBuffer, 6, 0, + (struct sockaddr *)&peerAddr, socklen); + } + break; + + case WHO_IS_LEADER_CMD: + tmpHost.ipAddr = peerIp; + tmpHost.maxKeyCapacity = 0; + addHost(tmpHost); + writeHostList(); + outBuffer[0] = WHO_IS_LEADER_RES; + //leader == 0 means I don't know who it is + write4(&outBuffer[1], leader); + udpSend(outBuffer, 5, peerIp); + break; + + case JOIN_REQ: + if (state == LEAD_NORMAL1_STATE || state == LEAD_NORMAL2_STATE) { + tmpHost.ipAddr = peerIp; + tmpHost.maxKeyCapacity = read4(&inBuffer[1]); + addHost(tmpHost); + writeHostList(); + if (state == LEAD_NORMAL1_STATE) + setState(LEAD_NORMAL2_STATE); + outBuffer[0] = JOIN_RES; + outBuffer[1] = 0; //status, success + udpSend(outBuffer, 2, peerIp); + } else if (state == LEAD_REBUILD1_STATE) { + //note: I don't need to addHost(). + checkReplied(peerIp); + outBuffer[0] = JOIN_RES; + outBuffer[1] = 0; //status, success + udpSend(outBuffer, 2, peerIp); + if (allReplied()) { + makeAssignments(); + setState(LEAD_REBUILD2_STATE); + outBuffer[0] = DHT_UPDATE_CMD; + write2(&outBuffer[1], numHosts); + write2(&outBuffer[3], numBlocks); + memcpy(&outBuffer[5], hostArray, numHosts*sizeof(struct hostData)); + memcpy(&outBuffer[5+numHosts*sizeof(struct hostData)], + blockOwnerArray, numBlocks*2); + udpSendAll(outBuffer, 5 + sizeof(struct hostData) * numHosts + + 2 * numBlocks); + } + } + break; + + case JOIN_RES: + if (state == REBUILD1_STATE) { + setState(REBUILD2_STATE); + } else if (state == INIT2_STATE) { + setState(NORMAL_STATE); + } + break; + + case LEAVE_REQ: + if (state == LEAD_NORMAL1_STATE || state == LEAD_NORMAL2_STATE) { //TODO: make this graceful, instead of just rebuilding + removeHost(peerIp); + if (state != LEAD_NORMAL2_STATE) + setState(LEAD_NORMAL2_STATE); + } + break; + + case DHT_UPDATE_CMD: + if (state == REBUILD2_STATE && peerIp == leader) { + free(hostArray); + free(blockOwnerArray); + numHosts = read2(&inBuffer[1]); + numBlocks = read2(&inBuffer[3]); + while (hostArraySize < numHosts) + hostArraySize *= 2; + hostArray = calloc(hostArraySize, sizeof(struct hostData)); + blockOwnerArray = calloc(numBlocks, 2); + memcpy(hostArray, &inBuffer[5], numHosts*sizeof(struct hostData)); + memcpy(blockOwnerArray, &inBuffer[5+numHosts*sizeof(struct hostData)], numBlocks*2); + writeHostList(); + setState(REBUILD3_STATE); + outBuffer[0] = DHT_UPDATE_RES; + udpSend(outBuffer, 1, peerIp); + } + break; + + case DHT_UPDATE_RES: + if (state == LEAD_REBUILD2_STATE) { + checkReplied(peerIp); + if (allReplied()) { + setState(LEAD_REBUILD3_STATE); + outBuffer[0] = FILL_DHT_CMD; + udpSendAll(outBuffer, 1); + if (fillStatus != 0) + dhtLog("udpListen(): ERROR: fillTask already running\n"); + fillStatus = 1; + if (pthread_create(&threadFillTask, NULL, fillTask, NULL) != 0) + dhtLog("udpListen(): ERROR creating threadFillTask\n"); + } + } + break; + + case ELECT_LEADER_CMD: + tmpUInt = read4(&inBuffer[1]); + if ((state == ELECT1_STATE || state == ELECT2_STATE) + && tmpUInt >= electionOriginator) { //already participating in a higher-priority election + outBuffer[0] = ELECT_LEADER_RES; + outBuffer[1] = 0xFF; + udpSend(outBuffer, 2, peerIp); + } else + { //join election + electionOriginator = tmpUInt; + electionParent = peerIp; + setState(ELECT1_STATE); + outBuffer[0] = ELECT_LEADER_CMD; + write4(&outBuffer[1], electionOriginator); + //don't bother forwarding the message to originator or parent + checkReplied(electionOriginator); + checkReplied(electionParent); + if (allReplied()) { //in case that is everybody I know of + setState(ELECT2_STATE); + outBuffer[0] = ELECT_LEADER_RES; + outBuffer[1] = 0; + write2(&outBuffer[2], numHosts); + memcpy(&outBuffer[4], hostArray, sizeof(struct hostData) + * numHosts); + udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts, + electionParent); + } else + { + udpSendAll(outBuffer, 5); + } + } + break; + + case ELECT_LEADER_RES: + if (state == ELECT1_STATE) { + checkReplied(peerIp); + if (inBuffer[1] != 0xFF) { + tmpUShort = read2(&inBuffer[2]); + hostDataPtr = (struct hostData *)&inBuffer[4]; + for (i = 0; i < tmpUShort; i++) + addHost(hostDataPtr[i]); + writeHostList(); + } + if (allReplied()) { + setState(ELECT2_STATE); + if (electionOriginator == myHostData.ipAddr) { + leader = hostArray[0].ipAddr; + if (leader == myHostData.ipAddr) { //I am the leader + dhtLog("I am the leader!\n"); + setState(LEAD_REBUILD1_STATE); + outBuffer[0] = REBUILD_CMD; + udpSendAll(outBuffer, 1); + } else + { //notify leader + outBuffer[0] = CONGRATS_CMD; + write2(&outBuffer[1], numHosts); + hostDataPtr = (struct hostData *)&outBuffer[3]; + for (i = 0; i < numHosts; i++) + hostDataPtr[i] = hostArray[i]; + udpSend(outBuffer, 3 + sizeof(struct hostData) * numHosts, + leader); + } + } else + { + outBuffer[0] = ELECT_LEADER_RES; + outBuffer[1] = 0; + write2(&outBuffer[2], numHosts); + hostDataPtr = (struct hostData *)&outBuffer[4]; + for (i = 0; i < numHosts; i++) + hostDataPtr[i] = hostArray[i]; + udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts, + electionParent); + } + } + } + break; + + case CONGRATS_CMD: + if (state == ELECT2_STATE) { //I am the leader + leader = myHostData.ipAddr; + dhtLog("I am the leader!\n"); + tmpUShort = read2(&inBuffer[1]); + hostDataPtr = (struct hostData *)&inBuffer[3]; + for (i = 0; i < tmpUShort; i++) + addHost(hostDataPtr[i]); + writeHostList(); + setState(LEAD_REBUILD1_STATE); + outBuffer[0] = REBUILD_CMD; + udpSendAll(outBuffer, 1); + } + break; + + case REBUILD_REQ: + if (state == LEAD_NORMAL1_STATE || state == LEAD_NORMAL2_STATE) { + setState(LEAD_REBUILD1_STATE); + outBuffer[0] = REBUILD_CMD; + udpSendAll(outBuffer, 1); + } + break; + + case REBUILD_CMD: + leader = peerIp; //consider this a declaration of authority + setState(REBUILD1_STATE); + outBuffer[0] = JOIN_REQ; + write4(&outBuffer[1], myHostData.maxKeyCapacity); + udpSend(outBuffer, 5, leader); + break; + + case FILL_DHT_CMD: + if (state == REBUILD3_STATE && peerIp == leader) { + setState(REBUILD4_STATE); + if (fillStatus != 0) + dhtLog("udpListen(): ERROR: fillTask already running\n"); + fillStatus = 1; + if (pthread_create(&threadFillTask, NULL, fillTask, NULL) != 0) + dhtLog("udpListen(): ERROR creating threadFillTask\n"); + } + break; + + case FILL_DHT_RES: + if (state == LEAD_REBUILD3_STATE) { + checkReplied(peerIp); + if (allReplied() && fillStatus == 2) { + fillStatus = 0; + setState(LEAD_REBUILD4_STATE); + outBuffer[0] = RESUME_NORMAL_CMD; + udpSendAll(outBuffer, 1); + } + } + break; + + case RESUME_NORMAL_CMD: + if (state == REBUILD5_STATE && peerIp == leader) { + setState(NORMAL_STATE); + outBuffer[0] = RESUME_NORMAL_RES; + udpSend(outBuffer, 1, leader); + } + break; + + case RESUME_NORMAL_RES: + if (state == LEAD_REBUILD4_STATE) { + checkReplied(peerIp); + if (allReplied()) { + setState(LEAD_NORMAL1_STATE); + } + } + break; + } } } if (state == REBUILD4_STATE) { switch (fillStatus) { case 0: dhtLog("udpListen(): ERROR: fillStatus=0 in REBUILD4_STATE\n"); - break; + break; case 1: //do nothing - break; + break; case 2: //done filling the dht, notify leader - fillStatus = 0; - setState(REBUILD5_STATE); - outBuffer[0] = FILL_DHT_RES; - udpSend(outBuffer, 1, leader); - break; + fillStatus = 0; + setState(REBUILD5_STATE); + outBuffer[0] = FILL_DHT_RES; + udpSend(outBuffer, 1, leader); + break; case 3: //error encountered -> restart rebuild - fillStatus = 0; - setState(REBUILD0_STATE); - outBuffer[0] = REBUILD_REQ; - udpSend(outBuffer, 1, leader); - break; + fillStatus = 0; + setState(REBUILD0_STATE); + outBuffer[0] = REBUILD_REQ; + udpSend(outBuffer, 1, leader); + break; } } if (state == LEAD_REBUILD3_STATE) { switch (fillStatus) { case 0: dhtLog("udpListen(): ERROR: fillStatus=0 in LEAD_REBUILD3_STATE\n"); - break; + break; case 1: //do nothing - break; + break; case 2: //I'm done, now is everybody else also done? - if (allReplied()) { - fillStatus = 0; - setState(LEAD_REBUILD4_STATE); - outBuffer[0] = RESUME_NORMAL_CMD; - udpSendAll(outBuffer, 1); - } - break; + if (allReplied()) { + fillStatus = 0; + setState(LEAD_REBUILD4_STATE); + outBuffer[0] = RESUME_NORMAL_CMD; + udpSendAll(outBuffer, 1); + } + break; case 3: //error encountered -> restart rebuild - fillStatus = 0; - setState(LEAD_REBUILD1_STATE); - outBuffer[0] = REBUILD_CMD; - udpSendAll(outBuffer, 1); - break; + fillStatus = 0; + setState(LEAD_REBUILD1_STATE); + outBuffer[0] = REBUILD_CMD; + udpSendAll(outBuffer, 1); + break; } } if (timerSet) { gettimeofday(&now, NULL); if (timercmp(&now, &timer, >)) { - if (timeoutCntr < retry_vals[state]) { - timeoutCntr++; - timeradd(&now, &timeout_vals[state], &timer); - dhtLog("udpListen(): retry: %d\n", timeoutCntr); - switch (state) { - case INIT1_STATE: - outBuffer[0] = WHO_IS_LEADER_CMD; - udpSend(outBuffer, 1, seed); - break; - - case INIT2_STATE: - outBuffer[0] = JOIN_REQ; - write4(&outBuffer[1], myHostData.maxKeyCapacity); - udpSend(outBuffer, 5, leader); - break; - - case ELECT1_STATE: - outBuffer[0] = ELECT_LEADER_CMD; - write4(&outBuffer[1], electionOriginator); - udpSendAll(outBuffer, 5); - break; - - case ELECT2_STATE: - if (electionOriginator == myHostData.ipAddr) { //retry notify leader - outBuffer[0] = CONGRATS_CMD; - write2(&outBuffer[1], numHosts); - memcpy(&outBuffer[3], hostArray, sizeof(struct hostData) - * numHosts); - udpSend(outBuffer, 3 + sizeof(struct hostData) * numHosts, - leader); - } else - { - outBuffer[0] = ELECT_LEADER_RES; - outBuffer[1] = 0; - write2(&outBuffer[2], numHosts); - memcpy(&outBuffer[4], hostArray, sizeof(struct hostData) - * numHosts); - udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts, - electionParent); - } - break; - - case REBUILD0_STATE: - outBuffer[0] = REBUILD_REQ; - udpSend(outBuffer, 1, leader); - break; - - case REBUILD1_STATE: - outBuffer[0] = JOIN_REQ; - write4(&outBuffer[1], myHostData.maxKeyCapacity); - udpSend(outBuffer, 5, leader); - break; - - case REBUILD5_STATE: - outBuffer[0] = FILL_DHT_RES; - udpSend(outBuffer, 1, leader); - break; - - case LEAD_REBUILD1_STATE: - outBuffer[0] = REBUILD_CMD; - udpSendAll(outBuffer, 1); - break; - - case LEAD_REBUILD2_STATE: - outBuffer[0] = DHT_UPDATE_CMD; - write2(&outBuffer[1], numHosts); - write2(&outBuffer[3], numBlocks); - memcpy(&outBuffer[5], hostArray, numHosts - * sizeof(struct hostData)); - memcpy(&outBuffer[5+numHosts*sizeof(struct hostData)], - blockOwnerArray, numBlocks*2); - udpSendAll(outBuffer, 5 + sizeof(struct hostData) * numHosts - + 2 * numBlocks); - break; - - case LEAD_REBUILD3_STATE: - outBuffer[0] = FILL_DHT_CMD; - udpSendAll(outBuffer, 1); - break; - - case LEAD_REBUILD4_STATE: - outBuffer[0] = RESUME_NORMAL_CMD; - udpSendAll(outBuffer, 1); - break; - - case EXIT1_STATE: //TODO... - break; - - case NORMAL_STATE: - case LEAD_NORMAL1_STATE: - case LEAD_NORMAL2_STATE: - case REBUILD2_STATE: - case REBUILD3_STATE: - case REBUILD4_STATE: - case EXIT2_STATE: //we shouldn't get here - break; - } - } else - { - dhtLog("udpListen(): timed out in state %s after %d retries\n", - state_names[state], timeoutCntr); - switch (state) { - case INIT1_STATE: - setState(EXIT2_STATE); - break; - - case LEAD_NORMAL2_STATE: - setState(LEAD_REBUILD1_STATE); - outBuffer[0] = REBUILD_CMD; - udpSendAll(outBuffer, 1); - break; - - case ELECT1_STATE: - dhtLog("removing unresponsive hosts, before:\n"); - writeHostList(); - removeUnresponsiveHosts(); - dhtLog("after\n"); - writeHostList(); - setState(ELECT2_STATE); - if (electionOriginator == myHostData.ipAddr) { - leader = hostArray[0].ipAddr; - if (leader == myHostData.ipAddr) { //I am the leader - dhtLog("I am the leader!\n"); - setState(LEAD_REBUILD1_STATE); - outBuffer[0] = REBUILD_CMD; - udpSendAll(outBuffer, 1); - } else - { //notify leader - outBuffer[0] = CONGRATS_CMD; - write2(&outBuffer[1], numHosts); - memcpy(&outBuffer[3], hostArray, sizeof(struct hostData) - * numHosts); - udpSend(outBuffer, 3 + sizeof(struct hostData) * numHosts, - leader); - } - } else - { - outBuffer[0] = ELECT_LEADER_RES; - outBuffer[1] = 0; - write2(&outBuffer[2], numHosts); - memcpy(&outBuffer[4], hostArray, sizeof(struct hostData) - * numHosts); - udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts, - electionParent); - } - break; - - case INIT2_STATE: - case ELECT2_STATE: - case REBUILD0_STATE: - case REBUILD1_STATE: - case REBUILD2_STATE: - case REBUILD3_STATE: - case REBUILD4_STATE: - case REBUILD5_STATE: - case LEAD_REBUILD1_STATE: - case LEAD_REBUILD2_STATE: - case LEAD_REBUILD3_STATE: - case LEAD_REBUILD4_STATE: - //start election - electionOriginator = myHostData.ipAddr; - setState(ELECT1_STATE); - outBuffer[0] = ELECT_LEADER_CMD; - write4(&outBuffer[1], myHostData.ipAddr); //originator = me - udpSendAll(outBuffer, 5); - break; - - case EXIT1_STATE: - setState(EXIT2_STATE); - break; - - case NORMAL_STATE: - case LEAD_NORMAL1_STATE: - case EXIT2_STATE: //we shouldn't get here - break; - } - } + if (timeoutCntr < retry_vals[state]) { + timeoutCntr++; + timeradd(&now, &timeout_vals[state], &timer); + dhtLog("udpListen(): retry: %d\n", timeoutCntr); + switch (state) { + case INIT1_STATE: + outBuffer[0] = WHO_IS_LEADER_CMD; + udpSend(outBuffer, 1, seed); + break; + + case INIT2_STATE: + outBuffer[0] = JOIN_REQ; + write4(&outBuffer[1], myHostData.maxKeyCapacity); + udpSend(outBuffer, 5, leader); + break; + + case ELECT1_STATE: + outBuffer[0] = ELECT_LEADER_CMD; + write4(&outBuffer[1], electionOriginator); + udpSendAll(outBuffer, 5); + break; + + case ELECT2_STATE: + if (electionOriginator == myHostData.ipAddr) { //retry notify leader + outBuffer[0] = CONGRATS_CMD; + write2(&outBuffer[1], numHosts); + memcpy(&outBuffer[3], hostArray, sizeof(struct hostData) + * numHosts); + udpSend(outBuffer, 3 + sizeof(struct hostData) * numHosts, + leader); + } else + { + outBuffer[0] = ELECT_LEADER_RES; + outBuffer[1] = 0; + write2(&outBuffer[2], numHosts); + memcpy(&outBuffer[4], hostArray, sizeof(struct hostData) + * numHosts); + udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts, + electionParent); + } + break; + + case REBUILD0_STATE: + outBuffer[0] = REBUILD_REQ; + udpSend(outBuffer, 1, leader); + break; + + case REBUILD1_STATE: + outBuffer[0] = JOIN_REQ; + write4(&outBuffer[1], myHostData.maxKeyCapacity); + udpSend(outBuffer, 5, leader); + break; + + case REBUILD5_STATE: + outBuffer[0] = FILL_DHT_RES; + udpSend(outBuffer, 1, leader); + break; + + case LEAD_REBUILD1_STATE: + outBuffer[0] = REBUILD_CMD; + udpSendAll(outBuffer, 1); + break; + + case LEAD_REBUILD2_STATE: + outBuffer[0] = DHT_UPDATE_CMD; + write2(&outBuffer[1], numHosts); + write2(&outBuffer[3], numBlocks); + memcpy(&outBuffer[5], hostArray, numHosts + * sizeof(struct hostData)); + memcpy(&outBuffer[5+numHosts*sizeof(struct hostData)], + blockOwnerArray, numBlocks*2); + udpSendAll(outBuffer, 5 + sizeof(struct hostData) * numHosts + + 2 * numBlocks); + break; + + case LEAD_REBUILD3_STATE: + outBuffer[0] = FILL_DHT_CMD; + udpSendAll(outBuffer, 1); + break; + + case LEAD_REBUILD4_STATE: + outBuffer[0] = RESUME_NORMAL_CMD; + udpSendAll(outBuffer, 1); + break; + + case EXIT1_STATE: //TODO... + break; + + case NORMAL_STATE: + case LEAD_NORMAL1_STATE: + case LEAD_NORMAL2_STATE: + case REBUILD2_STATE: + case REBUILD3_STATE: + case REBUILD4_STATE: + case EXIT2_STATE: //we shouldn't get here + break; + } + } else + { + dhtLog("udpListen(): timed out in state %s after %d retries\n", + state_names[state], timeoutCntr); + switch (state) { + case INIT1_STATE: + setState(EXIT2_STATE); + break; + + case LEAD_NORMAL2_STATE: + setState(LEAD_REBUILD1_STATE); + outBuffer[0] = REBUILD_CMD; + udpSendAll(outBuffer, 1); + break; + + case ELECT1_STATE: + dhtLog("removing unresponsive hosts, before:\n"); + writeHostList(); + removeUnresponsiveHosts(); + dhtLog("after\n"); + writeHostList(); + setState(ELECT2_STATE); + if (electionOriginator == myHostData.ipAddr) { + leader = hostArray[0].ipAddr; + if (leader == myHostData.ipAddr) { //I am the leader + dhtLog("I am the leader!\n"); + setState(LEAD_REBUILD1_STATE); + outBuffer[0] = REBUILD_CMD; + udpSendAll(outBuffer, 1); + } else + { //notify leader + outBuffer[0] = CONGRATS_CMD; + write2(&outBuffer[1], numHosts); + memcpy(&outBuffer[3], hostArray, sizeof(struct hostData) + * numHosts); + udpSend(outBuffer, 3 + sizeof(struct hostData) * numHosts, + leader); + } + } else + { + outBuffer[0] = ELECT_LEADER_RES; + outBuffer[1] = 0; + write2(&outBuffer[2], numHosts); + memcpy(&outBuffer[4], hostArray, sizeof(struct hostData) + * numHosts); + udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts, + electionParent); + } + break; + + case INIT2_STATE: + case ELECT2_STATE: + case REBUILD0_STATE: + case REBUILD1_STATE: + case REBUILD2_STATE: + case REBUILD3_STATE: + case REBUILD4_STATE: + case REBUILD5_STATE: + case LEAD_REBUILD1_STATE: + case LEAD_REBUILD2_STATE: + case LEAD_REBUILD3_STATE: + case LEAD_REBUILD4_STATE: + //start election + electionOriginator = myHostData.ipAddr; + setState(ELECT1_STATE); + outBuffer[0] = ELECT_LEADER_CMD; + write4(&outBuffer[1], myHostData.ipAddr); //originator = me + udpSendAll(outBuffer, 5); + break; + + case EXIT1_STATE: + setState(EXIT2_STATE); + break; + + case NORMAL_STATE: + case LEAD_NORMAL1_STATE: + case EXIT2_STATE: //we shouldn't get here + break; + } + } } } if (state != oldState) diff --git a/Robust/src/Runtime/DSTM/interface/dsmlock.c b/Robust/src/Runtime/DSTM/interface/dsmlock.c index 881cc705..5c1f6fc0 100644 --- a/Robust/src/Runtime/DSTM/interface/dsmlock.c +++ b/Robust/src/Runtime/DSTM/interface/dsmlock.c @@ -7,20 +7,20 @@ inline void initdsmlocks(volatile int *addr) { inline void atomic_dec(volatile int *v) { __asm__ __volatile__ (LOCK_PREFIX "decl %0" - : "+m" (*v)); + : "+m" (*v)); } inline void atomic_inc(volatile int *v) { __asm__ __volatile__ (LOCK_PREFIX "incl %0" - : "+m" (*v)); + : "+m" (*v)); } static inline int atomic_sub_and_test(int i, volatile int *v) { unsigned char c; __asm__ __volatile__ (LOCK_PREFIX "subl %2,%0; sete %1" - : "+m" (*v), "=qm" (c) - : "ir" (i) : "memory"); + : "+m" (*v), "=qm" (c) + : "ir" (i) : "memory"); return c; } @@ -33,8 +33,8 @@ static inline int atomic_sub_and_test(int i, volatile int *v) { */ static inline void atomic_add(int i, volatile int *v) { __asm__ __volatile__ (LOCK_PREFIX "addl %1,%0" - : "+m" (*v) - : "ir" (i)); + : "+m" (*v) + : "ir" (i)); } inline int read_trylock(volatile int *lock) { @@ -59,7 +59,7 @@ inline void read_unlock(volatile int *rw) { inline void write_unlock(volatile int *rw) { __asm__ __volatile__ (LOCK_PREFIX "addl %1, %0" - : "+m" (*rw) : "i" (RW_LOCK_BIAS) : "memory"); + : "+m" (*rw) : "i" (RW_LOCK_BIAS) : "memory"); } inline int is_write_locked(volatile int *lock) { diff --git a/Robust/src/Runtime/DSTM/interface/dstm.h b/Robust/src/Runtime/DSTM/interface/dstm.h index 20c154fb..14909bf2 100644 --- a/Robust/src/Runtime/DSTM/interface/dstm.h +++ b/Robust/src/Runtime/DSTM/interface/dstm.h @@ -271,15 +271,15 @@ void transStart(); //#define TRANSREAD(x,y,z) /* Use "z" which is program point at which TRANSREAD is generated, use this as transRead2(inputvalue,z) */ #define TRANSREAD(x,y) { \ unsigned int inputvalue; \ - if ((inputvalue=(unsigned int)y)==0) x=NULL; \ + if ((inputvalue=(unsigned int)y)==0) x=NULL; \ else { \ chashlistnode_t * cnodetmp=&c_table[(inputvalue&c_mask)>>1]; \ do { \ if (cnodetmp->key==inputvalue) {x=(void *)& ((objheader_t*)cnodetmp->val)[1]; break; } \ cnodetmp=cnodetmp->next; \ if (cnodetmp==NULL) {x=(void *)transRead2(inputvalue); asm volatile ("" : "=m" (c_table),"=m" (c_mask)); break; } \ - } while(1); \ - }} + } while(1); \ + }} __attribute__((pure)) objheader_t *transRead(unsigned int); __attribute__((pure)) objheader_t *transRead2(unsigned int); diff --git a/Robust/src/Runtime/DSTM/interface/dstmserver.c b/Robust/src/Runtime/DSTM/interface/dstmserver.c index a7c5191c..de4e8e8e 100644 --- a/Robust/src/Runtime/DSTM/interface/dstmserver.c +++ b/Robust/src/Runtime/DSTM/interface/dstmserver.c @@ -187,28 +187,28 @@ void *dstmAccept(void *acceptfd) { /* Read oid requested and search if available */ recv_data_buf((int)acceptfd, &readbuffer, &oid, sizeof(unsigned int)); while((srcObj = mhashSearch(oid)) == NULL) { - int ret; - if((ret = sched_yield()) != 0) { - printf("%s(): error no %d in thread yield\n", __func__, errno); - } + int ret; + if((ret = sched_yield()) != 0) { + printf("%s(): error no %d in thread yield\n", __func__, errno); + } } h = (objheader_t *) srcObj; /* If object is write locked, just wait */ /* May want to remove at some point */ while((*(volatile int *)STATUSPTR(h))<=0) - sched_yield(); + sched_yield(); GETSIZE(size, h); size += sizeof(objheader_t); sockid = (int) acceptfd; if (h == NULL) { - ctrl = OBJECT_NOT_FOUND; - send_data(sockid, &ctrl, sizeof(char)); + ctrl = OBJECT_NOT_FOUND; + send_data(sockid, &ctrl, sizeof(char)); } else { - // Type - char msg[]={OBJECT_FOUND, 0, 0, 0, 0}; - *((int *)&msg[1])=size; - send_data(sockid, &msg, sizeof(msg)); - send_data(sockid, h, size); + // Type + char msg[]={OBJECT_FOUND, 0, 0, 0, 0}; + *((int *)&msg[1])=size; + send_data(sockid, &msg, sizeof(msg)); + send_data(sockid, h, size); } break; @@ -229,22 +229,22 @@ void *dstmAccept(void *acceptfd) { transinfo.numlocked = 0; transinfo.numnotfound = 0; if((val = readClientReq(&transinfo, (int)acceptfd, &readbuffer)) != 0) { - printf("Error: In readClientReq() %s, %d\n", __FILE__, __LINE__); - pthread_exit(NULL); + printf("Error: In readClientReq() %s, %d\n", __FILE__, __LINE__); + pthread_exit(NULL); } break; case TRANS_PREFETCH: #ifdef RANGEPREFETCH if((val = rangePrefetchReq((int)acceptfd, &readbuffer)) != 0) { - printf("Error: In rangePrefetchReq() %s, %d\n", __FILE__, __LINE__); - break; + printf("Error: In rangePrefetchReq() %s, %d\n", __FILE__, __LINE__); + break; } #else LOGTIME('X',0,0,myrdtsc(),0); if((val = prefetchReq((int)acceptfd, &readbuffer)) != 0) { - printf("Error: In prefetchReq() %s, %d\n", __FILE__, __LINE__); - break; + printf("Error: In prefetchReq() %s, %d\n", __FILE__, __LINE__); + break; } #endif break; @@ -252,13 +252,13 @@ void *dstmAccept(void *acceptfd) { case TRANS_PREFETCH_RESPONSE: #ifdef RANGEPREFETCH if((val = getRangePrefetchResponse((int)acceptfd, &readbuffer)) != 0) { - printf("Error: In getRangePrefetchRespose() %s, %d\n", __FILE__, __LINE__); - break; + printf("Error: In getRangePrefetchRespose() %s, %d\n", __FILE__, __LINE__); + break; } #else if((val = getPrefetchResponse((int) acceptfd, &readbuffer)) != 0) { - printf("Error: In getPrefetchResponse() %s, %d\n", __FILE__, __LINE__); - break; + printf("Error: In getPrefetchResponse() %s, %d\n", __FILE__, __LINE__); + break; } #endif break; @@ -273,8 +273,8 @@ void *dstmAccept(void *acceptfd) { recv_data_buf((int)acceptfd, &readbuffer, &numoid, sizeof(unsigned int)); size = (sizeof(unsigned int) + sizeof(unsigned short)) * numoid + 2 * sizeof(unsigned int); if((buffer = calloc(1,size)) == NULL) { - printf("%s() Calloc error at %s, %d\n", __func__, __FILE__, __LINE__); - pthread_exit(NULL); + printf("%s() Calloc error at %s, %d\n", __func__, __FILE__, __LINE__); + pthread_exit(NULL); } recv_data_buf((int)acceptfd, &readbuffer, buffer, size); @@ -295,8 +295,8 @@ void *dstmAccept(void *acceptfd) { case THREAD_NOTIFY_RESPONSE: size = sizeof(unsigned short) + 2 * sizeof(unsigned int); if((buffer = calloc(1,size)) == NULL) { - printf("%s() Calloc error at %s, %d\n", __func__, __FILE__, __LINE__); - pthread_exit(NULL); + printf("%s() Calloc error at %s, %d\n", __func__, __FILE__, __LINE__); + pthread_exit(NULL); } recv_data_buf((int)acceptfd, &readbuffer, buffer, size); @@ -441,17 +441,17 @@ int processClientReq(fixed_data_t *fixed, trans_commit_data_t *transinfo, int useWriteUnlock = 0; //TODO verify is this piece of unlocking code ever used for(i = 0; i< transinfo->numlocked; i++) { if(transinfo->objlocked[i] == -1) { - useWriteUnlock = 1; - continue; + useWriteUnlock = 1; + continue; } if((header = mhashSearch(transinfo->objlocked[i])) == NULL) { - printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__); // find the header address - return 1; + printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__); // find the header address + return 1; } if(useWriteUnlock) { - write_unlock(STATUSPTR(header)); + write_unlock(STATUSPTR(header)); } else { - read_unlock(STATUSPTR(header)); + read_unlock(STATUSPTR(header)); } } break; @@ -462,10 +462,10 @@ int processClientReq(fixed_data_t *fixed, trans_commit_data_t *transinfo, printf("Error: In transCommitProcess() %s, %d\n", __FILE__, __LINE__); /* Free memory */ if (transinfo->objlocked != NULL) { - free(transinfo->objlocked); + free(transinfo->objlocked); } if (transinfo->objnotfound != NULL) { - free(transinfo->objnotfound); + free(transinfo->objnotfound); } return 1; } @@ -528,7 +528,7 @@ char handleTransReq(fixed_data_t *fixed, trans_commit_data_t *transinfo, unsigne &v_matchnolock, &v_matchlock, &v_nomatch, &numBytes, &control, oid, version); } else { //Objs modified if(i == fixed->numread) { - oidlocked[objlocked++] = -1; + oidlocked[objlocked++] = -1; } int tmpsize; headptr = (objheader_t *) ptr; @@ -543,24 +543,24 @@ char handleTransReq(fixed_data_t *fixed, trans_commit_data_t *transinfo, unsigne if(retval==TRANS_DISAGREE || retval==TRANS_SOFT_ABORT) { //unlock objects as soon versions mismatch or locks cannot be acquired) if (objlocked > 0) { - int useWriteUnlock = 0; - for(j = 0; j < objlocked; j++) { - if(oidlocked[j] == -1) { - useWriteUnlock = 1; - continue; - } - if((headptr = mhashSearch(oidlocked[j])) == NULL) { - printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__); - return 0; - } - if(useWriteUnlock) { - write_unlock(STATUSPTR(headptr)); - } else { - read_unlock(STATUSPTR(headptr)); - } - } - if(v_nomatch > 0) - free(oidlocked); + int useWriteUnlock = 0; + for(j = 0; j < objlocked; j++) { + if(oidlocked[j] == -1) { + useWriteUnlock = 1; + continue; + } + if((headptr = mhashSearch(oidlocked[j])) == NULL) { + printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__); + return 0; + } + if(useWriteUnlock) { + write_unlock(STATUSPTR(headptr)); + } else { + read_unlock(STATUSPTR(headptr)); + } + } + if(v_nomatch > 0) + free(oidlocked); } objlocked=0; break; @@ -646,34 +646,34 @@ char getCommitCountForObjMod(unsigned int *oidnotfound, unsigned int *oidlocked, /* Check if Obj is locked by any previous transaction */ if (write_trylock(STATUSPTR(mobj))) { // Can acquire write lock if (version == ((objheader_t *)mobj)->version) { /* match versions */ - (*v_matchnolock)++; - *control = TRANS_AGREE; + (*v_matchnolock)++; + *control = TRANS_AGREE; } else { /* If versions don't match ...HARD ABORT */ - (*v_nomatch)++; - oidvernotmatch[*objvernotmatch] = oid; - (*objvernotmatch)++; - int size; - GETSIZE(size, mobj); - size += sizeof(objheader_t); - *numBytes += size; - /* Send TRANS_DISAGREE to Coordinator */ - *control = TRANS_DISAGREE; + (*v_nomatch)++; + oidvernotmatch[*objvernotmatch] = oid; + (*objvernotmatch)++; + int size; + GETSIZE(size, mobj); + size += sizeof(objheader_t); + *numBytes += size; + /* Send TRANS_DISAGREE to Coordinator */ + *control = TRANS_DISAGREE; } //Keep track of oid locked oidlocked[(*objlocked)++] = OID(((objheader_t *)mobj)); } else { //we are locked if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */ - (*v_matchlock)++; - *control=TRANS_SOFT_ABORT; + (*v_matchlock)++; + *control=TRANS_SOFT_ABORT; } else { /* If versions don't match ...HARD ABORT */ - (*v_nomatch)++; - oidvernotmatch[*objvernotmatch] = oid; - (*objvernotmatch)++; - int size; - GETSIZE(size, mobj); - size += sizeof(objheader_t); - *numBytes += size; - *control = TRANS_DISAGREE; + (*v_nomatch)++; + oidvernotmatch[*objvernotmatch] = oid; + (*objvernotmatch)++; + int size; + GETSIZE(size, mobj); + size += sizeof(objheader_t); + *numBytes += size; + *control = TRANS_DISAGREE; } } } @@ -695,33 +695,33 @@ char getCommitCountForObjRead(unsigned int *oidnotfound, unsigned int *oidlocked /* Check if Obj is locked by any previous transaction */ if (read_trylock(STATUSPTR(mobj))) { //Can further acquire read locks if (version == ((objheader_t *)mobj)->version) { /* match versions */ - (*v_matchnolock)++; - *control=TRANS_AGREE; + (*v_matchnolock)++; + *control=TRANS_AGREE; } else { /* If versions don't match ...HARD ABORT */ - (*v_nomatch)++; - oidvernotmatch[(*objvernotmatch)++] = oid; - int size; - GETSIZE(size, mobj); - size += sizeof(objheader_t); - *numBytes += size; - /* Send TRANS_DISAGREE to Coordinator */ - *control = TRANS_DISAGREE; + (*v_nomatch)++; + oidvernotmatch[(*objvernotmatch)++] = oid; + int size; + GETSIZE(size, mobj); + size += sizeof(objheader_t); + *numBytes += size; + /* Send TRANS_DISAGREE to Coordinator */ + *control = TRANS_DISAGREE; } //Keep track of oid locked oidlocked[(*objlocked)++] = OID(((objheader_t *)mobj)); } else { /* Some other transaction has aquired a write lock on this object */ if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */ - (*v_matchlock)++; - *control=TRANS_SOFT_ABORT; + (*v_matchlock)++; + *control=TRANS_SOFT_ABORT; } else { /* If versions don't match ...HARD ABORT */ - (*v_nomatch)++; - oidvernotmatch[*objvernotmatch] = oid; - (*objvernotmatch)++; - int size; - GETSIZE(size, mobj); - size += sizeof(objheader_t); - *numBytes += size; - *control = TRANS_DISAGREE; + (*v_nomatch)++; + oidvernotmatch[*objvernotmatch] = oid; + (*objvernotmatch)++; + int size; + GETSIZE(size, mobj); + size += sizeof(objheader_t); + *numBytes += size; + *control = TRANS_DISAGREE; } } } @@ -928,8 +928,8 @@ int prefetchReq(int acceptfd, struct readstruct * readbuffer) { oid = oidmid.oid; if (mid != oidmid.mid) { if (mid!=-1) { - forcesend_buf(sd, &writebuffer, NULL, 0); - freeSockWithLock(transPResponseSocketPool, mid, sd); + forcesend_buf(sd, &writebuffer, NULL, 0); + freeSockWithLock(transPResponseSocketPool, mid, sd); } mid=oidmid.mid; sd = getSockWithLock(transPResponseSocketPool, mid); @@ -973,57 +973,57 @@ int prefetchReq(int acceptfd, struct readstruct * readbuffer) { /* Calculate the oid corresponding to the offset value */ for(i = 0; i< numoffset; i++) { - /* Check for arrays */ - if(TYPE(header) >= NUMCLASSES) { - int elementsize = classsize[TYPE(header)]; - struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t)); - unsigned short length = ao->___length___; - /* Check if array out of bounds */ - if(offsetarry[i]< 0 || offsetarry[i] >= length) { - break; - } - oid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*offsetarry[i]))); - } else { - oid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offsetarry[i])); - } - - /* Don't continue if we hit a NULL pointer */ - if (oid==0) - break; - - LOGTIME('B',oid,0,myrdtsc(),gid); //send next oid found from prefetch request - - if((header = mhashSearch(oid)) == NULL) { - size = sizeof(int)+sizeof(int) + sizeof(char) + sizeof(unsigned int); - char sendbuffer[size+1]; - sendbuffer[0]=TRANS_PREFETCH_RESPONSE; - *((int *) (sendbuffer+1)) = size; - *((char *)(sendbuffer + sizeof(char)+sizeof(int))) = OBJECT_NOT_FOUND; - *((unsigned int *)(sendbuffer + sizeof(char)+sizeof(int) + sizeof(char))) = oid; - *((int *)(sendbuffer+sizeof(int) + sizeof(char)+sizeof(char)+sizeof(unsigned int))) = gid; - - send_buf(sd, &writebuffer, sendbuffer, size+1); - LOGTIME('J',oid, 0,myrdtsc(), gid); //send first oid not found prefetch request - break; - } else { /* Obj Found */ - int incr = 1; - GETSIZE(objsize, header); - size = sizeof(int)+sizeof(int) + sizeof(char) + sizeof(unsigned int) + sizeof(objheader_t) + objsize; - char sendbuffer[size+1]; - sendbuffer[0]=TRANS_PREFETCH_RESPONSE; - *((int *)(sendbuffer + incr)) = size; - incr += sizeof(int); - *((char *)(sendbuffer + incr)) = OBJECT_FOUND; - incr += sizeof(char); - *((unsigned int *)(sendbuffer+incr)) = oid; - incr += sizeof(unsigned int); - *((int *)(sendbuffer+incr)) = gid; - incr += sizeof(int); - memcpy(sendbuffer + incr, header, objsize + sizeof(objheader_t)); - send_buf(sd, &writebuffer, sendbuffer, size+1); - LOGOIDTYPE("SRES", oid, TYPE(header), (myrdtsc()-clockoffset)); - LOGTIME('C',oid,TYPE(header),myrdtsc(), gid); //send first oid found from prefetch request - } + /* Check for arrays */ + if(TYPE(header) >= NUMCLASSES) { + int elementsize = classsize[TYPE(header)]; + struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t)); + unsigned short length = ao->___length___; + /* Check if array out of bounds */ + if(offsetarry[i]< 0 || offsetarry[i] >= length) { + break; + } + oid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*offsetarry[i]))); + } else { + oid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offsetarry[i])); + } + + /* Don't continue if we hit a NULL pointer */ + if (oid==0) + break; + + LOGTIME('B',oid,0,myrdtsc(),gid); //send next oid found from prefetch request + + if((header = mhashSearch(oid)) == NULL) { + size = sizeof(int)+sizeof(int) + sizeof(char) + sizeof(unsigned int); + char sendbuffer[size+1]; + sendbuffer[0]=TRANS_PREFETCH_RESPONSE; + *((int *) (sendbuffer+1)) = size; + *((char *)(sendbuffer + sizeof(char)+sizeof(int))) = OBJECT_NOT_FOUND; + *((unsigned int *)(sendbuffer + sizeof(char)+sizeof(int) + sizeof(char))) = oid; + *((int *)(sendbuffer+sizeof(int) + sizeof(char)+sizeof(char)+sizeof(unsigned int))) = gid; + + send_buf(sd, &writebuffer, sendbuffer, size+1); + LOGTIME('J',oid, 0,myrdtsc(), gid); //send first oid not found prefetch request + break; + } else { /* Obj Found */ + int incr = 1; + GETSIZE(objsize, header); + size = sizeof(int)+sizeof(int) + sizeof(char) + sizeof(unsigned int) + sizeof(objheader_t) + objsize; + char sendbuffer[size+1]; + sendbuffer[0]=TRANS_PREFETCH_RESPONSE; + *((int *)(sendbuffer + incr)) = size; + incr += sizeof(int); + *((char *)(sendbuffer + incr)) = OBJECT_FOUND; + incr += sizeof(char); + *((unsigned int *)(sendbuffer+incr)) = oid; + incr += sizeof(unsigned int); + *((int *)(sendbuffer+incr)) = gid; + incr += sizeof(int); + memcpy(sendbuffer + incr, header, objsize + sizeof(objheader_t)); + send_buf(sd, &writebuffer, sendbuffer, size+1); + LOGOIDTYPE("SRES", oid, TYPE(header), (myrdtsc()-clockoffset)); + LOGTIME('C',oid,TYPE(header),myrdtsc(), gid); //send first oid found from prefetch request + } } //end of for } } //end of while @@ -1063,47 +1063,47 @@ void processReqNotify(unsigned int numoid, unsigned int *oidarry, unsigned short /* Check to see if versions are same */ checkversion: if (write_trylock(STATUSPTR(header))) { // Can acquire write lock - newversion = header->version; - if(newversion == *(versionarry + i)) { - //Add to the notify list - if((header->notifylist = insNode(header->notifylist, threadid, mid)) == NULL) { - printf("Error: Obj notify list points to NULL %s, %d\n", __FILE__, __LINE__); - return; - } - write_unlock(STATUSPTR(header)); - } else { - write_unlock(STATUSPTR(header)); - if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - perror("processReqNotify():socket()"); - return; - } - bzero(&remoteAddr, sizeof(remoteAddr)); - remoteAddr.sin_family = AF_INET; - remoteAddr.sin_port = htons(LISTEN_PORT); - remoteAddr.sin_addr.s_addr = htonl(mid); - - if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) { - printf("Error: processReqNotify():error %d connecting to %s:%d\n", errno, - inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT); - close(sd); - return; - } else { - - //Send Update notification - msg[0] = THREAD_NOTIFY_RESPONSE; - *((unsigned int *)&msg[1]) = oid; - size = sizeof(unsigned int); - *((unsigned short *)(&msg[1]+size)) = newversion; - size += sizeof(unsigned short); - *((unsigned int *)(&msg[1]+size)) = threadid; - size = 1+ 2*sizeof(unsigned int) + sizeof(unsigned short); - send_data(sd, msg, size); - } - close(sd); - } + newversion = header->version; + if(newversion == *(versionarry + i)) { + //Add to the notify list + if((header->notifylist = insNode(header->notifylist, threadid, mid)) == NULL) { + printf("Error: Obj notify list points to NULL %s, %d\n", __FILE__, __LINE__); + return; + } + write_unlock(STATUSPTR(header)); + } else { + write_unlock(STATUSPTR(header)); + if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { + perror("processReqNotify():socket()"); + return; + } + bzero(&remoteAddr, sizeof(remoteAddr)); + remoteAddr.sin_family = AF_INET; + remoteAddr.sin_port = htons(LISTEN_PORT); + remoteAddr.sin_addr.s_addr = htonl(mid); + + if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) { + printf("Error: processReqNotify():error %d connecting to %s:%d\n", errno, + inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT); + close(sd); + return; + } else { + + //Send Update notification + msg[0] = THREAD_NOTIFY_RESPONSE; + *((unsigned int *)&msg[1]) = oid; + size = sizeof(unsigned int); + *((unsigned short *)(&msg[1]+size)) = newversion; + size += sizeof(unsigned short); + *((unsigned int *)(&msg[1]+size)) = threadid; + size = 1+ 2*sizeof(unsigned int) + sizeof(unsigned short); + send_data(sd, msg, size); + } + close(sd); + } } else { - randomdelay(); - goto checkversion; + randomdelay(); + goto checkversion; } } i++; diff --git a/Robust/src/Runtime/DSTM/interface/gCollect.c b/Robust/src/Runtime/DSTM/interface/gCollect.c index 7a2a859b..1e6fbef3 100644 --- a/Robust/src/Runtime/DSTM/interface/gCollect.c +++ b/Robust/src/Runtime/DSTM/interface/gCollect.c @@ -117,27 +117,27 @@ void clearBlock(objstr_t *block) { for(; next != NULL; curr=next, next = next->next) { unsigned int val=(unsigned int)next->val; if ((val>=tmpbegin)&(valnext=next->next; - free(next); - next=curr; - //loop condition is broken now...need to check before incrementing - // if (next==NULL) - // break; + prehashlistnode_t *tmp=curr->next=next->next; + free(next); + next=curr; + //loop condition is broken now...need to check before incrementing + // if (next==NULL) + // break; } } { unsigned int val=(unsigned int)orig->val; if ((val>=tmpbegin)&(valnext==NULL) { - orig->key=0; - orig->val=NULL; - } else { - next=orig->next; - orig->val=next->val; - orig->key=next->key; - orig->next=next->next; - free(next); - } + if (orig->next==NULL) { + orig->key=0; + orig->val=NULL; + } else { + next=orig->next; + orig->val=next->val; + orig->key=next->key; + orig->next=next->next; + free(next); + } } } @@ -146,7 +146,7 @@ void clearBlock(objstr_t *block) { lockindex++; volatile unsigned int * lockptr_new=&pflookup.larray[lockindex].lock; while(!write_trylock(lockptr_new)) { - sched_yield(); + sched_yield(); } write_unlock(lockptr_current); lockptr_current=lockptr_new; diff --git a/Robust/src/Runtime/DSTM/interface/llookup.c b/Robust/src/Runtime/DSTM/interface/llookup.c index 4f39f11e..7515851f 100644 --- a/Robust/src/Runtime/DSTM/interface/llookup.c +++ b/Robust/src/Runtime/DSTM/interface/llookup.c @@ -138,17 +138,17 @@ unsigned int lhashRemove(unsigned int oid) { if (curr->oid == oid) { // Find a match in the hash table llookup.numelements--; // Decrement the number of elements in the global hashtable if ((curr == &ptr[index]) && (curr->next == NULL)) { // Delete the first item inside the hashtable with no linked list of lhashlistnode_t - curr->oid = 0; - curr->mid = 0; + curr->oid = 0; + curr->mid = 0; } else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first item with a linked list of lhashlistnode_t connected - curr->oid = curr->next->oid; - curr->mid = curr->next->mid; - node = curr->next; - curr->next = curr->next->next; - free(node); + curr->oid = curr->next->oid; + curr->mid = curr->next->mid; + node = curr->next; + curr->next = curr->next->next; + free(node); } else { // Regular delete from linked listed - prev->next = curr->next; - free(curr); + prev->next = curr->next; + free(curr); } pthread_mutex_unlock(&llookup.locktable); return 0; @@ -184,30 +184,30 @@ unsigned int lhashResize(unsigned int newsize) { isfirst = 1; while (curr != NULL) { //Inner loop to go through linked lists if (curr->oid == 0) { //Exit inner loop if there the first element for a given bin/index is NULL - break; //oid = mid =0 for element if not present within the hash table + break; //oid = mid =0 for element if not present within the hash table } next = curr->next; index = lhashFunction(curr->oid); // Insert into the new table if(llookup.table[index].next == NULL && llookup.table[index].oid == 0) { - llookup.table[index].oid = curr->oid; - llookup.table[index].mid = curr->mid; - llookup.numelements++; + llookup.table[index].oid = curr->oid; + llookup.table[index].mid = curr->mid; + llookup.numelements++; } else { - if((newnode = calloc(1, sizeof(lhashlistnode_t))) == NULL) { - printf("Calloc error %s, %d\n", __FILE__, __LINE__); - return 1; - } - newnode->oid = curr->oid; - newnode->mid = curr->mid; - newnode->next = llookup.table[index].next; - llookup.table[index].next = newnode; - llookup.numelements++; + if((newnode = calloc(1, sizeof(lhashlistnode_t))) == NULL) { + printf("Calloc error %s, %d\n", __FILE__, __LINE__); + return 1; + } + newnode->oid = curr->oid; + newnode->mid = curr->mid; + newnode->next = llookup.table[index].next; + llookup.table[index].next = newnode; + llookup.numelements++; } //free the linked list of lhashlistnode_t if not the first element in the hash table if (isfirst != 1) { - free(curr); + free(curr); } isfirst = 0; diff --git a/Robust/src/Runtime/DSTM/interface/machinepile.c b/Robust/src/Runtime/DSTM/interface/machinepile.c index 00c13150..5dec869f 100644 --- a/Robust/src/Runtime/DSTM/interface/machinepile.c +++ b/Robust/src/Runtime/DSTM/interface/machinepile.c @@ -34,17 +34,17 @@ void insertPile(int mid, unsigned int oid, int siteid, short numoffset, short *o int matchstatus; if ((*tmp)==NULL||((toid=(*tmp)->oid)>oid)) { - objnode = (objpile_t *) malloc(sizeof(objpile_t)); - objnode->offset = offset; - objnode->oid = oid; - objnode->numoffset = numoffset; - objnode->siteid = siteid; - objnode->next = *tmp; - *tmp = objnode; - return; + objnode = (objpile_t *) malloc(sizeof(objpile_t)); + objnode->offset = offset; + objnode->oid = oid; + objnode->numoffset = numoffset; + objnode->siteid = siteid; + objnode->next = *tmp; + *tmp = objnode; + return; } if (toid < oid) - continue; + continue; /* Fill objpiles DS */ int i; @@ -52,25 +52,25 @@ void insertPile(int mid, unsigned int oid, int siteid, short numoffset, short *o short * ooffset=(*tmp)->offset; for(i=0; ionumoffset) { - //We've matched, let's just extend the current prefetch - (*tmp)->numoffset=numoffset; - (*tmp)->offset=offset; - return; - } - if (ooffset[i]offset[i]) { - //Place item before the current one - objnode = (objpile_t *) malloc(sizeof(objpile_t)); - objnode->offset = offset; - objnode->oid = oid; - objnode->numoffset = numoffset; - objnode->siteid = siteid; - objnode->next = *tmp; - *tmp = objnode; - return; - } + if (i>onumoffset) { + //We've matched, let's just extend the current prefetch + (*tmp)->numoffset=numoffset; + (*tmp)->offset=offset; + return; + } + if (ooffset[i]offset[i]) { + //Place item before the current one + objnode = (objpile_t *) malloc(sizeof(objpile_t)); + objnode->offset = offset; + objnode->oid = oid; + objnode->numoffset = numoffset; + objnode->siteid = siteid; + objnode->next = *tmp; + *tmp = objnode; + return; + } } //if we get to the end, we're already covered by this prefetch return; diff --git a/Robust/src/Runtime/DSTM/interface/mlookup.c b/Robust/src/Runtime/DSTM/interface/mlookup.c index 9ad6dd8f..776e970c 100644 --- a/Robust/src/Runtime/DSTM/interface/mlookup.c +++ b/Robust/src/Runtime/DSTM/interface/mlookup.c @@ -88,17 +88,17 @@ unsigned int mhashRemove(unsigned int key) { if (curr->key == key) { // Find a match in the hash table mlookup.numelements--; // Decrement the number of elements in the global hashtable if ((curr == &ptr[index]) && (curr->next == NULL)) { // Delete the first item inside the hashtable with no linked list of mhashlistnode_t - curr->key = 0; - curr->val = NULL; + curr->key = 0; + curr->val = NULL; } else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first item with a linked list of mhashlistnode_t connected - curr->key = curr->next->key; - curr->val = curr->next->val; - node = curr->next; - curr->next = curr->next->next; - free(node); + curr->key = curr->next->key; + curr->val = curr->next->val; + node = curr->next; + curr->next = curr->next->next; + free(node); } else { // Regular delete from linked listed - prev->next = curr->next; - free(curr); + prev->next = curr->next; + free(curr); } pthread_mutex_unlock(&mlookup.locktable); return 0; @@ -140,7 +140,7 @@ unsigned int mhashResize(unsigned int newsize) { mhashlistnode_t *tmp,*next; if ((key=curr->key) == 0) { //Exit inner loop if there the first element for a given bin/index is NULL - break; //key = val =0 for element if not present within the hash table + break; //key = val =0 for element if not present within the hash table } next = curr->next; index = (key & mask) >>1; @@ -148,24 +148,24 @@ unsigned int mhashResize(unsigned int newsize) { // Insert into the new table if(tmp->key ==0) { - tmp->key=curr->key; - tmp->val=curr->val; - if (!isfirst) - free(curr); + tmp->key=curr->key; + tmp->val=curr->val; + if (!isfirst) + free(curr); } /* - NOTE: Add this case if you change this... - This case currently never happens because of the way things rehash.... - else if (isfirst) { - mhashlistnode_t *newnode = calloc(1, sizeof(mhashlistnode_t)); - newnode->key = curr->key; - newnode->val = curr->val; - newnode->next = tmp->next; - tmp->next=newnode; - } */ + NOTE: Add this case if you change this... + This case currently never happens because of the way things rehash.... + else if (isfirst) { + mhashlistnode_t *newnode = calloc(1, sizeof(mhashlistnode_t)); + newnode->key = curr->key; + newnode->val = curr->val; + newnode->next = tmp->next; + tmp->next=newnode; + } */ else { - curr->next=tmp->next; - tmp->next=curr; + curr->next=tmp->next; + tmp->next=curr; } isfirst = 0; curr = next; @@ -191,8 +191,8 @@ unsigned int *mhashGetKeys(unsigned int *numKeys) { if (mlookup.table[i].key != 0) { curr = &mlookup.table[i]; while (curr != NULL) { - keys[keyindex++] = curr->key; - curr = curr->next; + keys[keyindex++] = curr->key; + curr = curr->next; } } } diff --git a/Robust/src/Runtime/DSTM/interface/prefetch.c b/Robust/src/Runtime/DSTM/interface/prefetch.c index b4844581..58131560 100644 --- a/Robust/src/Runtime/DSTM/interface/prefetch.c +++ b/Robust/src/Runtime/DSTM/interface/prefetch.c @@ -62,10 +62,10 @@ void *transPrefetchNew() { /* Send Prefetch Request */ perMcPrefetchList_t *ptr = pilehead; while(ptr != NULL) { - // Get sock from shared pool - int sd = getSock2(transPrefetchSockPool, ptr->mid); - sendRangePrefetchReq(ptr, sd, myIpAddr); - ptr = ptr->next; + // Get sock from shared pool + int sd = getSock2(transPrefetchSockPool, ptr->mid); + sendRangePrefetchReq(ptr, sd, myIpAddr); + ptr = ptr->next; } /* Deallocated pilehead */ @@ -101,10 +101,10 @@ perMcPrefetchList_t *processLocal(char *ptr, int numprefetches) { LOGTIME('b',oid,0,0,countInvalidObj); //forward prefetch if(oid!=0) { - int machinenum = lhashSearch(oid); - if(machinenum != myIpAddr) { - insertPrefetch(machinenum, oid, numoffset, offsetarray, &head); - } + int machinenum = lhashSearch(oid); + if(machinenum != myIpAddr) { + insertPrefetch(machinenum, oid, numoffset, offsetarray, &head); + } } //update ptr ptr=((char *)&offsetarray[numoffset])+sizeof(int); @@ -118,59 +118,59 @@ perMcPrefetchList_t *processLocal(char *ptr, int numprefetches) { //Start searching the dfsList for(top=0; top>=0; ) { if(top == offstop) { - isLastOffset=1; + isLastOffset=1; } oid=getNextOid(header, offsetarray, dfsList, top, &countInvalidObj, &isLastOffset); LOGTIME('O',oid,0,0,countInvalidObj); if (oid&1) { - int oldisField=TYPE(header) < NUMCLASSES; - top+=2; - dfsList[top]=oid; - dfsList[top+1]=0; - header=searchObjInv(oid, top, &countInvalidObj, &isLastOffset); - if (header==NULL) { - LOGTIME('c',oid,top,0,countInvalidObj); - //forward prefetch - int machinenum = lhashSearch(oid); - if(machinenum != myIpAddr) { - if (oldisField&&(dfsList[top-1]!=GET_RANGE(offsetarray[top+1]))) { - insertPrefetch(machinenum, oid, 2+numoffset-top, &offsetarray[top-2], &head); - } else { - insertPrefetch(machinenum, oid, numoffset-top, &offsetarray[top], &head); - } - } - } else if (topoid)>oid)) { - objnode = (objOffsetPile_t *) malloc(sizeof(objOffsetPile_t)); - objnode->offsets = offsets; - objnode->oid = oid; - objnode->numoffset = numoffset; - objnode->next = *tmp; - *tmp = objnode; - return; + objnode = (objOffsetPile_t *) malloc(sizeof(objOffsetPile_t)); + objnode->offsets = offsets; + objnode->oid = oid; + objnode->numoffset = numoffset; + objnode->next = *tmp; + *tmp = objnode; + return; } if (toid < oid) - continue; + continue; /* Fill list DS */ int i; @@ -376,24 +376,24 @@ void insertPrefetch(int mid, unsigned int oid, short numoffset, short *offsets, short * ooffset=(*tmp)->offsets; for(i=0; ionumoffset) { - //We've matched, let's just extend the current prefetch - (*tmp)->numoffset=numoffset; - (*tmp)->offsets=offsets; - return; - } - if (ooffset[i]offsets[i]) { - //Place item before the current one - objnode = (objOffsetPile_t *) malloc(sizeof(objOffsetPile_t)); - objnode->offsets = offsets; - objnode->oid = oid; - objnode->numoffset = numoffset; - objnode->next = *tmp; - *tmp = objnode; - return; - } + if (i>onumoffset) { + //We've matched, let's just extend the current prefetch + (*tmp)->numoffset=numoffset; + (*tmp)->offsets=offsets; + return; + } + if (ooffset[i]offsets[i]) { + //Place item before the current one + objnode = (objOffsetPile_t *) malloc(sizeof(objOffsetPile_t)); + objnode->offsets = offsets; + objnode->oid = oid; + objnode->numoffset = numoffset; + objnode->next = *tmp; + *tmp = objnode; + return; + } } //if we get to the end, we're already covered by this prefetch return; @@ -496,11 +496,11 @@ int getRangePrefetchResponse(int sd, struct readstruct * readbuffer) { /* Insert into prefetch hash lookup table */ void * oldptr; if((oldptr = prehashSearch(oid)) != NULL) { - if(((objheader_t *)oldptr)->version < ((objheader_t *)ptr)->version) { - prehashInsert(oid, ptr); - } + if(((objheader_t *)oldptr)->version < ((objheader_t *)ptr)->version) { + prehashInsert(oid, ptr); + } } else { - prehashInsert(oid, ptr); + prehashInsert(oid, ptr); } ptr=(void *)(((unsigned int)ptr)+objsize); size-=objsize; @@ -528,8 +528,8 @@ int rangePrefetchReq(int acceptfd, struct readstruct * readbuffer) { baseoid = oidmid.oid; if(mid != oidmid.mid) { if(mid!= -1) { - forcesend_buf(sd, &writebuffer, NULL, 0); - freeSockWithLock(transPResponseSocketPool, mid, sd); + forcesend_buf(sd, &writebuffer, NULL, 0); + freeSockWithLock(transPResponseSocketPool, mid, sd); } mid = oidmid.mid; sd = getSockWithLock(transPResponseSocketPool, mid); @@ -543,10 +543,10 @@ int rangePrefetchReq(int acceptfd, struct readstruct * readbuffer) { if (pilehead!= NULL) { perMcPrefetchList_t *ptr = pilehead; while(ptr != NULL) { - // Get sock from shared pool - int sd = getSock2(transPrefetchSockPool, ptr->mid); - sendRangePrefetchReq(ptr, sd, mid); - ptr = ptr->next; + // Get sock from shared pool + int sd = getSock2(transPrefetchSockPool, ptr->mid); + sendRangePrefetchReq(ptr, sd, mid); + ptr = ptr->next; } proPrefetchQDealloc(pilehead); @@ -577,21 +577,21 @@ unsigned int getNextOid(objheader_t * header, short * offsetarray, unsigned int //Negative currindex=startindex-stride*currcount; if (currindex<0) - return 0; + return 0; //Also have to check whether we will eventually index into array if (currindex>=length) { - //Skip to the point that we will index into array - int delta=(currindex-length-1)/stride+1; //-1, +1 is to make sure that it rounds up - if ((delta+currcount)>range) - return 0; - currindex-=delta*stride; + //Skip to the point that we will index into array + int delta=(currindex-length-1)/stride+1; //-1, +1 is to make sure that it rounds up + if ((delta+currcount)>range) + return 0; + currindex-=delta*stride; } } else { //Going positive, compute current index currindex=startindex+stride*currcount; if(currindex >= length) - return 0; + return 0; } int elementsize = classsize[TYPE(header)]; @@ -603,7 +603,7 @@ unsigned int getNextOid(objheader_t * header, short * offsetarray, unsigned int //go to the next offset header=searchObjInv(dfsList[top+2], top, countInvalidObj, isLastOffset); if (header==NULL) - return 2; + return 2; } return *((unsigned int *)(((char *)header) + sizeof(objheader_t) + startindex)); diff --git a/Robust/src/Runtime/DSTM/interface/prelookup.c b/Robust/src/Runtime/DSTM/interface/prelookup.c index d3692074..5ac35ee5 100644 --- a/Robust/src/Runtime/DSTM/interface/prelookup.c +++ b/Robust/src/Runtime/DSTM/interface/prelookup.c @@ -66,10 +66,10 @@ void prehashInsert(unsigned int key, void *val) { tmp = ptr; while(tmp != NULL) { if(tmp->key == key) { - isFound=1; - tmp->val = val; //Replace value for an exsisting key - pthread_mutex_unlock(&pflookup.lock); - return; + isFound=1; + tmp->val = val; //Replace value for an exsisting key + pthread_mutex_unlock(&pflookup.lock); + return; } tmp=tmp->next; } @@ -148,17 +148,17 @@ unsigned int prehashRemove(unsigned int key) { if (curr->key == key) { // Find a match in the hash table pflookup.numelements--; // Decrement the number of elements in the global hashtable if ((curr == &ptr[index]) && (curr->next == NULL)) { // Delete the first item inside the hashtable with no linked list of prehashlistnode_t - curr->key = 0; - curr->val = NULL; + curr->key = 0; + curr->val = NULL; } else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first item with a linked list of prehashlistnode_t connected - curr->key = curr->next->key; - curr->val = curr->next->val; - node = curr->next; - curr->next = curr->next->next; - free(node); + curr->key = curr->next->key; + curr->val = curr->next->val; + node = curr->next; + curr->next = curr->next->next; + free(node); } else { // Regular delete from linked listed - prev->next = curr->next; - free(curr); + prev->next = curr->next; + free(curr); } pthread_mutex_unlock(&pflookup.lock); return 0; @@ -194,30 +194,30 @@ unsigned int prehashResize(unsigned int newsize) { do { unsigned int key; if ((key=curr->key) == 0) { //Exit inner loop if there the first element for a given bin/index is NULL - break; //key = val =0 for element if not present within the hash table + break; //key = val =0 for element if not present within the hash table } next = curr->next; index = (key & mask)>>1; tmp=&pflookup.table[index]; // Insert into the new table if(tmp->key==0) { - tmp->key=curr->key; - tmp->val=curr->val; - if (!isfirst) - free(curr); + tmp->key=curr->key; + tmp->val=curr->val; + if (!isfirst) + free(curr); } /* - NOTE: Add this case if you change this... - This case currently never happens because of the way things rehash.... - else if (isfirst) { - prehashlistnode_t * newnode = calloc(1, sizeof(prehashlistnode_t)); - newnode->key = curr->key; - newnode->val = curr->val; - newnode->next = tmp->next; - tmp->next=newnode; - } */ + NOTE: Add this case if you change this... + This case currently never happens because of the way things rehash.... + else if (isfirst) { + prehashlistnode_t * newnode = calloc(1, sizeof(prehashlistnode_t)); + newnode->key = curr->key; + newnode->val = curr->val; + newnode->next = tmp->next; + tmp->next=newnode; + } */ else { - curr->next=tmp->next; - tmp->next=curr; + curr->next=tmp->next; + tmp->next=curr; } isfirst = 0; diff --git a/Robust/src/Runtime/DSTM/interface/sandbox.c b/Robust/src/Runtime/DSTM/interface/sandbox.c index 4418df09..ed48dda6 100644 --- a/Robust/src/Runtime/DSTM/interface/sandbox.c +++ b/Robust/src/Runtime/DSTM/interface/sandbox.c @@ -45,24 +45,24 @@ int checktrans() { /* Inner loop to traverse the linked list of the cache lookupTable */ while(curr != NULL) { if (curr->key == 0) - break; + break; objheader_t *headeraddr=(objheader_t*) curr->val; unsigned int machinenum; objheader_t *tmp; if (STATUS(headeraddr) & NEW) { - //new objects cannot be stale + //new objects cannot be stale } else if ((tmp=mhashSearch(curr->key)) != NULL) { - //memory barrier - CFENCE; - if (tmp->version!=headeraddr->version) { - //version mismatch - deletehead(head); - return 1; //return 1 when objects are inconsistent - } + //memory barrier + CFENCE; + if (tmp->version!=headeraddr->version) { + //version mismatch + deletehead(head); + return 1; //return 1 when objects are inconsistent + } } else { - machinenum = lhashSearch(curr->key); - head = createList(head, headeraddr, machinenum, c_numelements); + machinenum = lhashSearch(curr->key); + head = createList(head, headeraddr, machinenum, c_numelements); } curr = curr->next; @@ -87,17 +87,17 @@ nodeElem_t * createList(nodeElem_t *head, objheader_t *headeraddr, unsigned int while(tmp != NULL) { if(tmp->mid == mid) { if (STATUS(headeraddr) & DIRTY) { - offset = (sizeof(unsigned int) + sizeof(short)) * tmp->nummod; - *((unsigned int *)(((char *)tmp->objmod) + offset))=OID(headeraddr); - offset += sizeof(unsigned int); - *((unsigned short *)(((char *)tmp->objmod) + offset)) = headeraddr->version; - tmp->nummod++; + offset = (sizeof(unsigned int) + sizeof(short)) * tmp->nummod; + *((unsigned int *)(((char *)tmp->objmod) + offset))=OID(headeraddr); + offset += sizeof(unsigned int); + *((unsigned short *)(((char *)tmp->objmod) + offset)) = headeraddr->version; + tmp->nummod++; } else { - offset = (sizeof(unsigned int) + sizeof(short)) * tmp->numread; - *((unsigned int *)(((char *)tmp->objread) + offset))=OID(headeraddr); - offset += sizeof(unsigned int); - *((unsigned short *)(((char *)tmp->objread) + offset)) = headeraddr->version; - tmp->numread++; + offset = (sizeof(unsigned int) + sizeof(short)) * tmp->numread; + *((unsigned int *)(((char *)tmp->objread) + offset))=OID(headeraddr); + offset += sizeof(unsigned int); + *((unsigned short *)(((char *)tmp->objread) + offset)) = headeraddr->version; + tmp->numread++; } found = 1; break; @@ -232,8 +232,8 @@ int verify(nodeElem_t *pile) { recv_data(sd, &control, sizeof(char)); getReplyCtrl[i] = control; if(control == OBJ_INCONSISTENT) { /* Inconsistent */ - checkObj = 1; - break; + checkObj = 1; + break; } countConsistent++; } @@ -332,18 +332,18 @@ void checkObjVersion(struct readstruct * readbuffer, int sd, unsigned int numrea return; } else { if(is_write_locked(STATUSPTR(header))) { //object write locked - control = OBJ_INCONSISTENT; - send_data(sd, &control, sizeof(char)); - return; + control = OBJ_INCONSISTENT; + send_data(sd, &control, sizeof(char)); + return; } CFENCE; //compare versions if(version == header->version) - v_match++; + v_match++; else { - control = OBJ_INCONSISTENT; - send_data(sd, &control, sizeof(char)); - return; + control = OBJ_INCONSISTENT; + send_data(sd, &control, sizeof(char)); + return; } } } // end of objects read @@ -363,17 +363,17 @@ void checkObjVersion(struct readstruct * readbuffer, int sd, unsigned int numrea return; } else { if(is_write_locked(STATUSPTR(header))) { //object write locked - control = OBJ_INCONSISTENT; - send_data(sd, &control, sizeof(char)); - return; + control = OBJ_INCONSISTENT; + send_data(sd, &control, sizeof(char)); + return; } //compare versions if(version == header->version) - v_match++; + v_match++; else { - control = OBJ_INCONSISTENT; - send_data(sd, &control, sizeof(char)); - return; + control = OBJ_INCONSISTENT; + send_data(sd, &control, sizeof(char)); + return; } } } // end of objects modified diff --git a/Robust/src/Runtime/DSTM/interface/sockpool.c b/Robust/src/Runtime/DSTM/interface/sockpool.c index c39f1428..a4564fa0 100644 --- a/Robust/src/Runtime/DSTM/interface/sockpool.c +++ b/Robust/src/Runtime/DSTM/interface/sockpool.c @@ -6,16 +6,16 @@ inline int test_and_set(volatile unsigned int *addr) { int oldval; /* Note: the "xchg" instruction does not need a "lock" prefix */ __asm__ __volatile__ ("xchgl %0, %1" - : "=r" (oldval), "=m" (*(addr)) - : "0" (1), "m" (*(addr))); + : "=r" (oldval), "=m" (*(addr)) + : "0" (1), "m" (*(addr))); return oldval; } inline void UnLock(volatile unsigned int *addr) { int oldval; /* Note: the "xchg" instruction does not need a "lock" prefix */ __asm__ __volatile__ ("xchgl %0, %1" - : "=r" (oldval), "=m" (*(addr)) - : "0" (0), "m" (*(addr))); + : "=r" (oldval), "=m" (*(addr)) + : "0" (0), "m" (*(addr))); } #elif # error need implementation of test_and_set @@ -28,8 +28,8 @@ inline void Lock(volatile unsigned int *s) { int i=0; while(*s) { if (i++>MAXSPINS) { - sched_yield(); - i=0; + sched_yield(); + i=0; } } } @@ -267,32 +267,32 @@ int getSock(sock_pool_t *sockpool, unsigned int mid) { if (sockpool[i].mid == mid) { int j; for (j = 0; j < MAX_CONN_PER_MACHINE; j++) { - if (sockpool[i].sd[j] != -1 && (sockpool[i].inuse[j] == 0)) { - sockpool[i].inuse[j] = 1; - return sockpool[i].sd[j]; - } - if (sockpool[i].sd[j] == -1) { - //Open Connection - int sd; - if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - printf("%s() Error: In creating socket at %s, %d\n", __func__, __FILE__, __LINE__); - return -1; - } - struct sockaddr_in remoteAddr; - bzero(&remoteAddr, sizeof(remoteAddr)); - remoteAddr.sin_family = AF_INET; - remoteAddr.sin_port = htons(LISTEN_PORT); - remoteAddr.sin_addr.s_addr = htonl(mid); - - if(connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) { - printf("%s(): Error %d connecting to %s:%d\n", __func__, errno, inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT); - close(sd); - return -1; - } - sockpool[i].sd[j] = sd; - sockpool[i].inuse[j] = 1; - return sockpool[i].sd[j]; - } + if (sockpool[i].sd[j] != -1 && (sockpool[i].inuse[j] == 0)) { + sockpool[i].inuse[j] = 1; + return sockpool[i].sd[j]; + } + if (sockpool[i].sd[j] == -1) { + //Open Connection + int sd; + if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { + printf("%s() Error: In creating socket at %s, %d\n", __func__, __FILE__, __LINE__); + return -1; + } + struct sockaddr_in remoteAddr; + bzero(&remoteAddr, sizeof(remoteAddr)); + remoteAddr.sin_family = AF_INET; + remoteAddr.sin_port = htons(LISTEN_PORT); + remoteAddr.sin_addr.s_addr = htonl(mid); + + if(connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) { + printf("%s(): Error %d connecting to %s:%d\n", __func__, errno, inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT); + close(sd); + return -1; + } + sockpool[i].sd[j] = sd; + sockpool[i].inuse[j] = 1; + return sockpool[i].sd[j]; + } } printf("%s()->Error: Less number of MAX_CONN_PER_MACHINE\n", __func__); return -1; @@ -309,8 +309,8 @@ int freeSock(sock_pool_t *sockpool, int sd) { int j; for (j = 0; j < MAX_CONN_PER_MACHINE; j++) { if (sockpool[i].sd[j] == sd) { - sockpool[i].inuse[j] = 0; - return 0; + sockpool[i].inuse[j] = 0; + return 0; } } } diff --git a/Robust/src/Runtime/DSTM/interface/threadnotify.c b/Robust/src/Runtime/DSTM/interface/threadnotify.c index deab6f06..61050503 100644 --- a/Robust/src/Runtime/DSTM/interface/threadnotify.c +++ b/Robust/src/Runtime/DSTM/interface/threadnotify.c @@ -83,18 +83,18 @@ unsigned int notifyhashInsert(unsigned int tid, notifydata_t *ndata) { tmp = &ptr[index]; while(tmp != NULL) { if(tmp->threadid == tid) { - isFound = 1; - tmp->ndata = ndata; - pthread_mutex_unlock(&nlookup.locktable); - return 0; + isFound = 1; + tmp->ndata = ndata; + pthread_mutex_unlock(&nlookup.locktable); + return 0; } tmp = tmp->next; } if(!isFound) { if ((node = calloc(1, sizeof(notifylistnode_t))) == NULL) { - printf("Calloc error %s, %d\n", __FILE__, __LINE__); - pthread_mutex_unlock(&nlookup.locktable); - return 1; + printf("Calloc error %s, %d\n", __FILE__, __LINE__); + pthread_mutex_unlock(&nlookup.locktable); + return 1; } node->threadid = tid; node->ndata = ndata; @@ -138,17 +138,17 @@ unsigned int notifyhashRemove(unsigned int tid) { if (curr->threadid == tid) { // Find a match in the hash table nlookup.numelements--; // Decrement the number of elements in the global hashtable if ((curr == &ptr[index]) && (curr->next == NULL)) { // Delete the first item inside the hashtable with no linked list of notifylistnode_t - curr->threadid = 0; - curr->ndata = NULL; + curr->threadid = 0; + curr->ndata = NULL; } else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first bin item with a linked list of notifylistnode_t connected - curr->threadid = curr->next->threadid; - curr->ndata = curr->next->ndata; - node = curr->next; - curr->next = curr->next->next; - free(node); + curr->threadid = curr->next->threadid; + curr->ndata = curr->next->ndata; + node = curr->next; + curr->next = curr->next->next; + free(node); } else { // Regular delete from linked listed - prev->next = curr->next; - free(curr); + prev->next = curr->next; + free(curr); } pthread_mutex_unlock(&nlookup.locktable); return 0; @@ -184,7 +184,7 @@ unsigned int notifyhashResize(unsigned int newsize) { isfirst = 1; while (curr != NULL) { //Inner loop to go through linked lists if (curr->threadid == 0) { //Exit inner loop if there the first element for a given bin/index is NULL - break; //threadid = threadcond =0 for element if not present within the hash table + break; //threadid = threadcond =0 for element if not present within the hash table } next = curr->next; index = notifyhashFunction(curr->threadid); @@ -193,24 +193,24 @@ unsigned int notifyhashResize(unsigned int newsize) { #endif // Insert into the new table if(nlookup.table[index].next == NULL && nlookup.table[index].threadid == 0) { - nlookup.table[index].threadid = curr->threadid; - nlookup.table[index].ndata = curr->ndata; - nlookup.numelements++; + nlookup.table[index].threadid = curr->threadid; + nlookup.table[index].ndata = curr->ndata; + nlookup.numelements++; } else { - if((newnode = calloc(1, sizeof(notifylistnode_t))) == NULL) { - printf("Calloc error %s, %d\n", __FILE__, __LINE__); - return 1; - } - newnode->threadid = curr->threadid; - newnode->ndata = curr->ndata; - newnode->next = nlookup.table[index].next; - nlookup.table[index].next = newnode; - nlookup.numelements++; + if((newnode = calloc(1, sizeof(notifylistnode_t))) == NULL) { + printf("Calloc error %s, %d\n", __FILE__, __LINE__); + return 1; + } + newnode->threadid = curr->threadid; + newnode->ndata = curr->ndata; + newnode->next = nlookup.table[index].next; + nlookup.table[index].next = newnode; + nlookup.numelements++; } //free the linked list of notifylistnode_t if not the first element in the hash table if (isfirst != 1) { - free(curr); + free(curr); } isfirst = 0; diff --git a/Robust/src/Runtime/DSTM/interface/trans.c b/Robust/src/Runtime/DSTM/interface/trans.c index 77a6c823..0c1bfce1 100644 --- a/Robust/src/Runtime/DSTM/interface/trans.c +++ b/Robust/src/Runtime/DSTM/interface/trans.c @@ -341,8 +341,8 @@ void prefetch(int siteid, int ntuples, unsigned int *oids, unsigned short *endof int top=endoffsets[ntuples-1]; if (node==NULL) { - LOGEVENT('D'); - return; + LOGEVENT('D'); + return; } /* Set queue node values */ @@ -366,18 +366,18 @@ void prefetch(int siteid, int ntuples, unsigned int *oids, unsigned short *endof node=gettail(); prefetchpile_t *pilehead = foundLocal(node,numpref,siteid); if (pilehead!=NULL) { - // Get sock from shared pool - - /* Send Prefetch Request */ - prefetchpile_t *ptr = pilehead; - while(ptr != NULL) { - globalid++; - int sd = getSock2(transPrefetchSockPool, ptr->mid); - sendPrefetchReq(ptr, sd, globalid); - ptr = ptr->next; - } - - mcdealloc(pilehead); + // Get sock from shared pool + + /* Send Prefetch Request */ + prefetchpile_t *ptr = pilehead; + while(ptr != NULL) { + globalid++; + int sd = getSock2(transPrefetchSockPool, ptr->mid); + sendPrefetchReq(ptr, sd, globalid); + ptr = ptr->next; + } + + mcdealloc(pilehead); } resetqueue(); } //end do prefetch if condition @@ -659,9 +659,9 @@ __attribute__((pure)) objheader_t *transRead(unsigned int oid) { if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { if(STATUS(tmp) & DIRTY) { #ifdef TRANSSTATS - ndirtyCacheObj++; + ndirtyCacheObj++; #endif - goto remoteread; + goto remoteread; } #ifdef TRANSSTATS nprehashSearch++; @@ -703,10 +703,10 @@ remoteread: int size; GETSIZE(size, objcopy); if((headerObj = prefetchobjstrAlloc(size + sizeof(objheader_t))) == NULL) { - printf("%s(): Error in getting memory from prefetch cache at %s, %d\n", __func__, - __FILE__, __LINE__); - pthread_mutex_unlock(&prefetchcache_mutex); - return NULL; + printf("%s(): Error in getting memory from prefetch cache at %s, %d\n", __func__, + __FILE__, __LINE__); + pthread_mutex_unlock(&prefetchcache_mutex); + return NULL; } pthread_mutex_unlock(&prefetchcache_mutex); memcpy(headerObj, objcopy, size+sizeof(objheader_t)); @@ -765,9 +765,9 @@ __attribute__((pure)) objheader_t *transRead2(unsigned int oid) { if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { if(STATUS(tmp) & DIRTY) { #ifdef TRANSSTATS - ndirtyCacheObj++; + ndirtyCacheObj++; #endif - goto remoteread; + goto remoteread; } #ifdef TRANSSTATS LOGEVENT('P') @@ -814,10 +814,10 @@ remoteread: int size; GETSIZE(size, objcopy); if((headerObj = prefetchobjstrAlloc(size+sizeof(objheader_t))) == NULL) { - printf("%s(): Error in getting memory from prefetch cache at %s, %d\n", __func__, - __FILE__, __LINE__); - pthread_mutex_unlock(&prefetchcache_mutex); - return NULL; + printf("%s(): Error in getting memory from prefetch cache at %s, %d\n", __func__, + __FILE__, __LINE__); + pthread_mutex_unlock(&prefetchcache_mutex); + return NULL; } pthread_mutex_unlock(&prefetchcache_mutex); memcpy(headerObj, objcopy, size+sizeof(objheader_t)); @@ -874,14 +874,14 @@ plistnode_t *createPiles() { while(curr != NULL) { //if the first bin in hash table is empty if(curr->key == 0) - break; + break; headeraddr=(objheader_t *) curr->val; //Get machine location for object id (and whether local or not) if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) { - machinenum = myIpAddr; + machinenum = myIpAddr; } else if ((machinenum = lhashSearch(curr->key)) == 0) { - printf("Error: No such machine %s, %d\n", __FILE__, __LINE__); - return NULL; + printf("Error: No such machine %s, %d\n", __FILE__, __LINE__); + return NULL; } //Make machine groups @@ -1023,57 +1023,57 @@ int transCommit() { tosend[sockindex].oidcreated = pile->oidcreated; int sd = 0; if(pile->mid != myIpAddr) { - if((sd = getSock2WithLock(transRequestSockPool, pile->mid)) < 0) { - printf("transRequest(): socket create error\n"); - free(listmid); - free(tosend); - return 1; - } - socklist[sockindex] = sd; - /* Send bytes of data with TRANS_REQUEST control message */ - send_buf(sd, &writebuffer, &(tosend[sockindex].f), sizeof(fixed_data_t)); - - /* Send list of machines involved in the transaction */ - { - int size=sizeof(unsigned int)*(tosend[sockindex].f.mcount); - send_buf(sd, &writebuffer, tosend[sockindex].listmid, size); - } - - /* Send oids and version number tuples for objects that are read */ - { - int size=(sizeof(unsigned int)+sizeof(unsigned short))*(tosend[sockindex].f.numread); - send_buf(sd, &writebuffer, tosend[sockindex].objread, size); - } - - /* Send objects that are modified */ - void *modptr; - if((modptr = calloc(1, tosend[sockindex].f.sum_bytes)) == NULL) { - printf("Calloc error for modified objects %s, %d\n", __FILE__, __LINE__); - free(listmid); - free(tosend); - return 1; - } - int offset = 0; - int i; - for(i = 0; i < tosend[sockindex].f.nummod; i++) { - int size; - objheader_t *headeraddr; - if((headeraddr = t_chashSearch(tosend[sockindex].oidmod[i])) == NULL) { - printf("%s() Error: No such oid %s, %d\n", __func__, __FILE__, __LINE__); - free(modptr); - free(listmid); - free(tosend); - return 1; - } - GETSIZE(size,headeraddr); - size+=sizeof(objheader_t); - memcpy(modptr+offset, headeraddr, size); - offset+=size; - } - forcesend_buf(sd, &writebuffer, modptr, tosend[sockindex].f.sum_bytes); - free(modptr); + if((sd = getSock2WithLock(transRequestSockPool, pile->mid)) < 0) { + printf("transRequest(): socket create error\n"); + free(listmid); + free(tosend); + return 1; + } + socklist[sockindex] = sd; + /* Send bytes of data with TRANS_REQUEST control message */ + send_buf(sd, &writebuffer, &(tosend[sockindex].f), sizeof(fixed_data_t)); + + /* Send list of machines involved in the transaction */ + { + int size=sizeof(unsigned int)*(tosend[sockindex].f.mcount); + send_buf(sd, &writebuffer, tosend[sockindex].listmid, size); + } + + /* Send oids and version number tuples for objects that are read */ + { + int size=(sizeof(unsigned int)+sizeof(unsigned short))*(tosend[sockindex].f.numread); + send_buf(sd, &writebuffer, tosend[sockindex].objread, size); + } + + /* Send objects that are modified */ + void *modptr; + if((modptr = calloc(1, tosend[sockindex].f.sum_bytes)) == NULL) { + printf("Calloc error for modified objects %s, %d\n", __FILE__, __LINE__); + free(listmid); + free(tosend); + return 1; + } + int offset = 0; + int i; + for(i = 0; i < tosend[sockindex].f.nummod; i++) { + int size; + objheader_t *headeraddr; + if((headeraddr = t_chashSearch(tosend[sockindex].oidmod[i])) == NULL) { + printf("%s() Error: No such oid %s, %d\n", __func__, __FILE__, __LINE__); + free(modptr); + free(listmid); + free(tosend); + return 1; + } + GETSIZE(size,headeraddr); + size+=sizeof(objheader_t); + memcpy(modptr+offset, headeraddr, size); + offset+=size; + } + forcesend_buf(sd, &writebuffer, modptr, tosend[sockindex].f.sum_bytes); + free(modptr); } else { //handle request locally - handleLocalReq(&tosend[sockindex], &transinfo, &getReplyCtrl[sockindex]); + handleLocalReq(&tosend[sockindex], &transinfo, &getReplyCtrl[sockindex]); } sockindex++; pile = pile->next; @@ -1084,43 +1084,43 @@ int transCommit() { for(i = 0; i < pilecount; i++) { int sd = socklist[i]; if(sd != 0) { - char control; - recv_data(sd, &control, sizeof(char)); - //Update common data structure with new ctrl msg - getReplyCtrl[i] = control; - /* Recv Objects if participant sends TRANS_DISAGREE */ + char control; + recv_data(sd, &control, sizeof(char)); + //Update common data structure with new ctrl msg + getReplyCtrl[i] = control; + /* Recv Objects if participant sends TRANS_DISAGREE */ #ifdef CACHE - if(control == TRANS_DISAGREE) { - int length; - recv_data(sd, &length, sizeof(int)); - void *newAddr; - pthread_mutex_lock(&prefetchcache_mutex); - if ((newAddr = prefetchobjstrAlloc((unsigned int)length)) == NULL) { - printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__); - free(tosend); - free(listmid); - pthread_mutex_unlock(&prefetchcache_mutex); - return 1; - } - pthread_mutex_unlock(&prefetchcache_mutex); - recv_data(sd, newAddr, length); - int offset = 0; - while(length != 0) { - unsigned int oidToPrefetch; - objheader_t * header; - header = (objheader_t *)(((char *)newAddr) + offset); - oidToPrefetch = OID(header); - STATUS(header)=0; - int size = 0; - GETSIZE(size, header); - size += sizeof(objheader_t); - //make an entry in prefetch hash table - prehashInsert(oidToPrefetch, header); - LOGEVENT('E'); - length = length - size; - offset += size; - } - } //end of receiving objs + if(control == TRANS_DISAGREE) { + int length; + recv_data(sd, &length, sizeof(int)); + void *newAddr; + pthread_mutex_lock(&prefetchcache_mutex); + if ((newAddr = prefetchobjstrAlloc((unsigned int)length)) == NULL) { + printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__); + free(tosend); + free(listmid); + pthread_mutex_unlock(&prefetchcache_mutex); + return 1; + } + pthread_mutex_unlock(&prefetchcache_mutex); + recv_data(sd, newAddr, length); + int offset = 0; + while(length != 0) { + unsigned int oidToPrefetch; + objheader_t * header; + header = (objheader_t *)(((char *)newAddr) + offset); + oidToPrefetch = OID(header); + STATUS(header)=0; + int size = 0; + GETSIZE(size, header); + size += sizeof(objheader_t); + //make an entry in prefetch hash table + prehashInsert(oidToPrefetch, header); + LOGEVENT('E'); + length = length - size; + offset += size; + } + } //end of receiving objs #endif } } @@ -1138,10 +1138,10 @@ int transCommit() { /* Invalidate objects in other machine cache */ int retval; if((retval = invalidateObj(tosend, pilecount,finalResponse,socklist)) != 0) { - printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__); - free(tosend); - free(listmid); - return 1; + printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__); + free(tosend); + free(listmid); + return 1; } } #endif @@ -1150,39 +1150,39 @@ int transCommit() { int sd = socklist[i]; if(sd != 0) { #ifdef CACHE - if(finalResponse == TRANS_COMMIT) { - int retval; - /* Update prefetch cache */ - if((retval = updatePrefetchCache(&(tosend[i]))) != 0) { - printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__); - free(tosend); - free(listmid); - return 1; - } + if(finalResponse == TRANS_COMMIT) { + int retval; + /* Update prefetch cache */ + if((retval = updatePrefetchCache(&(tosend[i]))) != 0) { + printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__); + free(tosend); + free(listmid); + return 1; + } #ifdef ABORTREADERS - removetransaction(tosend[i].oidmod,tosend[i].f.nummod); - removethisreadtransaction(tosend[i].objread, tosend[i].f.numread); + removetransaction(tosend[i].oidmod,tosend[i].f.nummod); + removethisreadtransaction(tosend[i].objread, tosend[i].f.numread); #endif - } + } #ifdef ABORTREADERS - else if (!treplyretry) { - removethistransaction(tosend[i].oidmod,tosend[i].f.nummod); - removethisreadtransaction(tosend[i].objread,tosend[i].f.numread); - } + else if (!treplyretry) { + removethistransaction(tosend[i].oidmod,tosend[i].f.nummod); + removethisreadtransaction(tosend[i].objread,tosend[i].f.numread); + } #endif #endif - send_data(sd, &finalResponse, sizeof(char)); + send_data(sd, &finalResponse, sizeof(char)); } else { - /* Complete local processing */ - doLocalProcess(finalResponse, &(tosend[i]), &transinfo); + /* Complete local processing */ + doLocalProcess(finalResponse, &(tosend[i]), &transinfo); #ifdef ABORTREADERS - if(finalResponse == TRANS_COMMIT) { - removetransaction(tosend[i].oidmod,tosend[i].f.nummod); - removethisreadtransaction(tosend[i].objread,tosend[i].f.numread); - } else if (!treplyretry) { - removethistransaction(tosend[i].oidmod,tosend[i].f.nummod); - removethisreadtransaction(tosend[i].objread,tosend[i].f.numread); - } + if(finalResponse == TRANS_COMMIT) { + removetransaction(tosend[i].oidmod,tosend[i].f.nummod); + removethisreadtransaction(tosend[i].objread,tosend[i].f.numread); + } else if (!treplyretry) { + removethistransaction(tosend[i].oidmod,tosend[i].f.nummod); + removethisreadtransaction(tosend[i].objread,tosend[i].f.numread); + } #endif } } @@ -1261,14 +1261,14 @@ void handleLocalReq(trans_req_data_t *tdata, trans_commit_data_t *transinfo, cha commitCountForObjRead(getReplyCtrl, oidnotfound, oidlocked, &numoidnotfound, &numoidlocked, &v_nomatch, &v_matchlock, &v_matchnolock, oid, version); } else { // Objects Modified if(i == tdata->f.numread) { - oidlocked[numoidlocked++] = -1; + oidlocked[numoidlocked++] = -1; } int tmpsize; objheader_t *headptr; headptr = (objheader_t *) t_chashSearch(tdata->oidmod[i-numread]); if (headptr == NULL) { - printf("Error: handleLocalReq() returning NULL, no such oid %s, %d\n", __FILE__, __LINE__); - return; + printf("Error: handleLocalReq() returning NULL, no such oid %s, %d\n", __FILE__, __LINE__); + return; } oid = OID(headptr); version = headptr->version; @@ -1324,7 +1324,7 @@ void doLocalProcess(char finalResponse, trans_req_data_t *tdata, trans_commit_da * all Participant machines after the TRANS_REQUEST protocol */ char decideResponse(char *getReplyCtrl, char *treplyretry, int pilecount) { int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what - message to send */ + message to send */ for (i = 0; i < pilecount; i++) { char control; control = getReplyCtrl[i]; @@ -1421,26 +1421,26 @@ void commitCountForObjMod(char *getReplyCtrl, unsigned int *oidnotfound, unsigne /* Check if Obj is locked by any previous transaction */ if (write_trylock(STATUSPTR(mobj))) { // Can acquire write lock if (version == ((objheader_t *)mobj)->version) { /* match versions */ - (*v_matchnolock)++; - //Keep track of what is locked - oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj)); + (*v_matchnolock)++; + //Keep track of what is locked + oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj)); } else { /* If versions don't match ...HARD ABORT */ - (*v_nomatch)++; - /* Send TRANS_DISAGREE to Coordinator */ - *getReplyCtrl = TRANS_DISAGREE; + (*v_nomatch)++; + /* Send TRANS_DISAGREE to Coordinator */ + *getReplyCtrl = TRANS_DISAGREE; - //Keep track of what is locked - oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj)); - return; + //Keep track of what is locked + oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj)); + return; } } else { //A lock is acquired some place else if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */ - (*v_matchlock)++; + (*v_matchlock)++; } else { /* If versions don't match ...HARD ABORT */ - (*v_nomatch)++; - /* Send TRANS_DISAGREE to Coordinator */ - *getReplyCtrl = TRANS_DISAGREE; - return; + (*v_nomatch)++; + /* Send TRANS_DISAGREE to Coordinator */ + *getReplyCtrl = TRANS_DISAGREE; + return; } } } @@ -1460,26 +1460,26 @@ void commitCountForObjRead(char *getReplyCtrl, unsigned int *oidnotfound, unsign /* Check if Obj is locked by any previous transaction */ if (read_trylock(STATUSPTR(mobj))) { // Can further acquire read locks if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */ - (*v_matchnolock)++; - //Keep track of what is locked - oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj)); + (*v_matchnolock)++; + //Keep track of what is locked + oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj)); } else { /* If versions don't match ...HARD ABORT */ - (*v_nomatch)++; - /* Send TRANS_DISAGREE to Coordinator */ - *getReplyCtrl = TRANS_DISAGREE; - //Keep track of what is locked - oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj)); - return; + (*v_nomatch)++; + /* Send TRANS_DISAGREE to Coordinator */ + *getReplyCtrl = TRANS_DISAGREE; + //Keep track of what is locked + oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj)); + return; } } else { //Has reached max number of readers or some other transaction //has acquired a lock on this object if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */ - (*v_matchlock)++; + (*v_matchlock)++; } else { /* If versions don't match ...HARD ABORT */ - (*v_nomatch)++; - /* Send TRANS_DISAGREE to Coordinator */ - *getReplyCtrl = TRANS_DISAGREE; - return; + (*v_nomatch)++; + /* Send TRANS_DISAGREE to Coordinator */ + *getReplyCtrl = TRANS_DISAGREE; + return; } } } @@ -1620,30 +1620,30 @@ prefetchpile_t *foundLocal(char *ptr, int numprefetches, int mysiteid) { int countInvalidObj=0; if (oid==0) { - numLocal++; - continue; + numLocal++; + continue; } //Look up fields locally int isLastOffset=0; if(endindex==0) - isLastOffset=1; + isLastOffset=1; for(newbase=baseindex; newbase 1) { - return 0; + return 0; } } } else { @@ -1731,10 +1731,10 @@ void *transPrefetch(void *t) { /* Send Prefetch Request */ prefetchpile_t *ptr = pilehead; while(ptr != NULL) { - globalid++; - int sd = getSock2(transPrefetchSockPool, ptr->mid); - sendPrefetchReq(ptr, sd,globalid); - ptr = ptr->next; + globalid++; + int sd = getSock2(transPrefetchSockPool, ptr->mid); + sendPrefetchReq(ptr, sd,globalid); + ptr = ptr->next; } /* Release socket */ @@ -1870,7 +1870,7 @@ int getPrefetchResponse(int sd, struct readstruct *readbuffer) { if((oldptr = prehashSearch(oid)) != NULL) { /* If older version then update with new object ptr */ if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) { - prehashInsert(oid, modptr); + prehashInsert(oid, modptr); } } else { /* Else add the object ptr to hash table*/ prehashInsert(oid, modptr); @@ -1924,8 +1924,8 @@ unsigned short getObjType(unsigned int oid) { #ifdef CACHE pthread_mutex_lock(&prefetchcache_mutex); if ((objheader = prefetchobjstrAlloc(size)) == NULL) { - printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__); - pthread_exit(NULL); + printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__); + pthread_exit(NULL); } pthread_mutex_unlock(&prefetchcache_mutex); recv_data(sd, objheader, size); @@ -1934,9 +1934,9 @@ unsigned short getObjType(unsigned int oid) { #else char *buffer; if((buffer = calloc(1, size)) == NULL) { - printf("%s() Calloc Error %s at line %d\n", __func__, __FILE__, __LINE__); - fflush(stdout); - return 0; + printf("%s() Calloc Error %s at line %d\n", __func__, __FILE__, __LINE__); + fflush(stdout); + return 0; } recv_data(sd, buffer, size); objheader = (objheader_t *)buffer; @@ -2022,11 +2022,11 @@ int processConfigFile() { while (token != NULL) { tmpAddr = inet_addr(token); if ((int)tmpAddr == -1) { - printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token); - fclose(configFile); - return -1; + printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token); + fclose(configFile); + return -1; } else - addHost(htonl(tmpAddr)); + addHost(htonl(tmpAddr)); token = strtok(NULL, delimiters); } } @@ -2191,8 +2191,8 @@ void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) { } else { for(i = 0; i < ndata->numoid; i++) { if(ndata->oidarry[i] == oid) { - objIsFound = 1; - index = i; + objIsFound = 1; + index = i; } } if(objIsFound == 0) { @@ -2200,18 +2200,18 @@ void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) { return; } else { if(version <= ndata->versionarry[index]) { - printf("threadNotify(): New version %d has not changed since last version for oid = %d, %s, %d\n", version, oid, __FILE__, __LINE__); - return; + printf("threadNotify(): New version %d has not changed since last version for oid = %d, %s, %d\n", version, oid, __FILE__, __LINE__); + return; } else { #ifdef CACHE - /* Clear from prefetch cache and free thread related data structure */ - if((ptr = prehashSearch(oid)) != NULL) { - prehashRemove(oid); - } -#endif - pthread_mutex_lock(&(ndata->threadnotify)); - pthread_cond_signal(&(ndata->threadcond)); - pthread_mutex_unlock(&(ndata->threadnotify)); + /* Clear from prefetch cache and free thread related data structure */ + if((ptr = prehashSearch(oid)) != NULL) { + prehashRemove(oid); + } +#endif + pthread_mutex_lock(&(ndata->threadnotify)); + pthread_cond_signal(&(ndata->threadcond)); + pthread_mutex_unlock(&(ndata->threadnotify)); } } } @@ -2288,21 +2288,21 @@ plistnode_t *pInsert(plistnode_t *pile, objheader_t *headeraddr, unsigned int mi int tmpsize; if (STATUS(headeraddr) & NEW) { - tmp->oidcreated[tmp->numcreated] = OID(headeraddr); - tmp->numcreated++; - GETSIZE(tmpsize, headeraddr); - tmp->sum_bytes += sizeof(objheader_t) + tmpsize; + tmp->oidcreated[tmp->numcreated] = OID(headeraddr); + tmp->numcreated++; + GETSIZE(tmpsize, headeraddr); + tmp->sum_bytes += sizeof(objheader_t) + tmpsize; } else if (STATUS(headeraddr) & DIRTY) { - tmp->oidmod[tmp->nummod] = OID(headeraddr); - tmp->nummod++; - GETSIZE(tmpsize, headeraddr); - tmp->sum_bytes += sizeof(objheader_t) + tmpsize; + tmp->oidmod[tmp->nummod] = OID(headeraddr); + tmp->nummod++; + GETSIZE(tmpsize, headeraddr); + tmp->sum_bytes += sizeof(objheader_t) + tmpsize; } else { - offset = (sizeof(unsigned int) + sizeof(short)) * tmp->numread; - *((unsigned int *)(((char *)tmp->objread) + offset))=OID(headeraddr); - offset += sizeof(unsigned int); - *((short *)(((char *)tmp->objread) + offset)) = headeraddr->version; - tmp->numread++; + offset = (sizeof(unsigned int) + sizeof(short)) * tmp->numread; + *((unsigned int *)(((char *)tmp->objread) + offset))=OID(headeraddr); + offset += sizeof(unsigned int); + *((short *)(((char *)tmp->objread) + offset)) = headeraddr->version; + tmp->numread++; } found = 1; break; diff --git a/Robust/src/Runtime/GenericHashtable.c b/Robust/src/Runtime/GenericHashtable.c index 9aa31c0b..f00ac00d 100755 --- a/Robust/src/Runtime/GenericHashtable.c +++ b/Robust/src/Runtime/GenericHashtable.c @@ -51,11 +51,11 @@ int genputtable(struct genhashtable *ht, void * key, void * object) { for(i=0; isrc); - struct genpointerlist *nextptr=tmpptr->next; - tmpptr->next=newbins[hashcode]; - newbins[hashcode]=tmpptr; - tmpptr=nextptr; + unsigned int hashcode=genhashfunction(ht, tmpptr->src); + struct genpointerlist *nextptr=tmpptr->next; + tmpptr->next=newbins[hashcode]; + newbins[hashcode]=tmpptr; + tmpptr=nextptr; } } ht->bins=newbins; @@ -96,11 +96,11 @@ int genputtable_I(struct genhashtable *ht, void * key, void * object) { for(i=0; isrc); - struct genpointerlist *nextptr=tmpptr->next; - tmpptr->next=newbins[hashcode]; - newbins[hashcode]=tmpptr; - tmpptr=nextptr; + unsigned int hashcode=genhashfunction(ht, tmpptr->src); + struct genpointerlist *nextptr=tmpptr->next; + tmpptr->next=newbins[hashcode]; + newbins[hashcode]=tmpptr; + tmpptr=nextptr; } } ht->bins=newbins; @@ -151,9 +151,9 @@ void * getnext(struct genhashtable *ht, void * key) { while(ptr!=NULL) { if (((ht->comp_function==NULL)&&(ptr->src==key))||((ht->comp_function!=NULL)&&(*ht->comp_function)(ptr->src,key))) if (ptr->inext!=NULL) { - return ptr->inext->src; + return ptr->inext->src; } else - return NULL; + return NULL; ptr=ptr->next; } #ifndef MULTICORE @@ -200,13 +200,13 @@ void genfreekey(struct genhashtable *ht, void * key) { struct genpointerlist *tmpptr=ptr->next; ptr->next=tmpptr->next; if (tmpptr==ht->list) - ht->list=tmpptr->inext; + ht->list=tmpptr->inext; if (tmpptr==ht->last) - ht->last=tmpptr->iprev; + ht->last=tmpptr->iprev; if (tmpptr->iprev!=NULL) - tmpptr->iprev->inext=tmpptr->inext; + tmpptr->iprev->inext=tmpptr->inext; if (tmpptr->inext!=NULL) - tmpptr->inext->iprev=tmpptr->iprev; + tmpptr->inext->iprev=tmpptr->iprev; RUNFREE(tmpptr); ht->counter--; return; @@ -251,9 +251,9 @@ void genfreehashtable(struct genhashtable * ht) { if (ht->bins[i]!=NULL) { struct genpointerlist *genptr=ht->bins[i]; while(genptr!=NULL) { - struct genpointerlist *tmpptr=genptr->next; - RUNFREE(genptr); - genptr=tmpptr; + struct genpointerlist *tmpptr=genptr->next; + RUNFREE(genptr); + genptr=tmpptr; } } } diff --git a/Robust/src/Runtime/ObjectHash.c b/Robust/src/Runtime/ObjectHash.c index 2d43900c..a7165494 100755 --- a/Robust/src/Runtime/ObjectHash.c +++ b/Robust/src/Runtime/ObjectHash.c @@ -73,14 +73,14 @@ int ObjectHashremove(struct ObjectHash *thisvar, int key) { *ptr=(*ptr)->next; if (toremove->lprev!=NULL) { - toremove->lprev->lnext=toremove->lnext; + toremove->lprev->lnext=toremove->lnext; } else { - thisvar->listhead=toremove->lnext; + thisvar->listhead=toremove->lnext; } if (toremove->lnext!=NULL) { - toremove->lnext->lprev=toremove->lprev; + toremove->lnext->lprev=toremove->lprev; } else { - thisvar->listtail=toremove->lprev; + thisvar->listtail=toremove->lprev; } RUNFREE(toremove); @@ -124,11 +124,11 @@ int ObjectHashadd(struct ObjectHash * thisvar,int key, int data, int data2, int for(i=thisvar->size-1; i>=0; i--) { struct ObjectNode *ptr; for(ptr=thisvar->bucket[i]; ptr!=NULL; ) { - struct ObjectNode * nextptr=ptr->next; - unsigned int newhashkey=(unsigned int)ptr->key % newsize; - ptr->next=newbucket[newhashkey]; - newbucket[newhashkey]=ptr; - ptr=nextptr; + struct ObjectNode * nextptr=ptr->next; + unsigned int newhashkey=(unsigned int)ptr->key % newsize; + ptr->next=newbucket[newhashkey]; + newbucket[newhashkey]=ptr; + ptr=nextptr; } } thisvar->size=newsize; @@ -178,11 +178,11 @@ int ObjectHashadd_I(struct ObjectHash * thisvar,int key, int data, int data2, in for(i=thisvar->size-1; i>=0; i--) { struct ObjectNode *ptr; for(ptr=thisvar->bucket[i]; ptr!=NULL; ) { - struct ObjectNode * nextptr=ptr->next; - unsigned int newhashkey=(unsigned int)ptr->key % newsize; - ptr->next=newbucket[newhashkey]; - newbucket[newhashkey]=ptr; - ptr=nextptr; + struct ObjectNode * nextptr=ptr->next; + unsigned int newhashkey=(unsigned int)ptr->key % newsize; + ptr->next=newbucket[newhashkey]; + newbucket[newhashkey]=ptr; + ptr=nextptr; } } thisvar->size=newsize; diff --git a/Robust/src/Runtime/Queue.c b/Robust/src/Runtime/Queue.c index 7c1429bf..3429dc6b 100644 --- a/Robust/src/Runtime/Queue.c +++ b/Robust/src/Runtime/Queue.c @@ -190,29 +190,29 @@ int assertQueue(struct Queue * queue) { if( i->prev == NULL ) { if( queue->head != i ) { - return 0; + return 0; } // i->prev != NULL } else { if( i->prev->next == NULL ) { - return 0; + return 0; } else if( i->prev->next != i ) { - return 0; + return 0; } } if( i->next == NULL ) { if( queue->tail != i ) { - return 0; + return 0; } // i->next != NULL } else { if( i->next->prev == NULL ) { - return 0; + return 0; } else if( i->next->prev != i ) { - return 0; + return 0; } } diff --git a/Robust/src/Runtime/SimpleHash.c b/Robust/src/Runtime/SimpleHash.c index 5515d863..d5a45b80 100755 --- a/Robust/src/Runtime/SimpleHash.c +++ b/Robust/src/Runtime/SimpleHash.c @@ -73,14 +73,14 @@ int RuntimeHashremovekey(struct RuntimeHash *thisvar, int key) { *ptr=(*ptr)->next; if (toremove->lprev!=NULL) { - toremove->lprev->lnext=toremove->lnext; + toremove->lprev->lnext=toremove->lnext; } else { - thisvar->listhead=toremove->lnext; + thisvar->listhead=toremove->lnext; } if (toremove->lnext!=NULL) { - toremove->lnext->lprev=toremove->lprev; + toremove->lnext->lprev=toremove->lprev; } else { - thisvar->listtail=toremove->lprev; + thisvar->listtail=toremove->lprev; } RUNFREE(toremove); @@ -104,14 +104,14 @@ int RuntimeHashremove(struct RuntimeHash *thisvar, int key, int data) { *ptr=(*ptr)->next; if (toremove->lprev!=NULL) { - toremove->lprev->lnext=toremove->lnext; + toremove->lprev->lnext=toremove->lnext; } else { - thisvar->listhead=toremove->lnext; + thisvar->listhead=toremove->lnext; } if (toremove->lnext!=NULL) { - toremove->lnext->lprev=toremove->lprev; + toremove->lnext->lprev=toremove->lprev; } else { - thisvar->listtail=toremove->lprev; + thisvar->listtail=toremove->lprev; } RUNFREE(toremove); @@ -155,11 +155,11 @@ int RuntimeHashadd(struct RuntimeHash * thisvar,int key, int data) { for(i=thisvar->size-1; i>=0; i--) { struct RuntimeNode *ptr; for(ptr=thisvar->bucket[i]; ptr!=NULL; ) { - struct RuntimeNode * nextptr=ptr->next; - unsigned int newhashkey=(unsigned int)ptr->key % newsize; - ptr->next=newbucket[newhashkey]; - newbucket[newhashkey]=ptr; - ptr=nextptr; + struct RuntimeNode * nextptr=ptr->next; + unsigned int newhashkey=(unsigned int)ptr->key % newsize; + ptr->next=newbucket[newhashkey]; + newbucket[newhashkey]=ptr; + ptr=nextptr; } } thisvar->size=newsize; @@ -237,11 +237,11 @@ int RuntimeHashadd_I(struct RuntimeHash * thisvar,int key, int data) { for(i=thisvar->size-1; i>=0; i--) { struct RuntimeNode *ptr; for(ptr=thisvar->bucket[i]; ptr!=NULL; ) { - struct RuntimeNode * nextptr=ptr->next; - unsigned int newhashkey=(unsigned int)ptr->key % newsize; - ptr->next=newbucket[newhashkey]; - newbucket[newhashkey]=ptr; - ptr=nextptr; + struct RuntimeNode * nextptr=ptr->next; + unsigned int newhashkey=(unsigned int)ptr->key % newsize; + ptr->next=newbucket[newhashkey]; + newbucket[newhashkey]=ptr; + ptr=nextptr; } } thisvar->size=newsize; diff --git a/Robust/src/Runtime/chash.c b/Robust/src/Runtime/chash.c index ecc109a3..3f3a11ac 100644 --- a/Robust/src/Runtime/chash.c +++ b/Robust/src/Runtime/chash.c @@ -89,17 +89,17 @@ unsigned int cRemove(ctable_t *table, void * key) { if (curr->key == key) { // Find a match in the hash table table->numelements--; // Decrement the number of elements in the global hashtable if ((curr == &ptr[index]) && (curr->next == NULL)) { // Delete the first item inside the hashtable with no linked list of cnode_t - curr->key = 0; - curr->val = NULL; + curr->key = 0; + curr->val = NULL; } else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first item with a linked list of cnode_t connected - curr->key = curr->next->key; - curr->val = curr->next->val; - node = curr->next; - curr->next = curr->next->next; - free(node); + curr->key = curr->next->key; + curr->val = curr->next->val; + node = curr->next; + curr->next = curr->next->next; + free(node); } else { // Regular delete from linked listed - prev->next = curr->next; - free(curr); + prev->next = curr->next; + free(curr); } return 0; } @@ -132,23 +132,23 @@ unsigned int cResize(ctable_t *table, unsigned int newsize) { cnode_t * newnode=&ntable[index]; if(newnode->key==0) { - newnode->key=curr->key; - newnode->val=curr->val; - newnode->lnext=last; - last=newnode; + newnode->key=curr->key; + newnode->val=curr->val; + newnode->lnext=last; + last=newnode; } else { - cnode_t *tmp=malloc(sizeof(cnode_t)); - tmp->next=newnode->next; - newnode->next=tmp; - tmp->key=curr->key; - tmp->val=curr->val; - tmp->lnext=last; - last=tmp; + cnode_t *tmp=malloc(sizeof(cnode_t)); + tmp->next=newnode->next; + newnode->next=tmp; + tmp->key=curr->key; + tmp->val=curr->val; + tmp->lnext=last; + last=tmp; } if (isfirst) { - isfirst=0; + isfirst=0; } else { - free(curr); + free(curr); } curr = next; } @@ -170,7 +170,7 @@ void cDelete(ctable_t *ctable) { while(curr != NULL) { next = curr->next; if(isFirst != 1) { - free(curr); + free(curr); } isFirst = 0; curr = next; diff --git a/Robust/src/Runtime/checkpoint.c b/Robust/src/Runtime/checkpoint.c index 1ac35077..e26b4e37 100644 --- a/Robust/src/Runtime/checkpoint.c +++ b/Robust/src/Runtime/checkpoint.c @@ -152,64 +152,64 @@ void ** makecheckpoint(int numparams, void ** srcpointer, struct ctable * forwar pointer=pointerarray[type]; #ifdef TASK if (type==TAGTYPE) { - void *objptr=((struct ___TagDescriptor___*)ptr)->flagptr; - if (objptr!=NULL) { - void *dst; - if ((dst=cSearch(forward, objptr))==NULL) { - void *copy=createcopy(objptr); - cInsert(forward, objptr, copy); - cInsert(reverse, copy, objptr); - addNewItem(todo, objptr); - ((struct ___TagDescriptor___*)cpy)->flagptr=copy; - } else { - ((struct ___TagDescriptor___*) cpy)->flagptr=dst; - } - } + void *objptr=((struct ___TagDescriptor___*)ptr)->flagptr; + if (objptr!=NULL) { + void *dst; + if ((dst=cSearch(forward, objptr))==NULL) { + void *copy=createcopy(objptr); + cInsert(forward, objptr, copy); + cInsert(reverse, copy, objptr); + addNewItem(todo, objptr); + ((struct ___TagDescriptor___*)cpy)->flagptr=copy; + } else { + ((struct ___TagDescriptor___*) cpy)->flagptr=dst; + } + } } else #endif if (pointer==0) { - /* Array of primitives */ - /* Do nothing */ + /* Array of primitives */ + /* Do nothing */ } else if (((int)pointer)==1) { - /* Array of pointers */ - struct ArrayObject *ao=(struct ArrayObject *) ptr; - struct ArrayObject *ao_cpy=(struct ArrayObject *) cpy; - int length=ao->___length___; - int i; - for(i=0; i___length___)+sizeof(int)))[i]; - if (objptr==NULL) { - ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=NULL; - } else if ((dst=cSearch(forward,objptr))!=NULL) - ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=dst; - else { - void * copy=createcopy(objptr); - cInsert(forward, objptr, copy); - cInsert(reverse, copy, objptr); - addNewItem(todo, objptr); - ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=copy; - } - } + /* Array of pointers */ + struct ArrayObject *ao=(struct ArrayObject *) ptr; + struct ArrayObject *ao_cpy=(struct ArrayObject *) cpy; + int length=ao->___length___; + int i; + for(i=0; i___length___)+sizeof(int)))[i]; + if (objptr==NULL) { + ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=NULL; + } else if ((dst=cSearch(forward,objptr))!=NULL) + ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=dst; + else { + void * copy=createcopy(objptr); + cInsert(forward, objptr, copy); + cInsert(reverse, copy, objptr); + addNewItem(todo, objptr); + ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=copy; + } + } } else { - int size=pointer[0]; - int i; - for(i=1; i<=size; i++) { - int offset=pointer[i]; - void * objptr=*((void **)(((int)ptr)+offset)); - void *dst; - if (objptr==NULL) { - *((void **)(((int)cpy)+offset))=NULL; - } else if ((dst=cSearch(forward, objptr))!=NULL) - *((void **) &(((char *)cpy)[offset]))=dst; - else { - void * copy=createcopy(objptr); - cInsert(forward, objptr, copy); - cInsert(reverse, copy, objptr); - addNewItem(todo, objptr); - *((void **)(((int)cpy)+offset))=copy; - } - } + int size=pointer[0]; + int i; + for(i=1; i<=size; i++) { + int offset=pointer[i]; + void * objptr=*((void **)(((int)ptr)+offset)); + void *dst; + if (objptr==NULL) { + *((void **)(((int)cpy)+offset))=NULL; + } else if ((dst=cSearch(forward, objptr))!=NULL) + *((void **) &(((char *)cpy)[offset]))=dst; + else { + void * copy=createcopy(objptr); + cInsert(forward, objptr, copy); + cInsert(reverse, copy, objptr); + addNewItem(todo, objptr); + *((void **)(((int)cpy)+offset))=copy; + } + } } } } @@ -274,80 +274,80 @@ void restorecheckpoint(int numparams, void ** original, void ** checkpoint, stru size=classsize[type]; #ifdef TASK if (type==TAGTYPE) { - void *objptr=((struct ___TagDescriptor___*)ptr)->flagptr; - memcpy(cpy, ptr, size); - if (objptr!=NULL) { - if (cSearch(visited, objptr)==NULL) { - cInsert(visited, objptr, objptr); - addNewItem(todo, objptr); - } - *((void **) &(((struct ___TagDescriptor___ *)cpy)->flagptr))=cSearch(reverse, objptr); - } + void *objptr=((struct ___TagDescriptor___*)ptr)->flagptr; + memcpy(cpy, ptr, size); + if (objptr!=NULL) { + if (cSearch(visited, objptr)==NULL) { + cInsert(visited, objptr, objptr); + addNewItem(todo, objptr); + } + *((void **) &(((struct ___TagDescriptor___ *)cpy)->flagptr))=cSearch(reverse, objptr); + } } else #endif if (pointer==0) { - /* Array of primitives */ - struct ArrayObject *ao=(struct ArrayObject *) ptr; - int length=ao->___length___; - int cpysize=sizeof(struct ArrayObject)+length*size; - memcpy(cpy, ptr, cpysize); + /* Array of primitives */ + struct ArrayObject *ao=(struct ArrayObject *) ptr; + int length=ao->___length___; + int cpysize=sizeof(struct ArrayObject)+length*size; + memcpy(cpy, ptr, cpysize); } else if ((int)pointer==1) { - /* Array of pointers */ - struct ArrayObject *ao=(struct ArrayObject *) ptr; - struct ArrayObject *ao_cpy=(struct ArrayObject *) cpy; - int length=ao->___length___; - int i; - int cpysize=sizeof(struct ArrayObject)+length*size; - memcpy(ao_cpy, ao, cpysize); + /* Array of pointers */ + struct ArrayObject *ao=(struct ArrayObject *) ptr; + struct ArrayObject *ao_cpy=(struct ArrayObject *) cpy; + int length=ao->___length___; + int i; + int cpysize=sizeof(struct ArrayObject)+length*size; + memcpy(ao_cpy, ao, cpysize); - for(i=0; i___length___)+sizeof(int)))[i]; - if (objptr==NULL) - ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=NULL; - else { - if (cSearch(visited, objptr)==NULL) { - cInsert(visited, objptr, objptr); - addNewItem(todo, objptr); - } - *((void **) &((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i])=cSearch(reverse, objptr); - } - } + for(i=0; i___length___)+sizeof(int)))[i]; + if (objptr==NULL) + ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=NULL; + else { + if (cSearch(visited, objptr)==NULL) { + cInsert(visited, objptr, objptr); + addNewItem(todo, objptr); + } + *((void **) &((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i])=cSearch(reverse, objptr); + } + } } else { - int numptr=pointer[0]; - int i; - void *flagptr; - int oldflag; - int currflag; - if (hasflags[type]) { - flagptr=(void *)(((int *)cpy)[2]); - oldflag=(((int *)cpy)[1]); - currflag=(((int *)ptr)[1]); - } - memcpy(cpy, ptr, size); - for(i=1; i<=numptr; i++) { - int offset=pointer[i]; - void * objptr=*((void **)(((int)ptr)+offset)); - if (objptr==NULL) - *((void **)(((int)cpy)+offset))=NULL; - else { - if (cSearch(visited, objptr)==NULL) { - cInsert(visited, objptr, objptr); - addNewItem(todo, objptr); - } - *((void **) &(((char *)cpy)[offset]))=cSearch(reverse, objptr); - } - } - if (hasflags[type]) { - (((void **)cpy)[2])=flagptr; - if (currflag!=oldflag) { - flagorandinit(cpy, 0, 0xFFFFFFFF); + int numptr=pointer[0]; + int i; + void *flagptr; + int oldflag; + int currflag; + if (hasflags[type]) { + flagptr=(void *)(((int *)cpy)[2]); + oldflag=(((int *)cpy)[1]); + currflag=(((int *)ptr)[1]); + } + memcpy(cpy, ptr, size); + for(i=1; i<=numptr; i++) { + int offset=pointer[i]; + void * objptr=*((void **)(((int)ptr)+offset)); + if (objptr==NULL) + *((void **)(((int)cpy)+offset))=NULL; + else { + if (cSearch(visited, objptr)==NULL) { + cInsert(visited, objptr, objptr); + addNewItem(todo, objptr); + } + *((void **) &(((char *)cpy)[offset]))=cSearch(reverse, objptr); + } + } + if (hasflags[type]) { + (((void **)cpy)[2])=flagptr; + if (currflag!=oldflag) { + flagorandinit(cpy, 0, 0xFFFFFFFF); #ifdef MULTICORE - enqueueObject(cpy, NULL,0); //TODO + enqueueObject(cpy, NULL,0); //TODO #else - enqueueObject(cpy); + enqueueObject(cpy); #endif - } - } + } + } } } } diff --git a/Robust/src/Runtime/deque.c b/Robust/src/Runtime/deque.c index f7dcc6b6..dd91825d 100644 --- a/Robust/src/Runtime/deque.c +++ b/Robust/src/Runtime/deque.c @@ -291,7 +291,7 @@ void* dqPopBottom(deque* dq) { if( actualTop == currTop ) { // CAS succeeded if( oldBotNode != newBotNode ) { - poolfreeinto(dq->memPool, oldBotNode); + poolfreeinto(dq->memPool, oldBotNode); } return retVal; diff --git a/Robust/src/Runtime/garbage.c b/Robust/src/Runtime/garbage.c index c5098298..3fd65c39 100644 --- a/Robust/src/Runtime/garbage.c +++ b/Robust/src/Runtime/garbage.c @@ -129,98 +129,98 @@ void fixtable(chashlistnode_t ** tc_table, chashlistnode_t **tc_list, cliststruc chashlistnode_t *tmp,*next; if ((key=(void *)curr->key) == 0) { //Exit inner loop if there the first element is 0 - break; //key = val =0 for element if not present within the hash table + break; //key = val =0 for element if not present within the hash table } SENQUEUE(key, key); if (curr->val>=curr_heapbase&&curr->valval, curr->val); + SENQUEUE(curr->val, curr->val); } else { - //rewrite transaction cache entry - void *vptr=curr->val; - int type=((int *)vptr)[0]; - unsigned INTPTR *pointer=pointerarray[type]; - if (pointer==0) { - //array of primitives - do nothing - struct ArrayObject *ao=(struct ArrayObject *) vptr; - SENQUEUE((void *)ao->___objlocation___, *((void **)&ao->___objlocation___)); - } else if (((INTPTR)pointer)==1) { - //array of pointers - struct ArrayObject *ao=(struct ArrayObject *) vptr; - int length=ao->___length___; - int i; - SENQUEUE((void *)ao->___objlocation___, *((void **)&ao->___objlocation___)); + //rewrite transaction cache entry + void *vptr=curr->val; + int type=((int *)vptr)[0]; + unsigned INTPTR *pointer=pointerarray[type]; + if (pointer==0) { + //array of primitives - do nothing + struct ArrayObject *ao=(struct ArrayObject *) vptr; + SENQUEUE((void *)ao->___objlocation___, *((void **)&ao->___objlocation___)); + } else if (((INTPTR)pointer)==1) { + //array of pointers + struct ArrayObject *ao=(struct ArrayObject *) vptr; + int length=ao->___length___; + int i; + SENQUEUE((void *)ao->___objlocation___, *((void **)&ao->___objlocation___)); #ifdef STMARRAY - int lowindex=ao->lowindex; - int highindex=ao->highindex; - int j; - for(j=lowindex; j<=highindex; j++) { - unsigned int lockval; - GETLOCKVAL(lockval, ao, j); - if (lockval!=STMNONE) { - int lowi=(j<lowindex; + int highindex=ao->highindex; + int j; + for(j=lowindex; j<=highindex; j++) { + unsigned int lockval; + GETLOCKVAL(lockval, ao, j); + if (lockval!=STMNONE) { + int lowi=(j<___length___)+sizeof(int)))[i]; - SENQUEUE(objptr, ((void **)(((char *)&ao->___length___)+sizeof(int)))[i]); - } + void *objptr=((void **)(((char *)&ao->___length___)+sizeof(int)))[i]; + SENQUEUE(objptr, ((void **)(((char *)&ao->___length___)+sizeof(int)))[i]); + } #ifdef STMARRAY - } - } -#endif - } else { - INTPTR size=pointer[0]; - int i; - for(i=1; i<=size; i++) { - unsigned int offset=pointer[i]; - void * objptr=*((void **)(((char *)vptr)+offset)); - SENQUEUE(objptr, *((void **)(((char *)vptr)+offset))); - } - } - } - - next = curr->next; - index = (((unsigned INTPTR)key) & mask) >>4; - - curr->key=key; - tmp=&node[index]; - // Insert into the new table - if(tmp->key == 0) { - tmp->key = curr->key; - tmp->val = curr->val; - tmp->lnext=newlist; - newlist=tmp; - } else if (isfirst) { - chashlistnode_t *newnode; - if ((*cstr)->numarray[(*cstr)->num]; - (*cstr)->num++; - } else { - //get new list - cliststruct_t *tcl=calloc(1,sizeof(cliststruct_t)); - tcl->next=*cstr; - *cstr=tcl; - newnode=&tcl->array[0]; - tcl->num=1; - } - newnode->key = curr->key; - newnode->val = curr->val; - newnode->next = tmp->next; - newnode->lnext=newlist; - newlist=newnode; - tmp->next=newnode; - } else { - curr->lnext=newlist; - newlist=curr; - curr->next=tmp->next; - tmp->next=curr; - } - isfirst = 0; - curr = next; - } - while(curr!=NULL) ; + } + } +#endif + } else { + INTPTR size=pointer[0]; + int i; + for(i=1; i<=size; i++) { + unsigned int offset=pointer[i]; + void * objptr=*((void **)(((char *)vptr)+offset)); + SENQUEUE(objptr, *((void **)(((char *)vptr)+offset))); + } + } + } + + next = curr->next; + index = (((unsigned INTPTR)key) & mask) >>4; + + curr->key=key; + tmp=&node[index]; + // Insert into the new table + if(tmp->key == 0) { + tmp->key = curr->key; + tmp->val = curr->val; + tmp->lnext=newlist; + newlist=tmp; + } else if (isfirst) { + chashlistnode_t *newnode; + if ((*cstr)->numarray[(*cstr)->num]; + (*cstr)->num++; + } else { + //get new list + cliststruct_t *tcl=calloc(1,sizeof(cliststruct_t)); + tcl->next=*cstr; + *cstr=tcl; + newnode=&tcl->array[0]; + tcl->num=1; + } + newnode->key = curr->key; + newnode->val = curr->val; + newnode->next = tmp->next; + newnode->lnext=newlist; + newlist=newnode; + tmp->next=newnode; + } else { + curr->lnext=newlist; + newlist=curr; + curr->next=tmp->next; + tmp->next=curr; + } + isfirst = 0; + curr = next; + } + while(curr!=NULL) ; } free(ptr); (*tc_table)=node; @@ -459,16 +459,16 @@ void collect(struct garbagelist * stackptr) { int length=ao->___length___; int i; for(i=0; i___length___)+sizeof(int)))[i]; - ENQUEUE(objptr, ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]); + void *objptr=((void **)(((char *)&ao->___length___)+sizeof(int)))[i]; + ENQUEUE(objptr, ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]); } } else { INTPTR size=pointer[0]; int i; for(i=1; i<=size; i++) { - unsigned int offset=pointer[i]; - void * objptr=*((void **)(((char *)ptr)+offset)); - ENQUEUE(objptr, *((void **)(((char *)cpy)+offset))); + unsigned int offset=pointer[i]; + void * objptr=*((void **)(((char *)ptr)+offset)); + ENQUEUE(objptr, *((void **)(((char *)cpy)+offset))); } } } @@ -608,8 +608,8 @@ void * mygcmalloc(struct garbagelist * stackptr, int size) { /* Need to allocate base heap */ curr_heapbase=malloc(INITIALHEAPSIZE); if (curr_heapbase==NULL) { - printf("malloc failed. Garbage colletcor couldn't get enough memory. Try changing heap size.\n"); - exit(-1); + printf("malloc failed. Garbage colletcor couldn't get enough memory. Try changing heap size.\n"); + exit(-1); } #if defined(STM)||defined(THREADS)||defined(MLP) #else @@ -621,8 +621,8 @@ void * mygcmalloc(struct garbagelist * stackptr, int size) { to_heapbase=malloc(INITIALHEAPSIZE); if (to_heapbase==NULL) { - printf("malloc failed. Garbage collector couldn't get enough memory. Try changing heap size.\n"); - exit(-1); + printf("malloc failed. Garbage collector couldn't get enough memory. Try changing heap size.\n"); + exit(-1); } to_heaptop=to_heapbase+INITIALHEAPSIZE; @@ -640,21 +640,21 @@ void * mygcmalloc(struct garbagelist * stackptr, int size) { INTPTR to_heapsize=to_heaptop-to_heapbase; INTPTR last_heapsize=0; if (lastgcsize>0) { - last_heapsize=HEAPSIZE(lastgcsize, size); - if ((last_heapsize&7)!=0) - last_heapsize+=(8-(last_heapsize%8)); + last_heapsize=HEAPSIZE(lastgcsize, size); + if ((last_heapsize&7)!=0) + last_heapsize+=(8-(last_heapsize%8)); } if (curr_heapsize>last_heapsize) - last_heapsize=curr_heapsize; + last_heapsize=curr_heapsize; if (last_heapsize>to_heapsize) { - free(to_heapbase); - to_heapbase=malloc(last_heapsize); - if (to_heapbase==NULL) { - printf("Error Allocating enough memory\n"); - exit(-1); - } - to_heaptop=to_heapbase+last_heapsize; - to_heapptr=to_heapbase; + free(to_heapbase); + to_heapbase=malloc(last_heapsize); + if (to_heapbase==NULL) { + printf("Error Allocating enough memory\n"); + exit(-1); + } + to_heaptop=to_heapbase+last_heapsize; + to_heapptr=to_heapbase; } } @@ -671,8 +671,8 @@ void * mygcmalloc(struct garbagelist * stackptr, int size) { { int i; for(i=0; icurr_heapgcpoint) { #if defined(THREADS)||defined(DSTM)||defined(STM)||defined(MLP) - pthread_mutex_unlock(&gclock); + pthread_mutex_unlock(&gclock); #endif - return mygcmalloc(stackptr, size); + return mygcmalloc(stackptr, size); } bzero(tmp, curr_heaptop-tmp); diff --git a/Robust/src/Runtime/garbage.h b/Robust/src/Runtime/garbage.h index d66d5346..8728f37b 100644 --- a/Robust/src/Runtime/garbage.h +++ b/Robust/src/Runtime/garbage.h @@ -21,8 +21,8 @@ struct pointerblock { if ((!(((unsigned int)orig)&0x1))) { \ if (orig>=curr_heapbase&&orig=curr_heapbase&&origpointer)!=0) { - // check whether pointer is already resolved, or not. - table->unresolvedQueue=NULL; //released lock; - return ADDTABLEITEM(table,r,TRUE); + // check whether pointer is already resolved, or not. + table->unresolvedQueue=NULL; //released lock; + return ADDTABLEITEM(table,r,TRUE); } struct Queue* queue=createQueue(); addNewItemBack(queue,r); @@ -411,16 +411,16 @@ int WRITEBINCASE(Hashtable *T, REntry *r, BinItem *val, int key, int inc) { if (T->item.status==READY) { for(; val!=NULL; val=val->next) { if (val==((BinItem *)b)) { - //ready to retire - retval=READY; - if (isParent(r)) { - b->item.status=retval; //unsure if really needed at this point.. - be->head=NULL; // released lock - return retval; - } - break; + //ready to retire + retval=READY; + if (isParent(r)) { + b->item.status=retval; //unsure if really needed at this point.. + be->head=NULL; // released lock + return retval; + } + break; } else if (val->total!=0) { - break; + break; } } } @@ -560,12 +560,12 @@ int ADDVECTOR(MemoryQueue *Q, REntry *r) { flag=(void*)LOCKXCHG((unsigned INTPTR*)&(V->array[index]), (unsigned INTPTR)flag); if (flag!=NULL) { if (isParentCoarse(r)) { //parent's retire immediately - atomic_dec(&V->item.total); - V->index--; + atomic_dec(&V->item.total); + V->index--; } else { #if defined(RCR)&&!defined(OOO_DISABLE_TASKMEMPOOL) - if (atomic_sub_and_test(1, &r->count)) - poolfreeinto(Q->rentrypool, r); + if (atomic_sub_and_test(1, &r->count)) + poolfreeinto(Q->rentrypool, r); #endif } return READY; @@ -604,7 +604,7 @@ int ADDSCC(MemoryQueue *Q, REntry *r) { if (flag!=NULL) { #if defined(RCR)&&!defined(OOO_DISABLE_TASKMEMPOOL) if (atomic_sub_and_test(1, &r->count)) - poolfreeinto(Q->rentrypool, r); + poolfreeinto(Q->rentrypool, r); #endif return READY; } else { @@ -683,53 +683,53 @@ void RETIREBIN(Hashtable *T, REntry *r, BinItem *b) { int i; while (ptr!=NULL) { if (isReadBinItem(ptr)) { - ReadBinItem* rptr=(ReadBinItem*)ptr; - if (rptr->item.status==NOTREADY) { - for (i=0; iindex; i++) { - resolveDependencies(rptr->array[i]); - if (isParent(rptr->array[i])) { - //parents go immediately - atomic_dec(&rptr->item.total); - atomic_dec(&T->item.total); - } - } - } - rptr->item.status=READY; - if (rptr->item.next==NULL) { - break; - } - if (rptr->item.total!=0) { - haveread=TRUE; - } else if ((BinItem*)rptr==val) { - val=val->next; - } + ReadBinItem* rptr=(ReadBinItem*)ptr; + if (rptr->item.status==NOTREADY) { + for (i=0; iindex; i++) { + resolveDependencies(rptr->array[i]); + if (isParent(rptr->array[i])) { + //parents go immediately + atomic_dec(&rptr->item.total); + atomic_dec(&T->item.total); + } + } + } + rptr->item.status=READY; + if (rptr->item.next==NULL) { + break; + } + if (rptr->item.total!=0) { + haveread=TRUE; + } else if ((BinItem*)rptr==val) { + val=val->next; + } } else if(isWriteBinItem(ptr)) { - if (haveread) - break; - if(ptr->status==NOTREADY) { - resolveDependencies(((WriteBinItem*)ptr)->val); - ptr->status=READY; - if(isParent(((WriteBinItem*)ptr)->val)) { - atomic_dec(&T->item.total); - val=val->next; - } else - break; - } else { // write bin is already resolved - val=val->next; - } - /* - if(ptr->status==NOTREADY) { - resolveDependencies(((WriteBinItem*)ptr)->val); - } - ptr->status=READY; - if (isParent(((WriteBinItem*)ptr)->val)) { - atomic_dec(&T->item.total); - //val=val->next; - val=ptr->next; - } else - break; - } - */ + if (haveread) + break; + if(ptr->status==NOTREADY) { + resolveDependencies(((WriteBinItem*)ptr)->val); + ptr->status=READY; + if(isParent(((WriteBinItem*)ptr)->val)) { + atomic_dec(&T->item.total); + val=val->next; + } else + break; + } else { // write bin is already resolved + val=val->next; + } + /* + if(ptr->status==NOTREADY) { + resolveDependencies(((WriteBinItem*)ptr)->val); + } + ptr->status=READY; + if (isParent(((WriteBinItem*)ptr)->val)) { + atomic_dec(&T->item.total); + //val=val->next; + val=ptr->next; + } else + break; + } + */ } ptr=ptr->next; } @@ -764,21 +764,21 @@ void RESOLVECHAIN(MemoryQueue *Q) { if (head->next==NULL||head->total!=0) { //item is not finished if (head->status!=READY) { - //need to update status - head->status=READY; - if (isHashtable(head)) { - RESOLVEHASHTABLE(Q, (Hashtable *) head); - } else if (isVector(head)) { - RESOLVEVECTOR(Q, (Vector *) head); - } else if (isSingleItem(head)) { - RESOLVESCC(Q, (SCC *)head); - } - if (head->next==NULL) - break; - if (head->total!=0) - break; + //need to update status + head->status=READY; + if (isHashtable(head)) { + RESOLVEHASHTABLE(Q, (Hashtable *) head); + } else if (isVector(head)) { + RESOLVEVECTOR(Q, (Vector *) head); + } else if (isSingleItem(head)) { + RESOLVESCC(Q, (SCC *)head); + } + if (head->next==NULL) + break; + if (head->total!=0) + break; } else - break; + break; } MemoryQueueItem* nextitem=head->next; CAS((unsigned INTPTR*)&(Q->head), (unsigned INTPTR)head, (unsigned INTPTR)nextitem); @@ -801,34 +801,34 @@ void RESOLVEHASHTABLE(MemoryQueue *Q, Hashtable *T) { BinItem* ptr=val; if(ptr!=NULL&&ptr->status==NOTREADY) { do { - if (isWriteBinItem(ptr)) { - if (haveread) - break; - resolveDependencies(((WriteBinItem*)ptr)->val); - ptr->status=READY; - if (isParent(((WriteBinItem*)ptr)->val)) { - atomic_dec(&T->item.total); - val=val->next; - } else - break; - } else if (isReadBinItem(ptr)) { - int i; - ReadBinItem* rptr=(ReadBinItem*)ptr; - for(i=0; iindex; i++) { - resolveDependencies(rptr->array[i]); - if (isParent(rptr->array[i])) { - atomic_dec(&rptr->item.total); - atomic_dec(&T->item.total); - } - } - if (rptr->item.next==NULL||rptr->item.total!=0) { - haveread=TRUE; - } else if((BinItem*)rptr==val) { - val=val->next; - } - rptr->item.status=READY; - } - ptr=ptr->next; + if (isWriteBinItem(ptr)) { + if (haveread) + break; + resolveDependencies(((WriteBinItem*)ptr)->val); + ptr->status=READY; + if (isParent(((WriteBinItem*)ptr)->val)) { + atomic_dec(&T->item.total); + val=val->next; + } else + break; + } else if (isReadBinItem(ptr)) { + int i; + ReadBinItem* rptr=(ReadBinItem*)ptr; + for(i=0; iindex; i++) { + resolveDependencies(rptr->array[i]); + if (isParent(rptr->array[i])) { + atomic_dec(&rptr->item.total); + atomic_dec(&T->item.total); + } + } + if (rptr->item.next==NULL||rptr->item.total!=0) { + haveread=TRUE; + } else if((BinItem*)rptr==val) { + val=val->next; + } + rptr->item.status=READY; + } + ptr=ptr->next; } while(ptr!=NULL); } bin->head=val; // released lock; @@ -845,18 +845,18 @@ void RESOLVEVECTOR(MemoryQueue *q, Vector *V) { REntry* val=NULL; val=(REntry*)LOCKXCHG((unsigned INTPTR*)&(tmp->array[i]), (unsigned INTPTR)val); if (val!=NULL) { - SESEcommon *seseCommon=val->seseRec; - resolveDependencies(val); - if (isParent(val)) { - atomic_dec(&tmp->item.total); + SESEcommon *seseCommon=val->seseRec; + resolveDependencies(val); + if (isParent(val)) { + atomic_dec(&tmp->item.total); #ifdef RCR - poolfreeinto(q->rentrypool,val); + poolfreeinto(q->rentrypool,val); #endif - } + } #if defined(RCR)&&!defined(OOO_DISABLE_TASKMEMPOOL) - else if (atomic_sub_and_test(1, &((REntry *)val)->count)) - poolfreeinto(q->rentrypool,val); - RELEASE_REFERENCE_TO(seseCommon); + else if (atomic_sub_and_test(1, &((REntry *)val)->count)) + poolfreeinto(q->rentrypool,val); + RELEASE_REFERENCE_TO(seseCommon); #endif } } @@ -897,8 +897,8 @@ void resolveDependencies(REntry* rentry) { mask=mask>>shift; index+=shift; if(atomic_sub_and_test(1, &array[index].flag)) { - if(atomic_sub_and_test(1, &(seseCommon->unresolvedDependencies))) - workScheduleSubmit((void *)seseCommon); + if(atomic_sub_and_test(1, &(seseCommon->unresolvedDependencies))) + workScheduleSubmit((void *)seseCommon); } } } else if (type==PARENTCOARSE) { @@ -941,10 +941,10 @@ int RESOLVEBUFFORHASHTABLE(MemoryQueue * q, Hashtable* table, SESEcommon *seseCo if(r->type==WRITE) { int key=generateKey(OBJPTRPTR_2_OBJOID(r->pointer) ); if(q->binbuf[key]==NULL) { - // for multiple writes, add only the first write that hashes to the same bin - q->binbuf[key]=r; + // for multiple writes, add only the first write that hashes to the same bin + q->binbuf[key]=r; } else { - q->buf[i]=NULL; + q->buf[i]=NULL; } } } @@ -954,11 +954,11 @@ int RESOLVEBUFFORHASHTABLE(MemoryQueue * q, Hashtable* table, SESEcommon *seseCo if(r!=NULL && r->type==READ) { int key=generateKey(OBJPTRPTR_2_OBJOID(r->pointer) ); if(q->binbuf[key]==NULL) { - // read item that hashes to the bin which doen't contain any write - seseCommon->rentryArray[seseCommon->rentryIdx++]=r; - if(ADDTABLEITEM(table, r, FALSE)==READY) { - resolveDependencies(r); - } + // read item that hashes to the bin which doen't contain any write + seseCommon->rentryArray[seseCommon->rentryIdx++]=r; + if(ADDTABLEITEM(table, r, FALSE)==READY) { + resolveDependencies(r); + } } q->buf[i]=NULL; } @@ -970,7 +970,7 @@ int RESOLVEBUFFORHASHTABLE(MemoryQueue * q, Hashtable* table, SESEcommon *seseCo if(r!=NULL) { seseCommon->rentryArray[seseCommon->rentryIdx++]=r; if(ADDTABLEITEM(table, r, FALSE)==READY) { - resolveDependencies(r); + resolveDependencies(r); } } } @@ -995,7 +995,7 @@ int RESOLVEBUF(MemoryQueue * q, SESEcommon *seseCommon) { r->queue=q; r->isBufMode=TRUE; if(ADDRENTRY(q,r)==NOTREADY) { - localCount++; + localCount++; } } return localCount; @@ -1007,10 +1007,10 @@ int RESOLVEBUF(MemoryQueue * q, SESEcommon *seseCommon) { if(r->type==WRITE) { int key=generateKey(OBJPTRPTR_2_OBJOID(r->pointer) ); if(q->binbuf[key]==NULL) { - // for multiple writes, add only the first write that hashes to the same bin - q->binbuf[key]=r; + // for multiple writes, add only the first write that hashes to the same bin + q->binbuf[key]=r; } else { - q->buf[i]=NULL; + q->buf[i]=NULL; } } } @@ -1020,11 +1020,11 @@ int RESOLVEBUF(MemoryQueue * q, SESEcommon *seseCommon) { if(r!=NULL && r->type==READ) { int key=generateKey(OBJPTRPTR_2_OBJOID(r->pointer) ); if(q->binbuf[key]==NULL) { - // read item that hashes to the bin which doen't contain any write - seseCommon->rentryArray[seseCommon->rentryIdx++]=r; - if(ADDRENTRY(q,r)==NOTREADY) { - localCount++; - } + // read item that hashes to the bin which doen't contain any write + seseCommon->rentryArray[seseCommon->rentryIdx++]=r; + if(ADDRENTRY(q,r)==NOTREADY) { + localCount++; + } } q->buf[i]=NULL; } @@ -1036,7 +1036,7 @@ int RESOLVEBUF(MemoryQueue * q, SESEcommon *seseCommon) { if(r!=NULL) { seseCommon->rentryArray[seseCommon->rentryIdx++]=r; if(ADDRENTRY(q,r)==NOTREADY) { - localCount++; + localCount++; } } } @@ -1070,45 +1070,45 @@ void resolvePointer(REntry* rentry) { do { struct QueueItem* head=getHead(val); if(head!=NULL) { - REntry* rentry=(REntry*)head->objectptr; - if(*(rentry->pointer)==0) { - // encounters following unresolved pointer - table->unresolvedQueue=val; //released lock - break; - } - removeItem(val,head); - - //now, address is resolved - - //check if rentry is buffer mode - if(rentry->isBufMode==TRUE) { - if(currentSESE==0) { - queue=rentry->queue; - INITIALIZEBUF(queue); - currentSESE=(INTPTR)rentry; - ADDRENTRYTOBUF(queue,rentry); - } else if(currentSESE==(INTPTR)rentry) { - ADDRENTRYTOBUF(queue,rentry); - } else if(currentSESE!=(INTPTR)rentry) { - RESOLVEBUFFORHASHTABLE(queue,table,(SESEcommon*)rentry->seseRec); - currentSESE=(INTPTR)rentry; - INITIALIZEBUF(queue); - ADDRENTRYTOBUF(rentry->queue,rentry); - } - } else { - if(currentSESE!=0) { - //previous SESE has buf mode, need to invoke resolve buffer - RESOLVEBUFFORHASHTABLE(queue,table,(SESEcommon*)rentry->seseRec); - currentSESE=0; - } - //normal mode - if(ADDTABLEITEM(table, rentry, FALSE)==READY) { - resolveDependencies(rentry); - } - } + REntry* rentry=(REntry*)head->objectptr; + if(*(rentry->pointer)==0) { + // encounters following unresolved pointer + table->unresolvedQueue=val; //released lock + break; + } + removeItem(val,head); + + //now, address is resolved + + //check if rentry is buffer mode + if(rentry->isBufMode==TRUE) { + if(currentSESE==0) { + queue=rentry->queue; + INITIALIZEBUF(queue); + currentSESE=(INTPTR)rentry; + ADDRENTRYTOBUF(queue,rentry); + } else if(currentSESE==(INTPTR)rentry) { + ADDRENTRYTOBUF(queue,rentry); + } else if(currentSESE!=(INTPTR)rentry) { + RESOLVEBUFFORHASHTABLE(queue,table,(SESEcommon*)rentry->seseRec); + currentSESE=(INTPTR)rentry; + INITIALIZEBUF(queue); + ADDRENTRYTOBUF(rentry->queue,rentry); + } + } else { + if(currentSESE!=0) { + //previous SESE has buf mode, need to invoke resolve buffer + RESOLVEBUFFORHASHTABLE(queue,table,(SESEcommon*)rentry->seseRec); + currentSESE=0; + } + //normal mode + if(ADDTABLEITEM(table, rentry, FALSE)==READY) { + resolveDependencies(rentry); + } + } } else { - table->unresolvedQueue=NULL; // set hashtable as normal-mode. - break; + table->unresolvedQueue=NULL; // set hashtable as normal-mode. + break; } } while(TRUE); } else { diff --git a/Robust/src/Runtime/object.c b/Robust/src/Runtime/object.c index f56686bb..25fa5869 100644 --- a/Robust/src/Runtime/object.c +++ b/Robust/src/Runtime/object.c @@ -53,14 +53,14 @@ void CALL01(___Object______MonitorEnter____, struct ___Object___ * ___this___) { lpair->islastlock=1; while(1) { if (VAR(___this___)->tid==0) { - if (CAS32(&VAR(___this___)->tid, 0, self)==0) { - return; - } + if (CAS32(&VAR(___this___)->tid, 0, self)==0) { + return; + } } { #ifdef PRECISE_GC - if (unlikely(needtocollect)) - checkcollect((struct garbagelist *)___params___); + if (unlikely(needtocollect)) + checkcollect((struct garbagelist *)___params___); #endif } } @@ -103,8 +103,8 @@ void CALL01(___Object______wait____, struct ___Object___ * ___this___) { while(1) { if (VAR(___this___)->tid==0) { if (CAS32(&VAR(___this___)->tid, 0, self)==0) { - BARRIER(); - return; + BARRIER(); + return; } } #ifdef PRECISE_GC diff --git a/Robust/src/Runtime/oojgarbage.c b/Robust/src/Runtime/oojgarbage.c index fe0e02b7..6e17834b 100644 --- a/Robust/src/Runtime/oojgarbage.c +++ b/Robust/src/Runtime/oojgarbage.c @@ -27,38 +27,38 @@ void searchoojroots() { di=dq->head; do { - // check all the relevant indices of this - // node in the deque, noting if we are in - // the top/bottom node which can be partially - // full + // check all the relevant indices of this + // node in the deque, noting if we are in + // the top/bottom node which can be partially + // full - // WHAT? - //SESEcommon* common = (SESEcommon*) n->itsDataArr[j]; - //if(common==seseCommon){ - // skip the current running SESE - // continue; - //} - di=(dequeItem *) EXTRACTPTR((INTPTR)di); - SESEcommon* seseRec = (SESEcommon*) di->work; - if (seseRec!=NULL) { - struct garbagelist* gl = (struct garbagelist*) &(seseRec[1]); - struct garbagelist* glroot = gl; + // WHAT? + //SESEcommon* common = (SESEcommon*) n->itsDataArr[j]; + //if(common==seseCommon){ + // skip the current running SESE + // continue; + //} + di=(dequeItem *) EXTRACTPTR((INTPTR)di); + SESEcommon* seseRec = (SESEcommon*) di->work; + if (seseRec!=NULL) { + struct garbagelist* gl = (struct garbagelist*) &(seseRec[1]); + struct garbagelist* glroot = gl; - updateAscendantSESE(seseRec); + updateAscendantSESE(seseRec); - while( gl != NULL ) { - int k; - for( k = 0; k < gl->size; k++ ) { - void* orig = gl->array[k]; - ENQUEUE(orig, gl->array[k]); - } - gl = gl->next; - } - } - // we only have to move across the nodes - // of the deque if the top and bottom are - // not the same already - di=di->next; + while( gl != NULL ) { + int k; + for( k = 0; k < gl->size; k++ ) { + void* orig = gl->array[k]; + ENQUEUE(orig, gl->array[k]); + } + gl = gl->next; + } + } + // we only have to move across the nodes + // of the deque if the top and bottom are + // not the same already + di=di->next; } while( di !=NULL); } } @@ -88,48 +88,48 @@ void searchoojroots() { n = botNode; do { - // check all the relevant indices of this - // node in the deque, noting if we are in - // the top/bottom node which can be partially - // full - if( n == botNode ) { - jLo = botIndx; - } else { jLo = 0; } - if( n == topNode ) { - jHi = topIndx; - } else { jHi = DQNODE_ARRAYSIZE; } + // check all the relevant indices of this + // node in the deque, noting if we are in + // the top/bottom node which can be partially + // full + if( n == botNode ) { + jLo = botIndx; + } else { jLo = 0; } + if( n == topNode ) { + jHi = topIndx; + } else { jHi = DQNODE_ARRAYSIZE; } - for( j = jLo; j < jHi; ++j ) { + for( j = jLo; j < jHi; ++j ) { - // WHAT? - //SESEcommon* common = (SESEcommon*) n->itsDataArr[j]; - //if(common==seseCommon){ - // continue; - //} + // WHAT? + //SESEcommon* common = (SESEcommon*) n->itsDataArr[j]; + //if(common==seseCommon){ + // continue; + //} - SESEcommon* seseRec = (SESEcommon*) n->itsDataArr[j]; + SESEcommon* seseRec = (SESEcommon*) n->itsDataArr[j]; - struct garbagelist* gl = (struct garbagelist*) &(seseRec[1]); - struct garbagelist* glroot = gl; + struct garbagelist* gl = (struct garbagelist*) &(seseRec[1]); + struct garbagelist* glroot = gl; - updateAscendantSESE(seseRec); + updateAscendantSESE(seseRec); - while( gl != NULL ) { - int k; - for( k = 0; k < gl->size; k++ ) { - void* orig = gl->array[k]; - ENQUEUE(orig, gl->array[k]); - } - gl = gl->next; - } - } + while( gl != NULL ) { + int k; + for( k = 0; k < gl->size; k++ ) { + void* orig = gl->array[k]; + ENQUEUE(orig, gl->array[k]); + } + gl = gl->next; + } + } - // we only have to move across the nodes - // of the deque if the top and bottom are - // not the same already - if( botNode != topNode ) { - n = n->next; - } + // we only have to move across the nodes + // of the deque if the top and bottom are + // not the same already + if( botNode != topNode ) { + n = n->next; + } } while( n != topNode ); } } @@ -148,8 +148,8 @@ updateForwardList(struct Queue *forwardList, int prevUpdate) { while(gl!=NULL) { int i; for(i=0; isize; i++) { - void * orig=gl->array[i]; - ENQUEUE(orig, gl->array[i]); + void * orig=gl->array[i]; + ENQUEUE(orig, gl->array[i]); } gl=gl->next; } @@ -169,80 +169,80 @@ updateMemoryQueue(SESEcommon* seseParent) { MemoryQueueItem *memoryItem=memoryQueue->head; while(memoryItem!=NULL) { if(memoryItem->type==HASHTABLE) { - Hashtable *ht=(Hashtable*)memoryItem; - for(binidx=0; binidxarray[binidx]; - BinItem *binItem=bin->head; - while(binItem!=NULL) { - if(binItem->type==READBIN) { - ReadBinItem* readBinItem=(ReadBinItem*)binItem; - int ridx; - for(ridx=0; ridxindex; ridx++) { - REntry *rentry=readBinItem->array[ridx]; - SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec); - struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]); - updateAscendantSESE(seseRec); - while(gl!=NULL) { - int i; - for(i=0; isize; i++) { - void * orig=gl->array[i]; - ENQUEUE(orig, gl->array[i]); - } - gl=gl->next; - } - } - } else { //writebin - REntry *rentry=((WriteBinItem*)binItem)->val; - SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec); - struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]); - updateAscendantSESE(seseRec); - while(gl!=NULL) { - int i; - for(i=0; isize; i++) { - void * orig=gl->array[i]; - ENQUEUE(orig, gl->array[i]); - } - gl=gl->next; - } - } - binItem=binItem->next; - } - } + Hashtable *ht=(Hashtable*)memoryItem; + for(binidx=0; binidxarray[binidx]; + BinItem *binItem=bin->head; + while(binItem!=NULL) { + if(binItem->type==READBIN) { + ReadBinItem* readBinItem=(ReadBinItem*)binItem; + int ridx; + for(ridx=0; ridxindex; ridx++) { + REntry *rentry=readBinItem->array[ridx]; + SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec); + struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]); + updateAscendantSESE(seseRec); + while(gl!=NULL) { + int i; + for(i=0; isize; i++) { + void * orig=gl->array[i]; + ENQUEUE(orig, gl->array[i]); + } + gl=gl->next; + } + } + } else { //writebin + REntry *rentry=((WriteBinItem*)binItem)->val; + SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec); + struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]); + updateAscendantSESE(seseRec); + while(gl!=NULL) { + int i; + for(i=0; isize; i++) { + void * orig=gl->array[i]; + ENQUEUE(orig, gl->array[i]); + } + gl=gl->next; + } + } + binItem=binItem->next; + } + } } else if(memoryItem->type==VECTOR) { - Vector *vt=(Vector*)memoryItem; - int idx; - for(idx=0; idxindex; idx++) { - REntry *rentry=vt->array[idx]; - if(rentry!=NULL) { - SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec); - struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]); - updateAscendantSESE(seseRec); - while(gl!=NULL) { - int i; - for(i=0; isize; i++) { - void * orig=gl->array[i]; - ENQUEUE(orig, gl->array[i]); - } - gl=gl->next; - } - } - } + Vector *vt=(Vector*)memoryItem; + int idx; + for(idx=0; idxindex; idx++) { + REntry *rentry=vt->array[idx]; + if(rentry!=NULL) { + SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec); + struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]); + updateAscendantSESE(seseRec); + while(gl!=NULL) { + int i; + for(i=0; isize; i++) { + void * orig=gl->array[i]; + ENQUEUE(orig, gl->array[i]); + } + gl=gl->next; + } + } + } } else if(memoryItem->type==SINGLEITEM) { - SCC *scc=(SCC*)memoryItem; - REntry *rentry=scc->val; - if(rentry!=NULL) { - SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec); - struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]); - updateAscendantSESE(seseRec); - while(gl!=NULL) { - int i; - for(i=0; isize; i++) { - void * orig=gl->array[i]; - ENQUEUE(orig, gl->array[i]); - } - gl=gl->next; - } - } + SCC *scc=(SCC*)memoryItem; + REntry *rentry=scc->val; + if(rentry!=NULL) { + SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec); + struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]); + updateAscendantSESE(seseRec); + while(gl!=NULL) { + int i; + for(i=0; isize; i++) { + void * orig=gl->array[i]; + ENQUEUE(orig, gl->array[i]); + } + gl=gl->next; + } + } } memoryItem=memoryItem->next; } @@ -262,12 +262,12 @@ updateAscendantSESE(SESEcommon* seseRec) { if(prevSESE!=NULL) { struct garbagelist * prevgl=(struct garbagelist *)&(((SESEcommon*)(prevSESE))[1]); while(prevgl!=NULL) { - int i; - for(i=0; isize; i++) { - void * orig=prevgl->array[i]; - ENQUEUE(orig, prevgl->array[i]); - } - prevgl=prevgl->next; + int i; + for(i=0; isize; i++) { + void * orig=prevgl->array[i]; + ENQUEUE(orig, prevgl->array[i]); + } + prevgl=prevgl->next; } } } diff --git a/Robust/src/Runtime/option.c b/Robust/src/Runtime/option.c index 6b93254f..8fb9cf08 100644 --- a/Robust/src/Runtime/option.c +++ b/Robust/src/Runtime/option.c @@ -32,7 +32,7 @@ void processOptions() { options=strchr(options,' '); if (options!=NULL) options++; if (options==NULL) - break; + break; sscanf(options, "%f", &failurechance); injectfailures=1; printf("Injecting errors with chance=%f\n",failurechance); @@ -42,18 +42,18 @@ void processOptions() { options=strchr(options,' '); if (options!=NULL) options++; if (options==NULL) - break; + break; sscanf(options, "%d", &failurecount); options=strchr(options,' '); if (options!=NULL) options++; if (options==NULL) - break; + break; sscanf(options, "%f", &instfailurechance); options=strchr(options,' '); if (options!=NULL) options++; if (options==NULL) - break; + break; sscanf(options, "%d", &numfailures); options=strchr(options,' '); diff --git a/Robust/src/Runtime/runtime.c b/Robust/src/Runtime/runtime.c index 9223e230..ff7e5d95 100644 --- a/Robust/src/Runtime/runtime.c +++ b/Robust/src/Runtime/runtime.c @@ -101,7 +101,7 @@ int instanceof(struct ___Object___ *ptr, int type) { if (i>NUMCLASSES) { do { if (i==type) - return 1; + return 1; i=typearray2[i-NUMCLASSES]; } while(i!=-1); } @@ -132,7 +132,7 @@ void injectinstructionfailure() { instaccum+=failurecount; if ((((double)random())/RAND_MAX)0) - numfailures--; + numfailures--; printf("FAILURE!!! %d\n",numfailures); longjmp(error_handler,11); } @@ -145,7 +145,7 @@ void injectinstructionfailure() { instaccum+=failurecount; if ((((double)random())/RAND_MAX)0) - numfailures--; + numfailures--; printf("FAILURE!!! %d\n",numfailures); threadexit(); } @@ -273,11 +273,11 @@ void deepArrayCopy(struct ___Object___ * dst, struct ___Object___ * src) { struct ___Object___ * ptr=((struct ___Object___**)(((char*) &aosrc->___length___)+sizeof(int)))[i]; int ptrtype=((int *)ptr)[0]; if (ptrtype>=NUMCLASSES) { - struct ___Object___ * dstptr=((struct ___Object___**)(((char*) &aodst->___length___)+sizeof(int)))[i]; - deepArrayCopy(dstptr,ptr); + struct ___Object___ * dstptr=((struct ___Object___**)(((char*) &aodst->___length___)+sizeof(int)))[i]; + deepArrayCopy(dstptr,ptr); } else { - //hit an object - ((struct ___Object___ **)(((char*) &aodst->___length___)+sizeof(int)))[i]=ptr; + //hit an object + ((struct ___Object___ **)(((char*) &aodst->___length___)+sizeof(int)))[i]=ptr; } } } @@ -487,8 +487,8 @@ void CALL00(___System______gc____) { free(to_heapbase); to_heapbase=malloc(curr_heapsize); if (to_heapbase==NULL) { - printf("Error Allocating enough memory\n"); - exit(-1); + printf("Error Allocating enough memory\n"); + exit(-1); } to_heaptop=to_heapbase+curr_heapsize; to_heapptr=to_heapbase; diff --git a/Robust/src/Runtime/socket.c b/Robust/src/Runtime/socket.c index 5866aa05..7ced4ce3 100644 --- a/Robust/src/Runtime/socket.c +++ b/Robust/src/Runtime/socket.c @@ -171,17 +171,17 @@ struct ArrayObject * CALL01(___InetAddress______getHostByName_____AR_B, struct A struct ArrayObject *bytearray; #ifdef PRECISE_GC { - INTPTR ptrarray[]={1, (INTPTR) ___params___, (INTPTR)arraybytearray}; - bytearray=allocate_newarray(&ptrarray,BYTEARRAYTYPE,h->h_length); - arraybytearray=(struct ArrayObject *) ptrarray[2]; + INTPTR ptrarray[]={1, (INTPTR) ___params___, (INTPTR)arraybytearray}; + bytearray=allocate_newarray(&ptrarray,BYTEARRAYTYPE,h->h_length); + arraybytearray=(struct ArrayObject *) ptrarray[2]; } #else bytearray=allocate_newarray(BYTEARRAYTYPE,h->h_length); #endif ((void **)&((&arraybytearray->___length___)[1]))[i]=bytearray; { - int ha=ntohl(*(int *)h->h_addr_list[i]); - (&bytearray->___length___)[1]=ha; + int ha=ntohl(*(int *)h->h_addr_list[i]); + (&bytearray->___length___)[1]=ha; } } @@ -367,7 +367,7 @@ void CALL24(___Socket______nativeWrite_____AR_B_I_I, int offset, int length, str while(length>0) { bytewritten=write(fd, &charstr[offset], length); if (bytewritten==-1&&errno!=EAGAIN) - break; + break; length-=bytewritten; offset+=bytewritten; } diff --git a/Robust/src/Runtime/squeue.h b/Robust/src/Runtime/squeue.h index 656d9883..1cebcd51 100644 --- a/Robust/src/Runtime/squeue.h +++ b/Robust/src/Runtime/squeue.h @@ -142,21 +142,21 @@ static inline void* dqPopTopSelf(deque *p) { //remove if we can..steal work no matter what if (likely(next!=NULL)) { if (((dequeItem *)CAS(&(p->head),(INTPTR)ptr, (INTPTR)next))!=ptr) - return DQ_POP_EMPTY; + return DQ_POP_EMPTY; void * item=NULL; item=(void *)LOCKXCHG((unsigned INTPTR*) &(realptr->work), (unsigned INTPTR) item); realptr->next=NULL; BARRIER(); tagpoolfreeinto(&p->objret,ptr, realptr); if (item==NULL&&tryagain) { - tryagain=0; - continue; + tryagain=0; + continue; } return item; } else { void * item=NULL; if (realptr->work!=NULL) - item=(void *) LOCKXCHG((unsigned INTPTR*) &(realptr->work), (unsigned INTPTR) item); + item=(void *) LOCKXCHG((unsigned INTPTR*) &(realptr->work), (unsigned INTPTR) item); return item; } } diff --git a/Robust/src/Runtime/task.c b/Robust/src/Runtime/task.c index 3db7ea4e..a3027dbc 100644 --- a/Robust/src/Runtime/task.c +++ b/Robust/src/Runtime/task.c @@ -127,7 +127,7 @@ void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { if (tagptr->type==TAGTYPE) { struct ___TagDescriptor___ * td=(struct ___TagDescriptor___ *) tagptr; if (td==tagd) - return; + return; #ifdef PRECISE_GC int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd}; struct ArrayObject * ao=allocate_newarray(&ptrarray,TAGARRAYTYPE,TAGARRAYINTERVAL); @@ -146,28 +146,28 @@ void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { int i; struct ArrayObject *ao=(struct ArrayObject *) tagptr; for(i=0; i___cachedCode___; i++) { - struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___*, i); - if (td==tagd) - return; + struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___*, i); + if (td==tagd) + return; } if (ao->___cachedCode______length___) { - ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, tagd); - ao->___cachedCode___++; + ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, tagd); + ao->___cachedCode___++; } else { #ifdef PRECISE_GC - int ptrarray[]={2,(int) ptr, (int) obj, (int) tagd}; - struct ArrayObject * aonew=allocate_newarray(&ptrarray,TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___); - obj=(struct ___Object___ *)ptrarray[2]; - tagd=(struct ___TagDescriptor___ *) ptrarray[3]; - ao=(struct ArrayObject *)obj->___tags___; + int ptrarray[]={2,(int) ptr, (int) obj, (int) tagd}; + struct ArrayObject * aonew=allocate_newarray(&ptrarray,TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___); + obj=(struct ___Object___ *)ptrarray[2]; + tagd=(struct ___TagDescriptor___ *) ptrarray[3]; + ao=(struct ArrayObject *)obj->___tags___; #else - struct ArrayObject * aonew=allocate_newarray(TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___); + struct ArrayObject * aonew=allocate_newarray(TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___); #endif - aonew->___cachedCode___=ao->___length___+1; - for(i=0; i___length___; i++) { - ARRAYSET(aonew, struct ___TagDescriptor___*, i, ARRAYGET(ao, struct ___TagDescriptor___*, i)); - } - ARRAYSET(aonew, struct ___TagDescriptor___ *, ao->___length___, tagd); + aonew->___cachedCode___=ao->___length___+1; + for(i=0; i___length___; i++) { + ARRAYSET(aonew, struct ___TagDescriptor___*, i, ARRAYGET(ao, struct ___TagDescriptor___*, i)); + } + ARRAYSET(aonew, struct ___TagDescriptor___ *, ao->___length___, tagd); } } } @@ -192,24 +192,24 @@ void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { } else { struct ArrayObject *ao=(struct ArrayObject *) tagset; if (ao->___cachedCode______length___) { - ARRAYSET(ao, struct ___Object___*, ao->___cachedCode___++, obj); + ARRAYSET(ao, struct ___Object___*, ao->___cachedCode___++, obj); } else { - int i; + int i; #ifdef PRECISE_GC - int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd}; - struct ArrayObject * aonew=allocate_newarray(&ptrarray,OBJECTARRAYTYPE,OBJECTARRAYINTERVAL+ao->___length___); - obj=(struct ___Object___ *)ptrarray[2]; - tagd=(struct ___TagDescriptor___ *)ptrarray[3]; - ao=(struct ArrayObject *)tagd->flagptr; + int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd}; + struct ArrayObject * aonew=allocate_newarray(&ptrarray,OBJECTARRAYTYPE,OBJECTARRAYINTERVAL+ao->___length___); + obj=(struct ___Object___ *)ptrarray[2]; + tagd=(struct ___TagDescriptor___ *)ptrarray[3]; + ao=(struct ArrayObject *)tagd->flagptr; #else - struct ArrayObject * aonew=allocate_newarray(OBJECTARRAYTYPE,OBJECTARRAYINTERVAL); + struct ArrayObject * aonew=allocate_newarray(OBJECTARRAYTYPE,OBJECTARRAYINTERVAL); #endif - aonew->___cachedCode___=ao->___cachedCode___+1; - for(i=0; i___length___; i++) { - ARRAYSET(aonew, struct ___Object___*, i, ARRAYGET(ao, struct ___Object___*, i)); - } - ARRAYSET(aonew, struct ___Object___ *, ao->___cachedCode___, obj); - tagd->flagptr=(struct ___Object___ *) aonew; + aonew->___cachedCode___=ao->___cachedCode___+1; + for(i=0; i___length___; i++) { + ARRAYSET(aonew, struct ___Object___*, i, ARRAYGET(ao, struct ___Object___*, i)); + } + ARRAYSET(aonew, struct ___Object___ *, ao->___cachedCode___, obj); + tagd->flagptr=(struct ___Object___ *) aonew; } } } @@ -236,13 +236,13 @@ void tagclear(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { for(i=0; i___cachedCode___; i++) { struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___ *, i); if (td==tagd) { - ao->___cachedCode___--; - if (i___cachedCode___) - ARRAYSET(ao, struct ___TagDescriptor___ *, i, ARRAYGET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___)); - ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, NULL); - if (ao->___cachedCode___==0) - obj->___tags___=NULL; - goto PROCESSCLEAR; + ao->___cachedCode___--; + if (i___cachedCode___) + ARRAYSET(ao, struct ___TagDescriptor___ *, i, ARRAYGET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___)); + ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, NULL); + if (ao->___cachedCode___==0) + obj->___tags___=NULL; + goto PROCESSCLEAR; } } printf("ERROR 2 in tagclear\n"); @@ -252,23 +252,23 @@ PROCESSCLEAR: struct ___Object___ *tagset=tagd->flagptr; if (tagset->type!=OBJECTARRAYTYPE) { if (tagset==obj) - tagd->flagptr=NULL; + tagd->flagptr=NULL; else - printf("ERROR 3 in tagclear\n"); + printf("ERROR 3 in tagclear\n"); } else { struct ArrayObject *ao=(struct ArrayObject *) tagset; int i; for(i=0; i___cachedCode___; i++) { - struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, i); - if (tobj==obj) { - ao->___cachedCode___--; - if (i___cachedCode___) - ARRAYSET(ao, struct ___Object___ *, i, ARRAYGET(ao, struct ___Object___ *, ao->___cachedCode___)); - ARRAYSET(ao, struct ___Object___ *, ao->___cachedCode___, NULL); - if (ao->___cachedCode___==0) - tagd->flagptr=NULL; - goto ENDCLEAR; - } + struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, i); + if (tobj==obj) { + ao->___cachedCode___--; + if (i___cachedCode___) + ARRAYSET(ao, struct ___Object___ *, i, ARRAYGET(ao, struct ___Object___ *, ao->___cachedCode___)); + ARRAYSET(ao, struct ___Object___ *, ao->___cachedCode___, NULL); + if (ao->___cachedCode___==0) + tagd->flagptr=NULL; + goto ENDCLEAR; + } } printf("ERROR 4 in tagclear\n"); } @@ -314,8 +314,8 @@ void flagorand(void * ptr, int ormask, int andmask) { counter=obj->fses[offset++]; oldoffset=offset; for(j=0; jfses[offset]; - obj->fses[offset++]=(flag|ormask)&andmask; + flag=obj->fses[offset]; + obj->fses[offset++]=(flag|ormask)&andmask; } qsort(&obj->fses[oldoffset], sizeof(int), counter, (int (*)(const void *, const void *)) &flagcomp); } @@ -340,8 +340,8 @@ bool intflagorand(void * ptr, int ormask, int andmask) { counter=obj->fses[offset++]; oldoffset=offset; for(j=0; jfses[offset]; - obj->fses[offset++]=(flag|ormask)&andmask; + flag=obj->fses[offset]; + obj->fses[offset++]=(flag|ormask)&andmask; } qsort(&obj->fses[oldoffset], sizeof(int), counter, (int (*)(const void *, const void *)) &flagcomp); } @@ -401,42 +401,42 @@ void enqueueObject(void *vptr) { while(parameter!=NULL) { /* Check tags */ if (parameter->numbertags>0) { - if (tagptr==NULL) - goto nextloop; //that means the object has no tag but that param needs tag - else if(tagptr->type==TAGTYPE) { //one tag - struct ___TagDescriptor___ * tag=(struct ___TagDescriptor___*) tagptr; - for(i=0; inumbertags; i++) { - //slotid is parameter->tagarray[2*i]; - int tagid=parameter->tagarray[2*i+1]; - if (tagid!=tagptr->flag) - goto nextloop; /*We don't have this tag */ - } - } else { //multiple tags - struct ArrayObject * ao=(struct ArrayObject *) tagptr; - for(i=0; inumbertags; i++) { - //slotid is parameter->tagarray[2*i]; - int tagid=parameter->tagarray[2*i+1]; - int j; - for(j=0; j___cachedCode___; j++) { - if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, j)->flag) - goto foundtag; - } - goto nextloop; + if (tagptr==NULL) + goto nextloop; //that means the object has no tag but that param needs tag + else if(tagptr->type==TAGTYPE) { //one tag + struct ___TagDescriptor___ * tag=(struct ___TagDescriptor___*) tagptr; + for(i=0; inumbertags; i++) { + //slotid is parameter->tagarray[2*i]; + int tagid=parameter->tagarray[2*i+1]; + if (tagid!=tagptr->flag) + goto nextloop; /*We don't have this tag */ + } + } else { //multiple tags + struct ArrayObject * ao=(struct ArrayObject *) tagptr; + for(i=0; inumbertags; i++) { + //slotid is parameter->tagarray[2*i]; + int tagid=parameter->tagarray[2*i+1]; + int j; + for(j=0; j___cachedCode___; j++) { + if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, j)->flag) + goto foundtag; + } + goto nextloop; foundtag: - ; - } - } + ; + } + } } /* Check flags */ for(i=0; inumberofterms; i++) { - int andmask=parameter->intarray[i*2]; - int checkmask=parameter->intarray[i*2+1]; - if ((ptr->flag&andmask)==checkmask) { - enqueuetasks(parameter, prevptr, ptr, NULL, 0); - prevptr=parameter; - break; - } + int andmask=parameter->intarray[i*2]; + int checkmask=parameter->intarray[i*2+1]; + if ((ptr->flag&andmask)==checkmask) { + enqueuetasks(parameter, prevptr, ptr, NULL, 0); + prevptr=parameter; + break; + } } nextloop: parameter=parameter->next; @@ -456,25 +456,25 @@ int checktags(struct ___Object___ * currobj, struct fsanalysiswrapper * fswrappe //needs tag else if(tagptr->type==TAGTYPE) { //one tag if(fswrapper->numtags!=1) - return 0; //we don't have the right number of tags + return 0; //we don't have the right number of tags struct ___TagDescriptor___ * tag=(struct ___TagDescriptor___*) tagptr; if (fswrapper->tags[0]!=tagptr->flag) - return 0; + return 0; } else { //multiple tags struct ArrayObject * ao=(struct ArrayObject *) tagptr; int tag_counter=0; int foundtag=0; if(ao->___length___!=fswrapper->numtags) - return 0; //we don't have the right number of tags + return 0; //we don't have the right number of tags for(tag_counter=0; tag_counternumtags; tag_counter++) { - int tagid=fswrapper->tags[tag_counter]; - int j; - for(j=0; j___cachedCode___; j++) { - if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, tag_counter)->flag) - return 1; - } - return 0; + int tagid=fswrapper->tags[tag_counter]; + int j; + for(j=0; j___cachedCode___; j++) { + if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, tag_counter)->flag) + return 1; + } + return 0; } } } @@ -507,19 +507,19 @@ int domerge(int * flist1, int len1, int *flist2, int len2, int *merge) { while(itask==searchftl->task&& (*andlist)->index==searchftl->index) { - mergeitems(*andlist, searchftl); - break; + mergeitems(*andlist, searchftl); + break; } searchftl=searchftl->next; } @@ -615,38 +615,38 @@ struct failedtasklist * processfailstate(struct classanalysiswrapper * classwrap if (taskfail->task==task&&taskfail->index==index) { int start=0; while(startnumoptionaltaskdescriptors) { - struct taskdescriptor *currtask=NULL; - struct failedtasklist *tmpftl; - int currindex; - int totallength=0; - int *enterflags; - int numenterflags, offset; - struct parameterwrapper *pw; - for(j=start; jnumoptionaltaskdescriptors; j++) { - struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[j]; - if(currtask==NULL) { - currtask=otd->task; - currindex=otd->index; - } else if (currtask!=otd->task||currindex!=otd->index) - break; - totallength+=otd->numenterflags; - } - pw=currtask->descriptorarray[currindex]->queue; - enterflags=RUNMALLOC(totallength*sizeof(int)); - numenterflags=j-start; - offset=0; - for(start; startoptionaltaskdescriptorarray[start]; - enterflags[offset++]=otd->numenterflags; - memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int)); - offset+=otd->numenterflags; - } - tmpftl=RUNMALLOC(sizeof(struct failedtasklist)); - tmpftl->next=list; - tmpftl->task=currtask; - tmpftl->numflags=numenterflags; - tmpftl->flags=enterflags; - list=tmpftl; + struct taskdescriptor *currtask=NULL; + struct failedtasklist *tmpftl; + int currindex; + int totallength=0; + int *enterflags; + int numenterflags, offset; + struct parameterwrapper *pw; + for(j=start; jnumoptionaltaskdescriptors; j++) { + struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[j]; + if(currtask==NULL) { + currtask=otd->task; + currindex=otd->index; + } else if (currtask!=otd->task||currindex!=otd->index) + break; + totallength+=otd->numenterflags; + } + pw=currtask->descriptorarray[currindex]->queue; + enterflags=RUNMALLOC(totallength*sizeof(int)); + numenterflags=j-start; + offset=0; + for(start; startoptionaltaskdescriptorarray[start]; + enterflags[offset++]=otd->numenterflags; + memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int)); + offset+=otd->numenterflags; + } + tmpftl=RUNMALLOC(sizeof(struct failedtasklist)); + tmpftl->next=list; + tmpftl->task=currtask; + tmpftl->numflags=numenterflags; + tmpftl->flags=enterflags; + list=tmpftl; } } } @@ -681,10 +681,10 @@ struct failedtasklist * processnormfailstate(struct classanalysiswrapper * class for(j=start; jnumoptionaltaskdescriptors; j++) { struct optionaltaskdescriptor *otd=fswrapper->optionaltaskdescriptorarray[j]; if(currtask==NULL) { - currtask=otd->task; - currindex=otd->index; + currtask=otd->task; + currindex=otd->index; } else if (currtask!=otd->task||currindex!=otd->index) - break; + break; totallength+=otd->numenterflags; } pw=currtask->descriptorarray[currindex]->queue; @@ -745,70 +745,70 @@ void enqueueoptional(struct ___Object___ * currobj, int numfailedfses, int * fai struct fsanalysiswrapper *fswrapper=NULL; for(h=0; hnumfsanalysiswrappers; h++) { - struct fsanalysiswrapper * tmp=classwrapper->fsanalysiswrapperarray[h]; - if (tmp->flags==currobj->flag&&checktags(currobj, tmp)) { - //we only match exactly here - fswrapper=tmp; - break; - } + struct fsanalysiswrapper * tmp=classwrapper->fsanalysiswrapperarray[h]; + if (tmp->flags==currobj->flag&&checktags(currobj, tmp)) { + //we only match exactly here + fswrapper=tmp; + break; + } } if(fswrapper==NULL) //nothing to do in this state - return; + return; for(i=0; inumtaskfailures; i++) { - int j; - struct taskfailure * taskfail=fswrapper->taskfailurearray[i]; - if (taskfail->task==task&&taskfail->index==index) { - int start=0; - while(startnumoptionaltaskdescriptors) { - struct taskdescriptor *currtask=NULL; - int currindex; - int totallength=0; - int *enterflags; - int numenterflags, offset; - struct parameterwrapper *pw; - for(j=start; jnumoptionaltaskdescriptors; j++) { - struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[j]; - if(currtask==NULL) { - currtask=otd->task; - currindex=otd->index; - } else if (currtask!=otd->task||currindex!=otd->index) - break; - totallength+=otd->numenterflags; //1 is to store the lengths - } - pw=currtask->descriptorarray[currindex]->queue; - numenterflags=j-start; - enterflags=RUNMALLOC((totallength+numenterflags)*sizeof(int)); - - offset=0; - for(start; startoptionaltaskdescriptorarray[start]; - enterflags[offset++]=otd->numenterflags; - memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int)); - offset+=otd->numenterflags; - } - //Enqueue this one - if (enqueuetasks(pw, currobj->flagptr, currobj, enterflags, numenterflags)) - currobj->flagptr=pw; - } - } + int j; + struct taskfailure * taskfail=fswrapper->taskfailurearray[i]; + if (taskfail->task==task&&taskfail->index==index) { + int start=0; + while(startnumoptionaltaskdescriptors) { + struct taskdescriptor *currtask=NULL; + int currindex; + int totallength=0; + int *enterflags; + int numenterflags, offset; + struct parameterwrapper *pw; + for(j=start; jnumoptionaltaskdescriptors; j++) { + struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[j]; + if(currtask==NULL) { + currtask=otd->task; + currindex=otd->index; + } else if (currtask!=otd->task||currindex!=otd->index) + break; + totallength+=otd->numenterflags; //1 is to store the lengths + } + pw=currtask->descriptorarray[currindex]->queue; + numenterflags=j-start; + enterflags=RUNMALLOC((totallength+numenterflags)*sizeof(int)); + + offset=0; + for(start; startoptionaltaskdescriptorarray[start]; + enterflags[offset++]=otd->numenterflags; + memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int)); + offset+=otd->numenterflags; + } + //Enqueue this one + if (enqueuetasks(pw, currobj->flagptr, currobj, enterflags, numenterflags)) + currobj->flagptr=pw; + } + } } } else { /* Failed in failed state */ int i; int offset=0; for(i=0; iobjectset, (int) currobj, (int *) &next, (int *) &enterflags, &UNUSED, &UNUSED2); ObjectHashremove(flagptr->objectset, (int)currobj); if (enterflags!=NULL) - free(enterflags); + free(enterflags); flagptr=next; } @@ -835,12 +835,12 @@ void enqueueoptional(struct ___Object___ * currobj, int numfailedfses, int * fai int j; struct failedtasklist *andlist=NULL; for(j=0; jfses[offset++]; - struct failedtasklist *currlist=processnormfailstate(classwrapper, currobj, flagstate); - if (andlist==NULL) - andlist=currlist; - else - mergefailedlists(&andlist, currlist); + int flagstate=currobj->fses[offset++]; + struct failedtasklist *currlist=processnormfailstate(classwrapper, currobj, flagstate); + if (andlist==NULL) + andlist=currlist; + else + mergefailedlists(&andlist, currlist); } enqueuelist(currobj, andlist); } @@ -936,7 +936,7 @@ backtrackinit: #ifdef OPTIONAL tpd->failed[j]=failed[j]; if (failed[j]!=0&&failed[j]!=1) { - printf("BAD\n"); + printf("BAD\n"); } #endif } @@ -958,15 +958,15 @@ backtrackinit: for(j=numiterators-1; jiterators[j], taskpointerarray OPTARG(failed))) { - toiNext(¶meter->iterators[j], taskpointerarray OPTARG(failed)); + toiNext(¶meter->iterators[j], taskpointerarray OPTARG(failed)); } else if (j>0) { - /* Need to backtrack */ - toiReset(¶meter->iterators[j]); - j--; - goto backtrackinc; + /* Need to backtrack */ + toiReset(¶meter->iterators[j]); + j--; + goto backtrackinc; } else { - /* Nothing more to enqueue */ - return retval; + /* Nothing more to enqueue */ + return retval; } } } @@ -1066,20 +1066,20 @@ newtask: tmpreadfds=readfds; numselect=select(maxreadfd, &tmpreadfds, NULL, NULL, &timeout); if (numselect>0) { - /* Process ready fd's */ - int fd; - for(fd=0; fdparameterArray); + // Free up task parameter descriptor + RUNFREE(currtpd->parameterArray); #ifdef OPTIONAL - RUNFREE(currtpd->failed); + RUNFREE(currtpd->failed); #endif - RUNFREE(currtpd); - goto newtask; + RUNFREE(currtpd); + goto newtask; } int numparams=currtpd->task->numParameters; int numtotal=currtpd->task->numTotal; /* Make sure that the parameters are still in the queues */ for(i=0; iparameterArray[i]; - struct parameterdescriptor * pd=currtpd->task->descriptorarray[i]; - struct parameterwrapper *pw=(struct parameterwrapper *) pd->queue; - int j; - /* Check that object is still in queue */ + void * parameter=currtpd->parameterArray[i]; + struct parameterdescriptor * pd=currtpd->task->descriptorarray[i]; + struct parameterwrapper *pw=(struct parameterwrapper *) pd->queue; + int j; + /* Check that object is still in queue */ #ifdef OPTIONAL - { - int UNUSED, UNUSED2; - int *flags; - int numflags, isnonfailed; - int failed=currtpd->failed[i]; - if (!ObjectHashget(pw->objectset, (int) parameter, &UNUSED, (int *) &flags, &numflags, &isnonfailed)) { - RUNFREE(currtpd->parameterArray); - RUNFREE(currtpd->failed); - RUNFREE(currtpd); - goto newtask; - } else { - if (failed&&(flags!=NULL)) { - //Failed parameter - fsesarray[i]=flags; - numfsesarray[i]=numflags; - } else if (!failed && isnonfailed) { - //Non-failed parameter - fsesarray[i]=NULL; - numfsesarray[i]=0; - } else { - RUNFREE(currtpd->parameterArray); - RUNFREE(currtpd->failed); - RUNFREE(currtpd); - goto newtask; - } - } - } + { + int UNUSED, UNUSED2; + int *flags; + int numflags, isnonfailed; + int failed=currtpd->failed[i]; + if (!ObjectHashget(pw->objectset, (int) parameter, &UNUSED, (int *) &flags, &numflags, &isnonfailed)) { + RUNFREE(currtpd->parameterArray); + RUNFREE(currtpd->failed); + RUNFREE(currtpd); + goto newtask; + } else { + if (failed&&(flags!=NULL)) { + //Failed parameter + fsesarray[i]=flags; + numfsesarray[i]=numflags; + } else if (!failed && isnonfailed) { + //Non-failed parameter + fsesarray[i]=NULL; + numfsesarray[i]=0; + } else { + RUNFREE(currtpd->parameterArray); + RUNFREE(currtpd->failed); + RUNFREE(currtpd); + goto newtask; + } + } + } #else - { - if (!ObjectHashcontainskey(pw->objectset, (int) parameter)) { - RUNFREE(currtpd->parameterArray); - RUNFREE(currtpd); - goto newtask; - } - } + { + if (!ObjectHashcontainskey(pw->objectset, (int) parameter)) { + RUNFREE(currtpd->parameterArray); + RUNFREE(currtpd); + goto newtask; + } + } #endif parameterpresent: - ; - /* Check that object still has necessary tags */ - for(j=0; jnumbertags; j++) { - int slotid=pd->tagarray[2*j]+numparams; - struct ___TagDescriptor___ *tagd=currtpd->parameterArray[slotid]; - if (!containstag(parameter, tagd)) { - RUNFREE(currtpd->parameterArray); + ; + /* Check that object still has necessary tags */ + for(j=0; jnumbertags; j++) { + int slotid=pd->tagarray[2*j]+numparams; + struct ___TagDescriptor___ *tagd=currtpd->parameterArray[slotid]; + if (!containstag(parameter, tagd)) { + RUNFREE(currtpd->parameterArray); #ifdef OPTIONAL - RUNFREE(currtpd->failed); + RUNFREE(currtpd->failed); #endif - RUNFREE(currtpd); - goto newtask; - } - } + RUNFREE(currtpd); + goto newtask; + } + } - taskpointerarray[i+OFFSET]=parameter; + taskpointerarray[i+OFFSET]=parameter; } /* Copy the tags */ for(; iparameterArray[i]; + taskpointerarray[i+OFFSET]=currtpd->parameterArray[i]; } { - /* Checkpoint the state */ + /* Checkpoint the state */ #ifdef FASTCHECK - ___fcrevert___=NULL; + ___fcrevert___=NULL; #else - forward=cCreate(256, 0.4); - reverse=cCreate(256, 0.4); - void ** checkpoint=makecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, forward, reverse); + forward=cCreate(256, 0.4); + reverse=cCreate(256, 0.4); + void ** checkpoint=makecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, forward, reverse); #endif - int x; - if (x=setjmp(error_handler)) { - int counter; - /* Recover */ + int x; + if (x=setjmp(error_handler)) { + int counter; + /* Recover */ #ifdef DEBUG - printf("Fatal Error=%d, Recovering!\n",x); + printf("Fatal Error=%d, Recovering!\n",x); #endif - genputtable(failedtasks,currtpd,currtpd); + genputtable(failedtasks,currtpd,currtpd); #ifdef FASTCHECK - REVERT_OBJ(___fcrevert___); + REVERT_OBJ(___fcrevert___); #else - restorecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, checkpoint, forward, reverse); + restorecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, checkpoint, forward, reverse); #endif #ifdef OPTIONAL - for(counter=0; countertask->numParameters; counter++) { - //enqueue as failed - enqueueoptional(currtpd->parameterArray[counter], numfsesarray[counter], fsesarray[counter], currtpd->task, counter); - - //free fses copies - if (fsesarray[counter]!=NULL) - RUNFREE(fsesarray[counter]); - } + for(counter=0; countertask->numParameters; counter++) { + //enqueue as failed + enqueueoptional(currtpd->parameterArray[counter], numfsesarray[counter], fsesarray[counter], currtpd->task, counter); + + //free fses copies + if (fsesarray[counter]!=NULL) + RUNFREE(fsesarray[counter]); + } #endif #ifndef FASTCHECK - cDelete(forward); - cDelete(reverse); - freemalloc(); - forward=NULL; - reverse=NULL; + cDelete(forward); + cDelete(reverse); + freemalloc(); + forward=NULL; + reverse=NULL; #endif - } else { - if (injectfailures) { - if ((((double)random())/RAND_MAX)task->name); - longjmp(error_handler,10); - } - } - /* Actually call task */ + } else { + if (injectfailures) { + if ((((double)random())/RAND_MAX)task->name); + longjmp(error_handler,10); + } + } + /* Actually call task */ #ifdef PRECISE_GC - ((int *)taskpointerarray)[0]=currtpd->numParameters; - taskpointerarray[1]=NULL; + ((int *)taskpointerarray)[0]=currtpd->numParameters; + taskpointerarray[1]=NULL; #endif #ifdef OPTIONAL - //get the task flags set - for(i=0; ifses; - fsesarray[i]=fsescopy(fsesarray[i], numfsesarray[i]); - ((struct ___Object___ *)taskpointerarray[i+OFFSET])->fses=fsesarray[i]; - } + //get the task flags set + for(i=0; ifses; + fsesarray[i]=fsescopy(fsesarray[i], numfsesarray[i]); + ((struct ___Object___ *)taskpointerarray[i+OFFSET])->fses=fsesarray[i]; + } #endif - if(debugtask) { - printf("ENTER %s count=%d\n",currtpd->task->name, (instaccum-instructioncount)); - ((void (*)(void **))currtpd->task->taskptr)(taskpointerarray); - printf("EXIT %s count=%d\n",currtpd->task->name, (instaccum-instructioncount)); - } else - ((void (*)(void **))currtpd->task->taskptr)(taskpointerarray); + if(debugtask) { + printf("ENTER %s count=%d\n",currtpd->task->name, (instaccum-instructioncount)); + ((void (*)(void **))currtpd->task->taskptr)(taskpointerarray); + printf("EXIT %s count=%d\n",currtpd->task->name, (instaccum-instructioncount)); + } else + ((void (*)(void **))currtpd->task->taskptr)(taskpointerarray); #ifdef OPTIONAL - for(i=0; i___nextobject___; - COMMIT_OBJ(___fcrevert___); - ___fcrevert___=tmpptr; - } + while(___fcrevert___) { + struct ___Object___ *tmpptr=___fcrevert___->___nextobject___; + COMMIT_OBJ(___fcrevert___); + ___fcrevert___=tmpptr; + } #else - cDelete(forward); - cDelete(reverse); - freemalloc(); + cDelete(forward); + cDelete(reverse); + freemalloc(); #endif - // Free up task parameter descriptor - RUNFREE(currtpd->parameterArray); + // Free up task parameter descriptor + RUNFREE(currtpd->parameterArray); #ifdef OPTIONAL - RUNFREE(currtpd->failed); + RUNFREE(currtpd->failed); #endif - RUNFREE(currtpd); - forward=NULL; - reverse=NULL; - } + RUNFREE(currtpd); + forward=NULL; + reverse=NULL; + } } } } @@ -1333,16 +1333,16 @@ loopstart: /* Check for objects with existing tags */ for(i=0; idescriptorarray[i]; - int j; - for(j=0; jnumbertags; j++) { - int slotid=pd->tagarray[2*j]; - if(statusarray[slotid+numparams]!=0) { - processobject(parameter, i, pd, &iteratorcount, statusarray, numparams); - processtags(pd, i, parameter, &iteratorcount, statusarray, numparams); - goto loopstart; - } - } + struct parameterdescriptor *pd=task->descriptorarray[i]; + int j; + for(j=0; jnumbertags; j++) { + int slotid=pd->tagarray[2*j]; + if(statusarray[slotid+numparams]!=0) { + processobject(parameter, i, pd, &iteratorcount, statusarray, numparams); + processtags(pd, i, parameter, &iteratorcount, statusarray, numparams); + goto loopstart; + } + } } } @@ -1350,12 +1350,12 @@ loopstart: for(i=0; idescriptorarray[i]; - if (pd->numbertags>0) { - processobject(parameter, i, pd, &iteratorcount, statusarray, numparams); - processtags(pd, i, parameter, &iteratorcount, statusarray, numparams); - goto loopstart; - } + struct parameterdescriptor *pd=task->descriptorarray[i]; + if (pd->numbertags>0) { + processobject(parameter, i, pd, &iteratorcount, statusarray, numparams); + processtags(pd, i, parameter, &iteratorcount, statusarray, numparams); + goto loopstart; + } } } @@ -1363,10 +1363,10 @@ loopstart: for(i=0; idescriptorarray[i]; - processobject(parameter, i, pd, &iteratorcount, statusarray, numparams); - processtags(pd, i, parameter, &iteratorcount, statusarray, numparams); - goto loopstart; + struct parameterdescriptor *pd=task->descriptorarray[i]; + processobject(parameter, i, pd, &iteratorcount, statusarray, numparams); + processtags(pd, i, parameter, &iteratorcount, statusarray, numparams); + goto loopstart; } } @@ -1389,29 +1389,29 @@ void printdebug() { printf(" Parameter %d\n", j); ObjectHashiterator(set, &objit); while(ObjhasNext(&objit)) { - struct ___Object___ * obj=(struct ___Object___ *)Objkey(&objit); - struct ___Object___ * tagptr=obj->___tags___; - int nonfailed=Objdata4(&objit); - int numflags=Objdata3(&objit); - int flags=Objdata2(&objit); - Objnext(&objit); - printf(" Contains %lx\n", obj); - printf(" flag=%d\n", obj->flag); + struct ___Object___ * obj=(struct ___Object___ *)Objkey(&objit); + struct ___Object___ * tagptr=obj->___tags___; + int nonfailed=Objdata4(&objit); + int numflags=Objdata3(&objit); + int flags=Objdata2(&objit); + Objnext(&objit); + printf(" Contains %lx\n", obj); + printf(" flag=%d\n", obj->flag); #ifdef OPTIONAL - printf(" flagsstored=%x\n",flags); - printf(" numflags=%d\n", numflags); - printf(" nonfailed=%d\n",nonfailed); + printf(" flagsstored=%x\n",flags); + printf(" numflags=%d\n", numflags); + printf(" nonfailed=%d\n",nonfailed); #endif - if (tagptr==NULL) { - } else if (tagptr->type==TAGTYPE) { - printf(" tag=%lx\n",tagptr); - } else { - int tagindex=0; - struct ArrayObject *ao=(struct ArrayObject *)tagptr; - for(; tagindex___cachedCode___; tagindex++) { - printf(" tag=%lx\n",ARRAYGET(ao, struct ___TagDescriptor___*, tagindex)); - } - } + if (tagptr==NULL) { + } else if (tagptr->type==TAGTYPE) { + printf(" tag=%lx\n",tagptr); + } else { + int tagindex=0; + struct ArrayObject *ao=(struct ArrayObject *)tagptr; + for(; tagindex___cachedCode___; tagindex++) { + printf(" tag=%lx\n",ARRAYGET(ao, struct ___TagDescriptor___*, tagindex)); + } + } } } } @@ -1442,7 +1442,7 @@ void processtasks() { parameter->slot=j; /* Link new queue in */ while((*ptr)!=NULL) - ptr=&((*ptr)->next); + ptr=&((*ptr)->next); (*ptr)=parameter; } @@ -1480,18 +1480,18 @@ int toiHasNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * fa if (tagptr->type==TAGTYPE) { if ((it->tagobjindex==0)&& /* First object */ (it->tagid==((struct ___TagDescriptor___ *)tagptr)->flag)) /* Right tag type */ - return 1; + return 1; else - return 0; + return 0; } else { struct ArrayObject *ao=(struct ArrayObject *) tagptr; int tagindex=it->tagobjindex; for(; tagindex___cachedCode___; tagindex++) { - struct ___TagDescriptor___ *td=ARRAYGET(ao, struct ___TagDescriptor___ *, tagindex); - if (td->flag==it->tagid) { - it->tagobjindex=tagindex; /* Found right type of tag */ - return 1; - } + struct ___TagDescriptor___ *td=ARRAYGET(ao, struct ___TagDescriptor___ *, tagindex); + if (td->flag==it->tagid) { + it->tagobjindex=tagindex; /* Found right type of tag */ + return 1; + } } return 0; } @@ -1502,36 +1502,36 @@ int toiHasNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * fa int i; if (objptr->type!=OBJECTARRAYTYPE) { if (it->tagobjindex>0) - return 0; + return 0; if (!ObjectHashcontainskey(it->objectset, (int) objptr)) - return 0; + return 0; for(i=1; inumtags; i++) { - struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]]; - if (!containstag(objptr,tag2)) - return 0; + struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]]; + if (!containstag(objptr,tag2)) + return 0; } #ifdef OPTIONAL if (it->failedstate==1) { - int UNUSED, UNUSED2; - int * flags; - int isnonfailed; - ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed); - if (flags!=NULL) { - return 1; - } else { - it->tagobjindex++; - it->failedstate=0; - return 0; - } + int UNUSED, UNUSED2; + int * flags; + int isnonfailed; + ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed); + if (flags!=NULL) { + return 1; + } else { + it->tagobjindex++; + it->failedstate=0; + return 0; + } } else { - int UNUSED, UNUSED2; - int * flags; - int isnonfailed; - ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed); - if (!isnonfailed) { - it->failedstate=1; - } - return 1; + int UNUSED, UNUSED2; + int * flags; + int isnonfailed; + ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed); + if (!isnonfailed) { + it->failedstate=1; + } + return 1; } #endif return 1; @@ -1541,43 +1541,43 @@ int toiHasNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * fa int i; #ifdef OPTIONAL if (it->failedstate==1) { - int UNUSED, UNUSED2; - int * flags; - int isnonfailed; - struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, it->tagobjindex); - ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed); - if (flags!=NULL) { - return 1; - } else { - it->failedstate=0; - it->tagobjindex++; - } + int UNUSED, UNUSED2; + int * flags; + int isnonfailed; + struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, it->tagobjindex); + ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed); + if (flags!=NULL) { + return 1; + } else { + it->failedstate=0; + it->tagobjindex++; + } } #endif for(tagindex=it->tagobjindex; tagindex___cachedCode___; tagindex++) { - struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex); - if (!ObjectHashcontainskey(it->objectset, (int) objptr)) - continue; - for(i=1; inumtags; i++) { - struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]]; - if (!containstag(objptr,tag2)) - goto nexttag; - } + struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex); + if (!ObjectHashcontainskey(it->objectset, (int) objptr)) + continue; + for(i=1; inumtags; i++) { + struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]]; + if (!containstag(objptr,tag2)) + goto nexttag; + } #ifdef OPTIONAL - { - int UNUSED, UNUSED2; - int flags, isnonfailed; - struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex); - ObjectHashget(it->objectset, (int) objptr, &UNUSED, &flags, &UNUSED2, &isnonfailed); - if (!isnonfailed) { - it->failedstate=1; - } - } + { + int UNUSED, UNUSED2; + int flags, isnonfailed; + struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex); + ObjectHashget(it->objectset, (int) objptr, &UNUSED, &flags, &UNUSED2, &isnonfailed); + if (!isnonfailed) { + it->failedstate=1; + } + } #endif - it->tagobjindex=tagindex; - return 1; + it->tagobjindex=tagindex; + return 1; nexttag: - ; + ; } it->tagobjindex=tagindex; return 0; @@ -1586,16 +1586,16 @@ nexttag: #ifdef OPTIONAL if (it->failedstate==1) { if (Objdata2(&it->it)) - return 1; + return 1; else { - it->failedstate=0; - Objnext(&it->it); + it->failedstate=0; + Objnext(&it->it); } } if (ObjhasNext(&it->it)) { if (!Objdata4(&it->it)) { - //failed state only - it->failedstate=1; + //failed state only + it->failedstate=1; } return 1; } else @@ -1613,7 +1613,7 @@ int containstag(struct ___Object___ *ptr, struct ___TagDescriptor___ *tag) { struct ArrayObject *ao=(struct ArrayObject *)objptr; for(j=0; j___cachedCode___; j++) { if (ptr==ARRAYGET(ao, struct ___Object___*, j)) - return 1; + return 1; } return 0; } else @@ -1646,10 +1646,10 @@ void toiNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * fail failed[it->slot]=it->failedstate; objectarray[it->slot]=objptr; if (it->failedstate==0) { - it->failedstate=1; + it->failedstate=1; } else { - it->failedstate=0; - it->tagobjindex++; + it->failedstate=0; + it->tagobjindex++; } #else it->tagobjindex++; @@ -1661,10 +1661,10 @@ void toiNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * fail failed[it->slot]=it->failedstate; objectarray[it->slot]=ARRAYGET(ao, struct ___Object___ *, it->tagobjindex); if (it->failedstate==0) { - it->failedstate=1; + it->failedstate=1; } else { - it->failedstate=0; - it->tagobjindex++; + it->failedstate=0; + it->tagobjindex++; } #else objectarray[it->slot]=ARRAYGET(ao, struct ___Object___ *, it->tagobjindex++); diff --git a/Robust/src/Runtime/taskgarbage.c b/Robust/src/Runtime/taskgarbage.c index b00981c5..b36a7df6 100644 --- a/Robust/src/Runtime/taskgarbage.c +++ b/Robust/src/Runtime/taskgarbage.c @@ -27,15 +27,15 @@ void searchtaskroots() { #if !defined(MULTICORE) struct parameterwrapper * p=objectqueues[i]; while(p!=NULL) { - struct ObjectHash * set=p->objectset; - struct ObjectNode * ptr=set->listhead; - while(ptr!=NULL) { - void *orig=(void *)ptr->key; - ENQUEUE(orig, *((void **)(&ptr->key))); - ptr=ptr->lnext; - } - ObjectHashrehash(set); /* Rehash the table */ - p=p->next; + struct ObjectHash * set=p->objectset; + struct ObjectNode * ptr=set->listhead; + while(ptr!=NULL) { + void *orig=(void *)ptr->key; + ENQUEUE(orig, *((void **)(&ptr->key))); + ptr=ptr->lnext; + } + ObjectHashrehash(set); /* Rehash the table */ + p=p->next; } #endif } @@ -88,8 +88,8 @@ void searchtaskroots() { struct taskparamdescriptor *tpd=ptr->src; int i; for(i=0; inumParameters; i++) { - void * orig=tpd->parameterArray[i]; - ENQUEUE(orig, tpd->parameterArray[i]); + void * orig=tpd->parameterArray[i]; + ENQUEUE(orig, tpd->parameterArray[i]); } ptr=ptr->inext; } @@ -103,8 +103,8 @@ void searchtaskroots() { struct taskparamdescriptor *tpd=ptr->src; int i; for(i=0; inumParameters; i++) { - void * orig=tpd->parameterArray[i]; - ENQUEUE(orig, tpd->parameterArray[i]); + void * orig=tpd->parameterArray[i]; + ENQUEUE(orig, tpd->parameterArray[i]); } ptr=ptr->inext; } @@ -136,45 +136,45 @@ void fixtags() { struct ___Object___ *obj=tagd->flagptr; struct ___TagDescriptor___ *copy=((struct ___TagDescriptor___**)tagd)[1]; if (obj==NULL) { - /* Zero object case */ + /* Zero object case */ } else if (obj->type==-1) { - /* Single object case */ - copy->flagptr=((struct ___Object___**)obj)[1]; + /* Single object case */ + copy->flagptr=((struct ___Object___**)obj)[1]; } else if (obj->type==OBJECTARRAYTYPE) { - /* Array case */ - struct ArrayObject *ao=(struct ArrayObject *) obj; - int livecount=0; - int j; - int k=0; - struct ArrayObject *aonew; - - /* Count live objects */ - for(j=0; j___cachedCode___; j++) { - struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, j); - if (tobj->type==-1) - livecount++; - } - - livecount=((livecount-1)/OBJECTARRAYINTERVAL+1)*OBJECTARRAYINTERVAL; - aonew=(struct ArrayObject *) tomalloc(sizeof(struct ArrayObject)+sizeof(struct ___Object___*)*livecount); - memcpy(aonew, ao, sizeof(struct ArrayObject)); - aonew->type=OBJECTARRAYTYPE; - aonew->___length___=livecount; - copy->flagptr=aonew; - for(j=0; j___cachedCode___; j++) { - struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, j); - if (tobj->type==-1) { - struct ___Object___ * tobjcpy=((struct ___Object___**)tobj)[1]; - ARRAYSET(aonew, struct ___Object___*, k++,tobjcpy); - } - } - aonew->___cachedCode___=k; - for(; k___cachedCode___; j++) { + struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, j); + if (tobj->type==-1) + livecount++; + } + + livecount=((livecount-1)/OBJECTARRAYINTERVAL+1)*OBJECTARRAYINTERVAL; + aonew=(struct ArrayObject *) tomalloc(sizeof(struct ArrayObject)+sizeof(struct ___Object___*)*livecount); + memcpy(aonew, ao, sizeof(struct ArrayObject)); + aonew->type=OBJECTARRAYTYPE; + aonew->___length___=livecount; + copy->flagptr=aonew; + for(j=0; j___cachedCode___; j++) { + struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, j); + if (tobj->type==-1) { + struct ___Object___ * tobjcpy=((struct ___Object___**)tobj)[1]; + ARRAYSET(aonew, struct ___Object___*, k++,tobjcpy); + } + } + aonew->___cachedCode___=k; + for(; kflagptr=NULL; + /* No object live anymore */ + copy->flagptr=NULL; } } free(taghead); diff --git a/Robust/src/Runtime/workschedule.c b/Robust/src/Runtime/workschedule.c index 865efba6..1dc7a352 100644 --- a/Robust/src/Runtime/workschedule.c +++ b/Robust/src/Runtime/workschedule.c @@ -167,62 +167,62 @@ void* workerMain(void* arg) { if( workUnit != DQ_POP_EMPTY ) { - haveWork = TRUE; - goto dowork; + haveWork = TRUE; + goto dowork; } else { - // try to steal from another queue, starting - // with the last successful victim, don't check - // your own deque - int mynumWorkSchedWorkers=numWorkSchedWorkers; - for( i = 0; i < mynumWorkSchedWorkers - 1; ++i ) { + // try to steal from another queue, starting + // with the last successful victim, don't check + // your own deque + int mynumWorkSchedWorkers=numWorkSchedWorkers; + for( i = 0; i < mynumWorkSchedWorkers - 1; ++i ) { - workUnit = dqPopTop(&(deques[lastVictim]) ); + workUnit = dqPopTop(&(deques[lastVictim]) ); #ifdef SQUEUE - if( workUnit != DQ_POP_EMPTY ) { + if( workUnit != DQ_POP_EMPTY ) { #else - if( workUnit != DQ_POP_ABORT && - workUnit != DQ_POP_EMPTY ) { + if( workUnit != DQ_POP_ABORT && + workUnit != DQ_POP_EMPTY ) { #endif - // successful steal! - haveWork = TRUE; - goto dowork; - } - - // choose next victim - lastVictim++; if( lastVictim == mynumWorkSchedWorkers ) { - lastVictim = 0; - } - - if( lastVictim == myWorkerID ) { - lastVictim++; if( lastVictim == mynumWorkSchedWorkers ) { - lastVictim = 0; - } - } - } - // end steal attempts - - - // if we successfully stole work, break out of the - // while-not-have-work loop, otherwise we looked - // everywhere, so drop down to "I'm idle" code below - if( haveWork ) { - goto dowork; - } + // successful steal! + haveWork = TRUE; + goto dowork; + } + + // choose next victim + lastVictim++; if( lastVictim == mynumWorkSchedWorkers ) { + lastVictim = 0; + } + + if( lastVictim == myWorkerID ) { + lastVictim++; if( lastVictim == mynumWorkSchedWorkers ) { + lastVictim = 0; + } + } + } + // end steal attempts + + + // if we successfully stole work, break out of the + // while-not-have-work loop, otherwise we looked + // everywhere, so drop down to "I'm idle" code below + if( haveWork ) { + goto dowork; + } } // if we drop down this far, we didn't find any work, // so do a garbage collection, yield the processor, // then check if the entire system is out of work if( unlikely(needtocollect) ) { - checkcollect(&emptygarbagelist); + checkcollect(&emptygarbagelist); } sched_yield(); if( mainTaskRetired ) { - keepRunning = FALSE; - break; + keepRunning = FALSE; + break; } } // end the while-not-have-work loop @@ -241,7 +241,7 @@ dowork: #ifdef DEBUG_DEQUE if( workUnit == NULL ) { - printf("About to execute a null work item\n"); + printf("About to execute a null work item\n"); } #endif @@ -302,8 +302,8 @@ void workScheduleInit(int numProcessors, for(; x " + node2.getLabel() + " [" + "label=\"" + edgelabel + "\"" + edgedotnodeparams + "];"); - } - } - } + GraphNode gn = (GraphNode) it.next(); + Iterator edges = gn.edges(); + String label = ""; + String dotnodeparams=""; + + for(int i=0; i " + node2.getLabel() + " [" + "label=\"" + edgelabel + "\"" + edgedotnodeparams + "];"); + } + } + } } } @@ -313,19 +313,19 @@ public class GraphNode { HashSet toprocess=new HashSet(); toprocess.add(gn); while(!toprocess.isEmpty()) { - GraphNode gn2=(GraphNode)toprocess.iterator().next(); - toprocess.remove(gn2); - if (!gn2.merge) - newset.add(gn2); - else { - Iterator edges = gn2.edges(); - while (edges.hasNext()) { - Edge edge = (Edge) edges.next(); - GraphNode node = edge.getTarget(); - if (!newset.contains(node)&&nodes.contains(node)) - toprocess.add(node); - } - } + GraphNode gn2=(GraphNode)toprocess.iterator().next(); + toprocess.remove(gn2); + if (!gn2.merge) + newset.add(gn2); + else { + Iterator edges = gn2.edges(); + while (edges.hasNext()) { + Edge edge = (Edge) edges.next(); + GraphNode node = edge.getTarget(); + if (!newset.contains(node)&&nodes.contains(node)) + toprocess.add(node); + } + } } return newset; } @@ -342,7 +342,7 @@ public class GraphNode { return cycleset; for(int i=0; i1) - return true; + return true; Object [] array=s.toArray(); GraphNode gn=(GraphNode)array[0]; for(Iterator it=gn.edges(); it.hasNext(); ) { - Edge e=(Edge)it.next(); - if (e.getTarget()==gn) - return true; /* Self Cycle */ + Edge e=(Edge)it.next(); + if (e.getTarget()==gn) + return true; /* Self Cycle */ } return false; } @@ -417,7 +417,7 @@ public class GraphNode { * of the set of nodes 'nodes'*/ public static SCC computeSCC(Collection nodes) { if (nodes==null) { - throw new NullPointerException(); + throw new NullPointerException(); } DFS dfs=new DFS(nodes); dfs.sccmap=new HashMap(); @@ -425,38 +425,38 @@ public class GraphNode { dfs.finishingorder=new Vector(); boolean acyclic=dfs.go(); for (Iterator it = nodes.iterator(); it.hasNext(); ) { - GraphNode gn = (GraphNode) it.next(); - gn.resetscc(); + GraphNode gn = (GraphNode) it.next(); + gn.resetscc(); } for(int i=dfs.finishingorder.size()-1; i>=0; i--) { - GraphNode gn=(GraphNode)dfs.finishingorder.get(i); - if (gn.getStatus() == UNVISITED) { - dfs.dfsprev(gn); - dfs.sccindex++; /* Increment scc index */ - } + GraphNode gn=(GraphNode)dfs.finishingorder.get(i); + if (gn.getStatus() == UNVISITED) { + dfs.dfsprev(gn); + dfs.sccindex++; /* Increment scc index */ + } } return new SCC(acyclic,dfs.sccmap,dfs.sccmaprev,dfs.sccindex); } void dfsprev(GraphNode gn) { if (gn.getStatus()==FINISHED||!nodes.contains(gn)) - return; + return; gn.setStatus(FINISHED); Integer i=new Integer(sccindex); if (!sccmap.containsKey(i)) - sccmap.put(i,new HashSet()); + sccmap.put(i,new HashSet()); ((Set)sccmap.get(i)).add(gn); sccmaprev.put(gn,i); for(Iterator edgeit=gn.inedges(); edgeit.hasNext(); ) { - Edge e=(Edge)edgeit.next(); - GraphNode gn2=e.getSource(); - dfsprev(gn2); + Edge e=(Edge)edgeit.next(); + GraphNode gn2=e.getSource(); + dfsprev(gn2); } } public static boolean depthFirstSearch(Collection nodes) { if (nodes == null) { - throw new NullPointerException(); + throw new NullPointerException(); } DFS dfs = new DFS(nodes); @@ -470,18 +470,18 @@ public class GraphNode { boolean acyclic=true; i = nodes.iterator(); while (i.hasNext()) { - GraphNode gn = (GraphNode) i.next(); - gn.reset(); + GraphNode gn = (GraphNode) i.next(); + gn.reset(); } i = nodes.iterator(); while (i.hasNext()) { - GraphNode gn = (GraphNode) i.next(); - assert gn.getStatus() != PROCESSING; - if (gn.getStatus() == UNVISITED) { - if (!dfs(gn)) - acyclic=false; - } + GraphNode gn = (GraphNode) i.next(); + assert gn.getStatus() != PROCESSING; + if (gn.getStatus() == UNVISITED) { + if (!dfs(gn)) + acyclic=false; + } } return acyclic; } @@ -492,51 +492,51 @@ public class GraphNode { Iterator edges = gn.edges(); while (edges.hasNext()) { - Edge edge = (Edge) edges.next(); - edge.discover(edgetime++); - GraphNode node = edge.getTarget(); - if (!nodes.contains(node)) { /* Skip nodes which aren't in the set */ - if(finishingorder_edge != null) - finishingorder_edge.add(edge); - edge.finish(edgetime++); - continue; - } - if (node.getStatus() == UNVISITED) { - if (!dfs(node)) - acyclic=false; - } else if (node.getStatus()==PROCESSING) { - acyclic=false; - } - if(finishingorder_edge != null) - finishingorder_edge.add(edge); - edge.finish(edgetime++); + Edge edge = (Edge) edges.next(); + edge.discover(edgetime++); + GraphNode node = edge.getTarget(); + if (!nodes.contains(node)) { /* Skip nodes which aren't in the set */ + if(finishingorder_edge != null) + finishingorder_edge.add(edge); + edge.finish(edgetime++); + continue; + } + if (node.getStatus() == UNVISITED) { + if (!dfs(node)) + acyclic=false; + } else if (node.getStatus()==PROCESSING) { + acyclic=false; + } + if(finishingorder_edge != null) + finishingorder_edge.add(edge); + edge.finish(edgetime++); } if (finishingorder!=null) - finishingorder.add(gn); + finishingorder.add(gn); gn.finish(time++); return acyclic; } public static Vector topology(Collection nodes, Vector finishingorder_edge) { if (nodes==null) { - throw new NullPointerException(); + throw new NullPointerException(); } DFS dfs=new DFS(nodes); dfs.finishingorder=new Vector(); if(finishingorder_edge != null) { - dfs.finishingorder_edge = new Vector(); + dfs.finishingorder_edge = new Vector(); } boolean acyclic=dfs.go(); Vector topology = new Vector(); for(int i=dfs.finishingorder.size()-1; i>=0; i--) { - GraphNode gn=(GraphNode)dfs.finishingorder.get(i); - topology.add(gn); + GraphNode gn=(GraphNode)dfs.finishingorder.get(i); + topology.add(gn); } if(finishingorder_edge != null) { - for(int i=dfs.finishingorder_edge.size()-1; i>=0; i--) { - Edge gn=(Edge)dfs.finishingorder_edge.get(i); - finishingorder_edge.add(gn); - } + for(int i=dfs.finishingorder_edge.size()-1; i>=0; i--) { + Edge gn=(Edge)dfs.finishingorder_edge.get(i); + finishingorder_edge.add(gn); + } } return topology; } diff --git a/Robust/src/Util/Lattice.java b/Robust/src/Util/Lattice.java index 0ce2cee1..de9c98b3 100644 --- a/Robust/src/Util/Lattice.java +++ b/Robust/src/Util/Lattice.java @@ -53,9 +53,9 @@ public class Lattice { s.add(value); if (!table.containsKey(value)) { - Set lowerNeighbor = new HashSet(); - lowerNeighbor.add(bottom); - table.put(value, lowerNeighbor); + Set lowerNeighbor = new HashSet(); + lowerNeighbor.add(bottom); + table.put(value, lowerNeighbor); } // if value is already connected with top, it is no longer to be @@ -85,17 +85,17 @@ public class Lattice { oldReachableSize = reachableSet.size(); Set nextLevelNeighbors = new HashSet(); for (Iterator iterator = neighborSet.iterator(); iterator.hasNext(); ) { - T element = iterator.next(); - Set neighbors = get(element); - if (neighbors != null) { - nextLevelNeighbors.addAll(neighbors); - reachableSet.addAll(neighbors); - } - - if (reachableSet.contains(key)) { - // found cycle - return true; - } + T element = iterator.next(); + Set neighbors = get(element); + if (neighbors != null) { + nextLevelNeighbors.addAll(neighbors); + reachableSet.addAll(neighbors); + } + + if (reachableSet.contains(key)) { + // found cycle + return true; + } } neighborSet = nextLevelNeighbors; } while (oldReachableSize != reachableSet.size()); @@ -115,7 +115,7 @@ public class Lattice { if (a.equals(top)) { if (b.equals(top)) { - return false; + return false; } return true; } @@ -138,8 +138,8 @@ public class Lattice { } else { boolean reachable = false; for (Iterator iterator = neighborSet.iterator(); iterator.hasNext(); ) { - T neighbor = iterator.next(); - reachable = reachable || isGreaterThan(neighbor, b); + T neighbor = iterator.next(); + reachable = reachable || isGreaterThan(neighbor, b); } return reachable; } @@ -162,12 +162,12 @@ public class Lattice { T inputElement = inputIterator.next(); for (Iterator iterator = lowerSet.iterator(); iterator.hasNext(); ) { - T lowerElement = (T) iterator.next(); - if (!inputElement.equals(lowerElement)) { - if (!isGreaterThan(inputElement, lowerElement)) { - toberemoved.add(lowerElement); - } - } + T lowerElement = (T) iterator.next(); + if (!inputElement.equals(lowerElement)) { + if (!isGreaterThan(inputElement, lowerElement)) { + toberemoved.add(lowerElement); + } + } } } lowerSet.removeAll(toberemoved); @@ -178,16 +178,16 @@ public class Lattice { T lowerElement = iterator.next(); boolean isGreaterThanAll = true; for (Iterator iterator2 = lowerSet.iterator(); iterator2.hasNext(); ) { - T e = iterator2.next(); - if (!lowerElement.equals(e)) { - if (!isGreaterThan(lowerElement, e)) { - isGreaterThanAll = false; - break; - } - } + T e = iterator2.next(); + if (!lowerElement.equals(e)) { + if (!isGreaterThan(lowerElement, e)) { + isGreaterThanAll = false; + break; + } + } } if (isGreaterThanAll) { - return lowerElement; + return lowerElement; } } return null; @@ -199,8 +199,8 @@ public class Lattice { if (neighborSet != null) { lowerSet.addAll(neighborSet); for (Iterator iterator = neighborSet.iterator(); iterator.hasNext(); ) { - T neighbor = iterator.next(); - lowerSet = getLowerSet(neighbor, lowerSet); + T neighbor = iterator.next(); + lowerSet = getLowerSet(neighbor, lowerSet); } } return lowerSet; diff --git a/Robust/src/Util/MultiHash.java b/Robust/src/Util/MultiHash.java index bc0e3aee..50b69bcc 100755 --- a/Robust/src/Util/MultiHash.java +++ b/Robust/src/Util/MultiHash.java @@ -26,12 +26,12 @@ public class MultiHash { int tupleKey = generateTupleKey(o, views[i]); Hashtable tuplesTable = (Hashtable) viewTable.get(views[i]); if(tuplesTable.containsKey(tupleKey)) { - Set tupleSet = (Set) tuplesTable.get(tupleKey); - tupleSet.add(o); + Set tupleSet = (Set) tuplesTable.get(tupleKey); + tupleSet.add(o); } else { - Set tupleSet = new HashSet(); - tupleSet.add(o); - tuplesTable.put(tupleKey, tupleSet); + Set tupleSet = new HashSet(); + tupleSet.add(o); + tuplesTable.put(tupleKey, tupleSet); } } } @@ -50,7 +50,7 @@ public class MultiHash { ArrayList indices = new ArrayList(); for(int i = 0; i < 31; i++) { if((mask & viewIndex) != 0) { - indices.add(i); + indices.add(i); } mask = mask << 1; } @@ -85,9 +85,9 @@ public class MultiHash { int tupleKey = generateTupleKey(o, views[i]); Hashtable tuplesTable = (Hashtable) viewTable.get(views[i]); if(tuplesTable.containsKey(tupleKey)) { - tuplesTable.remove(tupleKey); + tuplesTable.remove(tupleKey); } else { - System.out.println("Cannot find such key"); + System.out.println("Cannot find such key"); } } } @@ -105,7 +105,7 @@ public class MultiHash { System.out.println("Hashtable "+i+":\t"+tmp.keySet().toString()); Object[] keySets = tmp.keySet().toArray(); for(int j = 0; j < keySets.length; j++) { - System.out.println(tmp.get(keySets[j])); + System.out.println(tmp.get(keySets[j])); } } } diff --git a/Robust/src/Util/OptimizedView.java b/Robust/src/Util/OptimizedView.java index e3001da5..89e7efcb 100755 --- a/Robust/src/Util/OptimizedView.java +++ b/Robust/src/Util/OptimizedView.java @@ -53,7 +53,7 @@ public class OptimizedView extends MultiHash ArrayList indices = new ArrayList(); for(int i = 0; i < 31; i++) { if((mask & viewIndex) != 0) { - indices.add(i); + indices.add(i); } mask = mask << 1; } diff --git a/Robust/src/Util/UtilAlgorithms.java b/Robust/src/Util/UtilAlgorithms.java index bac5d500..033258d9 100644 --- a/Robust/src/Util/UtilAlgorithms.java +++ b/Robust/src/Util/UtilAlgorithms.java @@ -24,9 +24,9 @@ public class UtilAlgorithms { HashSet s2 = (HashSet) a.get(key); if( s2 == null ) { - a.put(key, s1.clone() ); + a.put(key, s1.clone() ); } else { - s2.addAll(s1); + s2.addAll(s1); } } } @@ -50,18 +50,18 @@ public class UtilAlgorithms { Set bvals = (Set) b.get(akey); if( bvals == null ) { - // if b doesn't have the key, mark it for - // safe removal after we traverse the map - keysToRemove.add(akey); + // if b doesn't have the key, mark it for + // safe removal after we traverse the map + keysToRemove.add(akey); } else { - // otherwise we have the key, but pare - // down the value set, if needed, and if - // nothing is left, remove the key, too - avals.retainAll(bvals); - if( avals.isEmpty() ) { - keysToRemove.add(akey); - } + // otherwise we have the key, but pare + // down the value set, if needed, and if + // nothing is left, remove the key, too + avals.retainAll(bvals); + if( avals.isEmpty() ) { + keysToRemove.add(akey); + } } } diff --git a/Robust/src/c.cfg b/Robust/src/c.cfg index 0bd5843a..cf623151 100644 --- a/Robust/src/c.cfg +++ b/Robust/src/c.cfg @@ -1,3 +1,4 @@ +indent_with_tabs = 0 indent_columns = 2 nl_if_brace = Remove nl_brace_else = Remove diff --git a/Robust/src/java.cfg b/Robust/src/java.cfg index a09964d4..8ceb6558 100644 --- a/Robust/src/java.cfg +++ b/Robust/src/java.cfg @@ -1,3 +1,4 @@ +indent_with_tabs = 0 indent_columns = 2 indent_class = True nl_if_brace = Remove -- 2.34.1